forked from sclorg/nodejs-ex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
316 lines (276 loc) · 8.06 KB
/
server.js
File metadata and controls
316 lines (276 loc) · 8.06 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
require('./common.js');
// OpenShift sample Node application
var express = require('express'),
app = express(),
morgan = require('morgan');
Object.assign=require('object-assign')
app.engine('html', require('ejs').renderFile);
app.use(morgan('combined'))
var compression = require('compression');
app.use(compression());
var port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080,
ip = process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0',
mongoURL = process.env.OPENSHIFT_MONGODB_DB_URL || process.env.MONGO_URL,
mongoURLLabel = "";
if (mongoURL == null) {
var mongoHost, mongoPort, mongoDatabase, mongoPassword, mongoUser;
// If using plane old env vars via service discovery
if (process.env.DATABASE_SERVICE_NAME) {
var mongoServiceName = process.env.DATABASE_SERVICE_NAME.toUpperCase();
mongoHost = process.env[mongoServiceName + '_SERVICE_HOST'];
mongoPort = process.env[mongoServiceName + '_SERVICE_PORT'];
mongoDatabase = process.env[mongoServiceName + '_DATABASE'];
mongoPassword = process.env[mongoServiceName + '_PASSWORD'];
mongoUser = process.env[mongoServiceName + '_USER'];
// If using env vars from secret from service binding
} else if (process.env.database_name) {
mongoDatabase = process.env.database_name;
mongoPassword = process.env.password;
mongoUser = process.env.username;
var mongoUriParts = process.env.uri && process.env.uri.split("//");
if (mongoUriParts.length == 2) {
mongoUriParts = mongoUriParts[1].split(":");
if (mongoUriParts && mongoUriParts.length == 2) {
mongoHost = mongoUriParts[0];
mongoPort = mongoUriParts[1];
}
}
}
if (mongoHost && mongoPort && mongoDatabase) {
mongoURLLabel = mongoURL = 'mongodb://';
if (mongoUser && mongoPassword) {
mongoURL += mongoUser + ':' + mongoPassword + '@';
}
// Provide UI label that excludes user id and pw
mongoURLLabel += mongoHost + ':' + mongoPort + '/' + mongoDatabase;
mongoURL += mongoHost + ':' + mongoPort + '/' + mongoDatabase;
}
}
var db = null,
dbDetails = new Object();
var initDb = function(callback) {
if (mongoURL == null) return;
var mongodb = require('mongodb');
if (mongodb == null) return;
mongodb.connect(mongoURL, function(err, conn) {
if (err) {
callback(err);
return;
}
db = conn;
dbDetails.databaseName = db.databaseName;
dbDetails.url = mongoURLLabel;
dbDetails.type = 'MongoDB';
console.log('Connected to MongoDB at: %s', mongoURL);
});
};
function getQ(req, defaultLimit, mostRecentFirst=true) {
// try to initialize the db on every request if it's not already
// initialized.
if (!db) {
initDb(function(err){});
}
if (db) {
var col = db.collection('stats');
let limit = req.query.limit;
if(!limit) {
if(defaultLimit) {
limit = defaultLimit;
}
}
else {
limit = parseInt(limit);
}
var q;
let query = {};
let doQuery = false;
let installID = req.query.installID;
if(installID) {
query.installID = parseInt(installID);
doQuery = true;
}
let debugBuild = req.query.debugBuild;
if(debugBuild) {
query.debugBuild = (debugBuild == 'true');
doQuery = true;
}
let guid = req.query.guid;
if(guid) {
query.guid = parseInt(guid);
doQuery = true;
}
let puzzleN = req.query.puzzleN;
if(puzzleN) {
//console.log("querying for puzzleN: '" + puzzleN + "'");
query.puzzleN = parseInt(puzzleN);
doQuery = true;
}
let buildVer = req.query.buildVer;
if(buildVer) {
//console.log("querying for buildVer: '" + buildVer + "'");
query.buildVer = buildVer;
doQuery = true;
}
let clientIP = req.query.clientIP;
if(clientIP) {
//console.log("querying for clientIP: '" + clientIP + "'");
query.clientIP = clientIP;
doQuery = true;
}
if(doQuery) {
q = col.find(query);
}
else {
q = col.find();
}
if(mostRecentFirst) {
q = q.sort({_id:-1});
}
if(limit) {
q = q.limit(limit);
}
return { q, col };
}
return undefined;
}
app.get('/', function (req, res) {
var qq = getQ(req, 50);
if(qq && qq.q) {
qq.q.toArray(function(err,result, docs) {
if(err){
res.send(err);
}
else {
qq.col.count({}, function(err, numDocs) {
if(err) {
res.send(err);
}
else {
// Create a document with request IP and current time of request
// col.insert({ip: req.ip, date: Date.now()});
res.render('index.html', { dbInfo: dbDetails, dbLatest: result, dbNumItems: numDocs, dbNumResults: size(result) });
}
});
}
});
} else {
res.render('index.html', { dbLatest: null, dbNumItems: null });
}
});
app.get('/pagecount', function (req, res) {
// try to initialize the db on every request if it's not already
// initialized.
if (!db) {
initDb(function(err){});
}
if (db) {
db.collection('counts').count(function(err, count ){
res.send('{ pageCount: ' + count + '}');
});
} else {
res.send('{ pageCount: -1 }');
}
});
var bodyParser = require('body-parser')
//app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
// dump not pretty-printed with default no limit ....
app.get('/dumpall', function (req, res) {
app.set('json spaces', 0);
var qq = getQ(req, undefined, false);
if(qq && qq.q) {
qq.q.toArray(function(err,result, docs) {
if(err){
res.send(err);
}
else {
//res.send(prettyPrint(result));
res.json(result);
}
});
} else {
res.send('fail - no DB.');
}
});
// dump pretty-printed with default limit of 1000 results ....
app.get('/dumpp', function (req, res) {
app.set('json spaces', 3);
var qq = getQ(req, 1000);
if(qq && qq.q) {
qq.q.toArray(function(err,result, docs) {
//col.find().toArray(function(err,result, docs) {
if(err){
res.send(err);
}
else {
//res.send(prettyPrint(result));
res.json(result);
}
});
} else {
res.send('fail - no DB.');
}
});
app.post('/stats', function (req, res) {
// try to initialize the db on every request if it's not already
// initialized.
if (!db) {
initDb(function(err){});
}
// convert from whatever it is we're getting from the app to a JSON object .............
var b = req.body;
var keys = Object.keys(b);
console.log("Body keys: " + keys);
console.log("Body keys sz: " + size(keys));
if(size(keys) == 1) {
b = keys[0];
b = JSON.parse(b);
}
/*
console.log("Body keys: " + Object.keys(b));
console.log("Body is: " + prettyPrint(b));
b = JSON.stringify(b);
b = JSON.parse(b).data;
*/
console.log("Body2 is: " + prettyPrint(b));
//b = JSON.parse(b);
/*
// what we're receiving from app seems to come as a string rather than JSON ....?
if(typeof b == 'string') {
console.log("Body is string - trying to unescape + parse ......");
//b = unescape(b);
b = JSON.parse(b);
}
else {
console.log("Body is not a string ......");
}
//b = eval("(" + b + ")");
*/
console.log("Parsed body is: " + prettyPrint(b));
var clientIP = req.ip || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
b.date = new Date();
b.clientIP = clientIP;
console.log("ClientIP: " + clientIP);
console.log("Received stats: " + prettyPrint(b));
if (db) {
var col = db.collection('stats');
col.insertOne(b, (err, result) => {
res.send("success, data: " + prettyPrint(b));
});
} else {
res.send('fail - no DB. data: ' + prettyPrint(b));
}
});
// error handling
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500).send('Something bad happened!');
});
initDb(function(err){
console.log('Error connecting to Mongo. Message:\n'+err);
});
app.listen(port, ip);
console.log('Server running on http://%s:%s', ip, port);
module.exports = app ;