-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
2108 lines (2036 loc) · 115 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
// mongodb
require('./config/db').then(() => {
console.log("DB Connected");
}).catch((err) => {
console.error('ERROR CONNECTING TO DATABASE:')
console.error(err)
console.error('SERVER WILL EXIT WITH CODE 1 (FAIL)')
process.exit(1)
});
const app = require('express')();
const cors = require('cors')
const port = process.env.PORT || 3000;
const UserRouter = require('./routes/User')
const TempRouter = require('./routes/Temp')
const ConversationsRouter = require('./api/Conversations')
const MessagesRouter = require('./api/Messages')
const PublicApisRouter = require('./api/PublicApis')
const FeedRouter = require('./routes/Feed')
const AdminRouter = require('./routes/Admin')
const sanitizeFilename = require('sanitize-filename');
const swaggerUi = require('swagger-ui-express'); //For API docs
const swaggerDocument = require('./swagger.json'); //For API docs
const ImageLibrary = require('./libraries/Image');
const imageHandler = new ImageLibrary();
require('dotenv').config();
const fs = require('fs')
const S3 = require('aws-sdk/clients/s3')
const bucketName = process.env.AWS_BUCKET_NAME
const region = process.env.AWS_BUCKET_REGION
const accessKeyId = process.env.AWS_ACCESS_KEY
const secretAccessKey = process.env.AWS_SECRET_KEY
const s3 = new S3 ({
region,
accessKeyId,
secretAccessKey
})
const { v4: uuidv4 } = require('uuid');
const util = require('util')
const unlinkFile = util.promisify(fs.unlink)
//Image post
const multer = require('multer')
const path = require('path');
const stream = require('stream')
const storage = multer.diskStorage({
// Destination to store image
destination: (req, file, cb) => {
cb(null, process.env.TEMP_IMAGES_PATH)
},
filename: (req, file, cb) => {
let extName = path.extname(file.originalname)
if (extName == ".png" || extName == ".jpg" || extName == ".jpeg") {
var newUUID = uuidv4();
cb(null, newUUID + extName);
} else {
cb("Invalid file format")
}
}
});
const upload = multer({ storage: storage })
const { uploadFile, getFileStream } = require('./s3')
const { clients, addSocketToClients, getSocketToSendMessageTo, getSocketToDisconnect, clientConnectedToConversation, removeSocketDueToDisconnect, removeSocketFromClients, checkIfDeviceUUIDConnected } = require('./socketHandler')
var timeOutsOfSocketDisconnects = []
const User = require('./models/User');
const Conversation = require('./models/Conversation')
const Message = require('./models/Message')
const { popularPostHandler } = require('./popularPostHandler')
function generateDate(callback) { //todo: callback no longer needed im js lazy
return callback(Date.now())
}
function determineUsersForStatusSend(userId, callback) {
Conversation.find({members: {$in: [String(userId)]}}).then(convosOfUser => { // turn into function so can be used for online and offline setting
if (convosOfUser.length) {
console.log(convosOfUser.map(x => x._id));
var convoMembersOnly = convosOfUser.map(x => x.members).flat(1); //excludes this user
console.log(convoMembersOnly);
var filteredConvoMembersOnly = convoMembersOnly.filter(x => x.equals(userId) == false);
console.log(filteredConvoMembersOnly);
let uniqueConvoMembersOnly = filteredConvoMembersOnly.filter((element, index) => {
return filteredConvoMembersOnly.findIndex(x => x.equals(element)) === index;
});
console.log("uCMO");
console.log(uniqueConvoMembersOnly);
var clientsOfMembers = clients.clientList.filter(x => uniqueConvoMembersOnly.findIndex(y => y.equals(x.userId)) !== -1);
console.log(clientsOfMembers);
return callback(clientsOfMembers);
} else {
console.log("Couldn't find convo's so none to set for (or an issue occured).");
return callback("None");
}
}).catch(err => {
console.log("Error when finding convos, user most likely wont be online.");
console.log(err);
return callback("Error");
});
};
function saveToDataBase(messageSent, convoId, messagesId, userSenderId, callback) {
//console.log(messageSent)
Conversation.findOne({_id: {$eq: convoId}}).then((conversationData) => {
if (!conversationData) {
const forReturn = {
status: "FAILED",
message: "Coundn't find the conversation."
}
return callback(forReturn);
} else {
//Conversation exists
if (messageSent.isEncrypted == true) {
console.log(messageSent)
if (Array.isArray(messageSent.encryptedChatText)) {
var encryptedChatText = messageSent.encryptedChatText
const allEncryptedKeysUUIDs = encryptedChatText.map(x => x.keysUniqueId)
console.log("allEncryptedKeysUUIDs: ")
console.log(allEncryptedKeysUUIDs)
if (messageSent.cryptographicNonce.length == 24) {
const cryptographicNonce = Array.from(messageSent.cryptographicNonce)
//following if checks for at least one encrypted string that isnt empty and one public encryption key uuid used
if (encryptedChatText.some(x => x.encryptedString.trim().length !== 0) && conversationData.publicEncryptionKeys.some(x => allEncryptedKeysUUIDs.includes(x.keysUniqueId))) {
const newMessage = new Message({
_id: messagesId,
conversationId: convoId,
isEncrypted: true,
senderId: userSenderId,
chatText: "",
datePosted: messageSent.datePosted,
dateUpdated: messageSent.dateUpdated,
cryptographicNonce: cryptographicNonce,
encryptedChatText: messageSent.encryptedChatText,
isServerMessage: false,
involvedIds: messageSent.involvedIds,
messageReactions: [],
inReplyTo: (messageSent.inReplyTo !== "" ? messageSent.inReplyTo._id : ""),
attatchments: messageSent.attatchments
});
newMessage.save().then(result => {
const forReturn = {
status: "SUCCESS",
message: "Sent Message"
}
console.log(`forReturn ${forReturn}`)
return callback(forReturn);
}).catch(err => {
console.log(err)
const forReturn = {
status: "FAILED",
message: "Error with saving message"
}
console.log(`forReturn ${forReturn}`)
return callback(forReturn);
});
} else {
const forReturn = {
status: "FAILED",
message: "Message was empty or not encrypted properly for any keys."
}
console.log(`forReturn ${forReturn}`)
return callback(forReturn);
}
} else {
const forReturn = {
status: "FAILED",
message: "Bad cryptographic nonce."
}
console.log(`forReturn ${forReturn}`)
return callback(forReturn);
}
} else {
const forReturn = {
status: "FAILED",
message: "Message wasn't correct format for encrypted message."
}
console.log(`forReturn ${forReturn}`)
return callback(forReturn);
}
} else {
//Conversation exists
var textInMessage = messageSent.chatText.trim()
if (textInMessage !== "") {
const newMessage = new Message({
_id: messagesId,
conversationId: convoId,
isEncrypted: false,
senderId: userSenderId,
chatText: messageSent.chatText,
datePosted: messageSent.datePosted,
dateUpdated: messageSent.dateUpdated,
cryptographicNonce: [],
encryptedChatText: [],
isServerMessage: false,
involvedIds: messageSent.involvedIds,
messageReactions: [],
inReplyTo: (messageSent.inReplyTo !== "" ? messageSent.inReplyTo._id : ""),
attatchments: messageSent.attatchments
});
newMessage.save().then(result => {
const forReturn = {
status: "SUCCESS",
message: "Sent Message"
}
console.log(`forReturn ${forReturn}`)
return callback(forReturn);
}).catch(err => {
console.log(err)
const forReturn = {
status: "FAILED",
message: "Error with saving message"
}
console.log(`forReturn ${forReturn}`)
return callback(forReturn);
});
} else {
const forReturn = {
status: "FAILED",
message: "Message was empty."
}
console.log(`forReturn ${forReturn}`)
return callback(forReturn);
}
}
}
}).catch(err => {
console.log(err)
const forReturn = {
status: "FAILED",
message: "Error after finding conversation."
}
return callback(forReturn);
})
}
function addOrRemoveReaction(messageId, reaction, toAdd, pubId, callback) {
console.log("AORR")
Message.findOne({_id: {$eq: messageId}}).then(messageFound => {
if (!messageFound) {
return callback({
status: "FAILED",
message: "Couldn't find message."
});
} else {
const reactionAlready = messageFound.messageReactions.some(x => x.reaction == reaction && x.pubId == pubId)
if (toAdd !== reactionAlready) {
if (reactionAlready == false) {
Message.findOneAndUpdate({_id: {$eq: messageId}}, {$push: {messageReactions : {reaction: String(reaction), pubId: String(pubId)}}}).then(function () {
return callback({
status: "SUCCESS",
message: "Saved."
});
}).catch(err => {
console.log(err)
return callback({
status: "FAILED",
message: "Failed to save.",
lastReaction: reactionAlready
});
})
} else {
Message.findOneAndUpdate({_id: {$eq: messageId}}, {$pull: {messageReactions : {reaction: String(reaction), pubId: String(pubId)}}}).then(function () {
return callback({
status: "SUCCESS",
message: "Saved."
});
}).catch(err => {
console.log(err)
return callback({
status: "FAILED",
message: "Failed to save.",
lastReaction: reactionAlready
});
})
}
} else {
return callback({
status: "SUCCESS",
message: "Already the reaction."
});
}
}
}).catch(err => {
console.log(err)
return callback({
status: "FAILED",
message: "Error finding message."
});
})
}
function appNotActiveTimeOutForDisconnect(socketIdOfTheUser, pubId) {
function afterTimeOutIfNotCancelled() {
try {
const socketFound = io.sockets.sockets.get(socketIdOfTheUser);
io.to(socketIdOfTheUser).emit("timed-out-from-app-state")
socketFound.disconnect()
console.log(`Timed out from app state socket: ${socketIdOfTheUser}, ${pubId}`)
const indexToCheckIfTimingOut = timeOutsOfSocketDisconnects.findIndex(x => x.socketIdOfTheUser == socketIdOfTheUser)
timeOutsOfSocketDisconnects.splice(indexToCheckIfTimingOut, 1)
console.log(timeOutsOfSocketDisconnects)
} catch (err) {
console.log(`Error disconnecting due to app state change: ${err}`)
}
}
var indexIfAlreadyExists = timeOutsOfSocketDisconnects.findIndex(x => x.socketIdOfTheUser == socketIdOfTheUser)
if (indexIfAlreadyExists == -1) {
var timeoutID = setTimeout(afterTimeOutIfNotCancelled, 10000)
timeOutsOfSocketDisconnects.push({socketIdOfTheUser: socketIdOfTheUser, timeoutID: timeoutID})
console.log(timeOutsOfSocketDisconnects)
}
}
// Get the objectID type
var ObjectID = require('mongodb').ObjectID;
//Remove this before release
app.use(cors({
origin: '*'
}))
//For accepting post form data
const bodyParser = require('express').json;
app.use(bodyParser());
app.use('/user', UserRouter)
app.use('/tempRoute', TempRouter)
app.use('/conversations', ConversationsRouter)
app.use('/messages', MessagesRouter)
app.use('/publicApis', PublicApisRouter)
app.use('/feed', FeedRouter)
app.use('/admin', AdminRouter)
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); //For API docs
const https = require('https');
const e = require('express');
const { tokenValidation } = require('./middleware/TokenHandler');
let server;
if (process.env.NO_HTTPS) {
server = app.listen(port, () => {
console.log(`Server running on port ${port}`);
})
} else {
const options = {
key: fs.readFileSync('./ssl/private.key'),
cert: fs.readFileSync('./ssl/server.crt'),
ca: [
fs.readFileSync('./ssl/intermediate.crt'),
fs.readFileSync('./ssl/root.crt')
]
};
if (process.env.SSL_PASSPHRASE_FILEPATH) {
options.passphrase = fs.readFileSync('./ssl/passphrase.txt').toString()
} else if (process.env.SSL_PASSPHRASE) {
options.passphrase = process.env.SSL_PASSPHRASE
} else {
console.warn('SSL passphrase was not provided.')
}
server = https.createServer(options, app).listen(port, () => {
console.log(`Server running on port ${port}`);
});
}
const handlePopularPosts = () => {
handlerStatus = popularPostHandler();
}
setInterval(handlePopularPosts, 60*60*1000+5); //5 milisceonds bc why not
const io = require("socket.io")(server, {
cors: { origin: "*" },
'pingTimeout': 35000,
'pingInterval': 10000
});
let currentFileUploads = {};
io.on("connection", (socket) => {
//todo: for the socket being in its own file on front end, connect the socket, but have another self-made connect that sends id and uuids after.
var idOnConnection = socket.handshake.query.idSentOnConnect;
var uuidOfDevice = socket.handshake.query.uuidOfDevice;
var pendingReactions = [];
var reactionAdd = [];
var reactionRemove = [];
if (idOnConnection) {
User.findOne({_id: {$eq: idOnConnection}}).then(userFound => {
if (userFound) {
if (uuidOfDevice) {
//--Start of connection stuff
let foundSameUUID = clients.clientList.find(client => client.deviceUUID == uuidOfDevice && client.pubId == userFound.secondId);
if (typeof foundSameUUID !== "undefined") {
try {
io.sockets.sockets.get(foundSameUUID.socketId).disconnect(true);
} catch(err) {
console.log("Error occured disconnecting socket of: ", foundSameUUID);
}
clients.removeClient(foundSameUUID.socketId, userFound.secondId);
console.log("Client should have been removed and disconnected.");
}
console.log("Connected:", idOnConnection, uuidOfDevice);
console.log(clients);
clients.saveClient(userFound.secondId, userFound._id, "", socket.id, uuidOfDevice, {name: userFound.name, displayName: userFound.displayName, imageKey: userFound.profileImageKey});
console.log(clients);
socket.emit("client-connected")
//--Online Stuff
//Initial Set Online
determineUsersForStatusSend(userFound._id, function(result) {
if (result == "Error") {
socket.emit("initial-set-online-error")
} else if (result == "None") {
socket.emit("initial-set-online-and-conversation-users-online", [])
} else {
//Success
if (result.length) {
io.sockets.to(result.map(x => x.socketId)).emit("user-in-conversation-online", {pubId: userFound.secondId, name: userFound.name, displayName: userFound.displayName, imageKey: userFound.profileImageKey})
let uniqueAccountsOnly = result.filter((element, index) => {
return result.findIndex(x => x.pubId == element.pubId) === index;
});
socket.emit("initial-set-online-and-conversation-users-online", uniqueAccountsOnly.map(x => ({pubId: x.pubId, name: x.usersDetails.name, displayName: x.usersDetails.displayName, imageKey: x.usersDetails.imageKey})))
}
}
})
//-- socket
socket.on('join-conversation', (conversationId) => {
Conversation.findOne({_id: {$eq: conversationId}}).then(convoToJoin => {
if (!convoToJoin) {
socket.emit("join-conversation-failed", "Could not find conversation.")
} else {
if (convoToJoin.members.some(x => x.equals(userFound._id))) {
socket.join(conversationId)
const index = clients.clientList.findIndex(x => x.socketId == socket.id)
if (index !== -1) {
clients.clientList[index].conversationId = conversationId
console.log(`socket joined ${conversationId}`)
socket.emit("client-joined-conversation")
} else {
socket.disconnect() // if their socket isn't found trigger a disconnect to prompt a reopen to the socket connection as the socket should have been found.
}
} else {
socket.emit("join-conversation-failed", "Client not found in conversation.")
}
}
}).catch(err => {
console.log(err)
socket.emit("join-conversation-failed", "Error finding conversation.")
})
})
//--message stuff
socket.on("send-message", (message) => {
Conversation.findOne({_id: {$eq: message.conversationId}}).then(convoFound => {
if (!convoFound) {
socket.emit("failed-to-send-message", "Couldn't find conversation.")
} else {
const thisUsersClient = clients.clientList.find(x => x.socketId == socket.id)
if (!thisUsersClient) {
socket.disconnect()
} else {
if (message.conversationId == thisUsersClient.conversationId) {
let involvedIds = {};
let inReplyTo = "";
function checksComplete() {
if (message.isEncrypted !== true) {
if (message.chatText.trim().length !== 0) { //todo improve
const messagesId = new ObjectID()
console.log("Message Sending")
generateDate(function(datetime) {
var toSendToUsers = {
_id: messagesId,
publicId: userFound.secondId,
isEncrypted: false,
chatText: message.chatText,
datePosted: datetime,
dateUpdated: datetime,
cryptographicNonce: [],
encryptedChatText: [],
isServerMessage: false,
involvedIds: involvedIds,
messageReactions: [],
inReplyTo: inReplyTo,
attatchments: message.attatchments
}
socket.to(message.conversationId).emit("recieve-message", toSendToUsers)
saveToDataBase(toSendToUsers, message.conversationId, messagesId, userFound._id, function(messageSaved) {
console.log(messageSaved)
if (messageSaved.status !== "SUCCESS") {
socket.emit("message-sent-to-database", false, messageSaved.message, toSendToUsers)
} else {
socket.emit("message-sent-to-database", true, messageSaved.message, toSendToUsers)
}
})
})
} else {
socket.emit("empty-text-sent")
}
} else {
var encryptedChatText = message.encryptedChatText
const allEncryptedKeysUUIDs = encryptedChatText.map(x => x.keysUniqueId)
console.log("allEncryptedKeysUUIDs: ")
console.log(allEncryptedKeysUUIDs)
//following if checks for at least one encrypted string that isnt empty and one public encryption key uuid used
if (message.cryptographicNonce.length == 24) {
const cryptographicNonce = Array.from(message.cryptographicNonce)
if (encryptedChatText.some(x => x.encryptedString.trim().length !== 0) && conversationData.publicEncryptionKeys.some(x => allEncryptedKeysUUIDs.includes(x.keysUniqueId))) {
const messagesId = new ObjectID()
console.log("Message Sending")
generateDate(function(datetime) {
var toSendToUsers = {
_id: messagesId,
publicId: userFound.secondId,
isEncrypted: true,
chatText: "",
datePosted: datetime,
dateUpdated: datetime,
cryptographicNonce: cryptographicNonce,
encryptedChatText: message.encryptedChatText,
isServerMessage: false,
involvedIds: involvedIds,
messageReactions: [],
inReplyTo: inReplyTo,
attatchments: message.attatchments
}
socket.to(message.conversationId).emit("recieve-message", toSendToUsers)
saveToDataBase(toSendToUsers, message.conversationId, messagesId, userFound._id, function(messageSaved) {
console.log(messageSaved)
if (messageSaved.status !== "SUCCESS") {
socket.emit("message-sent-to-database", false, messageSaved.message, toSendToUsers)
} else {
socket.emit("message-sent-to-database", true, messageSaved.message, toSendToUsers)
}
})
})
} else {
socket.emit("empty-text-sent")
}
} else {
socket.emit("failed-to-send-message", "Bad nonce.")
}
}
}
if (message.inReplyTo !== "") { //add more checks around here if need be
Message.findOne({_id: message.inReplyTo}).then(msgReplyingTo => {
if (!msgReplyingTo || message.conversationId !== msgReplyingTo.conversationId) { //doesnt exist or not in conversation //TODO: make sure this works
socket.emit("failed-to-send-message", "Unable to find message being replied to.")
} else {
inReplyTo = {
_id: msgReplyingTo._id,
publicId: "",
senderName: "",
senderImageKey: "",
senderDisplayName: "",
isEncrypted: msgReplyingTo.isEncrypted,
chatText: msgReplyingTo.chatText,
datePosted: msgReplyingTo.datePosted,
dateUpdated: msgReplyingTo.dateUpdated,
cryptographicNonce: msgReplyingTo.cryptographicNonce,
encryptedChatText: msgReplyingTo.encryptedChatText,
isServerMessage: false,
involvedIds: msgReplyingTo.involvedIds,
messageReactions: msgReplyingTo.messageReactions,
inReplyTo: msgReplyingTo.inReplyTo,
attatchments: msgReplyingTo.attatchments
}
User.findOne({_id: msgReplyingTo.senderId}).then(userReplyingTo => {
if (!userReplyingTo) {
involvedIds.repliedToPubId = ""
inReplyTo.publicId = ""
inReplyTo.senderName = ""
inReplyTo.senderImageKey = ""
inReplyTo.senderDisplayName = ""
checksComplete()
} else {
involvedIds.repliedToPubId = userReplyingTo.secondId
inReplyTo.publicId = userReplyingTo.secondId
inReplyTo.senderName = userReplyingTo.name
inReplyTo.senderImageKey = userReplyingTo.profileImageKey
inReplyTo.senderDisplayName = userReplyingTo.displayName
checksComplete()
}
}).catch(err => {
console.log(err)
socket.emit("failed-to-send-message", "Error occured when finding user being replied to.")
})
}
}).catch(err => {
console.log(err)
socket.emit("failed-to-send-message", "Error occured when finding message being replied to.")
})
} else {
checksComplete()
}
} else {
socket.emit("client-not-connected-to-conversation")
}
}
}
}).catch(err => {
console.log(err)
socket.emit("failed-to-send-message", "Error occured when finding conversation.")
})
})
// on front end spamming allowed so whenever one of the pendings stop as it is being spammed that emit would work, the sockets emiting after each completion would make sure the client gets what is correct.
socket.on('toggle-message-reaction', (messageId, reaction, toAddSent) => {
console.log("Tmr")
if (typeof toAddSent == "boolean") {
if (reaction == "") { //TODO: change to better later
socket.emit("failed-to-toggle-message-reaction", "Invalid reaction sent.");
} else {
Message.findOne({_id: messageId}).then(messageFound => {
if (!messageFound) {
socket.emit("failed-to-toggle-message-reaction", "Couldn't find message.");
} else {
const thisUsersClient = clients.clientList.find(x => x.socketId == socket.id)
if (!thisUsersClient) {
socket.disconnect();// if their socket isn't found trigger a disconnect to prompt a reopen to the socket connection as the socket should have been found.
} else {
if (thisUsersClient.conversationId == messageFound.conversationId) {
//direct scoket emit maybe have something that stops spam after a few attempts
if (toAddSent == true) {
io.to(messageFound.conversationId).emit("recieve-reaction-add", reaction, messageId, userFound._id); // TODO think of socket emit methods and what not to still show spam maybe
} else {
io.to(messageFound.conversationId).emit("recieve-reaction-remove", reaction, messageId, userFound._id);
}
//main
if (pendingReactions.some(x => x == reaction)) {
if (toAddSent == true) {
reactionRemove = reactionRemove.filter(x => x !== reaction);
reactionAdd.push(reaction);
} else {
reactionAdd = reactionAdd.filter(x => x !== reaction);
reactionRemove.push(reaction);
}
} else {
pendingReactions.push(reaction);
const forRecallAORR = (toAdd) => {
addOrRemoveReaction(messageId, reaction, toAdd, userFound.secondId, function(sendBack) {
//this part first so the last emit is always the db one.
if (reactionAdd.some(x => x == reaction)) {
reactionAdd = reactionAdd.filter(x => x !== reaction)
forRecallAORR(true)
} else if (reactionRemove.some(x => x == reaction)) {
reactionRemove = reactionRemove.filter(x => x !== reaction)
forRecallAORR(false)
} else {
pendingReactions = pendingReactions.filter(x => x !== reaction)
}
//this part after as the recalls arent awaits anyway
if (sendBack.status == "FAILED") {
if (sendBack.message == "Disconnect.") {
socket.disconnect();
} else if (sendBack.message == "Failed to save.") {
if (sendBack.lastReaction == true) {
io.to(messageFound.conversationId).emit("recieve-reaction-add", reaction, messageId, userFound._id);
} else {
io.to(messageFound.conversationId).emit("recieve-reaction-remove", reaction, messageId, userFound._id);
}
} else {
socket.emit("failed-to-toggle-message-reaction", sendBack.message)
}
} else {
if (toAdd == true) {
io.to(messageFound.conversationId).emit("recieve-reaction-add", reaction, messageId, userFound._id);
} else {
io.to(messageFound.conversationId).emit("recieve-reaction-remove", reaction, messageId, userFound._id);
}
}
})
}
forRecallAORR(toAddSent)
}
} else {
socket.emit("client-not-connected-to-conversation");
}
}
}
}).catch(err => {
console.log(err)
socket.emit("failed-to-toggle-message-reaction", "Error finding message.")
})
}
} else {
socket.emit("failed-to-toggle-message-reaction", "To add or remove not clarified.");
}
})
socket.on('start-file-upload', (data) => {
//will have queued uploads kinda like wha discord got
var newUUID = uuidv4();
const thisUsersClient = clients.clientList.find(x => x.socketId == socket.id);
if (!thisUsersClient) {
socket.disconnect();// if their socket isn't found trigger a disconnect to prompt a reopen to the socket connection as the socket should have been found.
} else {
if (thisUsersClient["conversationId"] == data["conversationId"]) {
if (currentFileUploads.hasOwnProperty(socket.id)) {
socket.emit("file-upload-in-progress"); // make queue mayb
} else {
//todo more checks here i think
currentFileUploads[socket.id] = {
fileSize: data["fileSize"],
uploadData: "",
downloaded: 0
};
let filePosition = 0;
try {
//this part think abt bc on how it would queue but also resume a upload ykyk was thinking of some sort of id
} catch (err) {
console.log("New file.")
}
}
} else {
}
}
})
//--Inactive user stuff
//Function for if app comes back to foreground
socket.on('app-state-active', () => {
const indexToCheckIfTimingOut = timeOutsOfSocketDisconnects.findIndex(x => x.socketIdOfTheUser == socket.id)
if (indexToCheckIfTimingOut !== -1) {
try {
console.log(`Clearing timeout ${socket.id}`)
clearTimeout(timeOutsOfSocketDisconnects[indexToCheckIfTimingOut].timeoutID)
timeOutsOfSocketDisconnects.splice(indexToCheckIfTimingOut, 1)
} catch (err) {
console.log(err)
}
}
})
//Function for if app leaves foreground
socket.on('app-state-not-active', () => {
appNotActiveTimeOutForDisconnect(socket.id, userFound.secondId)
})
//--Disconnect
socket.on('disconnect', () => {
console.log('Disconnected');
const shouldSetOffline = clients.removeClient(socket.id, userFound.secondId);
console.log("Removed socket of pub id: " + userFound.secondId);
console.log(clients)
if (typeof shouldSetOffline !== "undefined") {
console.log("Another client, same account, but with different device.")
} else {
determineUsersForStatusSend(userFound._id, function(result) {
if (result == "Error") {
console.log("Error getting users for set offline.")
} else if (result == "None") {
console.log("None to set offline for.")
} else {
//Success
console.log("Setting user offline: " + userFound.secondId)
if (result.length) {io.sockets.to(result.map(x => x.socketId)).emit("user-in-conversation-offline", userFound.secondId)}
}
})
}
});
} else {
console.log("No device uuid sent");
socket.disconnect();
}
} else {
console.log("No valid _id sent");
socket.disconnect();
}
}).catch(err => {
console.log(err);
//probs change from disconnect to something else
socket.disconnect();
})
} else {
console.log("No user id sent");
socket.disconnect();
}
})
const serverMessage = (convoId, chatText, involvedIds, _id, datetime) => {
const newMessage = new Message({
_id: _id,
conversationId: convoId,
isEncrypted: false,
senderId: "",
chatText: chatText,
datePosted: datetime,
dateUpdated: datetime,
encryptedChatText: [],
isServerMessage: true,
involvedIds: involvedIds,
cryptographicNonce: [],
messageReactions: [],
inReplyTo: messageSent.inReplyTo,
attatchments: messageSent.attatchments
});
newMessage.save().then(result => {
return result;
}).catch(err => {
console.log(err)
return "FAILED"
});
}
app.post("/leaveConversations", (req, res) => {
//passed values
const idSent = req.body.idSent
const conversationId = req.body.conversationId
//main
if (idSent == "" || conversationId == "") {
res.json({
status: "FAILED",
message: "Issue with ids sent"
})
} else {
User.find({_id: {$eq: idSent}}).then(userFound => {
if (userFound.length) {
Conversation.find({_id: {$eq: conversationId}}).then(convoFound => {
if (convoFound.length) {
if (convoFound[0].isDirectMessage !== true) {
if (convoFound[0].members.includes(idSent)) {
if (convoFound[0].members.length !== 1) {
const idToTest = new ObjectID(idSent)
const ownerIdToTest = new ObjectID(convoFound[0].ownerId)
if (idToTest.equals(ownerIdToTest)) {
res.json({
status: "FAILED",
message: "Please assign an owner before leaving."
})
} else {
Conversation.findOneAndUpdate({_id: {$eq: conversationId}}, { $pull: { members: String(idToTest) }}).then(function() {
console.log("Updated")
getSocketToDisconnect(conversationId, idSent, function(toLeave) {
if (toLeave == null || toLeave.length == 0) {
const serverMessagesId = new ObjectID()
//Get date
generateDate(function(datetime) {
io.sockets.in(conversationId).emit("user-left-conversation", userFound[0].secondId, serverMessagesId, datetime);
serverMessage(conversationId, "Left", {userThatLeft: userFound[0].secondId}, serverMessagesId, datetime)
res.json({
status: "SUCCESS",
message: "Successfully left.",
})
})
} else {
var toLeaveItemsProcessed = 0
toLeave.forEach(function (item, index) {
const forAsync = async () => {
const socketFound = await io.sockets.sockets.get(toLeave[index])
socketFound.leave(conversationId);
toLeaveItemsProcessed++;
if (toLeaveItemsProcessed == toLeave.length) {
removeSocketFromClients(conversationId, userFound[0].secondId, function(socketRemoving) {
if (socketRemoving !== null) {
console.log("Socket removed from array")
const serverMessagesId = new ObjectID()
generateDate(function(datetime) {
io.sockets.in(conversationId).emit("user-left-conversation", userFound[0].secondId, serverMessagesId, datetime);
serverMessage(conversationId, "Left", {userThatLeft: userFound[0].secondId}, serverMessagesId, datetime)
res.json({
status: "SUCCESS",
message: "Successfully left.",
})
})
} else {
console.log("Didn't remove from array")
const serverMessagesId = new ObjectID()
generateDate(function(datetime) {
io.sockets.in(conversationId).emit("user-left-conversation", userFound[0].secondId, serverMessagesId, datetime);
serverMessage(conversationId, "Left", {userThatLeft: userFound[0].secondId}, serverMessagesId, datetime)
res.json({
status: "SUCCESS",
message: "Successfully left.",
})
})
}
})
}
}
forAsync()
})
}
})
}).catch(err => {
console.log(err)
res.json({
status: "FAILED",
message: "Error leaving."
})
})
}
} else {
const conversationIdString = conversationId.toString()
Message.deleteMany({conversationId: {$eq: conversationIdString}}).then(function() {
Conversation.findOneAndDelete({_id: {$eq: conversationId}}).then(function() {
getSocketToDisconnect(conversationId, idSent, function(toLeave) {
if (toLeave == null || toLeave.length == 0) {
res.json({
status: "SUCCESS",
message: "Successfully left.",
})
} else {
var toLeaveItemsProcessed = 0
toLeave.forEach(function (item, index) {
const forAsync = async () => {
const socketFound = await io.sockets.sockets.get(toLeave[index])
socketFound.leave(conversationId);
toLeaveItemsProcessed++;
if (toLeaveItemsProcessed == toLeave.length) {
const socketFound = io.sockets.sockets.get(toLeave)
socketFound.leave(conversationId);
removeSocketFromClients(conversationId, userFound[0].secondId, function(socketRemoving) {
if (socketRemoving !== null) {
console.log("Socket removed from array")
res.json({
status: "SUCCESS",
message: "Successfully left.",
})
} else {
console.log("Didn't remove from array")
res.json({
status: "SUCCESS",
message: "Successfully left.",
})
}
})
}
}
forAsync()
})
}
})
}).catch(err => {
console.log(err)
res.json({
status: "FAILED",
message: "Error when deleting conversations."
})
})
}).catch(err => {
console.log(err)
res.json({
status: "FAILED",
message: "Error when deleting messages."
})
})
}
} else {
res.json({
status: "FAILED",
message: "Your not in the conversation"
})
}
} else {
res.json({
status: "FAILED",
message: "You cant leave DMs"
})
}
}
}).catch(err => {
console.log(err)
res.json({
status: "FAILED",
message: "Error when deleting messages."
})
})
}
}).catch(err => {
console.log(err)
res.json({
status: "FAILED",
message: "Error when deleting messages."
})
})
}
})
//remove from gc
app.post("/removeMember", (req,res) => {
//sent
const sentId = req.body.sentId
const conversationId = req.body.conversationId
const pubIdOfUserToRemove = req.body.pubIdOfUserToRemove
//main
if (sentId == "" || conversationId == "" || pubIdOfUserToRemove == "") {