-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
443 lines (374 loc) · 14 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
const { json } = require("body-parser");
const express = require("express"),
app = express(),
mongoose = require("mongoose"),
Hash = require("./hash"),
Link = require("./models/link"),
bodyParser = require("body-parser"),
request = require("request"),
regression = require('regression'),
dotenv = require("dotenv");
/**
* Hash Class Invocation
*/
const hash = new Hash(10000019, 1000);
hash.setPrimeString(31);
dotenv.config();
app.use(bodyParser.urlencoded({extended: true}));
var redirectToHTTPS = require('express-http-to-https').redirectToHTTPS; //makes all request secure
app.use(redirectToHTTPS([/localhost:(\d{4})/], [/\/insecure/], 301));
var MemoryStore = require("memorystore")(require('express-session'));
app.use(require("express-session")({
secret : process.env.expressSECRET,
store: new MemoryStore({
checkPeriod: 86400000 // prune expires entries every 24h
}),
resave : false,
saveUninitialized : false
}));
/**
* CORS Bypass
*/
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
/**
* Mongoose Setup
*/
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
mongoose.Promise = global.Promise;
const URI = `mongodb+srv://${process.env.mongo_username}:${process.env.mongo_password}@cluster0.1j3r7.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
// mongoose.connect("mongodb://"+process.env.mongoDB+"/vote-the-internet",{ useNewUrlParser: true , useUnifiedTopology: true});
const connectionParams={
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
// mongoose.connect(URI, connectionParams);
// mongoose.connection.on('connected', () => console.log('Connected'));
// mongoose.connection.on('error', (err) => console.log('Connection failed with - ',err));
mongoose.connect(URI,connectionParams)
.then( () => {
console.log('Connected to database')
})
.catch( (err) => {
console.error(`Error connecting to the database. \n${err}`);
})
/**
* Constant 10 minute Heroku based request for minimized load times.
* Removes server idling.
*/
setInterval(() => {
request(process.env.url);
console.debug("API loaded again");
}, 9.99*1000*60);
/**
* helper function for creating a new Link Object
* data specified by param.
* @param {Object} data : Check API under models/link
*/
var createLink = (data)=>{
Link.create(data, (err, addedLink)=>{
if(err)
{
if(err.code === 11000)
{
Link.collection.dropIndex("username_1", (err, indexDrop)=>{
if(err)
{
console.error("Failed to drop index duplicate key");
throw new Error(err.message);
}
console.log("index duplicate key drop successful");
createLink(data);
});
}
else
{
throw new Error(err.message);
}
}
console.log("Successfully created new object", addedLink);
});
};
//******************************************************************** UPVOTE *************************************************************************** */
app.post("/upvote", (req, res)=>{
let query = req.query.q;
let hashed_host_query = hash.get_str_hash(query.split("/")[0]);
let hashed_path_query = hash.get_str_hash(query);
Link.findOne({"host.url" : hashed_host_query}).exec((err, foundLink)=>{
if(err)
{
console.error("Error while upvoting");
throw new Error(err.message);
}
try
{
if(!foundLink)
{
//create a new URL obj.
//check first if path name equals host name, db redux.
let pathname_obj = [];
var pathDownvoteCount = 0,
pathUpvoteCount = 1;
if(hashed_host_query != hashed_path_query)
{
pathname_obj = [{
url : hashed_path_query,
upvotes : 1,
downvotes : 0
}];
}
let newLink = {
host: {
url : hashed_host_query,
upvotes : 1,
downvotes : 0
},
pathname : pathname_obj
};
createLink(newLink);
let sendData = {
host : {
url : hashed_host_query,
upvotes : newLink.host.upvotes,
downvotes : newLink.host.downvotes
},
path : {
url : hashed_path_query,
upvotes : pathUpvoteCount,
downvotes : pathDownvoteCount
}
}
return res.send({code : 200, data : sendData});
}
else
{
let isNewPath = true;
var pathUpvoteCount = 1;
var pathDownvoteCount = 0;
foundLink.pathname.forEach(item => {
if(item.url == hashed_path_query)
{
item.upvotes++;
isNewPath = false;
pathUpvoteCount = item.upvotes;
pathDownvoteCount = item.downvotes;
}
});
if(isNewPath)
{
let newPath = {
url : hashed_path_query,
upvotes : 1,
downvotes : 0
}
foundLink.pathname.push(newPath);
}
foundLink.host.upvotes++;
foundLink.save();
let sendData = {
host : {
url : hashed_host_query,
upvotes : foundLink.host.upvotes,
downvotes : foundLink.host.downvotes
},
path : {
url : hashed_path_query,
upvotes : pathUpvoteCount,
downvotes : pathDownvoteCount
}
}
return res.send({code : 200, data : sendData});
}
}
catch(error)
{
console.error("Error while changing upvoting score");
throw new Error(error);
}
});
});
//******************************************************************** DOWNVOTE *************************************************************************** */
app.post("/downvote", (req, res)=>{
let query = req.query.q;
let hashed_host_query = hash.get_str_hash(query.split("/")[0]);
let hashed_path_query = hash.get_str_hash(query);
Link.findOne({"host.url" : hashed_host_query}).exec((err, foundLink)=>{
if(err)
{
console.error("Error while downvoting");
throw new Error(err.message);
}
try
{
if(!foundLink)
{
//create a new URL obj.
//check first if path name equals host name, db redux.
let pathname_obj = [];
var pathDownvoteCount = 1,
pathUpvoteCount = 0;
if(hashed_host_query != hashed_path_query)
{
pathname_obj = [{
url : hashed_path_query,
upvotes : 0,
downvotes : 1
}];
}
let newLink = {
host: {
url : hashed_host_query,
upvotes : 0,
downvotes : 1
},
pathname : pathname_obj
};
createLink(newLink);
let sendData = {
host : {
url : hashed_host_query,
upvotes : newLink.host.upvotes,
downvotes : newLink.host.downvotes
},
path : {
url : hashed_path_query,
upvotes : pathUpvoteCount,
downvotes : pathDownvoteCount
}
}
return res.send({code : 200, data : sendData});
}
else
{
let isNewPath = true;
var pathUpvoteCount = 0;
var pathDownvoteCount = 1;
foundLink.pathname.forEach(item => {
if(item.url == hashed_path_query)
{
item.downvotes++;
isNewPath = false;
pathUpvoteCount = item.upvotes;
pathDownvoteCount = item.downvotes;
}
});
if(isNewPath)
{
let newPath = {
url : hashed_path_query,
upvotes : 0,
downvotes : 1
}
foundLink.pathname.push(newPath);
}
foundLink.host.downvotes++;
foundLink.save();
let sendData = {
host : {
url : hashed_host_query,
upvotes : foundLink.host.upvotes,
downvotes : foundLink.host.downvotes
},
path : {
url : hashed_path_query,
upvotes : pathUpvoteCount,
downvotes : pathDownvoteCount
}
}
return res.send({code : 200, data : sendData});
}
}
catch(error)
{
console.error("Error while changing downvoting score");
throw new Error(error);
}
});
});
//******************************************************************** STATISTICS *************************************************************************** */
app.get("/stats", (req, res)=>{
var query = req.query.q;
let hashed_query = hash.get_str_hash(query.split("/")[0]);
let hashed_path_query = hash.get_str_hash(query);
Link.findOne({"host.url" : hashed_query}, (err, foundLink)=>{
if(err)
{
console.error("Error while viewing results");
throw new Error(err.message);
}
if(foundLink)
{
var pathDownvoteCount = 0,
pathUpvoteCount = 0;
foundLink.pathname.forEach(item=>{
if(item.url == hashed_path_query)
{
pathDownvoteCount = item.downvotes;
pathUpvoteCount = item.upvotes;
}
});
let sendData = {
host : {
url : hashed_query,
upvotes : foundLink.host.upvotes,
downvotes : foundLink.host.downvotes
},
path : {
url : hashed_path_query,
upvotes : pathUpvoteCount,
downvotes : pathDownvoteCount
}
}
return res.send({code : 200, data : sendData});
}
return res.send({code : 198, data : null});
});
});
//******************************************************************** Regression *************************************************************************** */
app.get("/predict", (req, res)=>{
var query = req.query.data;
try {
query = JSON.parse(query);
var data = [];
for (let i = 0; i < query.length; i++) {
data.push([i, query[i]]);
}
const result = regression.linear(data);
const gradient = result.equation[0];
const yIntercept = result.equation[1];
const value = data.length*gradient + yIntercept;
return res.send({code : 200, data : parseFloat(value).toPrecision(3)});
} catch (error) {
return res.send({code : 198, data : 0.0}); //error
}
});
//******************************************************************** TEMP : LeetHub Authentication *************************************************************************** */
app.get("/leethub/authorize", (req, res)=>{
var query = req.query.code;
// pass this to welcome (chrome extension)
return res.send({"code" : 200, "message" : "Authorizing LeetHub with your GitHub profile", "data": query});
});
//******************************************************************** DEFAULT ROUTES *************************************************************************** */
app.get("*", (req, res)=>{
return res.send("Invalid API route");
});
app.post("*", (req, res)=>{
return res.send("Invalid API route");
});
//******************************************************************** LAUNCH SERVER *************************************************************************** */
app.listen(process.env.PORT || 2622, process.env.IP,()=>{
console.log(`Server Connected at port ${process.env.PORT || 2622}`);
});