-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
executable file
·1615 lines (1603 loc) · 66.3 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 port = 5192;
const express = require("express");
const session = require("express-session");
const app = express();
const server = app.listen(port);
const fs = require("fs");
const path = require("path");
const io = require("socket.io")(server);
const bcrypt = require("bcryptjs");
const crypto = require("crypto");
const crypto_js = require("crypto-js");
const body_parser = require("body-parser");
// Redis is used by Socket.IO to store data.
const redis = require("redis");
const redis_client = redis.createClient();
const redis_store = require("connect-redis")(session);
redis_client.on("error", function(err) {
console.log("Redis Error: ", err);
});
var session_mware = session({
secret: generate_token(),
resave: false,
saveUninitialized: true,
cookie: { secure: false },
store: new redis_store({ host: 'localhost', port: 6379, client: redis_client, ttl: 86400 })
});
app.use(session_mware);
app.set("view engine", "ejs");
app.use("/assets", express.static("assets"));
app.use(body_parser.urlencoded({ extended: true }));
app.use(body_parser.json());
// Create required directories.
directory_check();
// The server's root directory. If the user is logged in, they'll see the main chat page, otherwise, they'll be shown the login page.
app.get("/", function(req, res) {
if(req.session.logged_in) {
res.render("home", { username: req.session.username, });
}
else {
res.render("login");
}
});
// Accessing the anonymous chat automatically logs out the user.
app.get("/anonymous", function(req, res) {
req.session.logged_in = 0;
req.session.anonymous = 1;
req.session.anonymous_id = "";
req.session.username = "";
res.render("anonymous");
});
// To login, the user can send a POST request with their username and password to "/login".
app.post("/login", function(req, res) {
var username = req.body.username;
var password = req.body.password;
if(!empty(username) && !empty(password)) {
// Gets the SHA256 hash of the user's username.
var username_hash = crypto.createHash("sha256").update(username.toLowerCase()).digest("hex");
var account_file = path.join(__dirname, "./data/accounts/" + username.toLowerCase() + ".txt");
var public_key_file = path.join(__dirname, "./data/keys/public/" + username_hash + ".txt");
var private_key_file = path.join(__dirname, "./data/keys/private/" + username_hash + ".txt");
// If the user's account file exists, it is opened, and its JSON content is parsed into an object.
if(fs.existsSync(account_file)) {
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
var account = JSON.parse(json);
// The user's password from the POST request is compared to their valid one that's encrypted using BCrypt, and stored on the server.
bcrypt.compare(password, account["password"], function(error, valid) {
// If the password is correct, the user is logged in, and their session variables are declared.
if(valid) {
req.session.logged_in = 1;
req.session.anonymous = 0;
req.session.username = account["username"];
// The user is then sent their public key, and private key (to be decrypted on the client side).
fs.readFile(private_key_file, { encoding:"utf-8" }, function(error, private_key) {
if(error) {
console.log(error);
}
else {
fs.readFile(public_key_file, { encoding:"utf-8" }, function(error, public_key) {
if(error) {
console.log(error);
}
else {
res.send(JSON.stringify({action:"refresh", private_key:private_key, public_key:public_key}));
}
});
}
});
}
else {
res.send(JSON.stringify({text:"Invalid credentials."}));
}
});
}
else {
res.send(JSON.strinigfy({text:"Invalid account file."}));
}
}
else {
console.log(error);
}
});
}
else {
res.send(JSON.stringify({text:"Account not found."}));
}
}
});
// To register, the user can send a POST request containing their username and password to "/register".
app.post("/register", function(req, res) {
var username = req.body.username;
var password = req.body.password;
if(!empty(username) && !empty(password)) {
// A hash of the user's username and password are created.
var username_hash = crypto.createHash("sha256").update(username.toLowerCase()).digest("hex");
var password_hash = crypto.createHash("sha512").update(password).digest("hex");
var account_file = path.join(__dirname, "./data/accounts/" + username.toLowerCase() + ".txt");
var public_key_file = path.join(__dirname, "./data/keys/public/" + username_hash + ".txt");
var private_key_file = path.join(__dirname, "./data/keys/private/" + username_hash + ".txt");
// If an account file under the user's username already exists, the user is informed of it.
if(fs.existsSync(account_file)) {
res.send("Account already exists.");
}
else {
// Only letters and numbers are allowed in usernames.
if(alphanumeric(username)) {
// Usernames have to be less than 14 characters long.
if(username.length > 14) {
res.send("Username is too long.");
}
else {
// The user's password is hashed using BCrypt.
bcrypt.hash(password, 10, function(error, hash) {
if(error) {
console.log(error);
}
else {
var account = {"username":username, "password":hash, "conversations":{}};
if(!empty(account)) {
fs.writeFile(account_file, JSON.stringify(account), function(error) {
if(error) {
console.log(error);
}
else {
if(fs.existsSync(account_file)) {
var settings_file = path.join(__dirname, "./data/settings/" + username.toLowerCase() + ".txt");
var settings = {"starting-conversations":"anybody", "message-notification":"enabled", "conversation-notification":"enabled", "chat-scrolling":"enabled", "conversation-sorting":"newest", "interface":"dark"};
fs.writeFile(settings_file, JSON.stringify(settings), function(error) {
if(error) {
console.log(error);
}
else {
// A public key and private key are generated for the user.
crypto.generateKeyPair("rsa", {
modulusLength:2048,
publicKeyEncoding: {
type:"spki",
format:"pem"
},
privateKeyEncoding: {
type:"pkcs8",
format:"pem"
}
}, function(error, public_key, private_key) {
if(error) {
console.log(error);
}
else {
// The user's private key is encrypted using the hash of their password as the encryption key.
var private_key_encrypted = aes_encrypt(private_key, password_hash);
fs.writeFile(public_key_file, public_key, function(error) {
if(error) {
console.log(error);
}
else {
fs.writeFile(private_key_file, private_key_encrypted, function(error) {
if(error) {
console.log(error);
}
else {
// If the public key and private key files exist, then the registration is complete.
if(fs.existsSync(public_key_file) && fs.existsSync(private_key_file) && !empty(public_key) && !empty(private_key_encrypted)) {
res.send("done");
}
// If the aforementioned files do not exist, then all the previously created files are deleted, and the user is told to try again.
else {
fs.unlink(account_file, function(error) {
if(error) {
console.log(error);
}
});
fs.unlink(public_key_file, function(error) {
if(error) {
console.log(error);
}
});
fs.unlink(private_key_file, function(error) {
if(error) {
console.log(error);
}
});
fs.unlink(settings_file, function(error) {
if(error) {
console.log(error);
}
});
res.send("Error. Try again.");
}
}
});
}
});
}
});
}
});
}
}
});
}
}
});
}
}
else {
res.send("Letters and numbers only.");
}
}
}
});
// The user can send a POST request to "/settings" to fetch their settings/preferences.
app.post("/settings", function(req, res) {
if(req.session.logged_in) {
var username = req.session.username.toLowerCase();
var settings_file = path.join(__dirname, "./data/settings/" + username + ".txt");
if(fs.existsSync(settings_file)) {
fs.readFile(settings_file, function(error, json) {
if(error) {
console.log(error);
}
else {
if(!empty(json)) {
res.send(json);
}
else {
res.send("Invalid settings file content.");
}
}
});
}
}
});
// Logging out.
app.post("/logout", function(req, res) {
req.session.logged_in = 0;
req.session.anonymous = 0;
req.session.anonymous_id = "";
req.session.username = "";
res.send("refresh");
});
// To get access to the session, Socket.IO uses a session middleware.
io.use(function(socket, next) {
session_mware(socket.request, socket.request.res, next);
});
// An object containing a list of anonymous users' IDs.
var anonymous_clients = new Object();
// An object containing a list of conversation IDs and their participants' anonymous IDs.
var anonymous_chats = new Object();
// An object containing a list of normal users.
var clients = new Object();
// An object containing a list of normal chats and their participants.
var current_chats = new Object();
io.sockets.on("connection", function(socket) {
if(!empty(socket.request.session.username) && socket.request.session.logged_in && !socket.request.session.anonymous) {
// If the current_chats object already contains the user's username, then Socket.IO just connects to the chat the user's supposed to be connected to.
if(!empty(current_chats[socket.request.session.username.toLowerCase()])) {
socket.join(current_chats[socket.request.session.username.toLowerCase()]);
}
// The client object consists of the user's username, and their Socket ID. Since the Socket ID changes frequently, this is a way to always keep track of it.
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
// If the user is found in the clients object, then their Socket ID is just updated.
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
// If they aren't found in the clients object, then they're added to it.
else {
clients = Object.assign(clients, client);
}
var account_file = path.join(__dirname, "./data/accounts/" + socket.request.session.username.toLowerCase() + ".txt");
// Fetching a list of conversations that the user is a part of.
socket.on("list-conversations", function() {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
var account = JSON.parse(json);
var conversation_list = account["conversations"];
var list = new Object();
// Automatically remove conversation IDs from the user's account file if the conversation file associated with the ID doesn't exist.
if(!empty(conversation_list)) {
var auto_check = true;
if(auto_check) {
var keys = Object.keys(conversation_list);
for(i = 0; i < keys.length; i++) {
if(account["conversations"][keys[i]]["visibility"] == true) {
var conversation_file = path.join(__dirname, "./data/conversations/" + keys[i] + ".txt");
var conversation_object = account["conversations"][keys[i]];
var file_info = fs.statSync(conversation_file);
var file_mtime = to_epoch(file_info.mtime);
var time_object = { modified:file_mtime };
Object.assign(conversation_object, { modified:file_mtime });
var conversation = { [keys[i]]:conversation_object };
Object.assign(list, conversation);
}
if(!fs.existsSync(path.join(__dirname, "./data/conversations/" + keys[i] + ".txt"))) {
delete account["conversations"][keys[i]];
// If the conversation ID stored in the user's account file doesn't actually have a corresponding file, then the user's account file is updated to reflect that fact.
var overwrite = true;
}
}
io.to(clients[socket.request.session.username.toLowerCase()]).emit("list-conversations", { content:list });
if(overwrite) {
if(!empty(account)) {
fs.writeFile(account_file, JSON.stringify(account), function(error) {
if(error) {
console.log(error);
}
});
}
}
}
}
}
}
else {
console.log(error);
}
});
});
// Fetch the contents of a conversation.
socket.on("fetch-conversation", function(data) {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
if(!empty(data)) {
var account_file = path.join(__dirname, "./data/accounts/" + socket.request.session.username.toLowerCase() + ".txt");
var conversation_file = path.join(__dirname, "./data/conversations/" + data.id + ".txt");
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
var account = JSON.parse(json);
var recipient_name = account["conversations"][data.id]["name"];
var recipient_public_key_file = path.join(__dirname, "./data/keys/public/" + crypto.createHash("sha256").update(recipient_name.toLowerCase()).digest("hex") + ".txt");
if(!empty(account["conversations"][data.id])) {
if(account["conversations"][data.id]["visibility"] == true) {
fs.readFile(conversation_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
fs.readFile(recipient_public_key_file, { encoding:"utf-8" }, function(error, recipient_public_key) {
if(error) {
console.log(error);
}
else {
// Get a SHA256 hash of the conversation ID, and then join it using Socket.IO.
var hash = crypto.createHash("sha256").update(data.id).digest("base64");
delete current_chats[socket.request.session.username.toLowerCase()];
var current_chat = { [socket.request.session.username.toLowerCase()]:hash };
Object.assign(current_chats, current_chat);
socket.join(hash);
if(!empty(json)) {
// To ensure that HTML elements cannot be added to messages.
var formatted = json.replace_all("<", "<").replace_all(">", ">");
var messages = JSON.parse(formatted);
var output = new Object();
var keys = Object.keys(messages);
for(i = 0; i < keys.length; i++) {
// When a user deletes a message, it is only hidden for them, until the other user deletes it as well, in which case it'll get deleted from the server.
if(messages[keys[i]]["visibility"][socket.request.session.username.toLowerCase()] == true) {
var message = { [keys[i]]:messages[keys[i]] };
Object.assign(output, message);
}
}
io.to(clients[socket.request.session.username.toLowerCase()]).emit("fetch-conversation", { content:output, recipient:recipient_name, conversation_id:data.id, recipient_public_key:recipient_public_key });
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("fetch-conversation", { recipient:recipient_name, conversation_id:data.id, recipient_public_key:recipient_public_key });
}
// When the user fetches the content of a conversation, that conversation no longer contains an "unread" message.
account["conversations"][data.id]["unread"] = false;
if(!empty(account)) {
fs.writeFile(account_file, JSON.stringify(account), function(error) {
if(error) {
console.log(error);
}
});
}
}
});
}
else {
console.log(error);
}
});
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("refresh");
}
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("refresh");
}
}
else {
console.log("Empty account file.");
}
}
else {
console.log(error);
}
});
}
});
// Close a conversation and leave it using Socket.IO.
socket.on("close-conversation", function(data) {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
if(!empty(data.id)) {
var hash = crypto.createHash("sha256").update(data.id).digest("base64");
delete current_chats[socket.request.session.username.toLowerCase()];
socket.leave(hash);
}
});
// Create a conversation.
socket.on("create-conversation", function(data) {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
if(!empty(data.username)) {
// The recipient's username.
var recipient_username = data.username.toLowerCase();
if(empty(data.title)) {
var title = "Untitled Conversation";
}
else {
var title = data.title.replace_all("<", "<").replace_all(">", ">");
}
// The user can't message themselves.
if(recipient_username != socket.request.session.username.toLowerCase()) {
// Read the sender's account file.
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
// Generate a conversation ID.
var id = generate_id();
// The sender's account.
var account = JSON.parse(json);
// The sender's conversations.
var conversations = account["conversations"];
// If the ID already exists, then regenerate it.
while(id in conversations || fs.existsSync(path.join(__dirname, "./data/conversations/" + id + ".txt"))) {
var id = generate_id();
}
// The conversation file.
var conversation_file = path.join(__dirname, "./data/conversations/" + id + ".txt");
// The recipient's account file.
var recipient_account_file = path.join(__dirname, "./data/accounts/" + recipient_username + ".txt");
var recipient_settings_file = path.join(__dirname, "./data/settings/" + recipient_username + ".txt");
var recipient_contacts_file = path.join(__dirname, "./data/contacts/" + recipient_username + ".txt");
// If the recipient's account file exists, then read it.
if(fs.existsSync(recipient_account_file) && fs.existsSync(recipient_settings_file)) {
fs.readFile(recipient_settings_file, { encoding:"utf-8" }, function(error, json) {
if(error) {
console.log(error);
}
else {
if(!empty(json)) {
var settings = JSON.parse(json);
if(settings["starting-conversations"] == "nobody") {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("notify", { title:"Error", text:"You cannot start a conversation with this user.", color:"rgb(120,120,250)", duration:4000 });
}
else {
var whitelisted = false;
if(settings["starting-conversations"] == "contacts") {
fs.readFile(recipient_contacts_file, { encoding:"utf-8" }, function(error, json) {
if(error) {
console.log(error);
}
else {
var contacts = JSON.parse(json);
if(socket.request.session.username.toLowerCase() in contacts) {
whitelisted = true;
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("notify", { title:"Error", text:"You cannot start a conversation with this user.", color:"rgb(120,120,250)", duration:4000 });
}
}
});
}
if(whitelisted || settings["starting-conversations"] == "anybody") {
fs.readFile(recipient_account_file, { encoding:"utf-8" }, function(error, json) {
if(!empty(json)) {
// The recipient's account.
var recipient_account = JSON.parse(json);
var recipient_name = recipient_account["username"];
// The recipient's conversation object.
var recipient_conversation = { [id]:{ "username":socket.request.session.username.toLowerCase(), "name":socket.request.session.username, "title":title, "visibility":true, "unread":false }};
var recipient_merged = Object.assign(recipient_account["conversations"], recipient_conversation);
// Add the conversation object to the recipient's account file.
if(!empty(recipient_account)) {
fs.writeFile(recipient_account_file, JSON.stringify(recipient_account), function(error) {
if(error) {
console.log(error);
}
else {
var conversation = { [id]:{ "username":recipient_username, "name":recipient_name, "title":title, "visibility":true, "unread":false }};
var merged = Object.assign(account["conversations"], conversation);
// Create the conversation file.
fs.writeFile(conversation_file, "", function(error) {
if(error) {
console.log(error);
}
else {
// Add the conversation object to the sender's account file.
if(!empty(account)) {
fs.writeFile(account_file, JSON.stringify(account), function(error) {
if(error) {
console.log(error);
}
else {
// Output the sender's conversation list.
var list = account["conversations"];
io.to(clients[socket.request.session.username.toLowerCase()]).emit("list-conversations", { content:list, id:id });
io.to(clients[recipient_username]).emit("refetch");
io.to(clients[recipient_username]).emit("notify", { title:"New Conversation", text:socket.request.session.username + " started a conversation with you.", color:"message", duration:4000, args:{ id:id, type:"conversation" }});
}
});
}
}
});
}
});
}
}
});
}
}
}
}
});
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("notify", { title:"Error", text:"Recipient not found.", color:"rgb(120,120,250)", duration:4000 });
}
}
}
else {
console.log(error);
}
});
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("notify", { title:"Error", text:"You can't message yourself.", color:"rgb(120,120,250)", duration:4000 });
}
}
});
// Process a new message.
socket.on("new-message", function(data) {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
if(!empty(data.text.sender) && !empty(data.text.recipient) && !empty(data.id)) {
var account_file = path.join(__dirname, "./data/accounts/" + socket.request.session.username.toLowerCase() + ".txt");
var conversation_file = path.join(__dirname, "./data/conversations/" + data.id + ".txt");
if(!fs.existsSync(conversation_file)) {
fs.writeFile(conversation_file, "", function(error) {
if(error) {
console.log(error);
}
});
}
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
var account = JSON.parse(json);
var recipient_username = account["conversations"][data.id]["username"];
var recipient_account_file = path.join(__dirname, "./data/accounts/" + recipient_username + ".txt");
var recipient_settings_file = path.join(__dirname, "./data/settings/" + recipient_username + ".txt");
var recipient_contacts_file = path.join(__dirname, "./data/contacts/" + recipient_username + ".txt");
if(fs.existsSync(recipient_account_file)) {
fs.readFile(recipient_settings_file, { encoding:"utf-8" }, function(error, json) {
if(error) {
console.log(error);
}
else {
if(!empty(json)) {
var recipient_settings = JSON.parse(json);
// If the recipient of the message has their privacy options set to allow anyone to message them.
if(recipient_settings["starting-conversations"] == "anybody") {
new_message();
}
// If only contacts can message them.
else if(recipient_settings["starting-conversations"] == "contacts") {
fs.readFile(recipient_contacts_file, { encoding:"utf-8" }, function(error, json) {
if(error) {
console.log(error);
}
else {
if(!empty(json)) {
var recipient_contacts = JSON.parse(json);
if(socket.request.session.username.toLowerCase() in recipient_contacts) {
new_message();
}
else {
fs.readFile(recipient_account_file, { encoding:"utf-8" }, function(error, json) {
if(error) {
console.log(error);
}
else {
if(!empty(json)) {
var recipient_account = JSON.parse(json);
if(!empty(recipient_account["conversations"][data.id]) && recipient_account["conversations"][data.id]["visibility"] == true) {
new_message();
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("notify", { title:"Error", text:"You can't message that user.", color:"rgb(120,120,250)", duration:4000 });
}
}
}
});
}
}
}
});
}
// If nobody can message them.
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("notify", { title:"Error", text:"You can't message that user.", color:"rgb(120,120,250)", duration:4000 });
}
function new_message() {
// When a conversation is deleted by a user, it's only hidden from them, until the other user also deletes it, in which case it's deleted from the server. If only one of them has deleted it, sending a message in that conversation would "unhide" it from the user who deleted it. Past messages won't be visible though.
if(!empty(account["conversations"][data.id])) {
if(account["conversations"][data.id]["visibility"] != true) {
account["conversations"][data.id]["visibility"] = true;
if(!empty(account)) {
fs.writeFile(account_file, JSON.stringify(account), function(error) {
if(error) {
console.log(error);
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("refetch");
}
});
}
}
fs.readFile(conversation_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
var messages = new Object();
if(!empty(json)) {
var messages = JSON.parse(json);
}
var id = generate_id();
while(id in messages) {
var id = generate_id();
}
// Each message's content is repeated twice. It's encrypted once with the sender's public key, so that they can decrypt it for themselves (since they don't have access to the recipient's private key), and once again with the recipient's public key so that the recipient can decrypt it.
var message = { [id]: { "from":socket.request.session.username, "text":{[socket.request.session.username.toLowerCase()]:data.text.sender, [recipient_username.toLowerCase()]:data.text.recipient}, "visibility":{ [socket.request.session.username.toLowerCase()]:true, [recipient_username]:true }}};
Object.assign(messages, message);
if(!empty(messages)) {
fs.writeFile(conversation_file, JSON.stringify(messages), function(error) {
if(error) {
console.log(error);
}
else {
var file_info = fs.statSync(conversation_file);
var file_mtime = to_epoch(file_info.mtime);
io.to(current_chats[socket.request.session.username.toLowerCase()]).emit("new-message", { sender:data.text.sender, recipient:data.text.recipient, id:id, from:socket.request.session.username, conversation_id:data.id, conversation_modified:file_mtime });
io.to(clients[recipient_username.toLowerCase()]).emit("new-message", { sender:data.text.sender, recipient:data.text.recipient, id:id, from:socket.request.session.username, conversation_id:data.id, conversation_modified:file_mtime, relay:"true" });
}
});
}
fs.readFile(recipient_account_file, { encoding:"utf-8" }, function(error, json) {
if(error) {
console.log(error);
}
else {
if(!empty(json)) {
var recipient_account = JSON.parse(json);
if(recipient_account["conversations"][data.id]["visibility"] != true) {
recipient_account["conversations"][data.id]["visibility"] = true;
if(!empty(recipient_account)) {
fs.writeFile(recipient_account_file, JSON.stringify(recipient_account), function(error) {
if(error) {
console.log(error);
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("refetch");
io.to(clients[recipient_username]).emit("refetch");
io.to(clients[recipient_username]).emit("notify", { title:"New Conversation", text:socket.request.session.username + " started a conversation with you.", color:"message", duration:4000, args:{ id:data.id }});
}
});
}
}
}
}
});
}
else {
console.log(error);
}
});
}
}
}
}
});
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("notify", { title:"Error", text:"Recipient not found.", color:"rgb(120,120,250)", duration:4000 });
}
}
}
else {
console.log(error);
}
});
}
});
socket.on("delete-message", function(data) {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
if(!empty(data.conversation) && !empty(data.message)) {
var account_file = path.join(__dirname, "./data/accounts/" + socket.request.session.username.toLowerCase() + ".txt");
var conversation_file = path.join(__dirname, "./data/conversations/" + data.conversation + ".txt");
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
var account = JSON.parse(json);
if(!empty(account["conversations"][data.conversation]) && account["conversations"][data.conversation]["visibility"] == true) {
fs.readFile(conversation_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
var messages = JSON.parse(json);
messages[data.message]["visibility"][socket.request.session.username.toLowerCase()] = false;
if(messages[data.message]["visibility"][socket.request.session.username.toLowerCase()] != true && messages[data.message]["visibility"][account["conversations"][data.conversation]["username"]] != true) {
delete messages[data.message];
}
fs.writeFile(conversation_file, JSON.stringify(messages), function(error) {
if(error) {
console.log(error);
}
else {
var file_info = fs.statSync(conversation_file);
var file_mtime = to_epoch(file_info.mtime);
io.to(clients[socket.request.session.username.toLowerCase()]).emit("delete-message", { id:data.message, conversation_id:data.conversation, conversation_modified:file_mtime });
}
});
}
}
});
}
}
}
else {
console.log(error);
}
});
}
});
socket.on("delete-conversation", function(data) {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
if(!empty(data)) {
var account_file = path.join(__dirname, "./data/accounts/" + socket.request.session.username.toLowerCase() + ".txt");
var conversation_file = path.join(__dirname, "./data/conversations/" + data.id + ".txt");
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
var account = JSON.parse(json);
if(!empty(account["conversations"][data.id])) {
account["conversations"][data.id]["visibility"] = false;
var recipient_username = account["conversations"][data.id]["username"];
var recipient_account_file = path.join(__dirname, "./data/accounts/" + recipient_username + ".txt");
fs.readFile(conversation_file, { encoding:"utf-8" }, function(error, json) {
if(error) {
console.log(error);
}
else {
if(!empty(json)) {
var messages = JSON.parse(json);
var keys = Object.keys(messages);
for(i = 0; i < keys.length; i++) {
messages[keys[i]]["visibility"][socket.request.session.username.toLowerCase()] = false;
}
fs.writeFile(conversation_file, JSON.stringify(messages), function(error) {
if(error) {
console.log(error);
}
});
}
}
});
if(!empty(account)) {
fs.writeFile(account_file, JSON.stringify(account), function(error) {
if(error) {
console.log(error);
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("refetch");
fs.readFile(recipient_account_file, { encoding:"utf-8" }, function(error, json) {
if(!empty(json)) {
var recipient_account = JSON.parse(json);
if(account["conversations"][data.id]["visibility"] != true && recipient_account["conversations"][data.id]["visibility"] != true) {
fs.unlink(conversation_file, function(error) {
if(error) {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("notify", { title:"Error", text:"Couldn't delete conversation.", color:"rgb(120,120,250)", duration:4000 });
}
else {
delete account["conversations"][data.id];
delete recipient_account["conversations"][data.id];
if(!empty(account)) {
fs.writeFile(account_file, JSON.stringify(account), function(error) {
if(error) {
console.log(error);
}
});
}
if(!empty(recipient_account)) {
fs.writeFile(recipient_account_file, JSON.stringify(recipient_account), function(error) {
if(error) {
console.log(error);
}
});
}
}
});
}
}
});
}
});
}
}
}
}
else {
console.log(error);
}
});
}
});
socket.on("unread-message", function(data) {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
if(!empty(data)) {
var account_file = path.join(__dirname, "./data/accounts/" + socket.request.session.username.toLowerCase() + ".txt");
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(error) {
console.log(error);
}
else {
if(!empty(json)) {
var account = JSON.parse(json);
if(!empty(account["conversations"][data.id])) {
account["conversations"][data.id]["unread"] = true;
if(!empty(account)) {
fs.writeFile(account_file, JSON.stringify(account), function(error) {
if(error) {
console.log(error);
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("unread-message", { conversation_id:data.id });
}
});
}
}
}
}
});
}
});
socket.on("rename-conversation", function(data) {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
if(!empty(data.id)) {
if(!empty(data.title)) {
var account_file = path.join(__dirname, "./data/accounts/" + socket.request.session.username.toLowerCase() + ".txt");
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
var account = JSON.parse(json);
if(!empty(account["conversations"][data.id])) {
var recipient_username = account["conversations"][data.id]["username"];
var recipient_account_file = path.join(__dirname, "./data/accounts/" + recipient_username + ".txt");
fs.readFile(recipient_account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {
if(!empty(json)) {
var recipient_account = JSON.parse(json);
var title = data.title.replace_all("<", "<").replace_all(">", ">");
account["conversations"][data.id]["title"] = title;
recipient_account["conversations"][data.id]["title"] = title;
if(!empty(account)) {
fs.writeFile(account_file, JSON.stringify(account), function(error) {
if(error) {
console.log(error);
}
});
}
if(!empty(recipient_account)) {
fs.writeFile(recipient_account_file, JSON.stringify(recipient_account), function(error) {
if(error) {
console.log(error);
}
});
}
}
}
});
io.to(clients[socket.request.session.username.toLowerCase()]).emit("refetch");
io.to(clients[recipient_username]).emit("refetch");
}
}
}
else {
console.log(error);
}
});
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("notify", { title:"Error", text:"Title cannot be left blank.", color:"rgb(120,120,250)", duration:4000 });
}
}
else {
io.to(clients[socket.request.session.username.toLowerCase()]).emit("refresh");
}
});
socket.on("fetch-conversation-info", function(data) {
var client = { [socket.request.session.username.toLowerCase()]:socket.id };
if(socket.request.session.username.toLowerCase() in clients) {
clients[socket.request.session.username.toLowerCase()] = socket.id;
}
else {
clients = Object.assign(clients, client);
}
if(!empty(data.id)) {
var account_file = path.join(__dirname, "./data/accounts/" + socket.request.session.username.toLowerCase() + ".txt");
var conversation_file = path.join(__dirname, "./data/conversations/" + data.id + ".txt");
fs.readFile(account_file, { encoding:"utf-8" }, function(error, json) {
if(!error) {