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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609 | 1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
| var nodemailer = require('nodemailer'),
sanitizeHtml = require('sanitize-html'),
moment = require('moment'),
mongodb = require('mongodb'),
// debug = require('debug')('freecc:cntr:story'),
utils = require('../utils'),
MongoClient = mongodb.MongoClient,
secrets = require('../../config/secrets');
module.exports = function(app) {
var router = app.loopback.Router();
var User = app.models.User;
var Story = app.models.Story;
router.get('/stories/hotStories', hotJSON);
router.get('/stories/comments/:id', comments);
router.post('/stories/comment/', commentSubmit);
router.post('/stories/comment/:id/comment', commentOnCommentSubmit);
router.put('/stories/comment/:id/edit', commentEdit);
router.get('/stories/submit', submitNew);
router.get('/stories/submit/new-story', preSubmit);
router.post('/stories/preliminary', newStory);
router.post('/stories/', storySubmission);
router.get('/stories/', hot);
router.post('/stories/search', getStories);
router.get('/stories/:storyName', returnIndividualStory);
router.post('/stories/upvote/', upvote);
app.use(router);
function hotRank(timeValue, rank) {
/*
* Hotness ranking algorithm: http://amix.dk/blog/post/19588
* tMS = postedOnDate - foundationTime;
* Ranking...
* f(ts, 1, rank) = log(10)z + (ts)/45000;
*/
var time48Hours = 172800000;
var hotness;
var z = Math.log(rank) / Math.log(10);
hotness = z + (timeValue / time48Hours);
return hotness;
}
function hotJSON(req, res, next) {
Story.find({order: 'timePosted DESC', limit: 1000}, function(err, stories) {
if (err) {
return next(err);
}
var foundationDate = 1413298800000;
var sliceVal = stories.length >= 100 ? 100 : stories.length;
return res.json(stories.map(function(elem) {
return elem;
}).sort(function(a, b) {
return hotRank(b.timePosted - foundationDate, b.rank, b.headline)
- hotRank(a.timePosted - foundationDate, a.rank, a.headline);
}).slice(0, sliceVal));
});
}
function hot(req, res) {
return res.render('stories/index', {
title: 'Hot stories currently trending on Camper News',
page: 'hot'
});
}
function submitNew(req, res) {
return res.render('stories/index', {
title: 'Submit a new story to Camper News',
page: 'submit'
});
}
/*
* no used anywhere
function search(req, res) {
return res.render('stories/index', {
title: 'Search the archives of Camper News',
page: 'search'
});
}
function recent(req, res) {
return res.render('stories/index', {
title: 'Recently submitted stories on Camper News',
page: 'recent'
});
}
*/
function preSubmit(req, res) {
var data = req.query;
var cleanData = sanitizeHtml(data.url, {
allowedTags: [],
allowedAttributes: []
}).replace(/";/g, '"');
if (data.url.replace(/&/g, '&') !== cleanData) {
req.flash('errors', {
msg: 'The data for this post is malformed'
});
return res.render('stories/index', {
page: 'stories/submit'
});
}
var title = data.title || '';
var image = data.image || '';
var description = data.description || '';
return res.render('stories/index', {
title: 'Confirm your Camper News story submission',
page: 'storySubmission',
storyURL: data.url,
storyTitle: title,
storyImage: image,
storyMetaDescription: description
});
}
function returnIndividualStory(req, res, next) {
var dashedName = req.params.storyName;
var storyName = dashedName.replace(/\-/g, ' ').trim();
Story.find({where: {'storyLink': storyName}}, function(err, story) {
if (err) {
return next(err);
}
if (story.length < 1) {
req.flash('errors', {
msg: "404: We couldn't find a story with that name. " +
'Please double check the name.'
});
return res.redirect('/stories/');
}
story = story.pop();
var dashedNameFull = story.storyLink.toLowerCase()
.replace(/\s+/g, ' ')
.replace(/\s/g, '-');
if (dashedNameFull !== dashedName) {
return res.redirect('../stories/' + dashedNameFull);
}
var userVoted = false;
try {
var votedObj = story.upVotes.filter(function(a) {
return a['upVotedByUsername'] === req.user['profile']['username'];
});
if (votedObj.length > 0) {
userVoted = true;
}
} catch(e) {
userVoted = false;
}
res.render('stories/index', {
title: story.headline,
link: story.link,
originalStoryLink: dashedName,
originalStoryAuthorEmail: story.author.email || '',
author: story.author,
description: story.description,
rank: story.upVotes.length,
upVotes: story.upVotes,
comments: story.comments,
id: story.id,
timeAgo: moment(story.timePosted).fromNow(),
image: story.image,
page: 'show',
storyMetaDescription: story.metaDescription,
hasUserVoted: userVoted
});
});
}
function getStories(req, res, next) {
MongoClient.connect(secrets.db, function(err, database) {
if (err) {
return next(err);
}
database.collection('stories').find({
'$text': {
'$search': req.body.data ? req.body.data.searchValue : ''
}
}, {
headline: 1,
timePosted: 1,
link: 1,
description: 1,
rank: 1,
upVotes: 1,
author: 1,
comments: 1,
image: 1,
storyLink: 1,
metaDescription: 1,
textScore: {
$meta: 'textScore'
}
}, {
sort: {
textScore: {
$meta: 'textScore'
}
}
}).toArray(function(err, items) {
if (err) {
return next(err);
}
if (items !== null && items.length !== 0) {
return res.json(items);
}
return res.sendStatus(404);
});
});
}
function upvote(req, res, next) {
var data = req.body.data;
Story.find({'id': data.id}, function(err, story) {
if (err) {
return next(err);
}
story = story.pop();
story.rank++;
story.upVotes.push(
{
upVotedBy: req.user.id,
upVotedByUsername: req.user.username
}
);
story.markModified('rank');
story.save();
// NOTE(Berks): This logic is full of wholes and race conditions
// this could be the source of many 'can't set headers after
// they are sent'
// errors. This needs cleaning
User.findOne(
{ where: { id: story.author.userId } },
function(err, user) {
if (err) { return next(err); }
user.progressTimestamps.push(Date.now() || 0);
user.save(function (err) {
req.user.save(function (err) {
if (err) { return next(err); }
});
req.user.progressTimestamps.push(Date.now() || 0);
if (err) {
return next(err);
}
});
}
);
return res.send(story);
});
}
function comments(req, res, next) {
var data = req.params.id;
Comment.find(
{ where: {'id': data } },
function(err, comment) {
if (err) {
return next(err);
}
comment = comment.pop();
return res.send(comment);
});
}
function newStory(req, res, next) {
if (!req.user) {
return next(new Error('Must be logged in'));
}
var url = req.body.data.url;
var cleanURL = sanitizeHtml(url, {
allowedTags: [],
allowedAttributes: []
}).replace(/"/g, '"');
if (cleanURL !== url) {
req.flash('errors', {
msg: "The URL you submitted doesn't appear valid"
});
return res.json({
alreadyPosted: true,
storyURL: '/stories/submit'
});
}
if (url.search(/^https?:\/\//g) === -1) {
url = 'http://' + url;
}
Story.find(
{ where: {'link': url} },
function(err, story) {
if (err) {
return next(err);
}
if (story.length) {
req.flash('errors', {
msg: "Someone's already posted that link. Here's the discussion."
});
return res.json({
alreadyPosted: true,
storyURL: '/stories/' + story.pop().storyLink
});
}
utils.getURLTitle(url, processResponse);
}
);
function processResponse(err, story) {
if (err) {
res.json({
alreadyPosted: false,
storyURL: url,
storyTitle: '',
storyImage: '',
storyMetaDescription: ''
});
} else {
res.json({
alreadyPosted: false,
storyURL: url,
storyTitle: story.title,
storyImage: story.image,
storyMetaDescription: story.description
});
}
}
}
function storySubmission(req, res, next) {
var data = req.body.data;
if (!req.user) {
return next(new Error('Not authorized'));
}
var storyLink = data.headline
.replace(/[^a-z0-9\s]/gi, '')
.replace(/\s+/g, ' ')
.toLowerCase()
.trim();
var link = data.link;
if (link.search(/^https?:\/\//g) === -1) {
link = 'http://' + link;
}
Story.count({
storyLink: { like: new RegExp('^' + storyLink + '(?: [0-9]+)?$', 'i') }
}, function (err, storyCount) {
if (err) {
return next(err);
}
// if duplicate storyLink add unique number
storyLink = (storyCount === 0) ? storyLink : storyLink + ' ' + storyCount;
var link = data.link;
if (link.search(/^https?:\/\//g) === -1) {
link = 'http://' + link;
}
var story = new Story({
headline: sanitizeHtml(data.headline, {
allowedTags: [],
allowedAttributes: []
}).replace(/"/g, '"'),
timePosted: Date.now(),
link: link,
description: sanitizeHtml(data.description, {
allowedTags: [],
allowedAttributes: []
}).replace(/"/g, '"'),
rank: 1,
upVotes: [({
upVotedBy: req.user.id,
upVotedByUsername: req.user.username
})],
author: {
picture: req.user.picture,
userId: req.user.id,
username: req.user.username,
email: req.user.email
},
comments: [],
image: data.image,
storyLink: storyLink,
metaDescription: data.storyMetaDescription,
originalStoryAuthorEmail: req.user.email
});
story.save(function (err) {
if (err) {
return next(err);
}
req.user.progressTimestamps.push(Date.now() || 0);
req.user.save(function (err) {
if (err) {
return next(err);
}
res.send(JSON.stringify({
storyLink: story.storyLink.replace(/\s+/g, '-').toLowerCase()
}));
});
});
});
}
function commentSubmit(req, res, next) {
var data = req.body.data;
if (!req.user) {
return next(new Error('Not authorized'));
}
var sanitizedBody = sanitizeHtml(data.body,
{
allowedTags: [],
allowedAttributes: []
}).replace(/"/g, '"');
if (data.body !== sanitizedBody) {
req.flash('errors', {
msg: 'HTML is not allowed'
});
return res.send(true);
}
var comment = new Comment({
associatedPost: data.associatedPost,
originalStoryLink: data.originalStoryLink,
originalStoryAuthorEmail: data.originalStoryAuthorEmail,
body: sanitizedBody,
rank: 0,
upvotes: 0,
author: {
picture: req.user.picture,
userId: req.user.id,
username: req.user.username,
email: req.user.email
},
comments: [],
topLevel: true,
commentOn: Date.now()
});
commentSave(comment, Story, res, next);
}
function commentOnCommentSubmit(req, res, next) {
var data = req.body.data;
if (!req.user) {
return next(new Error('Not authorized'));
}
var sanitizedBody = sanitizeHtml(
data.body,
{
allowedTags: [],
allowedAttributes: []
}
).replace(/"/g, '"');
if (data.body !== sanitizedBody) {
req.flash('errors', {
msg: 'HTML is not allowed'
});
return res.send(true);
}
var comment = new Comment({
associatedPost: data.associatedPost,
body: sanitizedBody,
rank: 0,
upvotes: 0,
originalStoryLink: data.originalStoryLink,
originalStoryAuthorEmail: data.originalStoryAuthorEmail,
author: {
picture: req.user.picture,
userId: req.user.id,
username: req.user.username,
email: req.user.email
},
comments: [],
topLevel: false,
commentOn: Date.now()
});
commentSave(comment, Comment, res, next);
}
function commentEdit(req, res, next) {
Comment.find({ id: req.params.id }, function(err, cmt) {
if (err) {
return next(err);
}
cmt = cmt.pop();
if (!req.user && cmt.author.userId !== req.user.id) {
return next(new Error('Not authorized'));
}
var sanitizedBody = sanitizeHtml(req.body.body, {
allowedTags: [],
allowedAttributes: []
}).replace(/"/g, '"');
if (req.body.body !== sanitizedBody) {
req.flash('errors', {
msg: 'HTML is not allowed'
});
return res.send(true);
}
cmt.body = sanitizedBody;
cmt.commentOn = Date.now();
cmt.save(function(err) {
if (err) {
return next(err);
}
res.send(true);
});
});
}
function commentSave(comment, Context, res, next) {
comment.save(function(err, data) {
if (err) {
return next(err);
}
try {
// Based on the context retrieve the parent
// object of the comment (Story/Comment)
Context.find({
id: data.associatedPost
}, function (err, associatedContext) {
if (err) {
return next(err);
}
associatedContext = associatedContext.pop();
if (associatedContext) {
associatedContext.comments.push(data.id);
associatedContext.save(function (err) {
if (err) {
return next(err);
}
res.send(true);
});
}
// Find the author of the parent object
User.findOne({
'profile.username': associatedContext.author.username
}, function(err, recipient) {
if (err) {
return next(err);
}
// If the emails of both authors differ,
// only then proceed with email notification
if (
typeof data.author !== 'undefined' &&
data.author.email &&
typeof recipient !== 'undefined' &&
recipient.email &&
(data.author.email !== recipient.email)
) {
var transporter = nodemailer.createTransport({
service: 'Mandrill',
auth: {
user: secrets.mandrill.user,
pass: secrets.mandrill.password
}
});
var mailOptions = {
to: recipient.email,
from: 'Team@freecodecamp.com',
subject: data.author.username +
' replied to your post on Camper News',
text: [
'Just a quick heads-up: ',
data.author.username + ' replied to you on Camper News.',
'You can keep this conversation going.',
'Just head back to the discussion here: ',
'http://freecodecamp.com/stories/' + data.originalStoryLink,
'- the Free Code Camp Volunteer Team'
].join('\n')
};
transporter.sendMail(mailOptions, function (err) {
if (err) {
return err;
}
});
}
});
});
} catch (e) {
return next(err);
}
});
}
};
|