-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClient.js
1858 lines (1585 loc) · 90.3 KB
/
Client.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 crypto = require('crypto');
const AirUnpacker = require('./AirUnpacker.js');
const AirPacker = require('./AirPacker.js');
const ByteBuffer = require('byte-buffer');
const EncryptionLib = require('./encryption_test.js');
const ConversionDatabase = require('./conversionDatabase.js');
const SMServerAPI = require("./SMServerAPI.js");
const SMServerWebsocket = require("./SMServerWebsocket.js");
const CommConst = require("./CommConst.js");
const LogLib = require("./Log.js");
const Zlib = require('zlib');
// Log.setSender("Client.js");
const {v4: uuidv4} = require('uuid');
const fs = require('fs');
const MESSAGE_QUERY_INTERVAL = 30 * 1000; //Double-checks messages every 30s. This is an insurance policy as the websocket can sometimes disconnect and messages can get lost
//TODO: Only use ONE SMServerAPI--it's re-generating a request every time it is require()d
//TODO: Handle promise rejections gracefully (Log.e or something)
/*
BIG TODOLIST:
Maybe add an option to autoconfigure SMServer?
Maybe customize the device name to include the iPhone name instead of just "AirBridge"?
*/
//TODO: Looks like the new update to SMServer will have an "addresses" list with contact addresses in it
function Client(connection) {
var Log = new LogLib.Log("Client.js","Client");
this.transmissionCheck = null;
this.authenticated = false;
this.connection = connection;
this.clientName = "Not authenticated";
this.platformName = "unknown";
this.installationId = "unknown";
this.clientLastSeenTime = 9999999999999; //Timestamp of last time_upper sent to the client
this.messageRefreshInterval = null;
this.receivedDataLength = null; //null if we don't have the complete length received yet. Does not include the 5 extra bytes for the message header
this.receivedData = new ByteBuffer();
this.fileToSend = new ByteBuffer();
this.filenameToSend = "unknown";
this.batteryLevel = 100;
this.isCharging = true;
var globalThis = this; //TODO: Make this less hacky
this.websocketMessageListener = null;
this.setupTransmissionCheck = function() {
var Log = new LogLib.Log("Client.js","setupTransmissionCheck");
var message = new AirPacker();
message.writeInt(CommConst.nhtInformation); //nhtInformation (Message type)
message.writeInt(CommConst.mmCommunicationsVersion); //mmCommunicationsVersion (AirMessage protocol version)
message.writeInt(CommConst.mmCommunicationsSubVersion); //mmCommunicationsSubVersion (AirMessage protocol subversion)
message.writeBoolean(true); //Transmission check required
Log.i("Setting up transmission check");
this.transmissionCheck = crypto.randomBytes(32);
Log.vv("Transmission check: "+this.transmissionCheck.toString('hex'));
message.writeVariableLengthBuffer(this.transmissionCheck); //Writes the length and the transmission check
message.writeHeader();
return message;
}.bind(this)
var onConnData = function(d) {
//TODO: GIFs sent from GBoard show up as two messages when sending
var Log = new LogLib.Log("Client.js","onConnData");
Log.i("New raw connection data from client (length of "+d.length+")");
//TODO: Add a timeout to data if it gets interrupted
var data = d;
//Add the data to the receivedData buffer
Log.v("Adding received data to bytebuffer");
this.receivedData.append(data.length);
this.receivedData.write(data);
//If we can't obtain an int length yet
if (this.receivedData.length < 4) {
//Data has been added to receivedData, but there still isn't enough for a length integer
Log.v("We don't have a complete tramsission length (the length int hasn't fully transmitted). Stop and wait for more data.");
return;
}
//If the length int IS complete and wasn't before
if (this.receivedData.length >= 4 && this.receivedDataLength == null) {
//Set the receivedDataLength to the int sent from the client
var tmpbuffer = Buffer.from(this.receivedData.buffer);
this.receivedDataLength = tmpbuffer.readUInt32BE(0);
Log.v("Got expected length of received data: "+this.receivedDataLength);
//this.buffer.readUInt32BE(this.readerIndex);
}
//If the length of receivedData is the right one
//NOTE: receivedDataLength only includes the length of the content, not the length or encryption header (which is 5 bytes)
if (this.receivedDataLength !== null && this.receivedData.length >= (this.receivedDataLength + 5)) { //Checks to see if we have all the data
//Save the bytebuffer into another variable and clear receivedData. Set the length to null.
Log.v("Length meets our expectations. Got data in full!");
Log.blankLine();
Log.i("Got a complete transmission from client.");
var dataInFull = this.receivedData.raw;
//SAVE THE BYTEBUFFER SOMEWHERE HERE
this.receivedData = new ByteBuffer();
this.receivedDataLength = null;
//Run whatever code we need as we've finally gotten all the data!
processCompleteIncomingTransmission(Buffer.from(dataInFull));
}
}.bind(this)
var onConnClose = function() {
var Log = new LogLib.Log("Client.js","onConnClose");
Log.w('connection from '+remoteAddress+' closed');
clearInterval(globalThis.messageRefreshInterval); //Stops checking for new messages
}.bind(this);
var onConnError = function(err) {
var Log = new LogLib.Log("Client.js","onConnError");
Log.e('Connection '+remoteAddress+' error: '+err.message);
}.bind(this);
var remoteAddress = this.connection.remoteAddress + ':' + this.connection.remotePort;
Log.i('new client connection from '+remoteAddress);
this.connection.on('data', onConnData.bind(this));
this.connection.on('end', (data) => {
Log.w("Connection ended: "+data);
});
this.connection.on('close', onConnClose);
this.connection.on('error', onConnError);
//MAYBE: Handle messages to the AirBridge bot separately in a separate library
var processCompleteIncomingTransmission = async function(message) {
var Log = new LogLib.Log("Client.js","processCompleteIncomingTransmission");
Log.i("Processing incoming transmission");
var unpacker = new AirUnpacker(message);
var messageLength = unpacker.readInt();
Log.v("Message length: "+messageLength);
var encryptionStatus = unpacker.readBoolean();
Log.v("Encryption status: "+encryptionStatus);
if (encryptionStatus == 1) {
Log.v("Message is encrypted, send to decryptAndProcess() function");
decryptAndProcess(unpacker);
} else {
Log.v("Message is not encrypted, processing...");
var messageType = unpacker.readInt(); //nhtInformation
Log.v("Message type: "+messageType);
//Is nhtInformation a vaoid thing to receive?
if (messageType == CommConst.nhtAuthentication) { //nhtAuthentication: The client wants to authenticate
Log.v("Client authentication message received. Processing...");
processNhtAuthentication(unpacker);
} else if (messageType == CommConst.nhtPing) {
Log.i("Client ping message received. Sending pong");
var responsePacker = new AirPacker();
Log.v("Packing int (message type): nhtPong: "+CommConst.nhtPong);
responsePacker.packInt(CommConst.nhtPong);
Log.v("Writing header (unencrypted)");
responsePacker.writeHeader(false);
Log.i("Sending pong message");
globalThis.connection.write(responsePacker.getBuffer());
}
//TODO: Implement nhtClose
}
}.bind(this);
//TODO: Maybe shut down stuff like event handlers once connection is closed?
var processNhtAuthentication = async function(unpacker) {
var Log = new LogLib.Log("Client.js","processNhtAuthentication");
Log.i("Processing nhtAuthentication");
//nhtAuthetication is technically an "unencrypted" message as it contains some unencrypted data.
//This data is assumed to be missing the initial length int, encryption boolean, and message type.
//Therefore, it is not decrypted before being sent to this function.
//This function's job is to decrypt this thing (if possible). If it can't, it'll return false and the client will get yelled at for having the wrong password
var decryptionFailed = false;
try {
var encryptedBlockLength = unpacker.readInt();
Log.v("Length of encrypted block: "+encryptedBlockLength);
var decryptedData = await unpacker.decryptRestOfData();
Log.vv("Decrypted data: "+decryptedData.toString("hex"));
var decryptedUnpacker = new AirUnpacker(decryptedData);
Log.v("Data was decrypted! Checking if decryption was correct");
var transmissionCheck = decryptedUnpacker.readVariableLengthData();
Log.v("Transmission check: "+transmissionCheck.toString("hex"));
var installationId = decryptedUnpacker.readVariableLengthUTF8String();
Log.v("Installation ID: "+installationId);
var clientName = decryptedUnpacker.readVariableLengthUTF8String();
Log.v("Client name: "+clientName);
var platformName = decryptedUnpacker.readVariableLengthUTF8String();
Log.v("Platform name: "+platformName);
} catch (err) {
Log.w("Decryption failed (possibly a wrong password): "+err);
decryptionFailed = true;
}
//TODO: Properly use .bind() and get rid of globalThis
if (decryptionFailed || Buffer.compare(transmissionCheck, globalThis.transmissionCheck) != 0) {
//Ope, somebody has the wrong password. Or maybe the transmission check was wrong.
Log.e(clientName+" on "+platformName+" most likely tried to log in with the wrong password");
globalThis.transmissionCheck = null; //Reset the transmission check
var messagePacker = new AirPacker();
Log.v("Packing int (message type): nhtAuthetication: "+CommConst.nhtAuthentication);
messagePacker.writeInt(CommConst.nhtAuthetication); //nhtAuthentication is the message type
Log.v("Packing int (authentication status): Unauthorized: 1");
messagePacker.writeInt(CommConst.nstAuthenticationUnauthorized); //Authentication is unauthorized (wrong password)
Log.v("Packing unencrypted header");
messagePacker.writeHeader(false); //Write the header, this message isn't encrypted
Log.i("Sending client the authentication error message");
globalThis.connection.write(messagePacker.getBuffer());
return;
}
Log.i("Decryption successful!");
Log.i(clientName+" on "+platformName+" successfully authenticated to the server");
globalThis.authenticated = true;
globalThis.clientName = clientName;
globalThis.platformName = platformName;
globalThis.installationId = installationId;
responsePacker = new AirPacker();
Log.i("Sending nhtAuthentication response to client");
Log.v("Packing int (message type): nhtAuthentication: "+CommConst.nhtAuthentication);
responsePacker.writeInt(CommConst.nhtAuthentication); //Message type is nhtAuthentication
Log.v("Packing int (authentication status): nstAuthenticationOK: "+CommConst.nstAuthenticationOK)
responsePacker.writeInt(CommConst.nstAuthenticationOK); //Authentication status is nstAuthenticationOK
Log.v("Packing string (installation ID): "+ConversionDatabase.getInstallationID());
responsePacker.writeString(ConversionDatabase.getInstallationID()); //Installation GUID
//This installation-specific UUID is stored inside the ConversionDatabase, and is randomly generated if missing
Log.v("Packing string (device name): AirBridge");
responsePacker.writeString("AirBridge"); //Device name.
Log.v("Packing string (system version): 10.15.7");
responsePacker.writeString("10.15.7"); //Mac system version. AirBridge pretends that it is macOS Catalina (10.15.17)
Log.v("Packing string (AirMessage client version): 3.0.1");
responsePacker.writeString("3.0.1"); //AirMessage server software version (3.2)
Log.v("Encrypting message");
var encryptedWithHeader = await responsePacker.encryptAndWriteHeader();
Log.v("Sending encrypted message to client");
globalThis.connection.write(encryptedWithHeader); //Sends the data to the client
//Sets up event listeners for websocket pushes
this.websocketMessageListenerSMServer = SMServerWebsocket.addEventListener("message", handleWebsocketMessage);
this.websocketMessageListenerSMServer = SMServerWebsocket.addEventListener("read", handleMessageActivityStatus);
}.bind(this);
//DOES THE CLIENT EXPECT THE LATEST DATABASE ENTRY ID?? Looks like it doesn't I don't think
//Sends nhtIDUpdate (211) as int
// Pack int: CommConst.nhtIDUpdate
// Pack long: ID (Is this a ROWID?)
// Send the message
//Sends the ID as a long
var decryptAndProcess = async function (unpacker) {
var Log = new LogLib.Log("Client.js","decryptAndProcess");
Log.i("Decrypting message and processing...");
if (!globalThis.authenticated) {
Log.e("Not decrypting message because client isn't authenticated!");
return;
}
var decrypted = await unpacker.decryptRestOfData();
var decryptedunpacker = new AirUnpacker(decrypted);
var messageType = decryptedunpacker.readInt();
//TODO: ADD TRY/CATCH TO ALL OF THESE
try {
Log.i("Message NHT type: "+messageType); //TODO: Say Nht type here
// case CommConst.nhtTimeRetrieval -> handleMessageTimeRetrieval(client, unpacker); //201
if (messageType == CommConst.nhtTimeRetrieval) {
processNhtTimeRetrieval(decryptedunpacker);
}
// case CommConst.nhtIDRetrieval -> handleMessageIDRetrieval(client, unpacker);
else if (messageType == CommConst.nhtIDRetrieval) {
processNhtIdRetrieval(decryptedunpacker);
}
// case CommConst.nhtMassRetrieval -> handleMessageMassRetrieval(client, unpacker);
else if (messageType == CommConst.nhtMassRetrieval) {
processNhtMassRetrieval(decryptedunpacker);
}
// case CommConst.nhtConversationUpdate -> handleMessageConversationUpdate(client, unpacker);
else if (messageType == CommConst.nhtConversationUpdate) {
processNhtConversationUpdate(decryptedunpacker);
}
// case CommConst.nhtAttachmentReq -> handleMessageAttachmentRequest(client, unpacker);
else if (messageType == CommConst.nhtAttachmentReq) {
processNhtAttachmentRequest(decryptedunpacker);
}
//
// case CommConst.nhtLiteConversationRetrieval -> handleMessageLiteConversationRetrieval(client, unpacker)
else if (messageType == CommConst.nhtLiteConversationRetrieval) {
processNhtLiteConversationRetrieval(decryptedunpacker);
//TODO: What is different about lite retrieval
}
// case CommConst.nhtLiteThreadRetrieval -> handleMessageLiteThreadRetrieval(client, unpacker);
else if (messageType == CommConst.nhtLiteThreadRetrieval) {
processNhtLiteThreadRetrieval(decryptedunpacker);
}
//
// case CommConst.nhtCreateChat -> handleMessageCreateChat(client, unpacker);
else if (messageType == CommConst.nhtCreateChat) {
processNhtCreateChat(decryptedunpacker);
}
// case CommConst.nhtSendTextExisting -> handleMessageSendTextExisting(client, unpacker);
else if (messageType == CommConst.nhtSendTextExisting) {
processNhtSendTextExisting(decryptedunpacker);
}
// case CommConst.nhtSendTextNew -> handleMessageSendTextNew(client, unpacker);
else if (messageType == CommConst.nhtSendTextNew) {
processNhtSendTextNew(decryptedunpacker);
}
// case CommConst.nhtSendFileExisting -> handleMessageSendFileExisting(client, unpacker);
else if (messageType == CommConst.nhtSendFileExisting) {
processNhtSendFileExisting(decryptedunpacker);
}
// case CommConst.nhtSendFileNew -> handleMessageSendFileNew(client, unpacker);
else if (messageType == CommConst.nhtSendFileNew) {
processNhtSendFileNew(decryptedunpacker);
}
else {
Log.e("ERROR: Unknown NHT type: "+messageType);
}
} catch (err) {
Log.e("Error processing message: "+err);
}
}.bind(this);
//TODO: Use lite conversation retrieval
var handleWebsocketMessage = async function(messages) {
// console.log(messages);
var Log = new LogLib.Log("Client.js", "handleWebsocketMessage");
Log.i("Handling message from websocket");
// messages = SMServerAPI.fixFormattingForMultipleMessages(messages);
var stacked = await SMServerAPI.stackTapbacks(messages, handleOrphanedTapbacks);
if (stacked.length == 0) {
return; //Must have been an orphaned tapback, as those are handled separately in the handleOrphanedTapbacks function
}
console.log(stacked);
Log.v("Setting last-seen message time to "+stacked[0].unixdate);
// globalThis.clientLastSeenTime = ConversionDatabase.convertAppleDateToUnixTimestamp(messages[0]);
globalThis.clientLastSeenTime = stacked[0].unixdate;
var responsePacker = new AirPacker();
await responsePacker.packAllMessagesFromSMServer(stacked);
var encrypted = await responsePacker.encryptAndWriteHeader();
Log.i("Encrypted, sending message to client...");
globalThis.connection.write(encrypted);
}.bind(this);
//TODO: Get stickers working, not just as attachments
var sendInfoMessageToClient = async function(message_text) {
var Log = new LogLib.Log("Client.js","sendInfoMessageToClient");
Log.i("Sending informational message to client: "+message_text);
var responsePacker = new AirPacker();
Log.v("Packing synthesized message from AirBridge");
responsePacker.packAllMessagesFromSMServer([{
subject: '',
is_from_me: false,
text: message_text,
cache_has_attachments: false,
associated_message_type: 0,
date_read: 0,
service: 'iMessage',
associated_message_guid: '',
id: 'AirBridge',
item_type: 0,
group_action_type: 0,
date: ConversionDatabase.convertUnixTimestampToAppleDate(Date.now()),
guid: uuidv4(),
conversation_id: 'AirBridge',
ROWID: ConversionDatabase.getInfoMessageROWID(),
balloon_bundle_id: '',
tapbacks: []
}]);
Log.v("Encrypting message");
var encrypted = await responsePacker.encryptAndWriteHeader();
Log.v("Sending message");
globalThis.connection.write(encrypted);
}.bind(this);
//TODO: On run, send a ping to all clients. Not sure how to do this
var processNhtSendTextNew = async function(unpacker) {
var Log = new LogLib.Log("Client.js","processNhtSendTextNew");
var start_time = Date.now();
Log.i("Processing nhtSendTextNew");
var requestID = unpacker.unpackShort(); //Request ID to avoid collisions
Log.v("Request ID: "+requestID);
// String[] members = new String[unpacker.unpackArrayHeader()]; //The members of the chat to send the message to
var members = unpacker.unpackUTF8StringArray();
Log.v("Members: "+members);
// for(int i = 0; i < members.length; i++) members[i] = unpacker.unpackString();
var service = unpacker.readVariableLengthUTF8String();
Log.v("Service: "+service);
// String service = unpacker.unpackString(); //The service of the chat
var message = unpacker.readVariableLengthUTF8String();
Log.v("Message: "+message);
// String message = unpacker.unpackString(); //The message to send
var responsePacker = new AirPacker();
Log.v("Packing int nhtSendResult: "+CommConst.nhtSendResult);
responsePacker.packInt(CommConst.nhtSendResult);
Log.v("Packing short requestID: "+requestID);
responsePacker.packShort(requestID);
if (members.length > 1) {
sendInfoMessageToClient("Sorry, AirBridge doesn't support the creation of group chats (yet)");
Log.w("User tried to create a group chat, which isn't supported yet");
Log.v("Packing error type: "+CommConst.nstSendResultScriptError);
responsePacker.packInt(CommConst.nstSendResultScriptError);
Log.v("Packing error message: AirBridge doesn't support group creation at the moment :(");
responsePacker.packNullableString("AirBridge doesn't support group creation at the moment :(");
} else {
Log.v("User isn't trying to create a group chat, proceeding");
Log.v("Packing error type: 0");
responsePacker.packInt(0);
Log.v("Packing error message: null");
responsePacker.packNullableString(null);
var recipient = members[0];
if (ConversionDatabase.isPhoneNumber(recipient)) {
Log.v("Fromatting phone number: "+recipient);
recipient = ConversionDatabase.getInternationalPhoneNumberFormat(recipient);
Log.v("Filtered to "+recipient);
//This makes sure the phone number is in the correct format.
}
//TODO: Get the phone number format right here
Log.v("Sending text message \""+message+"\" to chat "+members[0]+" via SMServerAPI");
SMServerAPI.sendTextMessage(message, members[0]).then(() => {
Log.v("Text message callback reached, setting timeout for 400ms");
//TODO: Maybe wait until the websocket registers?
//I think this is outdated as it will update when the websocket fires
// setTimeout(function() {
// Log.v("Timeout complete, sending messages after "+start_time+" to client");
// // updateClientWithRecentMessages();
// sendLastMessageFromConversationToClient(members[0], start_time);
// //This happens once SMServer sends the message
// }, 400); //TODO: FIIIIX THIS??
});
}
Log.v("Encrypting response");
var encrypted = await responsePacker.encryptAndWriteHeader();
Log.i("Sending nhtSendResult to client");
globalThis.connection.write(encrypted);
}.bind(this);
var processNhtSendFileNew = async function(unpacker) {
//TODO: add a waitForNextMessageFromClient() function that is awaitable? Use websockets?
// Use it to wait for the next message from client
//NEXT STEPS: TODO: Figure out how to send a file here, like nhtFileExisting
}.bind(this);
//sendTextExisting or createChat
var processNhtCreateChat = async function(unpacker) {
var Log = new LogLib.Log("Client.js","processNhtCreateChat");
Log.i("Processing nhtCreateChat");
//Nothing is actually created, as conversation creation is handled automatically
//when a message is sent. Groups, however, present a challenge.
// short requestID = unpacker.unpackShort(); //The request ID to avoid collisions
var requestID = unpacker.unpackShort();
Log.v("Request ID: "+requestID);
// String[] chatMembers = new String[unpacker.unpackArrayHeader()]; //The members of this conversation
var chatMembers = unpacker.unpackUTF8StringArray();
Log.v("Chat members: "+chatMembers);
// for(int i = 0; i < chatMembers.length; i++) chatMembers[i] = unpacker.unpackString();
// String service = unpacker.unpackString(); //The service of this conversation
var service = unpacker.unpackString();
Log.v("Service: "+service);
//
// //Creating the chat
// Constants.Tuple<Integer, String> result = AppleScriptManager.createChat(chatMembers, service);
//
// //Sending a response
// sendMessageRequestResponse(client, CommConst.nhtCreateChat, requestID, result.item1, result.item2);
var responsePacker = new AirPacker();
// packer.packInt(header);
Log.v("Packing int nhtCreateChat: "+CommConst.nhtCreateChat);
responsePacker.packInt(CommConst.nhtCreateChat);
// packer.packShort(requestID);
Log.v("Packing short requestID: "+requestID);
responsePacker.packShort(requestID);
// packer.packInt(resultCode); //Result code
if (chatMembers.length > 1) {
Log.w("Client tried to create a group chat, which isn't supported right now :(");
Log.v("Sending info message to client: Sorry, AirBridge doesn't support creating group chats (yet)");
sendInfoMessageToClient("Sorry, AirBridge doesn't support creating group chats (yet)");
Log.v("Packing int (error type): nstSendResultScriptError: "+CommConst.nstSendResultScriptError)
responsePacker.packInt(CommConst.nstSendResultScriptError); //AirBridge doesn't support creating group chats (yet)
Log.v("Packing nullable string (error details): AirBridge doesn't support creating group chats (yet)");
responsePacker.packNullableString("AirBridge doesn't support creating group chats (yet)");
} else {
Log.v("Packing int: error type: "+0);
responsePacker.packInt(0);
Log.v("Packing nullable string (error details): null");
responsePacker.packNullableString(null);
}
// packer.packNullableString(details);
//
// dataProxy.sendMessage(client, packer.toByteArray(), true);
Log.v("Encrypting response");
var encrypted = await responsePacker.encryptAndWriteHeader();
Log.i("Sending nhtCreateChat result to client");
globalThis.connection.write(encrypted);
//
// return true;
//Error codes:
// public static final int nstCreateChatOK = 0;
// public static final int nstCreateChatScriptError = 1; //Some unknown AppleScript error
// public static final int nstCreateChatBadRequest = 2; //Invalid data received
// public static final int nstCreateChatUnauthorized = 3; //System rejected request to send message
}.bind(this);
var processNhtMassRetrieval = async function(unpacker) { //MassRetrievalANCHOR
var Log = new LogLib.Log("Client.js","processNhtMassRetrieval");
Log.i("Processing nhtMassRetrieval");
var requestID = unpacker.unpackShort();
Log.v("Request ID: "+requestID);
var filterMessagesByDate = unpacker.unpackBoolean();
Log.v("Filter messages by date: "+filterMessagesByDate);
var timeSinceMessages = 0; //Unix timestamp as the earliest date to download messages from
if (filterMessagesByDate) {
timeSinceMessages = unpacker.unpackLong();
}
Log.v("Find message since time: "+timeSinceMessages);
var downloadAttachments = unpacker.unpackBoolean();
Log.v("Download attachments: "+downloadAttachments);
var restrictAttachmentsDate = false; //The following will be updated if downloadAttachments == true
var timeSinceAttachments = -1;
var restrictAttachmentsSize = false;
var attachmentsSizeLimit = -1;
var attachmentFilterWhitelist = null; //Only download attachment files if on this list
var attachmentFilterBlacklist = null; //Don't download attachment files if they're on this list
var attachmentFilterDLOther = false; //Download attachment files if they're not on either list. (catch-all)
if (downloadAttachments) {
restrictAttachmentsDate = unpacker.unpackBoolean();
if (restrictAttachmentsDate) {
timeSinceAttachments = unpacker.unpackLong();
}
restrictAttachmentsSize = unpacker.unpackBoolean();
if (restrictAttachmentsSize) {
attachmentsSizeLimit = unpacker.unpackLong();
}
attachmentFilterWhitelist = unpacker.readUTF8StringArray();
attachmentFilterBlacklist = unpacker.readUTF8StringArray();
attachmentFilterDLOther = unpacker.unpackBoolean();
}
Log.v("Restrict attachments by date: "+restrictAttachmentsDate);
Log.v("Find attachments since time: "+timeSinceAttachments);
Log.v("Restrict attachments by size: "+restrictAttachmentsSize);
Log.v("Attachment size limit: "+attachmentsSizeLimit);
Log.v("Attachment filter whitelist: "+attachmentFilterWhitelist);
Log.v("Attachment filter blacklist: "+attachmentFilterBlacklist);
Log.v("Download attachments not on the above whitelist: "+attachmentFilterDLOther);
// return;
//sets up a MassRetrievalRequest.,
// MassRetrievalRequest adds a conversationInfo instance to the conversationInfoList
// Filter messages based on given restrictions if necessary (could do this before, using prefiltering in the SMServerAPI)
// sendMassRetrievalInitial()
// Packet index = 1
// Read message data chunk by chunk
// I think chunk sizes are just on an as-needed basis
// sendMassRetrievalMessages with the request ID, the packet index
// var conversations = await SMServerAPI.getConversationsAfterTime(timeSinceMessages);
// var conversations = await SMServerAPI.getAllConversations(); //Should this be time-restricted like above?
var conversations = await SMServerAPI.getConversationsAfterTime(timeSinceMessages);
Log.v("Getting all conversations from SMServer");
Log.vv(JSON.stringify(conversations));
// SMServer.getMessagesForOneConversationWhileConditionIsTrue(conversations, (message) => {
// //compare function
// }, onChunkFromSMServer);
//sendMassRetrievalInitial:
// Pack int: nhtMassRetrieval
// Pack short: Request ID
// Pack int: 0 (request index)
// Pack array header: Length of conversations
// For each conversation:
// writeObject() for the conversation
// Pack int: Message count
// Send the message
//We need to get all the messages first as the client wants to know how many there are
globalThis.clientLastSeenTime = Date.now(); //The client will be caught up to all messages before the current time
var all_messages = [];
Log.v("Looping through conversations");
for (var i = 0; i < conversations.length; i++) {
Log.v("Getting messages for "+conversations[i]+", filtered by time");
var conv_messages = await SMServerAPI.getMessagesForOneConversationWhileConditionIsTrue(conversations[i].chat_identifier, (message) => {
var unixstamp = ConversionDatabase.convertAppleDateToUnixTimestamp(message.date);
return unixstamp >= timeSinceMessages;
});
Log.v("Got messages for "+conversations[i].id+", adding to all_messages array");
Log.vv("Messages: "+JSON.stringify(conv_messages));
all_messages = all_messages.concat(conv_messages);
}
Log.v("Loop complete, got messages for every conversation");
// all_messages = [{
// group_action_type: 0,
// balloon_bundle_id: '',
// date_read: 645402658616994000,
// associated_message_guid: '',
// item_type: 0,
// cache_has_attachments: false,
// associated_message_type: 0,
// text: 'Test test',
// id: '[email protected]',
// guid: '1C2D60C6-379D-4EEB-9B0F-B1C75BC6ABDF',
// service: 'iMessage',
// is_from_me: false,
// subject: 'Pop pop!',
// ROWID: 2,
// date: 645402655814933000,
// tapbacks: [],
// conversation_id: "[email protected]"
// }];
Log.i("Packing conversations for nhtMassRetrieval");
var initialPacker = new AirPacker();
Log.v("Packing int (message type): nhtMassRetrieval: "+CommConst.nhtMassRetrieval);
initialPacker.packInt(CommConst.nhtMassRetrieval);
Log.v("Packing int (request ID): "+requestID);
initialPacker.packShort(requestID);
Log.v("Packing int (request index): "+0); //Always going to be the first one, as it's the initial
initialPacker.packInt(0); //Request index (xmass retrieval message 0, 1, 2, etc)
Log.v("Packing array header (number of conversations): "+conversations.length);
initialPacker.packArrayHeader(conversations.length);
for (var i = 0; i < conversations.length; i++) {
Log.v("Packing one conversation from SMServer: "+JSON.stringify(conversations[i]));
initialPacker.packOneConversationFromSMServer(conversations[i]);
}
//Pack int: Message count
Log.v("Packing number of messages: "+all_messages.length);
initialPacker.packInt(all_messages.length);
//Send the message
Log.v("Encrypting initialPacker");
var encrypted = await initialPacker.encryptAndWriteHeader();
Log.i("Initial nhtMassRetrieval response finished and encrypted, sending");
globalThis.connection.write(encrypted);
console.log(all_messages);
all_messages = await SMServerAPI.stackTapbacks(all_messages, handleOrphanedTapbacks);
var sendMessageChunk = async function(messages, packet_index) { //This is the callback that runs on each chunk
var Log = new LogLib.Log("Client.js","processNhtMassRetrieval>sendMessageChunk");
Log.i("Sending message chunk "+packet_index);
Log.v("Stacking tapbacks");
// var messagesWithTapbacks = await SMServerAPI.stackTapbacks(messages, handleOrphanedTapbacks);
var messagesWithTapbacks = messages;
//CHANGED: This is now handled above so we don't get orphaned tapbacks
var chunkPacker = new AirPacker();
// Pack int: nhtMassRetrieval
Log.v("Packing int (message type): nhtMassRetrieval: "+CommConst.nhtMassRetrieval);
chunkPacker.packInt(CommConst.nhtMassRetrieval);
// Pack short: Request ID
Log.v("Packing short (Request ID): "+requestID);
chunkPacker.packShort(requestID);
Log.v("Packing int (packet index): "+packet_index);
chunkPacker.packInt(packet_index); //Forgot about this
// Pack array header: Number of conversation items
Log.v("Packing array header (number of messages): "+messagesWithTapbacks.length);
chunkPacker.packArrayHeader(messagesWithTapbacks.length);
// For each conversation item, writeObject() for it
for (var i = 0; i < messagesWithTapbacks.length; i++) {
Log.vv("Packing message: "+JSON.stringify(messagesWithTapbacks[i]));
await chunkPacker.packMessageDataFromSMServer(messagesWithTapbacks[i]);
}
// Send the message
Log.v("Encrypting message");
var encrypted = await chunkPacker.encryptAndWriteHeader();
Log.i("Sending encrypted message chunk to client");
globalThis.connection.write(encrypted);
};
var chunk_size = 60;
var packetIndex = 1;
Log.v("Looping through messages and sending chunks");
for (var i = 0; i < all_messages.length; i += chunk_size) {
//TODO: Deal with orphaned tapbacks between loop cycles
var chunk = all_messages.slice(i, i + chunk_size);
Log.vv("Chunk: "+JSON.stringify(chunk));
Log.v("Sending chunk");
await sendMessageChunk(chunk, packetIndex);
Log.v("Sent chunk");
packetIndex++;
//TODO: Does this need to be awaited? Can we send them all at once instead of sequentially?
}
if (downloadAttachments) {
await SMServerAPI.ensureAttachmentFoldersExist();
// console.log(all_messages);
var attachment_message_candidates = all_messages.filter((item) => {
var unixstamp = ConversionDatabase.convertAppleDateToUnixTimestamp(item.date);
return (unixstamp >= timeSinceAttachments);
});
var attachments = SMServerAPI.extractAttachmentInfoFromMessages(attachment_message_candidates);
attachments = SMServerAPI.filterAttachments(attachments);
for (var i = 0; i < attachments.length; i++) {
// console.log(attachments[i]);
//continue the sending of the attachment
var mime_type_parts = attachments[i].mime_type.split("/");
var attachmentIsAllowed = attachmentFilterDLOther;
for (var j = 0; j < attachmentFilterWhitelist.length; j++) {
// console.log(attachmentFilterWhitelist[i]);
var whitelist_mime_type_parts = attachmentFilterWhitelist[j].split("/");
if (whitelist_mime_type_parts[0] == mime_type_parts[0] && (whitelist_mime_type_parts[1] == mime_type_parts[1] || whitelist_mime_type_parts[1] == "*")) {
//Makes sure the first part "image" or "application" and second parts "rtf" or "pdf" both match. The second part can also be an asterisk (*)
attachmentIsAllowed = true;
}
}
for (var j = 0; j < attachmentFilterBlacklist.length; j++) {
var whitelist_mime_type_parts = attachmentFilterBlacklist[j].split("/");
if (whitelist_mime_type_parts[0] == mime_type_parts[0] && (whitelist_mime_type_parts[1] == mime_type_parts[1] || whitelist_mime_type_parts[1] == "*")) {
//Makes sure the first part "image" or "application" and second parts "rtf" or "pdf" both match. The second part can also be an asterisk (*)
attachmentIsAllowed = false;
}
}
if (attachmentIsAllowed) { //TODO: What if the attachment was sent from AirBridge--AirBridge doesn't send MIME types. Does iMessage add them?
var localpath = await SMServerAPI.downloadAttachmentIfNecessary(attachments[i]);
var promiseStats = function(filename) {
return new Promise((resCb, rejCb) => {
fs.stat(filename, (err, stats) => {
if (err) {
rejCb(err);
} else {
resCb(stats);
}
});
});
}
var stats = await promiseStats(localpath);
var fileLength = stats.size;
if (attachmentsSizeLimit == -1 || fileLength < attachmentsSizeLimit) {
Log.v("Attachment "+attachments[i].filename+" is allowed because its mime type "+attachments[i].mime_type+" matches and so does the date");
await globalThis.sendMassRetrievalFileFromFileID(requestID, attachments[i].filename);
// break;
} else {
Log.v("Attachment "+attachments[i].filename+" is allowed because its size is too large");
}
} else {
Log.v("Attachment "+attachments[i].filename+" is not allowed because its mime type "+attachments[i].mime_type+" does not match");
}
}
}
// Asynchronous at same time as message retrieval: onAttachmentChunkLoaded
// First run = request index = 0
// Filter by date, size, etc
// Run sendMassRetrievalFileChunk with request ID, request index, filename, isLast, guid, data, length
// Request index ++
// Once done with everything, sendMessageHeaderOnly() with nhtMassRetrievalFinish (encrypted)
// TODO: Cancel if the connection has closed?
//sendMassRetrievalMessages:
// Pack int: nhtMassRetrieval
// Pack short: request ID
// Pack int: packetIndex
// Pack array header: Number of conversationitems in the list
// For each conversationItem, writeObject() for it
// Send the message
//sendMassRetrievalFileChunk (send this for each attachment. Send the request ID and index along with filename)
// Pack int: nhtMassRetrievalFile
// Pack short: request ID
// Pack int: request index
// If the request index == 0, pack a string: filename
// Pack boolean: Is this the last chunk?
// Pack string: GUID of file
// Pack payload: Chunk of data, of the length that the client asked for earlier
// Send the message
//This is the final piece--just letting the client know that the process is complete
Log.i("Messages and attachments finished sending, waiting 5000ms to send finish message");
setTimeout(async function() { //Waits to make sure the client got all the messages (sending this too early causes an error)
Log.i("Sending mass retrieval finish message");
var finalResponsePacker = new AirPacker();
Log.v("Packing int (message type): nhtMassRetrievalFinish: "+CommConst.nhtMassRetrievalFinish);
finalResponsePacker.packInt(CommConst.nhtMassRetrievalFinish);
Log.v("Encrypting");
var encrypted = await finalResponsePacker.encryptAndWriteHeader();
Log.v("Sending encrypted nhtMassRetrievalFinish message. Mass retrieval is complete!!!");
globalThis.connection.write(encrypted);
}, 5000);
}.bind(this);
//Looks like each time the server returns the list of messages, the client tacks them on the end
var sendLastMessageFromConversationToClient = async function(conversation_id, start_time) {
globalThis.clientLastSeenTime = Date.now();
var Log = new LogLib.Log("Client.js","sendLastMessageFromConversationToClient");
Log.i("Sending last few messages to client after "+start_time);
Log.v("Getting last few messages from SMServer");
var lastMessages = await SMServerAPI.getLastMessageFromConversation(conversation_id, start_time);
Log.vv("Messages from time frame: "+JSON.stringify(lastMessages));
Log.v("Stacking tapbacks");
lastMessages = await SMServerAPI.stackTapbacks(lastMessages, handleOrphanedTapbacks);
var responsePacker = new AirPacker();
Log.v("Packing last "+lastMessages.length+" messages from SMServer: ");
await responsePacker.packAllMessagesFromSMServer(lastMessages);
Log.v("Encrypting messages from SMServer");
var encryptedWithHeader = await responsePacker.encryptAndWriteHeader();
Log.i("Message encrypted, sending");
globalThis.connection.write(encryptedWithHeader);
}.bind(this);
var handleOrphanedTapbacks = async function (tapback_messages) {
var Log = new LogLib.Log("Client.js","handleOrphanedTapbacks");
if (tapback_messages.length == 0) {
return; //Nothing to do here
}
Log.i("Handling "+tapback_messages.length+" orphaned tapbacks");
Log.vv(JSON.stringify(tapback_messages));
var responsePacker = new AirPacker();
//Pack int: nhtModifierUpdate
Log.v("Packing int (message type): nhtModifierUpdate: "+CommConst.nhtModifierUpdate);
responsePacker.packInt(CommConst.nhtModifierUpdate);
//For each tapback
Log.v("Packing array header (number of tapbacks): "+tapback_messages.length);
responsePacker.packArrayHeader(tapback_messages.length);
//Pack the TapbackModifierInfo
for (var i = 0; i < tapback_messages.length; i++) {
Log.v("Packing tapback "+i);
responsePacker.packTapback(tapback_messages[i]);
}
// Pack the item type:
// Pack a string: The message GUID
// Pack the message index (0, 1, 2, etc. This is the p:0/whatever)
// Pack a nullable string: Sender
// Pack boolean: isAddition
// Pack int: Tapback type
Log.v("Encrypting response");
var encrypted = await responsePacker.encryptAndWriteHeader();
//Send the message
Log.i("Sent encrypted response to client");
globalThis.connection.write(encrypted);
}.bind(this);
var handleMessageActivityStatus = async function(update) {
var Log = new LogLib.Log("Client.js","handleMessageActivityStatus");
Log.v(JSON.stringify(update));
var updates = [update];
// if (messages.length == 0) {
// return; //Nothing to do here
// }
var targetGUID = update.guid;
var message = null;
// await SMServerAPI.getAllMessagesWhileConditionIsTrue;
// NEXT STEPS: Search for and find the target message GUID and get the date read
var message = await SMServerAPI.findMessageByGUID(update.guid);
console.log(message);
// Then send it to the client via AirPacker.packActivityStatus()
Log.i("Handling "+updates.length+" activity status (read) updates");
var responsePacker = new AirPacker();
//Pack int: nhtModifierUpdate
Log.v("Packing int (message type): nhtModifierUpdate: "+CommConst.nhtModifierUpdate);
responsePacker.packInt(CommConst.nhtModifierUpdate);
//For each tapback
Log.v("Packing array header (number of activity status updates): "+updates.length);
responsePacker.packArrayHeader(updates.length);
//Pack the TapbackModifierInfo
for (var i = 0; i < updates.length; i++) {
Log.v("Packing tapback "+i);
responsePacker.packActivityStatus(message);
}
// Pack the item type:
// Pack a string: The message GUID
// Pack the message index (0, 1, 2, etc. This is the p:0/whatever)
// Pack a nullable string: Sender
// Pack boolean: isAddition
// Pack int: Tapback type
Log.v("Encrypting response");
var encrypted = await responsePacker.encryptAndWriteHeader();
//Send the message
Log.i("Sent encrypted response to client");
globalThis.connection.write(encrypted);
}.bind(this);
var processNhtTimeRetrieval = async function(unpacker) {
var Log = new LogLib.Log("Client.js","processNhtTimeRetrieval");
Log.i("Processing nhtTimeRetrieval");
var timeLower = unpacker.readLong();
Log.v("Time lower bound: "+timeLower+" ("+new Date(timeLower)+")");
var timeUpper = unpacker.readLong();
Log.v("Time upper bound: "+timeUpper+" ("+new Date(timeUpper)+")");
globalThis.clientLastSeenTime = timeUpper;
Log.v("Getting messages from time interval and stacking tapbacks");
var messages = await SMServerAPI.getAllMessagesFromSpecifiedTimeInterval(timeLower, timeUpper);
messages = await SMServerAPI.stackTapbacks(messages, handleOrphanedTapbacks);
Log.vv("Messages with stacked tapbacks: "+messages);
Log.v("Filtering messages by timeLower");
messages.filter(item => ConversionDatabase.convertAppleDateToUnixTimestamp(item.date) > timeLower);
//TODO: WHAT DOES THIS DOO?
//TODO: Should this be timeUpper?
//TODO: Implement nhtModifierUpdate for orphaned tapbacks
// Maybe use a callback that passes in orphaned tapbacks?
// messages = [{
// "group_action_type": 0,
// "id": "[email protected]",
// "associated_message_type": 0,
// "item_type": 0,
// "ROWID": 181,
// "balloon_bundle_id": "",
// "is_from_me": true,
// "associated_message_guid": "",
// "text": "test with attachments",
// "guid": "27454179-A3FD-4CFD-8A00-6C51F5D06764",
// "service": "iMessage",
// "attachments": [
// {
// "mime_type": "image/jpeg",
// "filename": "Attachments/0e/14/9F7813EE-27F9-4B6C-B065-97EB93EB1B45/64707785579__167BE7D7-C297-41ED-9BC3-7FD702817586.JPG"
// }
// ],
// "cache_has_attachments": true,
// "date_read": 0,
// "date": 647077862428000000,
// "subject": "Suuubject",
// "conversation_id": "[email protected]",
// "tapbacks": [{
// "associated_message_type": 2004,
// "associated_message_guid": 'p:0/688FB450-C715-4914-9D2F-A73F6FDB7BE7'
// //Sender is null if it's the user sending the tapback
// }]
// }];
var responsePacker = new AirPacker();
Log.v("Packing messages from SMServer");