-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
428 lines (368 loc) · 11 KB
/
app.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* Module dependencies.
*/
var express = require('express');
var _ = require('underscore');
_.mixin(require('underscore.string'));
var fs = require('fs');
var assert = require('assert');
var connect = require('connect');
require('express-namespace');
var app = module.exports = express.createServer();
var MemoryStore = connect.session.MemoryStore;
var debug = false;
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
// session longs for 24 hours
app.use(express.session({ secret: 'keyboard cat',
store: new MemoryStore({ maxAge: 1000*60*60*24 })}));
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
debug = true;
});
app.configure('production', function(){
app.use(express.errorHandler());
debug = false;
});
// Code
var VALIDATE_CYCLE = 25; // like 캐시 validation 주기
var BACKUP_CYCLE = 1;
var MAX_TEXT_LENGTH = 140;
try {
var MASTER_PASSWD = _(fs.readFileSync('master_passwd', 'utf-8')).trim();
} catch (e) {
console.error('A master password is required. Create "./master_passwd" file.');
process.exit(1);
}
var defaultDb = {
nextId: 1,
events: [],
likes: []
};
var db = getBackupDb();
function getNextId() {
return db.nextId++;
}
function getClientAddress(req) {
return req.headers['x-forwarded-for'] || req.connection.remoteAddress;
}
function getEvent(id) {
return _.detect(db.events, function (item) {
return item.id == id && !item.deleted;
});
}
function getEventsByTopic(topic) {
return _.filter(db.events, function (event) {
return event.topic == topic && !event.deleted;
});
}
function getDateRepr(date) {
assert.ok(date instanceof Date);
return _.sprintf("%04d%02d%02d", date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate());
}
var getPledges = (function () {
var pledges;
function setupPledges() {
_.each(['정몽준', '박원순'], function (name) {
_.each(['경제', '안전', '주택', '복지'], function (domain) {
var newid = getNextId();
db.events.push({
id: name+'_'+domain,
topic: '공약',
like: 0
});
});
});
}
return function () {
if (_.isUndefined(pledges)) {
if (!getEventsByTopic('공약').length) {
setupPledges();
}
pledges = _(db.events).chain()
.filter(function (event) {
return event.topic == '공약';
})
.groupBy(function (event) {
return event.id;
}).value();
_.each(pledges, function (pledge, id) {
pledges[id] = pledge[0];
});
}
return pledges;
}
})();
var getSortedEventsByTopic = (function () {
var sortedEventsSet = {'date': [], 'like': []};
var prevSortBy = null;
return function (topic, sortBy) {
// TODO: MongoDB 등의 데이터베이스 사용하기 (JSON 인터페이스라 비교적 쉽게 쓸 수 있을... 듯?)
// 현재는 데이터량이 작아서 상관 없겠지만, 메모리에 sort 방식에 따른 중복 copy를 들고 있는 비효율성 문제가 있음.
var sortedEvents = sortedEventsSet[sortBy][topic];
// 캐시 사용 가능 여부 체크
if (!debug && sortedEvents && sortedEvents.nextIdWhenLastSorted == db.nextId) {
return sortedEvents.events;
} else {
sortedEvents = getEventsByTopic(topic);
if (!sortedEvents.length) {
loadStatements(topic);
sortedEvents = getEventsByTopic(topic);
}
sortedEvents.sort(function (ev1, ev2) {
// 날짜의 대소관계만 비교하기 위해 YYYYMMDD 형태의 숫자로 변환
var date1 = parseInt(getDateRepr(new Date(ev1.date)));
var date2 = parseInt(getDateRepr(new Date(ev2.date)));
if (sortBy == 'date') { // 날짜를 우선 정렬
return (date1 != date2) ? (date2 - date1) : (ev2.id - ev1.id);
} else { // like를 우선 정렬
return (ev1.like != ev2.like) ? (ev2.like - ev1.like) : (date2 - date1);
}
return 0;
});
sortedEventsSet[sortBy][topic] = {
events: sortedEvents,
nextIdWhenLastSorted: db.nextId
};
return sortedEvents;
}
};
})();
function validateNumLiked(event) {
var expectedNumLiked = _.filter(db.likes, function (item) {
return item.id == event.id;
}).length;
if (expectedNumLiked !== event.like) {
console.warn('Like count for #%d does not match: '
+ 'expected: %d, actual: %d'
, event.id, expectedNumLiked, event.like);
// assume that expected one is always right
event.like = expectedNumLiked;
}
}
function getNumLiked(id) {
var event = getEvent(id);
event.like = (event.like || 0) + 1;
// occationally validate
if (event.like % VALIDATE_CYCLE === 0) {
_.delay(validateNumLiked, 0, event);
}
return event.like;
}
var updateCount = (function () {
var backupCount = 0,
nextBackupCount = 0;
return function (num) {
num = num || 1;
backupCount += num;
if (backupCount >= nextBackupCount) {
backupDb();
nextBackupCount = backupCount + BACKUP_CYCLE;
}
};
})();
function validateEvent(event) {
function validateDate(date) {
var t = date.split(/-/g);
var currentYear = (new Date()).getFullYear();
if (t.length !== 3) {
throw '잘못된 날짜 형식입니다.';
}
if (t[0] < 1900 || t[0] > currentYear) {
throw _.sprintf('%d년부터 %d년 사이를 입력해 주세요.', 1900, currentYear);
}
if (t[1] < 1 || t[1] > 12) {
throw '1월부터 12월 사이를 입력해 주세요.';
}
if (t[2] < 1 || t[2] > 31) {
throw '1일부터 31일 사이를 입력해 주세요.';
}
}
if (_.isUndefined(event.text) || event.text.length > 140) {
throw '140자가 넘는 글은 등록할 수 없습니다.';
}
if (_.isUndefined(event.link) || event.link.length == 0) {
throw '링크(출처)는 반드시 입력해야 합니다.';
}
// TODO: check URL format
if (_.isUndefined(event.passwd) || event.passwd.length == 0) {
throw '비밀번호는 반드시 입력해야 합니다.';
}
if (event.passwd.length < 4) {
throw '비밀번호는 4자 이상 입력해야 합니다.';
}
if (_.isUndefined(event.date)) {
throw '날짜는 반드시 입력해야 합니다.';
}
validateDate(event.date);
}
function getAbsoluteUrl(link) {
if (_.startsWith(link, 'http://') || _.startsWith(link, 'https://')) {
return link;
} else {
return 'http://' + link;
}
}
/**
* asynchronously backup the db
*/
function backupDb() {
try {
assert.ok(fs.statSync('db/').isDirectory());
} catch (err) {
fs.mkdirSync('db/', 0755);
}
console.log('saving database...');
_.each(db, function (table, name) {
fs.writeFile(_.sprintf('db/%s.json', name),
JSON.stringify(table),
function (err) {
if (err) {
throw res;
} else {
console.log("[%s] %s saved.", ''+new Date(), name);
}
});
});
}
function getBackupDb() {
var backup = {};
console.log('retrieving database...');
_.each(defaultDb, function (table, name) {
try {
backup[name] = JSON.parse(
fs.readFileSync(_.sprintf('db/%s.json', name, 'utf-8')));
} catch (err) {
backup[name] = typeof defaultDb[name] == 'object'
? _.clone(defaultDb[name]) : defaultDb[name];
}
});
return backup;
}
function loadStatements(topic) {
var statements = {};
try {
statements = JSON.parse(
fs.readFileSync('db/statements.json'));
} catch (err) {
console.error('db/statements.json not found.');
process.exit(1);
}
statements = statements[topic];
_.each(statements, function (statement) {
var newid = getNextId();
db.events.push({
id: newid,
topic: topic,
title: statement['text'].substring(0, 20),
text: statement['text'],
like: 0,
link: _.sprintf('http://pokr.kr/meeting/%s/dialog#%s',
statement['meeting_id'],
statement['statement_id'])
});
});
}
// Routes
app.get('/(event/:id)?', function(req, res) {
var sortBy = req.param('sortby', 'date');
if (!(sortBy == 'date' || sortBy == 'like')) {
res.send('Invalid parameters.', 400);
return;
}
res.render('index', {
title: '나는 서울 시장이다!',
style: '/stylesheets/style.css',
jsfiles: ['/javascripts/jquery-1.6.2.min.js'
, '/javascripts/underscore.string.js'
, '/javascripts/timeline.js'],
left_events: getSortedEventsByTopic('정몽준', sortBy),
right_events: getSortedEventsByTopic('박원순', sortBy),
pledges: getPledges(),
event_id: req.params.id || '',
sort_by: sortBy,
query_string: req.query // redirection 처리할 때 parameter 보존용
});
});
app.namespace('/admin', function () {
app.get('/', function(req, res){
res.render('admin_notlogged');
});
app.post('/', function (req, res) {
if (req.body.key == MASTER_PASSWD) {
var backup = getBackupDb();
res.render('admin', {
title: '관리자',
style: '/stylesheets/admin.css',
key: req.body.key,
db: JSON.stringify(db, null, 2),
backup: JSON.stringify(backup, null, 2)
});
} else {
res.redirect('/admin');
}
});
app.post('/backup', function(req, res) {
if (req.body.key == MASTER_PASSWD) {
backupDb();
}
res.redirect('/admin', 303);
});
app.post('/import', function(req, res) {
if (req.body.db && req.body.key == MASTER_PASSWD) {
console.log('importing database...');
db = JSON.parse(req.body.db);
}
res.redirect('/admin', 303);
});
});
app.post('/like', function(req, res) { // AJAX handler
if (_.isUndefined(req.session.liked)) {
req.session.liked = {};
}
if (!getEvent(req.body.id)) {
res.json({
success: 0,
message: '잘못된 이벤트입니다.'
});
return;
}
// 이미 추천한 이슈
if (req.session.liked[req.body.id]) {
res.json({
success: 0,
message: '1일 1PONG!\n내일 다시 PONG해주세요~! :D'
});
return;
}
db.likes.push({
id: req.body.id,
regdate: (new Date()).getTime(),
host: getClientAddress(req)
});
updateCount();
// XXX: 원래는 like가 증가해도 sortedEvent 캐시를 지워야 하지만
// 현재 클라이언트 JavaScript로 정렬 처리 중.
// 클라이언트에 큰 부하가 되지 않으니,
// 서버 부하를 줄이기 위해 cache 클리어하지 않음
// 세션에 추천 정보 기록
req.session.liked[req.body.id] = true;
res.json({
success: 1,
numLiked: getNumLiked(req.body.id)
});
});
var port = 3000;
if (process.argv.length > 2) {
port = parseInt(process.argv[2]);
}
app.listen(port);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);