forked from puripant/thai-provinces-visited
/
server.js
340 lines (321 loc) · 11.5 KB
/
server.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
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
require('dotenv').config();
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var assert = require('assert');
var http = require('http');
var qs = require('querystring');
var url_re = require('url');
var async = require('async');
var csv_parse = require('csv-parse');
var _ = require('lodash');
var moment = require('moment');
var serveStatic = require('serve-static')
var port = process.env.PORT || '8080';
var url = process.env.MONGODB || 'mongodb://localhost:27017/thaipv';
var site_url = (process.env.SITE_URL || `http://localhost:${port}`).replace(/\/$/, '');
// Serve up public folder
function setHeaders (res, path) {
res.setHeader('x-vendor', 'Boonmee Lab');
}
var servePublicStatic = serveStatic(__dirname + '/public', {
'setHeaders': setHeaders
});
// View template
var fs = require('fs');
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var template = {
play: _.template(fs.readFileSync('./public/index.html', 'utf8'))
};
var base_template_data = {
site_url: site_url,
current_url: '',
thumbnail_url: '',
title: 'มาอวดจังหวัดที่เคยไปกัน!',
description: 'พิมพ์ชื่อจังหวัดที่เคยไป แล้วแสดงเป็นแผนที่ไปอวดเพื่อนได้เลย! เมืองไทยมีที่เที่ยวมากมาย น้ำตก ทะเล ภูเขา เที่ยวไทย ไม่ไปไม่รู้',
page: '',
map_id: '',
province: [],
province_name: [],
avg_province: 0,
people_count: 99999,
GA_ID: process.env.GA_ID,
FB_APP_ID: process.env.FB_APP_ID
};
// CSV data
var province_list = [];
var province_file = __dirname + '/public/data/provinces-visited.csv';
var csv_parser = csv_parse({
delimiter: ',',
columns: true
}, function (err, data) {
if (err) {
console.error('parse csv failed:', err);
return;
}
province_list = data;
});
fs.createReadStream(province_file).pipe(csv_parser);
// Amazon AWS
const AWS = require('aws-sdk');
const awsConfig = {};
awsConfig.region = process.env.AWS_REGION;
awsConfig.accessKeyId = process.env.AWS_ACCESS_KEY;
awsConfig.secretAccessKey = process.env.AWS_SECRET;
AWS.config.update(awsConfig);
// S3 (http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/frames.html#!http%3A//docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3_20060301.html)
var s3 = new AWS.S3({
params: { Bucket: process.env.AWS_BUCKET }
});
var s3_resource_url = 'https://s3-' + process.env.AWS_REGION
+ '.amazonaws.com/' + process.env.AWS_BUCKET + '/';
function notfound(res) {
res.setHeader('content-type', 'text/html; charset=utf-8');
res.writeHead(404);
res.end('หาอะไรอยู่?<br><a href="' + site_url + '">กลับหน้าแรกดีกว่า</a>');
}
var mongoClient = MongoClient.connect(url, function(err, db) {
var server = http.createServer(function(req, res) {
function insertDB(data, done) {
assert.equal(typeof data, 'object');
assert.ok(Array.isArray(data.province));
assert.notEqual(data.province.length, 0);
assert.equal(typeof data.t, 'number');
data = _.pick(data, ['ip', 'province', 'ua', 't']);
// convert to number and sort ascendingly
data.province = _.uniq(data.province).map(id => Number(id)).sort((a, b) => b < a);
data.created_at = new Date();
db.collection('thaipv').insertOne(data, function(err, result) {
assert.equal(err, null);
if (err) {
done(err);
return;
}
done(null, result.insertedId);
});
}
function getStatById(id, done) {
function getObjectById(id, callback) {
db.collection("thaipv", function(err, collection) {
collection.find(id).toArray(callback);
});
}
function getPeopleCount(callback) {
db.collection("thaipv", function(err, collection) {
collection.count(callback);
});
}
function getSumProvince(callback) {
db.collection("thaipv", function(err, collection) {
collection.aggregate([
{
"$project": {
"province": 1,
"sumProvince": { "$size": "$province" }
}
},
{
"$group": {
"_id": null,
"sum_province": { "$sum": "$sumProvince" }
}
}
], callback);
});
}
var json_result;
if (!ObjectId.isValid(id)) {
done(new Error('พิมพ์ผิดมั้ง'));
return;
}
var query = { _id: new ObjectId(id) };
async.parallel({
objectById: async.apply(getObjectById, query),
// peopleCount: getPeopleCount,
// sumProvince: getSumProvince
}, function (error, results) {
if (error) {
done(error);
return;
}
let json = {
id: _.get(results, 'objectById.0._id'),
province: _.get(results, 'objectById.0.province'),
// people_count: _.get(results, 'peopleCount'),
// avg_province: Math.round(_.get(results, 'sumProvince.0.sum_province')/_.get(results, 'peopleCount'))
};
done(null, json);
// return
// {
// "_id": "595bc2e01107fc0b91194404",
// "province": [
// "Bangkok",
// "Ratchaburi",
// "Pattaya",
// "Hua Hin",
// "Chang Mai"
// ],
// "people_count": 23,
// "avg_province": 5
// }
});
}
function uploadFile(name, buffer, done) {
var params = {
Key: name,
Body: buffer,
ACL: 'public-read',
ContentEncoding: 'base64',
ContentType: 'image/png'
// other options supported by putObject, except Body and ContentLength.
// See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
};
s3.putObject(params, function(err, data) {
if (err) {
done(err);
} else {
done(null, data);
}
});
}
var req_path = url_re.parse(req.url).pathname;
var current_url = site_url + req_path;
var thumbnail_url = site_url + '/public/thumbnail.jpg';
var title = '';
var description = '';
var route = {
public: /^\/public(\/.+)$/gi,
view: /^\/view\/([0-9a-f]+)\/?$/gi,
};
var route_public_match = route.public.exec(req_path);
var route_view_match = route.view.exec(req_path);
if (req.method === 'GET' && route_public_match) {
// req.path =
req.url = route_public_match[1];
servePublicStatic(req, res, function() {
notfound(res);
});
} else if (req.method === 'POST' && req.url === '/api/play') {
// @path POST /api/play
// Store map data
// @params {array} body.province Province ID
// @params {number} body.t Time user takes to submit form in ms.
// @params {string} body.image Base64 encoded image
// @return {object} play stats
var body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
let data = JSON.parse(body);
data.ua = req.headers['user-agent'] || '';
data.ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
var image64 = data.image;
delete data.image;
insertDB(data, function(err, map_id) {
var buffer = new Buffer(image64.replace(/^data:image\/\w+;base64,/, ""), 'base64');
uploadFile(map_id + '.png', buffer, function(upload_err, upload_result) {
if (upload_err) {
res.writeHead(500);
res.end(upload_err.toString());
return;
}
res.writeHead(200);
res.end(JSON.stringify(JSON.parse('{ "id": "' + map_id + '" }')));
});
});
// Request Format
// {
// "province": ["Bangkok","Ratchaburi","Pattaya","Hua Hin","Chang Mai"]
// }
// return
// {"_id":"595bc2b50ff4f40b6c58428c"}
});
} else if (req.method === 'GET' && req_path === '/api/play') {
// @path GET /api/play
// Get play stats by ID
// @params {string} id
// @return {object} play stats
var queryy = url_re.parse(req.url, true).query;
req.on('data', function(chunk) {
// no-op
});
req.on('end', function() {
getStatById(queryy.id, function(err, result) {
if (err) {
res.writeHead(500);
res.end(err.toString());
return;
}
res.setHeader('content-type', 'application/json; charset=utf-8');
res.writeHead(200);
res.end(JSON.stringify(result));
});
});
} else if (req.method === 'GET' && req_path === '/') {
// @path GET /
var data = _.merge({}, base_template_data, {
current_url,
thumbnail_url,
page: 'play'
})
res.setHeader('content-type', 'text/html; charset=utf-8');
res.writeHead(200);
res.end(template.play(data));
} else if (req.method === 'GET' && route_view_match) {
// @path GET /view/:id
var id = route_view_match[1];
try {
getStatById(id, function(err, result) {
if (err || !result || !result.id) {
notfound(res);
return;
}
var all_province_ids = _.shuffle(_.range(1, 78));
var tovisit_province = _.difference(all_province_ids, result.province);
var province_names = _.compact(result.province.map(function(id) {
return _.get(_.find(province_list, ['id', String(id)]), 'provinceTH');
}));
var tovisit_province_names = _.compact(tovisit_province.map(function(id) {
return _.get(_.find(province_list, ['id', String(id)]), 'provinceTH');
})).slice(0, 10);
var province_names = _.compact(result.province.map(function(id) {
return _.get(_.find(province_list, ['id', String(id)]), 'provinceTH');
}));
title = 'เคยไปมาแล้ว ' + province_names.length + ' จังหวัด: ' + province_names.join(', ');
if (tovisit_province_names.length > 0) {
description = 'ขอแนะนำ! ' + tovisit_province_names.length + ' จังหวัดที่ควรไปโดนให้ไว: ' + tovisit_province_names.join(', ');
} else {
description = 'คุณคือผู้พิชิต 77 จังหวัดไทย ปรบมือ! 👏👏👏'
}
thumbnail_url = s3_resource_url + id + '.png';
var data = _.merge({}, base_template_data, result, {
current_url,
thumbnail_url,
title,
description,
page: 'result',
map_id: id
})
res.setHeader('content-type', 'text/html; charset=utf-8');
res.writeHead(200);
res.end(template.play(data));
});
} catch(err) {
res.writeHead(500);
res.end(err.toString());
}
} else {
notfound(res);
}
});
server.on("error", err => console.error(err));
server.listen(port);
console.log('server: ' + site_url);
});
process.on('uncaughtException', err => {
console.error(err, 'Uncaught Exception thrown');
process.exit(1);
});