-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1084 lines (852 loc) · 29.9 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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const randtoken = require('rand-token');
const nodemailer = require("nodemailer");
const smtpTransport = require('nodemailer-smtp-transport');
const mongo2 = require('mongodb');
const configData = require('./client/src/components/config.json');
const fileUpload = require('express-fileupload');
const fs = require('fs');
const AWS = require('aws-sdk');
const BASE_URL = configData.ip;
const path = require('path');
const { getMaxListeners } = require('process');
const { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } = require('constants');
/////////////////////////////////////////
// Added for Heroku deployment.
const PORT = process.env.PORT || 5000;
require('dotenv').config();
const app = express();
app.use(cors());
app.use(bodyParser.json({ limit: '8mb', extended: true }));
/////////////////////////////////////////
// Added for Heroku deployment.
app.set('port', (process.env.PORT || 5000));
//////////////////////////////
// Allows cors to work with react
app.all('/', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
/////////////////////////////////////////
const MongoClient = require('mongodb').MongoClient;
const url = '';
const client = new MongoClient(url);
client.connect();
app.use(fileUpload());
///////////////////////////////////////////////////
app.use(express.static(path.join(__dirname, 'client', 'public')));
///////////////////////////////////////////////////
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'public', 'index.html'))
});
///////////////////////////////////////////////////
// For signup API
app.post('/api/validateToken', async (req, res, next) => {
// incoming: validationID
// outgoing: status of whether or not the ID was found
const { validationID } = req.body;
const db = client.db();
const results = await db.collection('Validations').find({ ValidationID: validationID }).toArray();
var status = ""
if (results.length > 0) {
// Token is in the database
status = 'found';
var myquery = { ValidationId: validationID };
var newvalues = { $set: { IsValid: 1 } };
db.collection("Users").updateOne(myquery, newvalues, function (err, res) {
if (err) throw err;
console.log("1 document updated");
});
}
else {
// Token is not in the database
status = 'not found';
}
var ret = { status: status };
res.status(200).json(ret);
});
///////////////////////////////////////////////////
// For password reset code checker
app.post('/api/resetPasswordConfirmCode', async (req, res, next) => {
// incoming: username, code, newPassword
// outgoing: status of the password reset | 0 = code not found, 1 = password reset, 2 = right code but wrong username
const { username, code, newPassword } = req.body;
const db = client.db();
const results = await db.collection('ResetCodes').find({ ResetCode: code }).toArray();
var status = ""
if (results.length > 0) {
// Code found
if (username === results[0]['Username']) {
status = 1;
status = 1;
var myquery = { Login: username };
var newvalues = { $set: { Password: newPassword } };
db.collection("Users").updateOne(myquery, newvalues, function (err, res) {
if (err) throw err;
console.log("Password reset!");
});
} else {
status = 2;
}
} else {
// Code not found
status = 0;
}
var ret = { status: status };
res.status(200).json(ret);
});
///////////////////////////////////////////////////
// For password reset email send
app.post('/api/resetPasswordSendEmail', async (req, res, next) => {
// incoming: username
// outgoing: status of the password reset email | 0 = username not found, 1 = email sent
const { username } = req.body;
var email;
var resetCode = randtoken.generate(16);
const db = client.db();
const results = await db.collection('Users').find({ Login: username }).toArray();
var status = ""
if (results.length > 0) {
// Username found
status = 1;
email = results[0]['Email'];
// Add resetCode to database
var myobj = { ResetCode: resetCode, Username: username };
db.collection("ResetCodes").insertOne(myobj, function (err, res) {
if (err) throw err;
console.log("Reset code added to database!");
});
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'classproject1!'
}
}));
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"OnlySocks" <[email protected]>', // sender address
to: email, // list of receivers
subject: "Password reset code!", // Subject line
text: "Your code is " + resetCode, // plain text body
html: "<p>Your code is " + resetCode + "</p>", // html body
});
console.log("Message sent: %s", info.messageId);
// Message sent: <[email protected]>
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}
else {
// Username not found
status = 0;
}
var ret = { status: status };
res.status(200).json(ret);
});
///////////////////////////////////////////////////
// For adding a new favorite sock
app.post('/api/addNewFav', async (req, res, next) => {
// incoming: userId, profilePicture, theFile(base64)
// outgoing: Status of adding the new picture to database | 0 = success, 1 = failure
const { userId, profilePicture, theFile } = req.body;
const baseURLImage = "https://onlysocks.s3.amazonaws.com/FavoriteSocks/";
var dateNow = Date.now().toString();
try {
var FinalId = new mongo2.ObjectID(userId);
var myquery = { _id: FinalId };
var newvalues = { $set: { FavSockPicture: baseURLImage + dateNow + "-" + profilePicture } };
const db = client.db();
db.collection("Users").updateOne(myquery, newvalues, function (err, res) {
});
AWS.config.update({
accessKeyId: "accesskeyId", // Access key ID
secretAccessKey: "secretaccesskey", // Secret access key
region: "us-east-1" //Region
})
const s3 = new AWS.S3();
// Binary data base64
const fileContent = Buffer.from(theFile.replace(/^data:image\/\w+;base64,/, ""), 'base64');
// Setting up S3 upload parameters
const params = {
Bucket: 'onlysocks',
Key: "FavoriteSocks/" + dateNow + "-" + profilePicture.toString(), // File name you want to save as in S3
Body: fileContent,
ContentType: theFile.split(',')[0].split(':')[1].split(';')[0],
ACL: 'public-read'
};
// Uploading files to the bucket
s3.putObject(params, function (err, data) {
if (err) {
throw err;
}
});
var ret = { status: 0 };
res.status(200).json(ret);
} catch (error) {
console.log(error);
var ret = { status: 1 };
res.status(200).json(ret);
}
});
///////////////////////////////////////////////////
// For adding a new profile picture
app.post('/api/addNewProfilePicture', async (req, res, next) => {
// incoming: userId, profilePicture, theFile(base64)
// outgoing: Status of adding the new picture to database | 0 = success, 1 = failure
const { userId, profilePicture, theFile } = req.body;
const baseURLImage = "https://onlysocks.s3.amazonaws.com/ProfilePictures/";
var dateNow = Date.now().toString();
try {
var FinalId = new mongo2.ObjectID(userId);
var myquery = { _id: FinalId };
var newvalues = { $set: { ProfilePicture: baseURLImage + dateNow + "-" + profilePicture } };
const db = client.db();
db.collection("Users").updateOne(myquery, newvalues, function (err, res) {
});
AWS.config.update({
accessKeyId: "accessKeyId", // Access key ID
secretAccessKey: "secretAccessKey", // Secret access key
region: "us-east-1" //Region
})
// console.log(theFile);
const s3 = new AWS.S3();
// Binary data base64
const fileContent = Buffer.from(theFile.replace(/^data:image\/\w+;base64,/, ""), 'base64');
// Setting up S3 upload parameters
const params = {
Bucket: 'onlysocks',
Key: "ProfilePictures/" + dateNow + "-" + profilePicture.toString(), // File name you want to save as in S3
Body: fileContent,
ContentType: theFile.split(',')[0].split(':')[1].split(';')[0],
ACL: 'public-read'
};
// Uploading files to the bucket
s3.putObject(params, function (err, data) {
if (err) {
throw err;
}
});
var ret = { status: 0 };
res.status(200).json(ret);
} catch (error) {
console.log(error);
var ret = { status: 1 };
res.status(200).json(ret);
}
});
//////////////////////////////////////////////////
// For saving post pictures
app.post('/api/addNewPic', async (req, res, next) => {
// incoming: profilePicture, theFile(base64)
// outgoing: Status of adding the new picture to database | 0 = success, 1 = failure
const { profilePicture, theFile } = req.body;
const baseURLImage = "https://onlysocks.s3.amazonaws.com/Pictures/";
try {
AWS.config.update({
accessKeyId: "accessKeyId", // Access key ID
secretAccessKey: "secretAccessKey", // Secret access key
region: "us-east-1" //Region
})
const s3 = new AWS.S3();
// Binary data base64
const fileContent = Buffer.from(theFile.replace(/^data:image\/\w+;base64,/, ""), 'base64');
// Setting up S3 upload parameters
const params = {
Bucket: 'onlysocks',
Key: "Pictures/" + profilePicture.toString(), // File name you want to save as in S3
Body: fileContent,
ContentType: theFile.split(',')[0].split(':')[1].split(';')[0],
ACL: 'public-read'
};
// Uploading files to the bucket
s3.putObject(params, function (err, data) {
if (err) {
throw err;
}
});
var ret = { status: 0 };
res.status(200).json(ret);
} catch (error) {
console.log(error);
var ret = { status: 1 };
res.status(200).json(ret);
}
});
///////////////////////////////////////////////////
// For signup API
app.post('/api/signUp', async (req, res, next) => {
// incoming: First name, last name, login, password, email address
// outgoing: status of signup
const { login, password, firstName, lastName, email } = req.body;
const db = client.db();
const results = await db.collection('Users').find({ Login: login }).toArray();
var blankImage = "https://onlysocks.s3.amazonaws.com/ProfilePictures/blank.png";
var blankFavSock = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
var isValid = 0
var validationId = randtoken.generate(16);
if (results.length > 0) {
status = 'User already taken!';
}
else {
// Add credentials to the database here
var myobj = { Login: login, Password: password, FirstName: firstName, LastName: lastName, Email: email, IsValid: isValid, ValidationId: validationId, ProfilePicture: blankImage, FavSockPicture: blankFavSock };
db.collection("Users").insertOne(myobj, function (err, res) {
if (err) throw err;
console.log("User added!");
});
// Add validationid to database
var myobj = { Login: login, ValidationID: validationId };
db.collection("Validations").insertOne(myobj, function (err, res) {
if (err) throw err;
console.log("Validation token added to database!");
});
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'classproject1!'
}
}));
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"OnlySocks" <[email protected]>', // sender address
to: email, // list of receivers
subject: "Please verify your email for OnlySocks!", // Subject line
text: "http://onlysocks.org/" + "?validationId=" + validationId, // plain text body
html: "<a href=" + "http://onlysocks.org/" + "?validationId=" + validationId + ">Your validation link</a>", // html body
});
console.log("Message sent: %s", info.messageId);
// Message sent: <[email protected]>
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
status = 'User added to database!';
}
var ret = { status: status };
res.status(200).json(ret);
});
///////////////////////////////////////
//For deleting a post
async function deleteFunction(postId, status = 0) {
try {
var FinalId = new mongo2.ObjectID(postId);
var myquery = { _id: FinalId };
const db = client.db();
db.collection("Posts").deleteOne(myquery, function (err, obj) {
if (err) throw err;
});
// worked
status = 1;
}
catch (e) {
// didnt work
status = 0;
console.log(e);
}
return status;
}
app.post('/api/deleteAPost', async (req, res, next) => {
// incoming: postId
// outgoing: status of deletion | 0 = did not delete(error) , 1 = deleted
const { postId } = req.body;
var results = await deleteFunction(postId);
var ret = { status: results };
res.status(200).json(ret);
});
///////////////////////////////////////
//Create post API
app.post('/api/createPost', async (req, res, next) => {
// incoming: userid, login, content
// outgoing: status of post | 0 = not posted , 1 = posted , 2 = not enough content
const { userid, login, content } = req.body;
var status = 0;
var numlikes = 0;
try {
if (content.length > 1) {
const db = client.db();
await db.collection('Posts').insertOne({ Userid: userid, LoginName: login, ContentPost: content, Likes: numlikes, LikedUsers: [], Comments: [] });
status = 1; //posted
}
else
status = 2; //not enough to be posted
}
catch (e) {
console.log(console.type);
status = 0; //not posted
}
var ret = { status: status };
res.status(200).json(ret);
});
///////////////////////////////////////
//Deletes a comment
app.post('/api/deleteComment', async (req, res, next) => {
// incoming: postId, commentId
// outgoing: returns status of deletion | 0 = error or post not found, 1 = comment deleted
var status = 0;
try {
const { postId, commentId } = req.body;
var FinalId = new mongo2.ObjectID(postId);
var finalCommentId = new mongo2.ObjectID(commentId);
const db = client.db();
const results = await db.collection('Posts').find({ _id: FinalId }).toArray();
if (results.length > 0) {
var myquery = { _id: FinalId };
var newvalues = { $pull: { Comments: { _id: finalCommentId } } };
db.collection("Posts").updateOne(myquery, newvalues, function (err, res) {
});
status = 1;
}
else {
status = 0;
}
}
catch (e) {
console.log(e);
status = 0;
}
var ret = { Status: status };
res.status(200).json(ret);
});
///////////////////////////////////////
//Adds a comment
app.post('/api/addComment', async (req, res, next) => {
// incoming: postId, userId(of who is commenting), comment | text of comment
// outgoing: returns status of deletion | 0 = error adding comment, 1 = comment added, 2 = post not found
var status = 0;
try {
const { postId, userId, comment } = req.body;
var FinalId = new mongo2.ObjectID(postId);
const db = client.db();
const results = await db.collection('Posts').find({ _id: FinalId }).toArray();
if (results.length > 0) {
var js = { _id: new mongo2.ObjectID(), userId: userId, comment: comment }
var myquery = { _id: FinalId };
var newvalues = { $push: { Comments: js } };
db.collection("Posts").updateOne(myquery, newvalues, function (err, res) {
});
status = 1;
}
else {
status = 2;
}
}
catch (e) {
console.log(e);
status = 0;
}
var ret = { Status: status };
res.status(200).json(ret);
});
///////////////////////////////////////
//Get top liked posts
app.post('/api/getTopLikedPosts', async (req, res, next) => {
// incoming: none
// outgoing: top 3 liked posts of the entire website
const db = client.db();
const results = await db.collection('Posts').find({ Likes: { $exists: true } }).sort({ Likes: -1 }).limit(3).toArray();
var ret = { Results: results };
res.status(200).json(ret);
});
///////////////////////////////////////
//get Username
app.post('/api/getUsername', async (req, res, next) => {
// incoming: userId as string
// outgoing: username, status | 0 = success, 1 = failure
var status = 0;
const { userId } = req.body;
var FinalId = new mongo2.ObjectID(userId);
var user = '';
const db = client.db();
const results = await db.collection('Users').find({ _id: FinalId }).toArray();
if (results.length > 0) {
// User has been found
user = results[0]['Login'];
}
else {
//user not found
status = 1;
}
var ret = { Status: status, Username: user };
res.status(200).json(ret);
});
///////////////////////////////////////
//Update like API
app.post('/api/addLike', async (req, res, next) => {
// incoming: postid, userid
// outgoing: status of post | 0 = not liked, 1 = liked, 2 = already liked now unliking
var status = 0;
const { postid, userid } = req.body;
var FinalId = new mongo2.ObjectID(postid);
const db = client.db();
const results = await db.collection('Posts').find({ _id: FinalId }).toArray();
var numOfLikes = 0;
if (results.length > 0) {
// The post has been found
numOfLikes = results[0]['Likes'];
if (results[0]['LikedUsers'].includes(userid)) {
// User has already liked this post
var myquery = { _id: FinalId };
var newvalues = { $inc: { Likes: -1 } };
status = 2;
await db.collection("Posts").updateOne(myquery, newvalues, function (err, res) {
});
var myquery = { _id: FinalId };
var newvalues = { $pull: { LikedUsers: userid } };
db.collection("Posts").updateOne(myquery, newvalues, function (err, res) {
});
}
else {
var myquery = { _id: FinalId };
var newvalues = { $inc: { Likes: 1 }, $push: { LikedUsers: userid } };
status = 1;
await db.collection("Posts").updateOne(myquery, newvalues, function (err, res) {
});
}
}
else {
// The post has not been found
status = 0;
}
var ret = { Status: status, numOfLikes: numOfLikes };
res.status(200).json(ret);
});
///////////////////////////////////////
//Get posts
app.post('/api/getPosts', async (req, res, next) => {
// incoming: userid, array of people following
// outgoing: list of statuses from people the user is following
var statuses;
var username;
var numlikes;
var comments;
var postids2;
var ret = [];
var i;
const { userid, following } = req.body;
if (following === "undefined") {
res.status(200).json(ret);
return next;
}
const db = client.db();
const results = await db.collection('Posts').find().toArray();
const results2 = await db.collection('Users').find().toArray();
var keyMap = {};
for (i = 0; i < results2.length; i++) {
var tempLogin = results2[i].Login.toString();
var tempId = results2[i]._id.toString();
keyMap[tempId] = tempLogin;
}
for (i = 0; i < results.length; i++) {
if (userid == results[i].Userid || (following.split(',').includes(results[i]['Userid']))) {
statuses = results[i].ContentPost;
username = results[i].LoginName;
numlikes = results[i].Likes;
postids2 = results[i]._id;
comments = results[i].Comments;
comments.forEach(element => {
element["username"] = keyMap[element["userId"]];
});
ret.push({ username: username, status: statuses, likes: numlikes, postids: postids2, comments: comments });
}
}
res.status(200).json(ret);
});
app.post('/api/getProfilePosts', async (req, res, next) => {
// incoming: userid, array of people following
// outgoing: list of statuses from people the user is following
var statuses;
var username;
var numlikes;
var comments;
var postids;
var ret = [];
var i;
const { userid, following } = req.body;
if (following === "undefined") {
res.status(200).json(ret);
return next;
}
const db = client.db();
const results = await db.collection('Posts').find().toArray();
const results2 = await db.collection('Users').find().toArray();
try {
var keyMap = {};
for (i = 0; i < results2.length; i++) {
var tempLogin = results2[i].Login.toString();
var tempId = results2[i]._id.toString();
keyMap[tempId] = tempLogin;
}
for (i = 0; i < results.length; i++) {
if (userid == results[i].Userid) {
statuses = results[i].ContentPost;
username = results[i].LoginName;
numlikes = results[i].Likes;
postids = results[i]._id;
comments = results[i].Comments;
comments.forEach(element => {
element["username"] = keyMap[element["userId"]];
});
ret.push({ username: username, status: statuses, likes: numlikes, postids: postids, comments: comments });
}
}
} catch (error) {
console.log(error);
}
res.status(200).json(ret);
});
// Returns an array of usernames to follow from a username search
app.post('/api/getUsers', async (req, res, next) => {
// incoming: partial username string
// outgoing: an array of all usernames that match the string
var error = '';
const { username, loggeduser } = req.body;
const db = client.db();
const results = await db.collection('Users').find({ Login: new RegExp(username) }).toArray();
var users = "";
var ret = [];
if (results.length > 0) {
for (var i = 0; i < results.length; i++) {
users = results[i].Login;
if (users != loggeduser)
ret.push({ username: users, followers: results[i].Followers, following: results[i].Following });
}
}
else {
error = 'No Users Found';
}
res.status(200).json(ret);
});
// Returns an array of followers that the current user has
app.post('/api/getFollowers', async (req, res, next) => {
// incoming: logged in users username
// outgoing: an array of all that username that follow the logged in user
var error = '';
var errornofollowers = '';
const { loggeduserid } = req.body;
const db = client.db();
const results = await db.collection('Users').find({ _id: new mongo2.ObjectId(loggeduserid) }).toArray();
var ret;
var newret = [];
try {
if (results.length > 0) {
ret = { followers: results[0].Followers };
for (var i = 0; i < ret.followers.length; i++) {
var objectidcon = new mongo2.ObjectId(ret.followers[i]);
const newresults = await db.collection('Users').find({ _id: objectidcon }).toArray();
var username = newresults[0].Login;
var userid = newresults[0]._id;
var userarray = newresults[0].Followers;
var isFollowing = 0;
if (newresults.length > 0) {
newret.push({ follower: username, followerid: userid });
}
else
errornofollowers = "You Have No Followers Loser"
}
newret.push({ followernum: ret.followers.length });
}
else {
error = 'No Users Found';
}
res.status(200).json(newret);
} catch (error) {
console.log(error);
}
});
app.post('/api/getUserId', async (req, res, next) => {
// incoming: username
// outgoing: userId
const { username } = req.body;
var userId = 0;
const db = client.db();
const results = await db.collection('Users').find({ Login: username }).toArray();
if (results.length > 0)
{
userId = results[0]._id;
}else
{
// pass
}
var ret = { userId: userId};
res.status(200).json(ret);
});
// Returns an array of users the current user is following
app.post('/api/getFollowing', async (req, res, next) => {
// incoming: logged in users username
// outgoing: an array of all usernames that the logged user is following
var error = '';
var errornofollowing = '';
const { loggeduserid } = req.body;
const db = client.db();
const results = await db.collection('Users').find({ _id: new mongo2.ObjectId(loggeduserid) }).toArray();
var ret;
var newret = [];
try {
if (results.length > 0) {
ret = { following: results[0].Following };
for (var i = 0; i < ret.following.length; i++) {
var objectidcon = new mongo2.ObjectId(ret.following[i]);
const newresults = await db.collection('Users').find({ _id: objectidcon }).toArray();
var username = newresults[0].Login;
var userid = newresults[0]._id;
var doesFollowback = 0;
if (newresults.length > 0) {
newret.push({ usersfollowing: username, userfollowingid: userid });
}
else
errornofollowing = "You Are Not Following Anyone"
}
newret.push({ followingnum: ret.following.length });
}
else {
error = 'No Users Found';
}
} catch (error) {
console.log(error);
}
res.status(200).json(newret);
});
///////////////////////////////////////
//Unfollow
app.post('/api/unFollow', async (req, res, next) => {
// incoming: femaleId (Person being unfollowed), maleId (The person that is doing the unfollowing)
// outgoing: status of follow request | 0 = failed, 1 = followed
var status = 0;
const { femaleId, maleId } = req.body;
var femaleIdFinal = new mongo2.ObjectID(femaleId);
var maleIdFinal = new mongo2.ObjectID(maleId);
const db = client.db();
const results = await db.collection('Users').find({ _id: femaleIdFinal }).toArray();
if (results.length > 0) {
var myquery = { _id: femaleIdFinal };
var newvalues = { $pull: { Followers: maleId } };
status = 1
// Updates the females follower list
db.collection("Users").updateOne(myquery, newvalues, function (err, res) {
});
// Updates the males following list
var myquery = { _id: maleIdFinal };
var newvalues = { $pull: { Following: femaleId } };
db.collection("Users").updateOne(myquery, newvalues, function (err, res) {
});
}
else {
// Female not found
status = 0;
}
var ret = { Status: status };
res.status(200).json(ret);
});
///////////////////////////////////////
//Add follow
app.post('/api/addFollow', async (req, res, next) => {
// incoming: femaleUsername (Person being followed), maleId (The person that is doing the following)
// outgoing: status of follow request | 0 = failed, 1 = followed
var status = 0;
const { femaleUsername, maleId } = req.body;
var maleIdFinal = new mongo2.ObjectID(maleId);
const db = client.db();
const results = await db.collection('Users').find({ Login: femaleUsername }).toArray();
if (results.length > 0) {
var myquery = { Login: femaleUsername };
var newvalues = { $push: { Followers: maleId } };
status = 1
// Updates the person who is being followed followers list
db.collection("Users").updateOne(myquery, newvalues, function (err, res) {
});
// Updates the person doing the followings following list
var myquery = { _id: maleIdFinal };
var newvalues = { $push: { Following: results[0]['_id'].toString() } };
db.collection("Users").updateOne(myquery, newvalues, function (err, res) {
});
}
else {
// Female not found
status = 0;
}
var ret = { Status: status };
res.status(200).json(ret);
});
///////////////////////////////////////
// For following API
app.post('/api/getFollowing', async (req, res, next) => {
// incoming: userId
// outgoing: following | -1 user could not be found
var following = [];
const { userId } = req.body;
var userIdFinal = new mongo2.ObjectID(userId);
const db = client.db();