-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSMServerAPI.js
1245 lines (1067 loc) · 57.2 KB
/
SMServerAPI.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 https = require('https');
const fetch = require('node-fetch');
const fs = require('fs');
const { URLSearchParams } = require('url');
const ConversionDatabase = require('./conversionDatabase.js');
const LogLib = require("./Log.js");
const FormData = require('form-data');
const SettingsManager = require("./settingsManager.js");
// Log.setSender("SMServerAPI.js");
// const SERVER_IP = "192.168.1.33";
// var SERVER_IP = SettingsManager.readSetting("SMSERVER_IP");
// const SERVER_PORT = "8741";
// const SERVER_PASSWORD = "toor";
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
//TODO: WHY IS WEBSOCKET ATTACHMENTS NOT WORKING???
//TODO: Auto-authenticate if a request fails due to no authentication
async function SMServerFetch(path, indata, emptyResponseIsOk) {
var SERVER_IP = await SettingsManager.readSetting("SMSERVER_IP");
var SERVER_PORT = await SettingsManager.readSetting("SMSERVER_PORT");
var SERVER_PASSWORD = await SettingsManager.readSetting("SMSERVER_PASSWORD");
var Log = new LogLib.Log("SMServerAPI.js","SMServerFetch");
//TODO: DEAL WITH RESPONSE CODES AS OUTLINED IN SMSERVER API
//TODO: HANDLE ECONNRESET: Error: socket hang up
//TODO: Check if SMServer certificate stays the same across installs?
//Not sure if the Node version on Cydia supports fetch, so we're writing our own fetch function!
//TODO: If we get ECONNRESET, wait and try again
path += "?";
for (property in indata) {
if (indata.hasOwnProperty(property)) {
path += property + "=" + encodeURIComponent(indata[property]) + "&";
// console.log(property);
}
}
path = path.slice(0, -1); //Removes the "&" from the end
var makeRequest = function(path) {
return new Promise((resCb, rejCb) => {
Log.v("Making request to "+path);
var options = {
host: SERVER_IP,
port: SERVER_PORT,
path: path
};
callback = function(response) {
var str = '';
//another chunk of data has been received, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been received, so we just print it out here
response.on('end', function () {
Log.v("Request finished successfully, parsing...");
var responseIsEmpty = (str == "" || str == undefined);
// Log.w("Response is empty: "+responseIsEmpty);
if (emptyResponseIsOk && responseIsEmpty) {
resCb({});
return; //Stops evaluating errors
} else {
try {
var parsed = JSON.parse(str);
resCb(parsed);
} catch (err) {
Log.e("Couldn't parse JSON: "+str);
//TODO: Test what happens if the password is wrong and handle that error
rejCb("Error: Couldn't parse JSON: "+parsed);
}
}
});
}
//There's no way SMServer has a signed certificate, so this is used to disable certificate checking.
//SMServer doesn't work on HTTP for some reason, so we must deal with its self-signed cert.
//This would be really dangerous, but seeing as we're only talking to localhost there's not much that can MITM this.
var req = https.request(options, callback);
req.end();
req.on('error', function(e) {
if (emptyResponseIsOk) {
//do nothing
} else {
rejCb(e);
}
});
});
}
var response = null;
var requestSuccessful = false;
for (var i = 0; i < 5; i++) {
try {
var response_try = await makeRequest(path);
response = response_try;
requestSuccessful = true;
break;
} catch (err) {
if (err.code == "ECONNREFUSED") {
Log.w("Connection to "+SERVER_IP+" was refused. SMServer could be busy or offline. Retrying in 5s...")
} else {
Log.e(err+". Retrying in 5s...");
}
}
}
if (!requestSuccessful) {
Log.e("Request was unsuccessful after trying multiple times. See above warning for details");
throw "Request unsuccessful";
}
// return await makeRequest(path);
return response;
}
// async function SMServerFetchFile(attachment_data, indata) {
//
// }
async function SMServerFetchPost(path, indata) {
var SERVER_IP = await SettingsManager.readSetting("SMSERVER_IP");
var SERVER_PORT = await SettingsManager.readSetting("SMSERVER_PORT");
var SERVER_PASSWORD = await SettingsManager.readSetting("SMSERVER_PASSWORD");
var Log = new LogLib.Log("SMServerAPI.js","SMServerFetchPost");
//Data must be sent in as MULTIPART/FORM-DATA
//Encode everything with encodeURIComponent, so spaces replace with %20
return new Promise((resCb, rejCb) => {
var options = {
host: SERVER_IP, //TODO: Make this a constant? It might end up being localhost, though
port: SERVER_PORT,
path: path
};
const params = new URLSearchParams();
for (property in indata) {
if (indata.hasOwnProperty(property)) {
// formData[property] = encodeURIComponent(indata[property]);
params.append(property, encodeURIComponent(indata[property])); //DOES THIS NEED TO BE URI ENCODED???
}
}
Log.v("Sending a post request to "+path);
fetch('https://'+SERVER_IP+':'+SERVER_PORT+path, {method: 'POST', body: params}).then(res => res.text()).then(text => console.log(text));
//TODO: DEAL WITH HTTP ERROR CODES
});
}
//TODO: Auto-configure SMServer to use a password that works with AirBridge by digging through the files?
// What about people who want to use SMServer's web interface too?
exports.fetch = fetch;
exports.SMServerFetch = SMServerFetch;
var authenticated = false;
exports.authenticate = async function() {
var Log = new LogLib.Log("SMServerAPI.js","authenticate");
Log.v("Authenticating to SMServer");
//TODO: Make a big scene if authentication doesn't work out
//Such as if SMServer is unreachable
var password = await SettingsManager.readSetting("SMSERVER_PASSWORD");
authenticated = await SMServerFetch("/requests", {password: password});
if (authenticated == false) {
Log.e("SMServer authentication failed. Check your SMServer password.");
}
return authenticated;
//TODO: Load PFX certificate if possible.
//
}
var fsAccessPromise = function(path) {
return new Promise(function(resolve, reject) {
fs.access(path, resolve);
});
}
var fsCreateDirPromise = function(path) {
return new Promise(function(resolve, reject) {
fs.mkdir(path, resolve);
});
}
var ensureFolderExists = async function(path) {
var folderAccess = await fsAccessPromise(path);
if (folderAccess) {
if (folderAccess.code == 'ENOENT') {
//Create the file
await fsCreateDirPromise(path);
} else {
Log.w("Couldn't access "+path+" folder: "+JSON.stringify(folderAccess));
}
}
return path;
}
exports.ensureAttachmentFoldersExist = async function() {
var Log = LogLib.Log("SMServerAPI.js", "ensureAttachmentFoldersExist");
await ensureFolderExists("./attachment_cache");
await ensureFolderExists("./sent_attachment_cache");
}
exports.downloadAttachmentIfNecessary = async function(attachment_info) {
var Log = new LogLib.Log("SMServerAPI.js", "downloadAttachmentIfNecessary");
var SERVER_IP = await SettingsManager.readSetting("SMSERVER_IP");
var SERVER_PORT = await SettingsManager.readSetting("SMSERVER_PORT");
var SERVER_PASSWORD = await SettingsManager.readSetting("SMSERVER_PASSWORD");
await exports.ensureAttachmentFoldersExist();
//https://192.168.1.46:8741/data?path=Attachments/03/03/8398059F-C566-4721-A387-1A63546C0D2C/64642773570__2531BEFC-FD22-4C4C-B5E8-554CF87FC3F1.JPG
//TODO: Check if SMServer certificate stays the same across installs?
//Not sure if the Node version on Cydia supports fetch, so we're writing our own fetch function!
//TODO: If we get ECONNRESET, wait and try again
//TODO: Functionify this, instead of sharing code between SMServerFetch and SMServerFetchFile
//TODO: Keep track of downloaded attachments in conversionDatabase
//TODO: If the attachment path exists, don't redownload it
// console.log("filename:"+attachment_info.filename);
console.log("Looking up "+attachment_info.filename);
//TODO: NEXT STEPS: Create the attachment_cache and sent_attachment_cache folders if they don't exist
var savedFilePathIfExists = ConversionDatabase.checkIfAttachmentAlreadySaved(attachment_info.filename);
Log.v("Saved file path (if the file exists): "+savedFilePathIfExists);
if (savedFilePathIfExists) { //This is undefined if it doesn't exist
//Check if the file exists. (If it doesn't, redownload it)
Log.v("File exists, returning with path "+savedFilePathIfExists);
if (fs.existsSync("./attachment_cache/"+savedFilePathIfExists)) {
Log.v("Saved file exists! Using path of existing file.");
return "./attachment_cache/"+savedFilePathIfExists;
} else {
Log.w("Looks like the saved attachment was deleted. Re-downloading...");
}
}
// const downloadedPath = await async function(url) {
var savePath = "./attachment_cache/"+ConversionDatabase.getAttachmentSavePath(attachment_info.filename);
Log.v("Will download file to "+savePath+". Fetching...");
// var fetchTimeout = setTimeout()
const res = await fetch("https://"+SERVER_IP+":"+SERVER_PORT+"/data?path="+encodeURIComponent(attachment_info.filename));
Log.v("Data fetched, sending to fileStream");
//TODO: Add indata conversion and put that in the fetch function
const fileStream = fs.createWriteStream(savePath);
var downloadedPath = await new Promise((resolve, reject) => { //before it was just "await new Promise..."
Log.v("Downloading file from SMServer:"+attachment_info.filename);
//TODO: Error handling if SMServer goes down or whatever
res.body.pipe(fileStream); //We need this!
res.body.on("error", (info) => {
Log.e("Error downloading file: "+info);
rejCb(info);
});
// fileStream.on("finish", resolve);
fileStream.on("finish", () => {
Log.v("File downloaded and saved to "+savePath);
resolve(savePath); //this sets downloadedPath above
});
});
// };
return downloadedPath;
}
//TODO: Whenever messages are downloaded, keep track of attachment paths!!
//TODO: Only download attachments if the script is not running on the iPhone
//TODO: When filtering messages, remove zero-width spaces
//TODO: Create a function that makes each message unique by inserting zero-width spaces
// Only really need to do this for messages sent from AM, as those are the only ones without GUIDs
exports.sendTextMessage = async function(text, chatid) { //TODO: Figure out how to upload photos and send them.
var Log = new LogLib.Log("SMServerAPI.js","sendTextMessage");
//Chatid can also be a phone number, but NEEDS to be in international format (ex. +11234567890)
Log.v("Sending text message to "+chatid);
if (!authenticated) {
Log.e("Cannot send text messages due to not being authenticated with SMServer");
throw 'Error: Cannot send text message due to not being authenticated with SMServer'
return;
}
//data should look something like this:
// {
// text: "This is the body of the text message",
// subject: "Subject line",
// chat: "1234567890", //Chat ID
// photos: "/var/mobile/Media/whatever.png", //Photo path on the phone
// attachments: 123 //Somehow files are sent here. I assume it's using the regular path?
// }
// text = '😀'; //Has the fancy unicode zero-width space
Log.v("Sending "+text+" to "+chatid);
SMServerFetchPost('/send', {
text: text,
subject: "",
chat: chatid
});
// console.log("\n\n\n\nMESSAGE SENTtTT");
//TODO: ADD A CRAP TON OF ERROR HANDLING
}
exports.sendTapbackGivenMessageText = async function(messageText, chatID, tapbackCode) { //TODO: Are chat IDs required?
var Log = new LogLib.Log("SMServerAPI.js","sendTapbackWithMessageText");
//We need to get an associated message GUID
// var searchResults = (await SMServerFetch("/requests", {search: messageText, search_case: false, search_gaps: false, search_group: "time"})).matches.texts;
var i = 95; //TODO: Make a function to get a chunk of messages from SMServer
var targetMessage = null;
var searchResults = await exports.getMessagesForOneConversationWhileConditionIsTrue(chatID, (message) => {
// console.log(message.text);
i -= 1;
if (i < 0) {
// console.log("I is 0, returning");
return false;
}
var messageIsNotTapback = (message.associated_message_guid == "" || message.associated_message_guid == undefined);
// if (message.text.indexOf(messageText) > -1 && messageIsNotTapback) {
if (message.text.trim() === messageText.trim() && messageIsNotTapback) {
//TODO: Get rid of newlines in the message text we're matching against.
//TODO: Maybe
targetMessage = message;
return false;
}
return true;
});
//TODO: If user wants to remove a tapback, stack tapbacks and find the one the user sent (is_from_me: true) and get the type. Remove it first.
// Also do this if a tapback exists??
//TODO: (Test with iPhone 4--why is the tapback sent a bunch of times?)
if (targetMessage == null) {
return false; //TODO: Handle this error if the message wasn't found
}
// searchResults.filter((message) => {
// return (message.)
// })
console.log(targetMessage);
await exports.sendTapback(tapbackCode, targetMessage.guid, false);
// exports.sendTapback(mostRecentResult)
//TODO: Wait, search doesn't return a GUID!!
}
exports.sendTapback = async function(tapbackType, associated_message_guid, remove_tap) { //TODO: Need a remove option?
await SMServerFetch("/send", {tapback: tapbackType, tap_guid: associated_message_guid, remove_tap: remove_tap}, true);
}
//TODO: Message does not show up when sending a video from other device
//TODO: What about message text???
exports.sendFile = async function(fileName, fileData, chatid, text) {
var SERVER_IP = await SettingsManager.readSetting("SMSERVER_IP");
var SERVER_PORT = await SettingsManager.readSetting("SMSERVER_PORT");
var SERVER_PASSWORD = await SettingsManager.readSetting("SMSERVER_PASSWORD");
await exports.ensureAttachmentFoldersExist();
var Log = new LogLib.Log("SMServerAPI.js","sendFile");
//TODO: Large files fail!!!!!!!!!!!!!!!!!
// Log.w("File size is "+fileData.length+" bytes");
//This is 1.96 MB
//TODO: Implement message text
// TODO: Figure out why file-receiving isn't working for pushing nhtMessageUpdate, but it works on message sync!!
// fs.writeFileSync("test.png", fileData);
// fileData = fs.readFileSync("C:/Users/aweso/Downloads/pcpartpicker.com_list_.png");
//TODO: What about multiple attachments??
var Log = new LogLib.Log("SMServerAPI.js","sendTextMessage");
//Chatid can also be a phone number, but NEEDS to be in international format (ex. +11234567890)
Log.v("Sending file to "+chatid);
if (!authenticated) {
Log.e("Cannot send text messages due to not being authenticated with SMServer");
throw 'Error: Cannot send text message due to not being authenticated with SMServer'
return;
}
var form = new FormData();
var buffer = fileData;
form.append('attachments', buffer, {
// contentType: 'image/png',
// contentType: 'application/octet-stream',
name: 'file',
filename: fileName
});
form.append('chat', chatid);
// form.append('text', 'Heyyy this is a test yo');
//data should look something like this:
// {
// text: "This is the body of the text message",
// subject: "Subject line",
// chat: "1234567890", //Chat ID
// photos: "/var/mobile/Media/whatever.png", //Photo path on the phone
// attachments: 123 //Somehow files are sent here. I assume it's using the regular path?
// }
Log.v("Sending file to "+chatid);
// SMServerFetchPost('/send', {
// text: text,
// subject: "",
// chat: chatid
// });
//TODO: Roll this into SMServerFetchPost (i.e. make SMServerFetchPost work with files too?)
return new Promise((resCb, rejCb) => {
// var form = new FormData();
// form.append('attachments', fileData, {knownLength: fileData.length});
path = "/send";
var options = {
host: SERVER_IP, //TODO: Make this a constant? It might end up being localhost, though
port: SERVER_PORT,
path: path
// attachments: [fileData]
};
var file = [fileName, fileData, 'image/png']; //TODO: Find the MIME type
console.log(options);
const params = new URLSearchParams();
// indata = {
// "chat": chatid,
// "text": "Heyy, this a file test is",
// "attachments": [fileData]
// }
//
// for (property in indata) {
// if (indata.hasOwnProperty(property)) {
// // formData[property] = encodeURIComponent(indata[property]);
// params.append(property, encodeURIComponent(indata[property])); //DOES THIS NEED TO BE URI ENCODED???
// }
// }
Log.v("Sending a post request to "+path);
//TODO: Does this need a "Content-length" attr in the headers: {} part next to method: 'POST', ???
fetch('https://'+SERVER_IP+':'+SERVER_PORT+path, {method: 'POST', body: form}).then(res => res.text()).then(text => console.log(text));
//TODO: DEAL WITH HTTP ERROR CODES
});
//TODO: Slice up the file data and send it in multiple passes so SMServer doesn't get confused?
}
exports.getListOfChats = async function(num_chats) {
var Log = new LogLib.Log("SMServerAPI.js","getListOfChats");
Log.v("Getting list of chats");
if (num_chats == undefined) {
var num_chats = 99999; //Number of chats to search through. Needs to be something ridiculously large.
}
var data = await SMServerFetch("/requests", { chats: num_chats });
Log.vv(JSON.stringify(data));
// console.log(data);
return data;
}
//TODO: On first connect, assign GUIDs for every conversation?
//TODO: Add a getAllMessagesWhileConditionIsTrue() method that takes a compare
//function and keeps downloading older and older messages until it is satisfied or
//runs out of messages? Useful for finding time_lower and tracing tapbacks to their
//original message
//TODO: Add a function that formats an SMServer message correctly--takes in an existing message from SMServer and adds "conversation_id" and "tapbacks":[]
//TODO: Keep track of last client request upper bound and check for new messages and push them?
exports.getMessagesForOneConversationWhileConditionIsTrue = async function(conversation, pre_filter_fn, chunk_callback) {
var Log = new LogLib.Log("SMServerAPI.js","getMessagesForOneConversationWhileConditionIsTrue");
Log.v("Getting messages for one conversation while condition is true: "+conversation);
//TODO: Add a callback argument that returns data as it is available, instead of waiting for it all to finish
//This function continuously gets messages from SMServer until pre_filter_fn returns false.
//Postfiltering is done by the parent function
//TODO: Check for duplicates!
//THE FOLLOWING IS UNTESTED
//time_lower and time_upper are both in UNIX seconds
var messages = [];
var filtered_messages = [];
var offset = 0; //How far back to start retrieving messages
var chunkSize = 100;
var continueLoop = true;
//So if we don't get all
while (continueLoop) {
var results = await SMServerFetch("/requests", {messages: conversation, num_messages: 100, read_messages: false, messages_offset: offset});
Log.v("Got "+chunkSize+" results from SMServer, checking to see if they all meet the criteria");
// if (results.texts.length == 0) { //results.texts[results.texts.length - 1] was failing here
// break; //If this request batch returns an empty list (i.e. exactly 100 messages in a chat), the loop ends as we're at the end.
// }
// messages = results.texts.concat(messages); //Adds the results
offset += chunkSize;
// console.log("\n");
// console.log(results);
// var timeOfEarliestMessage = ConversionDatabase.convertAppleDateToUnixTimestamp(results.texts[results.texts.length - 1].date);
//Filtering is now integrated into this loop
//This loop performs pre_filter_fn on the results SMServer has returned (for this chunk only).
//If pre_filter_fn returns false for any function in the chunk we just received,
var chunk_messages = [];
Log.v("Testing each message against the compare callback function");
for (var i = 0; i < results.texts.length; i++) {
var current_message = results.texts[i];
if (pre_filter_fn(current_message)) {
current_message.conversation_id = conversation;
chunk_messages.push(current_message);
} else {
// console.log("Prefilter function returned false!");
Log.v("Prefilter function returned false, end of conditional search!");
continueLoop = false;
break; //Stops counting messages after pre_filter_fn returns false
}
}
messages = messages.concat(chunk_messages);
if (chunk_callback) { //chunk_callback could be undefined
chunk_callback(chunk_messages);
}
if (results.texts.length < chunkSize) { //This happens if we are at the very beginning of the conversation and have downloaded all messages.
Log.v("Found end of conversation, stopping the loop");
// console.log("Results length is less than our chunk size");
continueLoop = false;
}
// console.log("Length of results is "+results.length+" vs "+chunkSize);
}
//TODO: What if we have an orphaned tapback at the beginning of the message query?
//TODO: Maybe return the prefiltered list, as that can be useful to check if a tapback on an older message
// was added at the very end.
// console.log("Does htis work at all?????????????????????");
//Now do filtering so only the messages within the specified time frame exactly get returned
// var filtered = messages.filter((item) => {
// //return true if it should be kept
// var unixstamp = ConversionDatabase.convertAppleDateToUnixTimestamp(item.date);
// console.log("Filterring!");
// if (unixstamp >= time_lower && unixstamp <= time_upper) {
// console.log(item.text+" matches the requirements!");
// } else {
// console.log(item.text+": "+new Date(unixstamp * 1000)+" is not in the correct timeframe")
// }
// return unixstamp >= time_lower && unixstamp <= time_upper;
// });
//TODO: Filter out tapbacks, digital touch, etc, and maybe associate with their parent messages in the future (instead of individual messages)
//Anything with no text and no subject, or an associated_message_guid, or a balloon_bundle_id
// console.log("messages: "+messages);
messages = exports.fixFormattingForMultipleMessages(messages, conversation);
return messages;
}
exports.getAllMessagesWhileConditionIsTrue = async function(pre_filter_fn, chunk_callback) {
var Log = new LogLib.Log("SMServerAPI.js","getMessagesForAllConversationsWhileConditionIsTrue");
Log.v("Getting all messages while condition is true");
//TODO: Add a callback argument that returns data as it is available, instead of waiting for it all to finish
//This function continuously gets messages from SMServer until pre_filter_fn returns false.
//Postfiltering is done by the parent function
//TODO: Check for duplicates!
var conversations_json = await exports.getAllConversations();
var conversations = [];
for (var i = 0; i < conversations_json.length; i++) {
conversations.push(conversations_json[i].chat_identifier);
}
//THE FOLLOWING IS UNTESTED
//time_lower and time_upper are both in UNIX seconds
var messages = [];
var filtered_messages = [];
var offset = 0; //How far back to start retrieving messages
var chunkSize = 100;
var continueLoop = true;
//So if we don't get all
while (continueLoop) {
var results = await SMServerFetch("/requests", {messages: conversations.join(","), num_messages: 100, read_messages: false, messages_offset: offset});
Log.v("Got "+chunkSize+" results from SMServer, checking to see if they all meet the criteria");
// if (results.texts.length == 0) { //results.texts[results.texts.length - 1] was failing here
// break; //If this request batch returns an empty list (i.e. exactly 100 messages in a chat), the loop ends as we're at the end.
// }
// messages = results.texts.concat(messages); //Adds the results
offset += chunkSize;
// console.log("\n");
// console.log(results);
// var timeOfEarliestMessage = ConversionDatabase.convertAppleDateToUnixTimestamp(results.texts[results.texts.length - 1].date);
//Filtering is now integrated into this loop
//This loop performs pre_filter_fn on the results SMServer has returned (for this chunk only).
//If pre_filter_fn returns false for any function in the chunk we just received,
var chunk_messages = [];
Log.v("Testing each message against the compare callback function");
for (var i = 0; i < results.texts.length; i++) {
var current_message = results.texts[i];
if (pre_filter_fn(current_message)) {
current_message.conversation_id = "AirBridge"; //Not from AirBridge, but this is just to give it a conversation to attach to
//This method shouldn't be used if you need the conversation ID (IDs are not added
//from /requests?messages, so the best we can do is loop through each conversation and
//add the data after the fact.) This function ignores conversation IDs but pretends that
//these messages are from AirBridge so if they get inadvertently sent to the client the client
//doesn't freak out if the conversation wasn't found.
chunk_messages.push(current_message);
} else {
// console.log("Prefilter function returned false!");
Log.v("Prefilter function returned false, end of conditional search!");
continueLoop = false;
break; //Stops counting messages after pre_filter_fn returns false
}
}
messages = messages.concat(chunk_messages);
if (chunk_callback) { //chunk_callback could be undefined
chunk_callback(chunk_messages);
}
if (results.texts.length < chunkSize) { //This happens if we are at the very beginning of the conversation and have downloaded all messages.
Log.v("Found end of conversation, stopping the loop");
// console.log("Results length is less than our chunk size");
continueLoop = false;
}
// console.log("Length of results is "+results.length+" vs "+chunkSize);
}
//TODO: What if we have an orphaned tapback at the beginning of the message query?
//TODO: Maybe return the prefiltered list, as that can be useful to check if a tapback on an older message
// was added at the very end.
// console.log("Does htis work at all?????????????????????");
//Now do filtering so only the messages within the specified time frame exactly get returned
// var filtered = messages.filter((item) => {
// //return true if it should be kept
// var unixstamp = ConversionDatabase.convertAppleDateToUnixTimestamp(item.date);
// console.log("Filterring!");
// if (unixstamp >= time_lower && unixstamp <= time_upper) {
// console.log(item.text+" matches the requirements!");
// } else {
// console.log(item.text+": "+new Date(unixstamp * 1000)+" is not in the correct timeframe")
// }
// return unixstamp >= time_lower && unixstamp <= time_upper;
// });
//TODO: Filter out tapbacks, digital touch, etc, and maybe associate with their parent messages in the future (instead of individual messages)
//Anything with no text and no subject, or an associated_message_guid, or a balloon_bundle_id
// console.log("messages: "+messages);
// messages = exports.fixFormattingForMultipleMessages(messages, conversation);
//TODO: Does this need to be broken down with extra data (i.e. conversationID) added?
return messages;
}
exports.stackTapbacks = async function(messages, orphanedTapbackCallback) {
var Log = new LogLib.Log("SMServerAPI.js","stackTapbacks");
Log.v("Stacking tapbacks");
Log.v("Original message count: "+messages.length);
//TODO: Add a callback for orphaned tapbacks, so we can run nhtModifierUpdate later.
//It is assumed the messages are ordered chronologically--i.e. newest message is at index 0
//WE NEED DATA FOR ALL OF THE FOLLOWING
// For each tapback, writeObject() for the TapbackModifierInfo item
// [Pack the sueprclass ModifierInfo]
// Pack a string: Item type (for StickerModifierInfo this is 1)
// Pack a string: message (Is this the GUID? Or just the message text?)
// Pack string: messageIndex (ROWID??? But it's a string)
// Pack mullable string: Sender (null if me)
// Pack boolean: isAddition (if the tapback was added or removed)
// Pack int: Tapback type (DOUBLE CHECK THE NUMBERS)
//We need to include messageIndex, Sender, isAddition, and tapback type.
var textMessages = [];
var orphanedTapbacks = [];
for (var i = (messages.length - 1); i >= 0; i--) { //Loops from oldest to newest message
// console.log(messages[i]);
if (messages[i].associated_message_guid == "") {
messages[i].tapbacks = [];
textMessages.unshift(messages[i]); //Adds to the beginning of the textMessages array to keep the output chronological
} else if (!messages[i].cache_has_attachments) { //If it has an associated message GUID and attachments, it must be a sticker. We only want tapbacks
// console.log("Found a tapback! "+messages[i].text+" associated with "+messages[i].associated_message_guid);
// if (messages[i].associated_message_type >= 3000 && messages[i].associated_message_type <= 4000) { //If the tapback has been removed
// //Okay, this will take some explanation. SMServer only shows you the tapbacks that currently
// //apply to messages. So if I like your text and then change it to a dislike, SMServer will only
// //keep track of the dislike and the like will vanish from the database. If you remove a tapback
// //(removed tapbacks have an associated_message_type of 3000 to 3005) then that will be the only
// //tapback saved from that person as it's the only one that applies right now. Therefore, if the
// //tapback has an associated_message_type of 300x, that means there are no active tapbacks from
// //this person. So we skip adding it to the database.
// continue;
// } //AirMessage asks for isAddition, so I guess I should pass along 300x values?
var parts = messages[i].associated_message_guid.split("/");
var targetedMessageGUID = parts[1];
//TODO: How to find tapback type? p:0/ is always at the beginning
//p:0 indicates the part number (i.e. if message is sent with attachment or whatever I think)
/*
{
text: 'Emphasized “Subjectline This is the body of the text message”',
date: 645406250523999900,
balloon_bundle_id: '',
ROWID: 10,
group_action_type: 0,
associated_message_guid: 'p:0/688FB450-C715-4914-9D2F-A73F6FDB7BE7',
id: '[email protected]',
cache_has_attachments: false,
guid: 'C5552DE4-3A88-4D63-9AD2-A11A23202C58',
service: 'iMessage',
is_from_me: true,
subject: '',
associated_message_type: 2004,
item_type: 0,
date_read: 0,
conversation_id: '[email protected]'
}
*/
var tapbackIsOrphaned = true;
for (var j = 0; j < textMessages.length; j++) {
//Loops through the text messages we have so far, looking for one that matches
//We are looping through the messages array backwards, so every message older
//than the current one is already in the textMessages array
if (targetedMessageGUID == textMessages[j].guid) {
//associated_message_type:
// 2000: Loved
// 2001: Liked
// 2002: Disliked
// 2003: Laughed
// 2004: Emphasized
// 2005: Questioned
// 300x: Removed tapback
textMessages[j].tapbacks.push(messages[i]);
tapbackIsOrphaned = false;
break;
}
//break in here
}
if (tapbackIsOrphaned) {
// console.log("[WARN] Orphaned tapback associated with: "+targetedMessageGUID+": "+messages[i].text);
// if (orphanedTapbackCallback) { //This could be undefined
// orphanedTapbackCallback(messages[i]);
// }
orphanedTapbacks.push(messages[i]);
}
//Yell that there's an orphaned tapback
}
}
Log.v("Tapback stacking completed with "+textMessages.length+" messages left and "+orphanedTapbacks.length+" orphaned tapbacks");
//TODO: Check if removing tapbacks works as expected
if (orphanedTapbackCallback) {//This could be Undefined
orphanedTapbackCallback(orphanedTapbacks);
}
return textMessages;
}
exports.fixMessageFormat = function(message, conversation_id) { //Adds some useful data to messages as they're returned from SMServer (note: tapbacks aren't included)
message.unixdate = ConversionDatabase.convertAppleDateToUnixTimestamp(message.date);
message.conversation_id = conversation_id;
return message;
}
exports.fixFormattingForMultipleMessages = function(messages, conversation_id) {
var fixed = [];
for (var i = 0; i < messages.length; i++) {
fixed.push(exports.fixMessageFormat(messages[i], conversation_id));
}
// console.log(fixed);
return fixed;
}
//TOOD: Add a function for getting all attachment info from messages (maybe auto-)
exports.extractAttachmentInfoFromMessages = function(messages) {
var attachments = [];
for (var i = 0; i < messages.length; i++) {
if (messages[i].attachments) { //If the attachments exist
attachments = attachments.concat(messages[i].attachments);
}
}
return attachments;
}
exports.filterAttachments = function(attachments) {
//TODO: Filter out attachments with no extension??
var filtered = [];
for (var i = 0; i < attachments.length; i++) {
if (attachments[i].filename.endsWith("unknown") || attachments[i].filename.endsWith(".pluginPayloadAttachment")) {
//Don't add it to the filtered list
} else {
filtered.push(attachments[i]);
}
}
return filtered;
}
//TODO: Auto-add necessary data (ex. conversation_id, unix_date, etc but not tapbacks) when data is returned from SMServer? or for getAllMessagesWhileConditionIsTrue?
// I'm thinking about doing this
exports.getAllMessagesFromSpecifiedTimeInterval = async function(time_lower, time_upper) { //I'm assuming these are in unix timestamps? Or Apple's format maybe?
//TODO: Use websockets for new messages!
//TODO: Send client a message when the iphone runs low on battery?
var Log = new LogLib.Log("SMServerAPI.js","getAllMessagesFromSpecifiedTimeInterval");
Log.v("Getting all messages from time "+time_lower+" to "+time_upper);
//time_lower and time_upper are both in UNIX milliseconds
//Looks like there isn't an easy way to find messages from X time to Y time
//We'll probably end up having to get the most recent 200 messages or so and see if we need to go back.
// var results = await SMServerFetch("/requests");
Log.v("Getting list of conversations after "+time_lower);
var conversations = await exports.getConversationsAfterTime(time_lower);
// console.log(conversations);
// var conversation_ids = [];
// for (var i = 0; i < conversations.length; i++) {
// conversation_ids.push(conversations[i].chat_identifier);
// }
// console.log("Got conversation IDs: "+conversation_ids);
//SMServer lets us query multiple converations at once, as long as each ID is separated with commas
//TODO: Sort these into their own conversations and label with the ID, as we'll need that later!
// var messages = [];
// for (var i = 0; i < conversations.length; i++) {
// var messagesFromConversation = await exports.getMessagesFromOneConversationFromTimeInterval(conversations[i].chat_identifier, time_lower, time_upper);
// //This adds a conversation_id to each message so AirPacker doesn't have to scramble to find it.
// //For some reason the conversation ID isn't included in the results, so we have to query each conversation individually
//
// for (var j = 0; j < messagesFromConversation.length; j++) {
// var message = messagesFromConversation[j];
// // console.log(message);
// // console.log(i+" / "+conversations.length)
// // console.log(conversations[i]);
// message.conversation_id = conversations[i].chat_identifier;
// messages.push(message);
// }
// }
//THIS WAS CHANGED AND IS UNTESTED
Log.v("Getting messages for each conversation");
var messages = [];
for (var i = 0; i < conversations.length; i++) {
Log.v("Getting messages after "+time_lower+" for conversation "+conversations[i]);
var conv_messages = await exports.getMessagesForOneConversationWhileConditionIsTrue(conversations[i].chat_identifier, (message) => {
//This is our compare function. Nifty!
var unixstamp = ConversionDatabase.convertAppleDateToUnixTimestamp(message.date);
// return unixstamp >= time_lower && unixstamp <= time_upper;
return unixstamp >= time_lower;
//TODO: This was changed as any conversations with messages both ahead of and behind time_upper
// would cause messages to be missed, because as as soon as the first (newest) message was seen,
// the function would stop
});
Log.v("Found "+conv_messages.length+" messages from conversation "+conversations[i]);
// console.log(conv_messages);
for (var j = 0; j < conv_messages.length; j++) {
var message = conv_messages[j];
message.conversation_id = conversations[i].chat_identifier; //This makes it easier to pass messages to the client later, as each message says which conversation it came from.
messages.push(message);
}
}
// console.log("all messages: "+messages);
Log.v("Filtering out messages after "+time_upper+". Current message count is "+messages.length);
var filtered = messages.filter((item) => {
//return true if it should be kept
var unixstamp = ConversionDatabase.convertAppleDateToUnixTimestamp(item.date);
// console.log("Filterring!");
// if (unixstamp >= time_lower && unixstamp <= time_upper) {
// console.log(item.text+" matches the requirements!");
// } else {
// console.log(item.text+": "+new Date(unixstamp)+" is not in the correct timeframe")
// }
return unixstamp >= time_lower && unixstamp <= time_upper;
});
//>>> FUTURE TODO: Put this into Promise.all() to be asynchronous and better!
Log.v("Messages filtered. Message count is now "+messages.length);
// console.log(allMessagesFromTime);
Log.v("Message time retrieval finished");
// messages = exports.fixFormattingForMultipleMessages(messages);
return messages;
//join with commas
}
//NOTE: When installing on an iPhone, Python is required for byte-buffer to work
//TODO: requests?search seems to include a chat_identifier field--use that instead of looping through each conversation?
//TODO: Is getting from time interval used anymore (newer method = while condition is true)?
// exports.getMessagesFromOneConversationFromTimeInterval = async function (conversation_id, time_lower, time_upper) {
// //TODO: Is this ever used?
// var Log = new LogLib.Log("SMServerAPI.js","getMessagesFromOneConversationFromTimeInterval");
// Log.v("Getting messages from conversation "+conversation_id+" from "+time_lower+" to "+time_upper);
// //TODO: Check for duplicates!
//
//
// //THE FOLLOWING IS UNTESTED
// //time_lower and time_upper are both in UNIX seconds
// // console.log("function ran");
// var timeOfEarliestMessage = 9999999999999999999;
// var messages = [];
// var offset = 0; //How far back to start retrieving messages
// var chunkSize = 100;
// //So if we don't get all
//
// // //TODO: Rewrite this using getMessagesForOneConversationWhileConditionIsTrue?
// // while (timeOfEarliestMessage >= time_lower) {
// // var results = await SMServerFetch("/requests", {messages: conversation_id, num_messages: 100, read_messages: false, messages_offset: offset});
// // if (results.texts.length == 0) { //results.texts[results.texts.length - 1] was failing here
// // break;
// // }
// // messages = results.texts.concat(messages); //Adds the results
// // offset += chunkSize;
// // // console.log("\n");
// // // console.log(results);
// // var timeOfEarliestMessage = ConversionDatabase.convertAppleDateToUnixTimestamp(results.texts[results.texts.length - 1].date);
// //
// // // console.log("Length of results is "+results.length+" vs "+chunkSize);
// // if (results.texts.length < chunkSize) {
// // // console.log("Results length is less than our chunk size");
// // break; //This happens if we are at the very beginning of the conversation.
// // }
// // }
// var messages = await exports.getMessagesForOneConversationWhileConditionIsTrue(conversation_id, (item) => {
// var unixstamp = ConversionDatabase.convertAppleDateToUnixTimestamp(item.date);
// return unixstamp >= time_lower;
// }); //TODO: Automatically stack tapbacks inside getMessagesForOneConversationWhileConditionIsTrue()?
//
// Log.v("Got "+messages.length+" messages from conversation during time interval");
//
// // console.log("Does htis work at all?????????????????????");
// //Now do filtering so only the messages within the specified time frame exactly get returned
// var filtered = messages.filter((item) => {
// //return true if it should be kept
// var unixstamp = ConversionDatabase.convertAppleDateToUnixTimestamp(item.date);
// console.log("Filterring!");
// if (unixstamp >= time_lower && unixstamp <= time_upper) {
// console.log(item.text+" matches the requirements!");
// } else {
// console.log(item.text+": "+new Date(unixstamp)+" is not in the correct timeframe")
// }
// return unixstamp >= time_lower && unixstamp <= time_upper;
// });
//
// //TODO: Filter out tapbacks, digital touch, etc, and maybe associate with their parent messages in the future (instead of individual messages)
// //Anything with no text and no subject, or an associated_message_guid, or a balloon_bundle_id
//
// return filtered;
// }
exports.getLastMessageFromConversation = async function (conversation_id, start_time) {
var Log = new LogLib.Log("SMServerAPI.js","getLastMessageFromConversation");
Log.v("Getting last messages from conversation "+conversation_id+" (after "+start_time+")")
// console.log("convo id: ");
// console.log(conversation_id);
//TODO: Maybe log all messages from after the message is sent, to avoid them getting lost?
Log.v("Fetching results");
var results = (await SMServerFetch("/requests", {messages: conversation_id, num_messages: 4, read_messages: false, messages_offset: 0})).texts; //TODO: Should this use getAllMessagesWhileConditionIsTrue?
Log.vv(JSON.stringify(results));
var results_filtered = [];
Log.v("Got "+results.length+" results. Filtering...");
for (var i = 0; i < results.length; i++) {
var unixsenddate = ConversionDatabase.convertAppleDateToUnixTimestamp(results[i].date);
if (unixsenddate > start_time) {
var result = results[i]; //TODO: Integrate conversation IDing into fetch (or a fetch wrapper) instead of having to deal with it each time
result.conversation_id = conversation_id;
results_filtered.push(result);