-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
executable file
·933 lines (827 loc) · 22.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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
var express = require("express");
var bodyParser = require("body-parser");
var { OAuth2Client } = require("google-auth-library");
var io = require("socket.io-client");
var AWS = require("aws-sdk");
const { Client } = require("pg")
AWS.config.update({ region: "us-east-1" });
var dynamodb = new AWS.DynamoDB();
var docClient = new AWS.DynamoDB.DocumentClient();
var app = express();
app.use(bodyParser.urlencoded({ limit: "500mb", extended: true }));
app.use(bodyParser.json({ limit: "500mb" }));
/*Temporary DB structure (feel free to add to prototypes)
user Collection:
{
_id: (primary key on db, same as google id)
socialId: (used for google/fb integration)
classes: [{
_id: (primary key of class in the class table)
name: (name of class)
notifications: (on/off)
}]
testPoints: (number of points for test bank)
}
//Chat could be implemented used Socket.io, which emits events to those who are connected, and stores messages in a database intermittently
class Collection:
{
_id: (primary key in db)
name: (name of class, MongoDB index exists for this field)
schedule: [{
day:
startTime:
endTime:
}]
locations: []
users: [{
_id: (primary key of each user in the class)
}]
chatMessages: (id of class chat)
}
classChat Collection:
{
_id:
chatMessages: {[
time: (time when message was sent)
text: (actual content)
byUser: (_id of user)
]}
}
location Collection:
{
name:
type: (library/study room/special)
mapCoords: (not sure how to implement)
activityLevel: (not sure how to measure)
}
*/
var CLIENT_ID =
"373351297766-5f4knsqmvuu540bl3oh24i6qu2uh4lif.apps.googleusercontent.com";
const oauthClient = new OAuth2Client(CLIENT_ID);
var origin = "https://google.com";
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", origin || "*");
res.header(
"Access-Control-Allow-Methods",
"GET,POST,PUT,HEAD,DELETE,OPTIONS"
);
res.header("Access-Control-Allow-Headers", "content-Type,x-requested-with");
next();
});
app.get("/", function (req, res) {
var query = {
TableName: "user",
Key: {
_id: "mytest"
}
};
docClient.get(query, function (err, data) {
if (err) {
//throw err;
res.send("err");
}
res.send(data);
});
});
//USER SECTION
//Get all user info
app.get("/user/:id", function (req, res) {
//var userId = req.params.id;
var socialId = req.params.socialId;
MongoClient.connect(url, function (err, db) {
if (err)
//throw err;
res.send(err);
console.log("Database connected");
const verifyToken = new Promise(function (resolve, reject) {
client.verifyIdToken(socialId, CLIENT_ID, function (e, login) {
if (login) {
var payload = login.getPayload();
var googleId = payload["sub"];
resolve(googleId);
} else {
reject("invalid token");
}
});
});
verifyToken
.then(function (userId) {
var query = {
TableName: "user",
Key: {
_id: userId
}
};
docClient.get(params, function (err, data) {
if (err)
//throw err;
res.send(err);
d;
});
var dbo = db.db("studysmart");
dbo
.collection("user")
.find(query)
.toArray(function (err, result) {
if (err)
//throw err;
res.send(err);
var resjson = result[0];
if (result.length == 0) {
db.close();
var errjson = {
error: "No user found"
};
res.json(errjson);
}
db.close();
res.error = null;
res.json(resjson);
});
})
.catch(function (err) {
console.log(err);
var resjson = {
error: "Authentication error",
newUser: false,
id: null
};
db.close();
res.json(resjson);
});
});
});
//Use this for sign in
app.post("/user/:id", function (req, res) {
//var userId = req.params.id;
var socialId = req.params.socialId;
const verifyToken = new Promise(function (resolve, reject) {
client.verifyIdToken(socialId, CLIENT_ID, function (e, login) {
if (login) {
var payload = login.getPayload();
var googleId = payload["sub"];
resolve(googleId);
} else {
reject("invalid token");
}
});
});
verifyToken
.then(function (userId) {
var query = { _id: userId };
var dbo = db.db("studysmart");
dbo
.collection("user")
.find(query)
.toArray(function (err, result) {
if (err)
//throw err;
res.send(err);
var resjson = result[0];
if (result.length == 0) {
var newUser = {
_id: userId,
socialId: socialId,
classes: [],
testPoints: 0
};
dbo
.collection("user")
.insertOneAndUpdate(newUser, function (err, result) {
if (err)
//throw err;
res.send(err);
var resjson = {
error: null,
newUser: true,
id: socialId
};
db.close();
res.json(resjson);
});
} else {
var toupdate = { $set: { socialId: socialId } };
dbo
.collection("user")
.findOneAndUpdate(query, toupdate, function (err, result) {
if (err)
//throw err;
res.send(err);
var resjson = {
error: null,
newUser: false,
id: socialId
};
db.close();
res.json(resjson);
});
}
});
})
.catch(function (err) {
console.log(err);
var resjson = {
error: "Authentication error",
newUser: false,
id: null
};
db.close();
res.json(resjson);
});
});
//CLASSES SECTION
//Get all class info, search by name or id
app.get("/class", function (req, res) { });
//Get class chat (or the last few messages). Start socket connection, and allow user to post chats
app.get("/classchat/:id", function (req, res) { });
//Create a new class (and class chat), check if name conflict
app.post("/class", function (req, res) { });
//LOCATIONS SECTION
//Get locations, possibly all or some locations
app.get("/locations", function (req, res) { });
//Get location info
app.get("/location/:id", function (req, res) { });
//Post location info
app.post("/location", function (req, res) { });
//Get libinfo
app.get("/libinfo", function (req, res) {
var query = {
TableName: "lib_info"
};
dynamodb.scan(query, function (err, data) {
if (err) {
throw err;
res.send("err");
}
res.send(JSON.stringify(data));
});
});
app.get("/libinfo/:name", function (req, res) {
var query = {
TableName: "lib_info",
Key: {
name: req.params.name
}
};
docClient.get(query, function (err, data) {
if (err) {
throw err;
res.send("err");
}
res.send(data);
});
});
//Get libinfo
app.get("/busyness_graphs", function (req, res) {
var query = {
TableName: "lib_busyness"
};
dynamodb.scan(query, function (err, data) {
if (err) {
// throw err;
res.send("err");
}
res.send(data);
});
});
//Get libinfo
app.get("/current_busyness", function (req, res) {
var query = {
TableName: "lib_busyness",
ProjectionExpression: "#name, current_busyness",
ExpressionAttributeNames: {
"#name": "name"
}
};
dynamodb.scan(query, function (err, data) {
if (err) {
// throw err;
res.send(err);
}
res.send(data);
});
});
//Post libinfo
app.post("/libinfo", function (req, res) {
var infoArr = req.body;
var arrLength = infoArr.length;
var completed = 0;
infoArr.forEach(info => {
var entry = {
TableName: "lib_info",
Item: {
name: info.name,
location: info.location,
department: info.department
}
};
docClient.put(entry, function (err, data) {
completed++;
if (err) {
//throw err;
res.send(err);
}
if (completed == arrLength) {
res.send("done");
}
});
});
});
//Get libinfo-v2
/*
Expected Output: one big JSON object where each library is a property of the object and is organized as shown below:
"Arts Library": {
"location": "1400 Public Affairs Building, Los Angeles, CA 90095-1392",
"phone": "(310) 206-5425",
"department": {
"Arts Library": [
{
"dp_open_time": "1pm - 5pm",
"date": "Su 13"
},
{
"dp_open_time": "8am - 9pm",
"date": "M 14"
},
{
"dp_open_time": "8am - 9pm",
"date": "Tu 15"
},
{
"dp_open_time": "8am - 9pm",
"date": "W 16"
},
{
"dp_open_time": "8am - 9pm",
"date": "Th 17"
},
{
"dp_open_time": "8am - 5pm",
"date": "F 18"
},
{
"dp_open_time": "1pm - 5pm",
"date": "Sa 19"
}
],
"CLICC Laptop & iPad Lending (Arts Library)": [
{
"dp_open_time": "1pm - 4:30pm",
"date": "Su 13"
},
{
"dp_open_time": "8am - 8:30pm",
"date": "M 14"
},
{
"dp_open_time": "8am - 8:30pm",
"date": "Tu 15"
},
{
"dp_open_time": "8am - 8:30pm",
"date": "W 16"
},
{
"dp_open_time": "8am - 8:30pm",
"date": "Th 17"
},
{
"dp_open_time": "8am - 4:30pm",
"date": "F 18"
},
{
"dp_open_time": "1pm - 4:30pm",
"date": "Sa 19"
}
],
"Reference Desk": [
{
"dp_open_time": "Closed",
"date": "Su 13"
},
{
"dp_open_time": "11am - 4pm",
"date": "M 14"
},
{
"dp_open_time": "11am - 4pm",
"date": "Tu 15"
},
{
"dp_open_time": "11am - 4pm",
"date": "W 16"
},
{
"dp_open_time": "11am - 4pm",
"date": "Th 17"
},
{
"dp_open_time": "11am - 4pm",
"date": "F 18"
},
{
"dp_open_time": "Closed",
"date": "Sa 19"
}
]
}
}
*/
app.get("/v2/num_rooms_free_at/:day/:time", function (req, res) {
var query = {
TableName: "lib_info"
};
const client = new Client({
user: 'studyroot',
host: 'studysmart-db.chpjzhfmtelr.us-west-1.rds.amazonaws.com',
database: 'mydb',
password: 'studysmart-db',
port: '5432'
});
var day = req.params.day;
var time = req.params.time;
client.connect();
client.query("SELECT building, count(*) \
FROM classroom_availabilities\
WHERE start_time<$1 AND end_time>$2 AND day=$3\
GROUP BY building\
ORDER BY building",
[time, time, day], (err1, result1) => {
if (err1) {
console.log(err1.stack);
client.end();
} else {
res.send(result1);
client.end();
}
});
});
app.get("/v2/get_rooms/:building/:day/:time", function (req, res) {
var query = {
TableName: "lib_info"
};
const client = new Client({
user: 'studyroot',
host: 'studysmart-db.chpjzhfmtelr.us-west-1.rds.amazonaws.com',
database: 'mydb',
password: 'studysmart-db',
port: '5432'
});
var day = req.params.day;
var time = req.params.time;
var building = req.params.building;
client.connect();
client.query("SELECT building,room, end_time-$1 as amount_of_time\
FROM classroom_availabilities\
WHERE start_time<$1 AND end_time>$2 AND day=$3 AND building=$4\
ORDER BY amount_of_time DESC",
[time, time, day, building], (err1, result1) => {
if (err1) {
console.log(err1.stack);
client.end();
} else {
res.send(result1);
client.end();
}
});
});
app.get("/v2/get_room_timetable/:building/:room", function (req, res) {
var query = {
TableName: "lib_info"
};
const client = new Client({
user: 'studyroot',
host: 'studysmart-db.chpjzhfmtelr.us-west-1.rds.amazonaws.com',
database: 'mydb',
password: 'studysmart-db',
port: '5432'
});
var building = req.params.building;
var room = req.params.room;
client.connect();
client.query("SELECT * \
FROM classroom_availabilities\
WHERE room=$1 AND building=$2",
[room, building], (err1, result1) => {
if (err1) {
console.log(err1.stack);
client.end();
} else {
res.send(result1);
client.end();
}
});
});
app.get("/v2/libinfo", function (req, res) {
var query = {
TableName: "lib_info"
};
const client = new Client({
user: 'studyroot',
host: 'studysmart-db.chpjzhfmtelr.us-west-1.rds.amazonaws.com',
database: 'mydb',
password: 'studysmart-db',
port: '5432'
});
client.connect();
client.query('select * from libraries', (err1, result1) => {
if (err1) {
console.log(err1.stack);
client.end();
} else {
client.query('select * from library_hours', (err2, result2) => {
if (err2) {
console.log(err2.stack);
client.end();
} else {
var outJson = {};
const libData = result1.rows;
const hrData = result2.rows;
//create field for each library
for (var i = 0; i < libData.length; i++) {
var libName = libData[i].name;
var libLoc = libData[i].location;
var libPhone = libData[i].phone;
outJson[libName] = {};
outJson[libName].location = libLoc;
outJson[libName].phone = libPhone;
outJson[libName].department = {};
//outJson[libName].department = [];
}
for (var i = 0; i < hrData.length; i++) {
var libName = hrData[i].library_name;
var depName = hrData[i].dep_name;
var date = hrData[i].date;
var times = hrData[i].times;
if (!(depName in outJson[libName].department)) {
outJson[libName].department[depName] = [];
}
var temp = { "dp_open_time": times, "date": date };
outJson[libName].department[depName].push(temp);
}
res.send(outJson);
client.end();
}
});
}
});
});
//Get studyinfo
app.get("/studyinfo", function (req, res) {
if (
!req.query.name &&
!req.query.date &&
!req.query.duration &&
!req.query.time
) {
var query = {
TableName: "study_info"
};
dynamodb.scan(query, function (err, data) {
if (err) {
throw err;
res.send("err");
}
res.send(JSON.stringify(data));
});
} else {
var query = {
TableName: "study_info"
};
var keyType = "";
query.ExpressionAttributeValues = {};
query.ExpressionAttributeNames = {};
if (req.query.name) {
query.IndexName = "name-index";
query.KeyConditionExpression = "#nm = :name";
query.ExpressionAttributeNames["#nm"] = "name";
query.ExpressionAttributeValues[":name"] = req.query.name;
keyType = "name";
} else if (req.query.date) {
query.IndexName = "date-index";
query.KeyConditionExpression = "#dt = :date";
query.ExpressionAttributeNames["#dt"] = "date";
query.ExpressionAttributeValues[":date"] = req.query.date;
keyType = "date";
} else if (req.query.duration) {
query.IndexName = "duration-index";
query.KeyConditionExpression = "#dur = :duration";
query.ExpressionAttributeNames["#dur"] = "duration";
query.ExpressionAttributeValues[":duration"] = req.query.duration;
keyType = "duration";
} else if (req.query.time) {
query.IndexName = "start-index";
query.KeyConditionExpression = "#st = :start";
query.ExpressionAttributeNames["#st"] = "start";
query.ExpressionAttributeValues[":start"] = req.query.time;
keyType = "start";
}
var FilterArr = [];
if (req.query.name && keyType != "name") {
FilterArr.push("#nm = :name");
query.ExpressionAttributeNames["#nm"] = "name";
query.ExpressionAttributeValues[":name"] = req.query.name;
}
if (req.query.date && keyType != "date") {
FilterArr.push("#dt = :date");
query.ExpressionAttributeNames["#dt"] = "date";
query.ExpressionAttributeValues[":date"] = req.query.date;
}
if (req.query.duration && keyType != "duration") {
FilterArr.push("#dur = :duration");
query.ExpressionAttributeNames["#dur"] = "duration";
query.ExpressionAttributeValues[":duration"] = req.query.duration;
}
if (req.query.time && keyType != "start") {
FilterArr.push("#st = :start");
query.ExpressionAttributeNames["#st"] = "start";
query.ExpressionAttributeValues[":start"] = req.query.time;
}
if (FilterArr.length > 0) {
query.FilterExpression = FilterArr.join(" and ");
}
docClient.query(query, function (err, data) {
if (err) {
throw err;
res.send("err");
}
res.send(data);
});
}
});
//Post libinfo
app.post("/studyinfo", function (req, res) {
var infoArr = req.body;
var arrLength = infoArr.length;
var completed = 0;
infoArr.forEach(info => {
var splitLink = info.Link.split("?")
.join("=")
.split("&")
.join("=")
.split("=");
var infoName, infoDate, infoDuration, infoStart;
for (var i = 0; i < splitLink.length; i++) {
if (splitLink[i] == "type") {
infoName = splitLink[i + 1];
} else if (splitLink[i] == "date") {
infoDate = splitLink[i + 1];
} else if (splitLink[i] == "duration") {
infoDuration = splitLink[i + 1];
} else if (splitLink[i] == "start") {
infoStart = splitLink[i + 1];
}
}
var entry = {
TableName: "study_info",
Item: {
link: info.Link,
name: infoName,
date: infoDate,
duration: infoDuration,
start: infoStart,
details: info["Room Details"],
time: info.Time
}
};
setTimeout(
e => {
docClient.put(e, function (err, data) {
completed++;
if (err) {
//throw err;
res.send(err);
}
if (completed == arrLength) {
res.send("done");
}
});
},
0,
entry
);
});
});
//Get yrl&powell
//date, duration, building, start
app.get("/librooms", function(req, res) {
if (
!req.query.building &&
!req.query.date &&
!req.query.duration &&
!req.query.start
) {
var query = {
TableName: "lib_rooms"
};
dynamodb.scan(query, function(err, data) {
if (err) {
throw err;
res.send("err");
}
res.send(data);
});
} else {
var query = {
TableName: "lib_rooms"
};
var keyType = "";
query.ExpressionAttributeValues = {};
query.ExpressionAttributeNames = {};
if (req.query.building) {
query.IndexName = "building-index";
query.KeyConditionExpression = "#bg = :building";
query.ExpressionAttributeNames["#bg"] = "building";
query.ExpressionAttributeValues[":building"] = req.query.building;
keyType = "building";
} else if (req.query.date) {
query.IndexName = "date-index";
query.KeyConditionExpression = "#dt = :date";
query.ExpressionAttributeNames["#dt"] = "date";
query.ExpressionAttributeValues[":date"] = req.query.date;
keyType = "date";
} else if (req.query.duration) {
query.IndexName = "duration-index";
query.KeyConditionExpression = "#dur = :duration";
query.ExpressionAttributeNames["#dur"] = "duration";
query.ExpressionAttributeValues[":duration"] = req.query.duration;
keyType = "duration";
} else if (req.query.start) {
query.IndexName = "start-index";
query.KeyConditionExpression = "#st = :start";
query.ExpressionAttributeNames["#st"] = "start";
query.ExpressionAttributeValues[":start"] = req.query.start;
keyType = "start";
}
var FilterArr = [];
if (req.query.building && keyType != "building") {
FilterArr.push("#bg = :building");
query.ExpressionAttributeNames["#bg"] = "building";
query.ExpressionAttributeValues[":building"] = req.query.building;
}
if (req.query.date && keyType != "date") {
FilterArr.push("#dt = :date");
query.ExpressionAttributeNames["#dt"] = "date";
query.ExpressionAttributeValues[":date"] = req.query.date;
}
if (req.query.duration && keyType != "duration") {
FilterArr.push("#dur = :duration");
query.ExpressionAttributeNames["#dur"] = "duration";
query.ExpressionAttributeValues[":duration"] = req.query.duration;
}
if (req.query.start && keyType != "start") {
FilterArr.push("#st = :start");
query.ExpressionAttributeNames["#st"] = "start";
query.ExpressionAttributeValues[":start"] = req.query.start;
}
if (FilterArr.length > 0) {
query.FilterExpression = FilterArr.join(" and ");
}
docClient.query(query, function(err, data) {
if (err) {
throw err;
res.send("err");
}
res.send(data);
});
}
});
//Post yrl & powell
/*app.post("/librooms", function(req, res) {
var infoArr = req.body;
var arrLength = infoArr.length;
var completed = 0;
// var combinedString = info.Room + "," + info["Building Name"]+ "," + info.Capacity + ","+ info.Date+ "," + info.Day+ "," + info["Start Time"]+ "," + "30"
infoArr.forEach(info => {
var entry = {
TableName: "lib_rooms",
Item: {
combined: info.Room + "," + info["Building Name"]+ "," + info.Capacity + ","+ info.Date+ "," + info.Day+ "," + info["Start Time"]+ "," + "30",
room: info.Room,
building: info["Building Name"],
capacity: info.Capacity,
date: info.Date, //change to date format
day: info.Day,
start: info["Start Time"], //change to seconds?
duration: "30"
}
};
setTimeout(
e => {
docClient.put(e, function(err, data) {
completed++;
if (err) {
//throw err;
res.send(err);
}
if (completed == arrLength) {
res.send("done");
}
});
},
0,
entry
);
});
});*/
app.listen(process.env.PORT || 3000);