-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
512 lines (436 loc) · 17.5 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
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
//*******************************************************************************************************
// SETUP
//*******************************************************************************************************
//Express
var express = require('express');
var app = express();
var util = require('util');
//async
var async = require('async');
//request
var request = require('request');
//mongoose
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/ideological");
//schedule
//used to pull data from API's every 1 hour for start
var every = require('schedule').every;
//Body-parser
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
//Passport
var passport = require('passport');
var LocalStrategy = require('passport-local');
var passportLocalMongoose = require('passport-local-mongoose');
//Models
var Article = require('./models/article');
var User = require('./models/user');
//Method-override
var methodOverride = require('method-override');
app.use(methodOverride('_method'));
app.set('view engine', 'ejs');
app.use(express.static('public'));
//Jimp
var Jimp = require("jimp");
//Unfluff
var extractor = require('unfluff');
//*******************************************************************************************************
// CONFIGURE PASSPORT
//*******************************************************************************************************
app.use(require('express-session')({
secret: "ideological is a great site to weed out fake news",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
//User._____ comes from passportLocalMongoose
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// every('3s').do(function(){
// //find the articles that currently have showcase set to true
// Article.find({"showcase":"True"}, function(err, showcaseArticles) {
// if(err) {
// console.log("Error finding the showcase articles");
// console.log(err);
// } else {
// //check to see if showcaseArticles is not empty -> if so, continue to set new showcase articles. if not, set the showcase of the current articles to false then continue
// if(showcaseArticles.length != 0) {
// showcaseArticles.forEach(function(article){
// var articleId = article._id;
// Article.findByIdAndUpdate(articleId, {showcase: "False"}, function(err, updatedArticle){
// if(err) {
// console.log("Error updating the showcase field on the article with id: " + articleId);
// console.log(err);
// } //else do nothing
// })
// });
// }//ends if
// //now it's time to set random articles shwocase field as True
// Article.count().exec(function(err, count) {
// if(err) {
// console.log("Error finding the count of the articles in the MongoDB");
// console.log(err);
// } else {
// for(var i=0; i<7; i++) {
// //get a random number within the range
// var randomNum = Math.floor(Math.random() * count);
// //find a random article
// Article.findOne().skip(randomNum).exec(function(err, randomArticle){
// if(err) {
// console.log("Error finding random article");
// console.log(err);
// } else {
// //random article is found. set the showcase value to true
// var articleId = randomArticle._id;
// Article.findByIdAndUpdate(articleId, {showcase: "True"}, function(err, updatedRandomArticle){
// if(err) {
// console.log("Error setting the showcase field for the article with id: " + articleId);
// console.log(err);
// } // else do nothing
// })
// }
// })
// }
// }
// })
// }
// })
// });
//Makes sure all routes are able to see currentUser object
//this is done by putting the var currentUser inside of res.locals
//again, this is a middleware, so we need to say next() in order for it to work correctly
//app.use calls this function on every route
app.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
});
//*******************************************************************************************************
// SCHEDULED MONGODB LOAD
//*******************************************************************************************************
// every('5s').do(function(){
// var sourceNames = ['al-jazeera-english','associated-press','bbc-news','bloomberg','breitbart-news','business-insider','cnn','google-news','independent','techcrunch','the-huffington-post','the-verge','the-new-york-times','time','the-wall-street-journal','the-washington-post','daily-mail'];
// var apis = [];
// for (var i = 0; i < sourceNames.length; i++) {
// apis[i] = " https://newsapi.org/v1/articles?source="+sourceNames[i]+"&apiKey=14748e642d924db294e082aad37b715f"
// }
// async.each(apis, function(api, callback){
// request(api, function(error, response, body){
// if(error) {
// console.log(error);
// } else {
// var info = JSON.parse(body);
// var articleSource = info["source"];
// info["articles"].forEach(function(article){
// Article.find({"title": article.title}, function(err, foundArticle){
// if(err) {
// console.log(err);
// }
// if(foundArticle == null) {
// console.log(article.title);
// console.log("found");
// //Don't add he article to the db
// } else {
// //Set up vars to be used to create the article object
// var author = article.author;
// var title = article.title;
// var description = article.description;
// var url = article.url;
// var urlToImage = article.urlToImage;
// //check the source
// if(articleSource == "bbc-news") {
// Jimp.read(urlToImage, function (err, image) {
// });
// }
// var publishedAt = article.publishedAt;
// var source = setSourceImage(articleSource);
// var truthRating = 0;
// var biasRatingArr = [];
// var biasRating = "_";
// var totalFeedback = 0;
// var showcase = "False";
// //Create an article object to be passed to the mongoose create api
// var newArticle = {
// author: author,
// title: title,
// description: description,
// url: url,
// urlToImage: urlToImage,
// publishedAt: publishedAt,
// source: source,
// truthRating: truthRating,
// biasRatingArr: biasRatingArr,
// biasRating: biasRating,
// totalFeedback: totalFeedback,
// showcase: showcase
// }
// //Create the article
// Article.create(newArticle, function(err, createdArticle){
// if(err) {
// console.log(err);
// } else {
// console.log(createdArticle);
// }
// });
// }
// });
// });// ends forEach
// }//ends else no error
// }); //ends request
// }); //ends async call
// });//ends every call
//*******************************************************************************************************
// ROUTES
//*******************************************************************************************************
app.get('/', function(req, res) {
//now find the topArticles
Article.find({showcase: "True"}, function(err, showcaseArticles) {
if(err) {
console.log("Error finding the showcaseArticles for the first load");
console.log(err);
} else {
// var posSet = new Set(showcaseArticles.positives);
// var negSet = new Set(showcaseArticles.negatives);
console.log(showcaseArticles);
Article.find({}).sort({truthRating: 'descending'}).limit(5).exec(function(err, topArticles) {
if(err) {
console.log("Can't find top articles");
console.log(err);
} else {
res.render("pages/index", {allData: showcaseArticles,topArticles: topArticles});
}
})
}
})
});
app.get('/rate/:id', function(req, res){
res.redirect('/');
});
app.put('/rate/:id', isLoggedIn, function(req, res){
//get the id
var articleId = req.params.id;
//get the updatedData
var updatedData = req.body;
//get the review data
var updatedValidity = updatedData.validity;
var updatedBias = updatedData.bias;
var positives = updatedData.positives;
var negatives = updatedData.negatives;
var finalPos;
var finalNegs;
if(util.isArray(positives)) {
finalPos = {$each: positives};
} else {
finalPos = positives;
}
if(util.isArray(negatives)) {
finalNegs = {$each: negatives};
} else {
finalNegs = negatives;
}
Article.findByIdAndUpdate(articleId, {$inc: {totalFeedback: 1, truthRating: updatedValidity}, $push: {biasRatingArr: updatedBias, positives: finalPos, negatives: finalNegs}}, function(err, updatedArticleMetrics){
if(err) {
console.log(err);
} else {
console.log(updatedArticleMetrics);
findArticleAndUpdateBias(articleId);
// var returnableData = {
// totalFeedback: updatedArticleMetrics.totalFeedback;
// truthRating: updatedArticleMetrics.truthRating;
// biasRating: updatedArticleMetrics.biasRating;
// };
// var JSONdata = JSON.stringify(returnableData);
res.redirect('/');
}
});
});
//get the article html body and parse
app.post('/:id/read/', function(req, res){
//get the article id
var articleId = req.params.id;
var articleURL = req.body.articleURL;
var articleTitle = "";
//setup the fetch object
const fetchURL = require('fetch').fetchUrl;
//get the article title and send back to the front end
Article.findById(articleId, function(err, foundArticle) {
if(err) {
console.log("Error finding the article with id: "+articleId);
console.log(err);
} else {
articleTitle = foundArticle.title;
}
})
fetchURL(articleURL, (error, meta, body) => {
if(error) {
return console.log('Error', error.message || error);
}
// console.log('META INFO');
// console.log(meta);
// console.log('BODY');
var bodyData = extractor(body.toString('utf-8'));
// console.log(bodyData.links);
res.send({body:bodyData.text, title: articleTitle, links:bodyData.links});
});
});
//Auth ROUTES
//show login form
app.get('/login', function(req, res){
res.render('pages/login');
});
//Login will submit to this route
//passport middleware is used to manage login logic
//takes strategy, successRedirect, and failureRedirect
//app,post('route', middleware, function)
//the authenticate method will call the authenticate we set up above
app.post('/login',passport.authenticate('local', {successRedirect: '/', failureRedirect: '/login'}) , function(req, res){
});
//show registration form
app.get('/register', function(req, res){
res.render('pages/register');
});
//Sign Up form will submit to this route
app.post('/register', function(req, res){
//provided by passport-local-mongoose
var newUser = new User({username: req.body.username});
var userPass = req.body.password;
//User.register takes 2 params
//1: the username
//2: the password. However, it stores this as a hash instead of the string literal
User.register(newUser, userPass, function(err, user){
if(err){
console.log(err);
//if there is an error, the return pulls out of the code loop and redirects them back to register
return res.render('pages/register');
}
//passport.authenticate logs the user in and redirects them to home
passport.authenticate('local')(req, res, function(){
res.redirect('/');
});
})
});
//logout route
app.get('/logout', function(req, res){
//The logout function comes from passport
req.logout();
res.redirect('/');
});
//*******************************************************************************************************
// FUNCTIONS
//*******************************************************************************************************
//logged in middleware
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect('/login');
}
function setSourceImage(source) {
if(source == "al-jazeera-english"){
return 'https://besticon-demo.herokuapp.com/icon?url=http://www.aljazeera.com&size=70..120..200';
} else if(source == "associated-press") {
return "https://besticon-demo.herokuapp.com/icon?url=https://apnews.com/&size=70..120..200";
} else if(source == "bbc-news") {
return "https://besticon-demo.herokuapp.com/icon?url=http://www.bbc.co.uk/news&size=70..120..200";
} else if(source == "bloomberg") {
return "https://besticon-demo.herokuapp.com/icon?url=http://www.bloomberg.com&size=70..120..200";
} else if(source == "breitbart-news") {
return "https://besticon-demo.herokuapp.com/icon?url=http://www.breitbart.com&size=70..120..200";
} else if(source == "business-insider") {
return "https://besticon-demo.herokuapp.com/icon?url=http://www.businessinsider.com&size=70..120..200";
} else if(source == "cnn") {
return "https://besticon-demo.herokuapp.com/icon?url=http://us.cnn.com&size=70..120..200";
} else if(source == "google-news") {
return "https://besticon-demo.herokuapp.com/icon?url=https://news.google.com&size=70..120..200";
} else if(source == "independent") {
return "https://besticon-demo.herokuapp.com/icon?url=http://www.independent.co.uk&size=70..120..200";
} else if(source == "techcrunch") {
return "https://besticon-demo.herokuapp.com/icon?url=https://techcrunch.cn&size=70..120..200";
} else if(source == "the-huffington-post") {
return "https://besticon-demo.herokuapp.com/icon?url=http://www.huffingtonpost.com&size=70..120..200";
} else if(source == "the-verge") {
return "https://besticon-demo.herokuapp.com/icon?url=http://www.theverge.com&size=70..120..200";
} else if(source == "the-new-york-times") {
return "https://besticon-demo.herokuapp.com/icon?url=http://www.nytimes.com&size=70..120..200";
} else if(source == "time") {
return "https://besticon-demo.herokuapp.com/icon?url=http://time.com&size=70..120..200";
} else if(source == "the-wall-street-journal"){
return "https://besticon-demo.herokuapp.com/icon?url=http://www.wsj.com&size=70..120..200";
}
}
function findArticleAndUpdateBias(articleId) {
Article.findById(articleId, function(err, foundArticle){
if(err) {
console.log(err);
} else{
setBiasMode(foundArticle);
}
});
}
function setBiasMode(foundArticle) {
if(foundArticle['biasRatingArr'].length != 0) {
var freq = [0,0,0];
for (var i = 0; i < foundArticle.biasRatingArr.length; i++) {
if(foundArticle.biasRatingArr[i] == 0) {
freq[0]++;
} else if(foundArticle.biasRatingArr[i] == 1){
freq[1]++;
} else if(foundArticle.biasRatingArr[i] == 2){
freq[2]++;
}
}
var mode = 0;
for (var i = 0; i < freq.length; i++) {
if(freq[i] > freq[mode]){
mode = i;
}
}
} else {
mode = null;
if(mode == null) {
Article.findByIdAndUpdate(foundArticle._id, {biasRating: "__"}, function(err, updatedArticleWithDefaultBias){
if(err) {
console.log(err);
} else {
console.log("Default");
console.log(updatedArticleWithDefaultBias);
}
});
}
}
if(mode == 0) {
Article.findByIdAndUpdate(foundArticle._id, {biasRating: "None/NA"}, function(err, updatedArticleWithNoBias){
if(err) {
console.log(err);
} else {
console.log("Default");
console.log(updatedArticleWithNoBias);
}
});
} else if(mode == 1) {
Article.findByIdAndUpdate(foundArticle._id, {biasRating: "Liberal"}, function(err, updatedArticleWithLibBias){
if(err) {
console.log(err);
} else {
console.log("Lib");
console.log(updatedArticleWithLibBias);
}
});
} else if(mode == 2){
Article.findByIdAndUpdate(foundArticle._id, {biasRating: "Conservative"}, function(err, updatedArticleWithConsBias){
if(err) {
console.log(err);
}else {
console.log("Cons");
console.log(updatedArticleWithConsBias);
}
});
}
}//ends function
//*******************************************************************************************************
// SERVER
//*******************************************************************************************************
app.listen(3030, function(){
console.log("News Server Is Running!");
});