-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp-cache-index.js
266 lines (214 loc) · 6.39 KB
/
app-cache-index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//generate sitemap.xml from active DB & copy it to server
var config = require('./config');
hbs = require('hbs'),
sm = require('./sitemapgen.js'),
Q = require('q'),
express = require('express'),
moment = require('moment'),
mysql = require('mysql'),
_ = require('underscore'),
pd = require('pretty-data').pd,
fs = require('fs'),
crypto = require('crypto'),
portscanner = require('portscanner'),
log4js = require('log4js');
//dev modules
var inspect = require('eyes').inspector();
// init
moment.lang('en-gb');
var logger = log4js.getLogger(),
dbConLocal = mysql.createConnection(config.mysqlConn_local),
dbConProd1 = mysql.createConnection(config.mysqlConn_1),
connectionState = false;
// dbConProd1 = dbConLocal; //set to local
//app
var app = express();
// error handling
// ECONNRESET error
// dbConProd1.on('close', function (err) {
// logger.error('mysqldb conn close');
// connectionState = false;
// });
// dbConProd1.on('error', function (err) {
// logger.error('mysqldb error: ' + err);
// connectionState = false;
// });
function attemptConnection(connection) {
if(!connectionState){
connection = mysql.createConnection(connection.config);
connection.connect(function (err) {
// connected! (unless `err` is set)
if (err) {
logger.error('mysql db unable to connect: ' + err);
connectionState = false;
} else {
logger.info('mysql connect!');
connectionState = true;
}
});
connection.on('close', function (err) {
logger.error('mysqldb conn close');
connectionState = false;
});
connection.on('error', function (err) {
logger.error('mysqldb error: ' + err);
if (!err.fatal) {
//throw err;
}
if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
//throw err;
} else {
connectionState = false;
attemptConnection(dbConProd1);
}
});
}
};
attemptConnection(dbConProd1);
var MV = {
serverPort: 3005,
mainInit: function(){
app.listen(this.serverPort);
console.log('Listening on port $', this.serverPort);
console.log('demo at: http://localhost:3005/cache-update');
},
authenticated: false,
// validates user
verifyUserInDB: function(user, pass, callback){
if(MV.authenticated) return callback(null, MV.authenticated);
if(user && pass){
console.log('DB login check');
var passHash = crypto.createHash('md5').update(pass).digest("hex").toUpperCase();
var queryStr = 'SELECT pass '+
'FROM administrators '+
'WHERE user = "' + user + '"';
dbConProd1.query(queryStr, function(err, rows, fields) {
if(err) console.error(err);
if(rows.length){
if(rows[0].pass === passHash) {
MV.authenticated = true;
return callback(null, MV.authenticated)
}
}
return callback(null, MV.authenticated);
});
} else {
return callback(new Error('Username & pass must be defined'), false);
}
},
// get all resorts list
getUrls: function(lang) {
lang = lang || 'en';
var deferred = Q.defer();
var queryStr = 'SELECT url, lang, IDCountry, IDResort '+
'FROM index_urls '+
'WHERE index_urls.lang NOT IN ("hu", "sp", "ru") '+
'AND index_urls.IDFacility = "" '+
'AND index_urls.IDAccommodation = "" '+
'GROUP BY index_urls.url '+
'ORDER BY IDResort ';
dbConProd1.query(queryStr, function(err, rows, fields) {
if(err) deferred.reject(err);
// rows.unshift({url:'/'+lang+'/', priority: 1, freq: 'daily'}); //append domain root
deferred.resolve(rows, fields);
});
return deferred.promise;
},
getDBStatus: function(lang) {
lang = lang || 'en';
var deferred = Q.defer();
var queryStr = 'SHOW TABLE STATUS FROM gogoski_com_1'; //LIKE "index_urls"';
dbConProd1.query(queryStr, function(err, rows, fields) {
if(err) deferred.reject(err);
// rows.unshift({url:'/'+lang+'/', priority: 1, freq: 'daily'}); //append domain root
deferred.resolve(rows, fields);
});
return deferred.promise;
},
urlSearch: function(url, lang, type ) {
lang = lang || 'en';
var deferred = Q.defer();
var queryStr = ' SELECT *'+
' FROM index_urls'+
' WHERE lang IN (?)'+
' AND IDFacility = 0'+
' AND index_urls.url LIKE ?';
dbConProd1.query(queryStr, [lang, url], function(err, rows, fields) {
if(err) deferred.reject(err);
// rows.unshift({url:'/'+lang+'/', priority: 1, freq: 'daily'}); //append domain root
deferred.resolve(rows, fields);
});
return deferred.promise;
},
getIndex: function(req, res){
MV.getUrls()
.then(
function(rows){
var groupedUrls = _.toArray(_.groupBy(rows, function(url){
return url.IDResort;
}));
var data = { urls: groupedUrls };
res.render('index-cache.hbs', data);
},
function(err){logger.error(err);}
);
},
getStatus: function(req, res){
MV.getDBStatus()
.then(
function(rows){
var aa = _.groupBy(rows, function(el){
// console.log(rows);
return true;
});
// console.log(aa);
var data = { lastScreenUpdate: moment().format('LLLL') };
res.render('status.hbs', data);
},
function(err){logger.error(err);}
);
},
getSearch: function(req, res){
var q = req.body;
MV.urlSearch('%'+q.search+'%', q.lang, q.type)
.then(
function(rows){
var data = {result: rows};
// data = [1,2,3]
res.render('search.hbs', data);
},
function(err){logger.error(err);}
);
}
};
// Asynchronous Auth Function
var auth = express.basicAuth(MV.verifyUserInDB);
var authLogout = express.basicAuth(function(user, pass, callback){
MV.authenticated = false;
return callback(null, false);
});
//Web index
app.configure(function(){
app.use(express.cookieParser());
app.use(express.cookieParser({secret: '1234567890QWERTY'}));
app.use(express.cookieSession({secret: '1234567890QWERTY'}));
// app.use(MV.auth); //auth for all
app.set('view engine', 'hbs');
app.use(express.bodyParser());
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
});
//routes
app.get('/', auth, MV.getIndex); //requires auth
app.get('/status', auth, MV.getStatus); //requires auth
app.all('/search', MV.getSearch);
app.get('/logout', authLogout);
var countries = ['', 'si', 'hr', 'it', 'de', 'fr', 'pl', 'cz', 'en'];
portscanner.checkPortStatus(MV.serverPort, 'localhost', function(error, status) {
// Status is 'open' if currently in use or 'closed' if available
if(status === 'closed'){
MV.mainInit();
} else {
console.error('Port '+MV.serverPort+' is in use, closing application.');
}
});