-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
744 lines (693 loc) · 20.7 KB
/
server.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
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const credentials = require(__dirname + '/config/credentials.json');
const https = require('https');
const session = require('express-session');
const mongoUtilities = require('./mongo/mongoServer.js');
const fs = require('fs');
const fileUpload = require('express-fileupload');
app.use(session({
secret: 'keyboard cat',
cookie: { maxAge: 365 * 24 * 60 * 60 * 1000 },
resave: true}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/', express.static(__dirname + '/static'));
app.use('/', (req, res, next) => {
if(!req.session.username && req.path !== '/loginUser' && req.path !== '/login' && req.path !== '/redirect') {
console.log('new user redirect');
res.redirect('/loginUser');
} else {
next();
}
});
app.get('/', (req, res) => {
if(req.session.username) {
console.log('existing user redirect');
res.redirect('/dashboard');
} else {
console.log('new user redirect');
res.redirect('/loginUser');
}
});
app.get('/tag', (req, res) => {
res.sendFile(__dirname + '/static/templates/d_tag.html');
});
app.get('/testGenerate', (req, res) => {
res.sendFile(__dirname + '/static/templates/d_testGenerator.html');
});
app.get('/markedQuestions', (req, res) => {
const username = req.session.username;
mongoUtilities.UserTaggingStatus.extractQuestions({ "username": username })
.then(data => {
res.send(data.questionsList);
})
.catch(err => {
console.log(err);
});
});
app.get('/taggedQuestions', (req, res) => {
res.sendFile(__dirname + '/static/templates/d_taggedDisplay.html');
});
app.get('/fetchMasterTable', (req, res) => {
});
app.get('/analyseTopics', (req, res) => {
res.sendFile(__dirname + '/static/templates/d_analyseTopics.html');
});
app.post('/searchTag', async (req, res) => {
const tagName = req.body.tagName;
const username = req.session.username;
try {
const list = await mongoUtilities.UserTaggingStatus.extractQuestions({ "username": username });
let problemCodes = [];
JSON.parse(list.questionsList).forEach(problem => {
if(problem.tagged) {
let found = false;
for(let tag of problem.tags) {
if(tag === tagName) {
found = true;
break;
}
}
if(found)
problemCodes.push(problem.problemcode);
}
});
res.send(problemCodes);
} catch(err) {
console.log(err);
}
});
app.post('/problemDescription', async (req, res) => {
const { problemCode, contestCode } = req.body;
const username = req.session.username;
try {
const tempResults = await mongoUtilities.Users.findUser({ "username": username});
const option = {
"host": "api.codechef.com",
"path": `/contests/${contestCode}/problems/${problemCode}?fields=`,
"method": "GET",
"headers": {
"content-Type": "application/json",
"Authorization": `Bearer ${tempResults.access_token}`
}
};
const request = https.request(option, (response) => {
let data = "";
response.on('data', chunk => {
data += chunk;
});
response.on('end', async () => {
// fs.writeFileSync('temp.json', JSON.stringify(JSON.parse(data), null, '\t'));
try {
await JSON.parse(data).result.data.content;
res.send(data);
} catch(err) {
console.log('120 session expired', err);
delete req.session.username;
res.send('session expired');
}
});
});
request.end();
} catch(err) {
console.log('128 session expired', err);
delete req.session.username;
res.send('session expired');
}
});
app.post('/problemDetails', async (req, res) => {
const problemcode = req.body.problemcode;
const username = req.session.username;
try {
const tempResults = await mongoUtilities.Users.findUser({ "username": username});
const option = {
"host": "api.codechef.com",
"path": `/submissions/?result=&year=&username=${username}&language=&problemCode=${problemcode}&contestCode=&fields=`,
"method": "GET",
"headers": {
"content-Type": "application/json",
"Authorization": `Bearer ${tempResults.access_token}`
}
}
const request = https.request(option, (response) => {
let data = "";
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', async () => {
try {
await JSON.parse(data).result.data.content;
res.send(data);
} catch(err) {
console.log('153 session expired', err);
delete req.session.username;
res.send('session expired');
}
});
});
request.end();
} catch(err) {
console.log('161 session expired', err);
delete req.session.username;
res.send('session expired');
}
});
app.post('/markQuestion', (req, res) => {
const tags = req.body.tags;
markQuestionBackend(req.session.username, tags, req.body.problemcode);
res.send('marked questions in the backend');
});
app.post('/unmarkQuestion', (req, res) => {
const problemcode = req.body.problemCode;
const username = req.session.username;
mongoUtilities.UserTaggingStatus.extractQuestions({ "username": username })
.then(data => {
let found = false;
let questionsList = JSON.parse(data.questionsList);
let newQuestionsList = [];
for(let question of questionsList) {
if(question.problemcode === problemcode) {
question.tagged = false;
delete question.tags;
found = true;
}
newQuestionsList.push(question);
}
if(found) {
mongoUtilities.UserTaggingStatus.updateQuestions({
"username": username
}, {
$set: {
"questionsList": JSON.stringify(newQuestionsList)
}
})
.then((data) => {
console.log('question unmarked successfully');
res.send('success');
})
.catch((err) => {
console.log(err);
res.send(err);
});
}
})
.catch((err) => {
console.log(err);
res.send(err);
});
});
app.get('/fetchUserQuestionsTable', (req, res) => {
const username = req.session.username;
mongoUtilities.UserTaggingStatus.extractQuestions({ "username": username })
.then((data) => {
res.send(JSON.stringify(data.questionsList));
})
.catch((err) => {
console.log(err);
});
});
app.get('/updateUserQuestionsTable', async (req, res) => {
const username = req.session.username;
try {
const tempResults = await mongoUtilities.Users.findUser({ "username": username});
const options = {
"host": "api.codechef.com",
"path": `/users/${username}`,
"method": "GET",
"headers": {
"content-Type": "application/json",
"Authorization": `Bearer ${tempResults.access_token}`
}
}
const request = https.request(options, response => {
let data = '';
response.on('data', chunk => {
data += chunk;
});
response.on('end', async () => {
data = JSON.parse(data);
try {
const list = await extractListOfQuestions(data.result.data.content.problemStats);
readUserQuestionListFromDatabase(list, username);
res.send('updation done');
} catch(err) {
console.log('243 session expired', err);
delete req.session.username;
res.send('session expired');
}
});
})
request.end();
} catch(err) {
console.log('254 session expired', err);
delete req.session.username;
res.send('session expired');
};
});
app.get('/dashboard', (req, res) => {
res.sendFile(__dirname + '/static/templates/d_dashboard.html');
});
app.get('/loginUser', (req, res) => {
res.sendFile(__dirname + '/static/templates/login_index.html');
});
app.get('/logout', (req, res) => {
delete req.session.username;
res.redirect('/loginUser');
});
app.get('/userDetails', (req, res) => {
mongoUtilities.Users.findUser({ username: req.session.username })
.then((data) => {
res.send(data);
})
.catch((err) => {
res.send(err);
});
});
app.get('/login', (req,res) => {
res.redirect(`https://api.codechef.com/oauth/authorize?response_type=code&client_id=${credentials['Client ID']}&state=xyz&redirect_uri=${credentials.redirectURL}`);
});
app.get('/redirect', (req, res) => {
const options = {
'method': 'POST',
'host': 'api.codechef.com',
'path': '/oauth/token',
'headers': {
'content-Type': 'application/json'
}
};
const post_body = {
"grant_type": "authorization_code",
"code": req.query.code,
"client_id": credentials['Client ID'],
"client_secret": credentials['Client Secret'],
"redirect_uri": credentials.redirectURL
};
const request = https.request(options, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', async () => {
data = JSON.parse(data);
try {
const userDetails = await getUserName(data.result.data.access_token);
mongoUtilities.Users.findUser({ username: userDetails.username })
.then((result) => {
if(result) {
mongoUtilities.Users.updateUser({
'username': userDetails.username,
}, {
$set: {
'access_token': data.result.data.access_token,
'refresh_token': data.result.data.refresh_token }
})
.then((msg) => {
console.log(msg);
})
.catch((err) => {
console.error(err);
});
} else {
mongoUtilities.Users.storeUser({
'access_token': data.result.data.access_token,
'username': userDetails.username,
'fullname': userDetails.fullname,
'refresh_token': data.result.data.refresh_token
})
.then((msg) => {
console.log(msg);
})
.catch((err) => {
console.error(err);
});
}
})
.catch(err => {
console.error(err);
});
req.session.username = userDetails.username;
res.redirect('/dashboard');
} catch(err) {
console.log('349 session expired', err);
delete req.session.username;
res.send('session expired');
}
})
});
request.write(JSON.stringify(post_body));
request.end();
});
app.get('/fetchAllLinksOfSubmittedProblems', async (req, res) => {
const username = req.session.username;
try {
const result = await mongoUtilities.ProblemLinks.extractLinks({ "username": username });
if(!result) {
res.send(JSON.stringify([]));
} else {
res.send(result.listOfLinks);
}
} catch(err) {
console.log(err);
}
});
app.get('/checkStatus', (req, res) => {
res.sendFile(__dirname + '/static/templates/d_statusDisplay.html');
});
app.post('/deleteLinkOfProblem', async (req, res) => {
const username = req.session.username;
const problemName = req.body.problemName;
try {
const result = await mongoUtilities.ProblemLinks.extractLinks({ "username": username });
const linksList = JSON.parse(result.listOfLinks);
let newLinksList = [];
linksList.forEach(elem => {
if(elem.problemName !== problemName) {
newLinksList.push(elem);
}
});
await mongoUtilities.ProblemLinks.updateLinks({
"username": username
},{
$set: {
"listOfLinks": JSON.stringify(newLinksList)
}
});
res.send('deletion of problem name done');
} catch(err) {
console.log(err);
}
});
app.post('/statusOfProblem', async (req, res) => {
const username = req.session.username;
try {
const temp_results = await mongoUtilities.Users.findUser({ "username": username });
const options = {
'method': 'GET',
'host': 'api.codechef.com',
'path': `/ide/status?link=${req.body.link}`,
'headers': {
'content-Type': 'application/json',
'Authorization': `Bearer ${temp_results.access_token}`
}
};
const request = https.request(options, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', async () => {
try {
await JSON.parse(data).result.data.langName;
res.send(data);
} catch(err) {
console.log('441 session expired', err);
delete req.session.username;
res.send('session expired');
}
});
});
request.end();
} catch(err) {
console.log('430 session expired', err);
delete req.session.username;
res.send('session expired');
}
});
app.use(fileUpload());
app.post('/codeUpload', async (req, res) => {
if (!req.files)
return res.status(400).send('No files were uploaded.');
const code = req.files.code;
const submitCode = code.data.toString();
const inputTestCases = req.body.testCases;
const languageOfSubmission = req.body.languageChosen;
const username = req.session.username;
try {
const tempResults = await mongoUtilities.Users.findUser({ "username": username});
const problemName = req.body.problemName;
const options = {
'method': 'POST',
'host': 'api.codechef.com',
'path': '/ide/run',
'headers': {
'content-Type': 'application/json',
'Authorization': `Bearer ${tempResults.access_token}`
}
};
const postBody = {
"sourceCode": submitCode,
"language": languageOfSubmission,
"input": inputTestCases
};
const request = https.request(options, (response) => {
let data = "";
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', async () => {
// console.log(username, data, problemName);
try {
await updateLinks(username, data, problemName);
res.redirect('/testGenerate');
} catch(err) {
console.log('489 session expired', err);
delete req.session.username;
res.redirect('/');
}
});
});
request.write(JSON.stringify(postBody));
request.end();
} catch(err) {
console.log('485 session expired', err);
delete req.session.username;
res.redirect('/login');
}
});
app.listen(5000, credentials.private_ip, () => {
console.log("your server has started and the website can be viewed at http://shmdeveloper.com");
});
//functions :)
const updateLinks = async (username, data, problemName) => {
const link = await JSON.parse(data).result.data.link;
try {
const result = await mongoUtilities.ProblemLinks.extractLinks({ "username": username });
if(!result) {
let linksList = [];
linksList.push({
"problemName": problemName,
"problemLink": link
});
mongoUtilities.ProblemLinks.insertLinks({
"username": username,
"listOfLinks": JSON.stringify(linksList)
});
} else {
let linksList = JSON.parse(result.listOfLinks);
linksList.push({
"problemName": problemName,
"problemLink": link
});
mongoUtilities.ProblemLinks.updateLinks({
"username": username
}, {
$set: {
"listOfLinks": JSON.stringify(linksList)
}
});
}
} catch(err) {
console.log(err);
}
};
const markQuestionBackend = (username, tags, problemcode) => {
mongoUtilities.UserTaggingStatus.extractQuestions({ "username": username })
.then(data => {
let found = false;
let questionsList = JSON.parse(data.questionsList);
for(let question of questionsList) {
if(question.problemcode === problemcode) {
question.tagged = true;
question.tags = tags;
found = true;
break;
}
}
if(found) {
mongoUtilities.UserTaggingStatus.updateQuestions({
"username": username
}, {
$set: {
"questionsList": JSON.stringify(questionsList)
}
})
.then((data) => {
console.log('question marked successfully');
})
.catch((err) => {
console.log(err);
});
}
})
.catch((err) => {
console.log(err);
});
};
const getUserName = (access_token) => {
return new Promise((resolve, reject) => {
const options = {
'method': 'GET',
'host': 'api.codechef.com',
'path': '/users/me',
'headers': {
'content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
};
const request = https.request(options, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
data = JSON.parse(data);
resolve({
username: data.result.data.content.username,
fullname: data.result.data.content.fullname
});
});
});
request.end();
});
};
const extractListOfQuestions = (problemStats) => {
return new Promise((res, rej) => {
let list = [];
Object.keys(problemStats).forEach(stat => {
Object.keys(problemStats[`${stat}`]).forEach(substat => {
problemStats[`${stat}`][`${substat}`].forEach(problemcode => {
list.push({
"problemcode": problemcode,
"status": stat,
"category": substat
});
})
});
});
console.log('user request for list fetch');
const uniqueList = new Set(list);
list = Array.from(uniqueList.values());
list.sort((a, b) => {
return a.problemcode.localeCompare(b.problemcode);
});
let reduceList = [];
let lastElem = list[0];
for(let i=1; i<list.length; i++) {
if(lastElem.problemcode === list[i].problemcode) {
if(list[i].status === 'solved')
lastElem = list[i];
} else {
reduceList.push(lastElem);
lastElem = list[i];
}
}
res(reduceList);
});
};
//function to regenerateAccessToken
const regenerateAccessToken = (refresh_token, username) => {
const options = {
'method': 'POST',
'host': 'api.codechef.com',
'path': '/oauth/token',
'headers': {
'content-Type': 'application/json'
}
};
const post_body = {
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": credentials['Client ID'],
"client_secret": credentials['Client Secret'],
};
const request = https.request(options, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', async () => {
data = JSON.parse(data);
mongoUtilities.Users.updateUser({
'username': username,
}, {
$set: {
'access_token': data.result.data.access_token,
'refresh_token': data.result.data.refresh_token }
})
.then((msg) => {
console.log(msg);
})
.catch((err) => {
console.error(err);
});
})
});
request.write(JSON.stringify(post_body));
request.end();
}
const updateBackendWithOnline = (backendList, onlineList) => {
return new Promise((res, rej) => {
onlineList.forEach(onlineData => {
onlineData.tagged = false;
let found = false;
backendList.forEach(backendData => {
if(!found && onlineData.problemcode === backendData.problemcode) {
found = true;
}
});
if(!found) {
backendList.push(onlineData);
}
});
res(backendList);
});
}
const readUserQuestionListFromDatabase = (onlineList, username) => {
mongoUtilities.UserTaggingStatus.extractQuestions({ "username": username })
.then(async (data) => {
if(!data) {
onlineList.forEach(elem => {
elem.tagged = false;
});
mongoUtilities.UserTaggingStatus.insertQuestions({
"username": username,
"questionsList": JSON.stringify(onlineList)
});
} else {
backendList = JSON.parse(data.questionsList);
try {
backendList = await updateBackendWithOnline(backendList, onlineList);
mongoUtilities.UserTaggingStatus.updateQuestions({
"username": username
},{
$set: {
"questionsList": JSON.stringify(backendList)
}
})
.then((data) => {
console.log("Backend updated with Online List");
})
.catch((msg) => {
console.log(msg);
});
} catch(e) {
console.log("error occurred while updating the backend list with the online list");
}
}
})
.catch((err) => {
console.log(err);
})
}