-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreads.js
351 lines (319 loc) · 12.7 KB
/
threads.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
const express = require('express');
const mongoose = require('mongoose');
var request = require('request');
const router = express.Router();
const ObjectId = mongoose.Schema.Types.ObjectId;
const {ensureAuthenticated} = require('../helper/auth');
const { fetch_links, fetch_title, remove_fetched } = require('../helper/utils');
// Load Thread Model
require('../models/Thread');
const Thread = mongoose.model('threads');
// Load Post Model
require('../models/Post');
const Post = mongoose.model('posts');
// Load Recommendation Model
require('../models/Recommendation');
const Recommendation = mongoose.model('recommendations');
//var post_link = 'http://micro.blog/posts/conversation?id=351177';
//var post_link = 'http://micro.blog/posts/conversation?id=353195';
// Fetch Route
router.get('/', (req, res) => {
Thread.find()
.sort({date: 'desc'})
.then(threads => {
res.render('threads/index', {
threads: threads
});
})
});
// Fetch Route
router.get('/discover', (req, res) => {
Thread.find({discover:true})
.sort({date: 'desc'})
.then(threads => {
res.render('threads/index', {
threads: threads
});
})
});
///thread/:{{id}}
router.get('/:id/recommendations', (req, res) => {
try {
Thread.findById(req.params.id)
.then(thread => {
var now_2hrs = new Date;
now_2hrs.setMinutes(now_2hrs.getMinutes()-120);
if(thread.discover == true && thread.date < now_2hrs){
console.log("Thread " + thread.title + " refreshed.")
res.redirect('/micro/threads/refresh/' + thread.id);
} else {
Recommendation.find({thread_id: req.params.id})
.sort({_id : 'desc'})
.exec((err, recs) => {
res.render('threads/recommendations', {
recs: recs
});
});
}
})
} catch (error) {
console.error(error);
req.flash('error_msg', 'Failed to fetch discover threads');
res.redirect('/micro/threads/');
}
});
///thread/:{{id}}
router.get('/:title/recommendations', (req, res) => {
Thread.find({title : req.params.title})
.then(thread => {
Recommendation.find({thread_id: req.params.id})
.sort({_id : 'desc'})
.exec((err, recs) => {
res.render('threads/recommendations', {
recs: recs
});
});
})
});
//Edit Threads Form for refresh
router.get('/edit', ensureAuthenticated, (req, res) => {
Thread.find()
.sort({date: 'desc'})
.then(threads => {
res.render('threads/edit', {
threads: threads
});
})
});
const purge_posts = function(thread_id){
var date = new Date();
var daysToDeletion = 15;
var deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));
return new Promise((resolve, reject) => {
try {
Post.deleteMany({thread_id:thread_id, date : {$lt : deletionDate}}, function(err){
if(err) reject(err);
else {
resolve("success");
}
});
} catch (error) {
reject(error);
}
});
}
const purge_recommendations = function(thread_id){
var date = new Date();
var daysToDeletion = 15;
var deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));
return new Promise((resolve, reject) => {
try {
Recommendation.deleteMany({thread_id:thread_id, date : {$lt : deletionDate}}, function(err){
if(err) reject(err);
else {
resolve("success");
}
});
} catch (error) {
reject(error);
}
});
}
const refresh_thread_date = function(thread_id){
return new Promise((resolve, reject) => {
try {
Thread.findById(thread_id)
.then(thread => {
thread.date = Date.now();
thread.save()
.then(thread => {
resolve("success");
});
});
} catch (error) {
reject(error);
}
});
}
//Edit Threads Form for refresh
router.get('/refresh/:id', async (req, res) => {
try {
Thread.findById(req.params.id)
.sort({date: 'desc'})
.then(thread => {
let errors = [];
let post_link = '';
if(thread.discover == true){
if(thread.postId === 'all'){
post_link = 'http://micro.blog/posts/discover';
} else{
post_link = 'http://micro.blog/posts/discover/' + thread.postId;
}
} else{
post_link = 'http://micro.blog/posts/conversation?id=' + thread.postId;
}
request.get({
url: post_link,
headers: {'Authorization': 'Token ' + app_token}
}, function (error, response, body) {
var thread_items = JSON.parse(body);
if(error){
errors.push("Failed to fetch thread " + error);
res.render('/', {
errors: errors
})
} else {
remove_fetched(thread_items.items, async function(items){
if(items.length == 0){
await Promise.all([purge_recommendations(thread.id)
, purge_posts(thread.id), refresh_thread_date(thread.id)]);
console.log("No items to be parsed for recommendations");
req.flash('info_msg', 'No new recommendations posted yet');
res.redirect('/micro/threads/' + thread.id + '/recommendations');
}
fetch_links(items, thread.id, function(recs){
var recommendations = [];
let is_error = false;
recs.forEach((link, linkIndex) => {
fetch_title(link.url, function(output){
var temp_title = '';
if(output.title) temp_title = output.title;
else temp_title = link.title;
const newRecommendation = {
thread_id: thread.id,
title: temp_title,
url: link.url,
context: link.context,
context_url: link.context_url,
author: link.username
}
new Recommendation(newRecommendation)
.save(async function(err, rec){
if(err) {
is_error = true;
}
recommendations.push(rec);
if(recommendations.length == recs.length){
await Promise.all([purge_recommendations(thread.id)
, purge_posts(thread.id), refresh_thread_date(thread.id)]);
console.log("Parsed " + recs.length + " items successfully as recommendations");
if(is_error) req.flash('info_msg', 'Thread Refreshed Successfully, with some failures');
else req.flash('success_msg', 'Thread Refreshed Successfully');
res.redirect('/micro/threads/' + thread.id + '/recommendations');
}
})
});
});
});
});
}
});
})
} catch (error) {
console.error(error);
req.flash('info_msg', 'Thread Refreshed Successfully, with some failures');
res.redirect('/micro/threads/' + thread.id + '/recommendations');
}
});
//Add Threads Form
router.get('/add', ensureAuthenticated, (req, res) => {
res.render('threads/add');
});
//Process Forms
router.post('/', ensureAuthenticated, (req, res) => {
try {
let errors = [];
if(!req.body.title){
errors.push({
text: "Please add a title"
});
}
if(!req.body.details){
errors.push({text: "Please add some details"})
}
if(errors.length > 0){
res.render('threads/add', {
errors: errors,
title: req.body.title,
details: req.body.details,
post_id: req.body.post_id
});
} else {
var isDiscover = false;
var ent_post_id = req.body.post_id;
if(req.body.discover === "on"){
isDiscover = true;
if(!req.body.post_id){
ent_post_id = 'all';
}
}
const newThread = {
title: req.body.title,
details: req.body.details,
postId: ent_post_id,
discover: isDiscover
}
new Thread(newThread)
.save()
.then(thread => {
let errors = [];
let post_link = '';
if(isDiscover == true){
if(!req.body.post_id){
post_link = 'http://micro.blog/posts/discover';
} else{
post_link = 'http://micro.blog/posts/discover/' + req.body.post_id;
}
} else{
post_link = 'http://micro.blog/posts/conversation?id=' + req.body.post_id;
}
console.log(post_link);
request.get({
url: post_link,
headers: {'Authorization': 'Token ' + app_token}
}, function (error, response, body) {
var thread_items = JSON.parse(body);
if(error){
errors.push("Failed to fetch thread " + error);
res.render('/', {
errors: errors
})
} else {
fetch_links(thread_items.items, thread.id, function(recs){
var recommendations = [];
recs.forEach((link, linkIndex) => {
fetch_title(link.url, function(output){
var temp_title = '';
if(output.title) temp_title = output.title;
else temp_title = link.title;
const newRecommendation = {
thread_id: thread.id,
title: temp_title,
url: link.url,
context: link.context,
context_url: link.context_url,
author: link.username
}
new Recommendation(newRecommendation)
.save()
.then(rec => {
recommendations.push(rec);
if(recommendations.length == recs.length){
req.flash('success_msg', 'Thread Added Successfully');
res.redirect('/micro/threads');
}
});
});
});
});
}
});
})
}
} catch (error) {
console.log(error);
req.flash('info_msg', 'Thread Added Successfully, with some failures');
res.redirect('/micro/threads');
}
});
module.exports = router;