fca-arif-babu 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/.github/workflows/publish.yml +20 -0
  2. package/LICENSE-MIT +21 -0
  3. package/README.md +20 -0
  4. package/index.js +489 -0
  5. package/package.json +47 -0
  6. package/replit.nix +3 -0
  7. package/src/addExternalModule.js +25 -0
  8. package/src/addUserToGroup.js +115 -0
  9. package/src/changeAdminStatus.js +103 -0
  10. package/src/changeArchivedStatus.js +55 -0
  11. package/src/changeAvatar.js +136 -0
  12. package/src/changeAvatarV2.js +86 -0
  13. package/src/changeBio.js +76 -0
  14. package/src/changeBlockedStatus.js +49 -0
  15. package/src/changeBlockedStatusMqtt.js +80 -0
  16. package/src/changeCover.js +72 -0
  17. package/src/changeGroupImage.js +135 -0
  18. package/src/changeName.js +78 -0
  19. package/src/changeNickname.js +59 -0
  20. package/src/changeThreadColor.js +65 -0
  21. package/src/changeThreadEmoji.js +55 -0
  22. package/src/changeUsername.js +58 -0
  23. package/src/createCommentPost.js +229 -0
  24. package/src/createNewGroup.js +88 -0
  25. package/src/createPoll.js +71 -0
  26. package/src/createPost.js +275 -0
  27. package/src/data/getThreadInfo.json +1 -0
  28. package/src/deleteMessage.js +56 -0
  29. package/src/deleteThread.js +56 -0
  30. package/src/editMessage.js +59 -0
  31. package/src/editMessageOld.js +67 -0
  32. package/src/follow.js +74 -0
  33. package/src/forwardAttachment.js +60 -0
  34. package/src/getAccess.js +112 -0
  35. package/src/getAvatarUser.js +78 -0
  36. package/src/getBotInitialData.js +42 -0
  37. package/src/getCurrentUserID.js +7 -0
  38. package/src/getEmojiUrl.js +29 -0
  39. package/src/getFriendsList.js +83 -0
  40. package/src/getMessage.js +835 -0
  41. package/src/getRegion.js +7 -0
  42. package/src/getThreadHistory.js +680 -0
  43. package/src/getThreadHistoryDeprecated.js +93 -0
  44. package/src/getThreadInfo.js +227 -0
  45. package/src/getThreadInfoDeprecated.js +80 -0
  46. package/src/getThreadList.js +270 -0
  47. package/src/getThreadListDeprecated.js +75 -0
  48. package/src/getThreadPictures.js +79 -0
  49. package/src/getUID.js +122 -0
  50. package/src/getUserID.js +66 -0
  51. package/src/getUserInfo.js +71 -0
  52. package/src/handleFriendRequest.js +57 -0
  53. package/src/handleMessageRequest.js +65 -0
  54. package/src/httpGet.js +64 -0
  55. package/src/httpPost.js +64 -0
  56. package/src/httpPostFormData.js +70 -0
  57. package/src/listenMqtt.js +703 -0
  58. package/src/listenNotification.js +85 -0
  59. package/src/logout.js +75 -0
  60. package/src/markAsDelivered.js +55 -0
  61. package/src/markAsRead.js +85 -0
  62. package/src/markAsReadAll.js +50 -0
  63. package/src/markAsSeen.js +61 -0
  64. package/src/muteThread.js +52 -0
  65. package/src/pinMessage.js +59 -0
  66. package/src/refreshFb_dtsg.js +89 -0
  67. package/src/removeUserFromGroup.js +79 -0
  68. package/src/resolvePhotoUrl.js +45 -0
  69. package/src/searchForThread.js +53 -0
  70. package/src/searchStickers.js +53 -0
  71. package/src/sendMessage.js +442 -0
  72. package/src/sendMessageMqtt.js +316 -0
  73. package/src/sendTypingIndicator.js +28 -0
  74. package/src/setMessageReaction.js +122 -0
  75. package/src/setMessageReactionMqtt.js +62 -0
  76. package/src/setPostReaction.js +112 -0
  77. package/src/setProfileGuard.js +44 -0
  78. package/src/setStoryReaction.js +64 -0
  79. package/src/setTitle.js +90 -0
  80. package/src/shareContact.js +110 -0
  81. package/src/shareLink.js +59 -0
  82. package/src/stopListenMqtt.js +23 -0
  83. package/src/threadColors.js +131 -0
  84. package/src/unfriend.js +52 -0
  85. package/src/unsendMessage.js +45 -0
  86. package/src/uploadAttachment.js +94 -0
  87. package/utils.js +1416 -0
package/utils.js ADDED
@@ -0,0 +1,1416 @@
1
+ /* eslint-disable no-prototype-builtins */
2
+ "use strict";
3
+
4
+ const getRandom = arr => arr[Math.floor(Math.random() * arr.length)];
5
+ function randomUserAgent() {
6
+ const platform = {
7
+ platform: ['Windows NT 10.0; Win64; x64', 'Macintosh; Intel Mac OS X 14.7; rv:132.0'],
8
+ browsers: {
9
+ chrome: ['122.0.0.0', '121.0.0.0'],
10
+ firefox: ['123.0', '122.0'],
11
+ edge: ['122.0.2365.92']
12
+ }
13
+ };
14
+ const browserName = getRandom(Object.keys(platform.browsers));
15
+ const version = getRandom(platform.browsers[browserName]);
16
+ const plat = getRandom(platform.platform);
17
+ const userAgentArray = [
18
+ defaultUserAgent,
19
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
20
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
21
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:45.0) Gecko/20100101 Firefox/45.0",
22
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
23
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7",
24
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8",
25
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.3",
26
+ ];
27
+ const ua = getRandom([
28
+ browserName === 'firefox' ? `Mozilla/5.0 (${plat}) Gecko/20100101 Firefox/${version}` : `Mozilla/5.0 (${plat}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${version} Safari/537.36`,
29
+ getRandom(userAgentArray)
30
+ ]);
31
+ return ua;
32
+ }
33
+ const defaultUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14.7; rv:132.0) Gecko/20100101 Firefox/132.0";
34
+ const headers = {
35
+ "content-type": "application/x-www-form-urlencoded",
36
+ "referer": "https://www.facebook.com/",
37
+ "origin": "https://www.facebook.com",
38
+ "connection": "keep-alive",
39
+ "Sec-Fetch-Site": "same-origin",
40
+ "Sec-Fetch-User": "?1",
41
+ "User-Agent": defaultUserAgent
42
+ };
43
+ let request = require("request").defaults({
44
+ jar: true
45
+ });
46
+ const stream = require("stream");
47
+ const querystring = require("querystring");
48
+ const url = require("url");
49
+
50
+ function setProxy(proxy) {
51
+ request = require("request").defaults({
52
+ jar: true,
53
+ ...(proxy && {
54
+ proxy
55
+ })
56
+ });
57
+ return;
58
+ }
59
+
60
+ function getHeaders(url, options, ctx, customHeader) {
61
+ const headers1 = {
62
+ "host": new URL(url).hostname,
63
+ ...headers
64
+ }
65
+ if (headers1["User-Agent"]) {
66
+ delete headers1["User-Agent"];
67
+ headers1["User-Agent"] = customHeader?.customUserAgent ?? options?.userAgent ?? defaultUserAgent;
68
+ }
69
+ if (ctx && ctx.region) headers1["X-MSGR-Region"] = ctx.region;
70
+ if (customHeader) {
71
+ Object.assign(headers1, customHeader);
72
+ if (customHeader.noRef) delete headers1.referer;
73
+ }
74
+ return headers1;
75
+ }
76
+
77
+
78
+ function isReadableStream(obj) {
79
+ return obj instanceof stream.Stream && typeof obj._read == "function" && getType(obj._readableState) == "Object";
80
+ }
81
+
82
+ function get(url, jar, qs, options, ctx, customHeader) {
83
+ let callback;
84
+ var returnPromise = new Promise(function (resolve, reject) {
85
+ callback = (error, res) => error ? reject(error) : resolve(res);
86
+ });
87
+ if (getType(qs) == "Object")
88
+ for (let prop in qs) {
89
+ if (getType(qs[prop]) == 'Object')
90
+ qs[prop] = JSON.stringify(qs[prop]);
91
+ }
92
+ var op = {
93
+ headers: getHeaders(url, options, ctx, customHeader),
94
+ timeout: 60000,
95
+ qs,
96
+ jar,
97
+ gzip: true
98
+ }
99
+
100
+ request.get(url, op, callback);
101
+
102
+ return returnPromise;
103
+ }
104
+
105
+ function post(url, jar, form, options, ctx, customHeader) {
106
+ let callback;
107
+ var returnPromise = new Promise(function (resolve, reject) {
108
+ callback = (error, res) => error ? reject(error) : resolve(res);
109
+ });
110
+
111
+ var op = {
112
+ headers: getHeaders(url, options, ctx, customHeader),
113
+ timeout: 60000,
114
+ form,
115
+ jar,
116
+ gzip: true
117
+ }
118
+
119
+ request.post(url, op, callback);
120
+
121
+ return returnPromise;
122
+ }
123
+
124
+ function postFormData(url, jar, form, qs, options, ctx) {
125
+ let callback;
126
+ var returnPromise = new Promise(function (resolve, reject) {
127
+ callback = (error, res) => error ? reject(error) : resolve(res);
128
+ });
129
+ if (getType(qs) == "Object")
130
+ for (let prop in qs) {
131
+ if (getType(qs[prop]) == 'Object')
132
+ qs[prop] = JSON.stringify(qs[prop]);
133
+ }
134
+ var op = {
135
+ headers: getHeaders(url, options, ctx, {
136
+ 'content-type': 'multipart/form-data'
137
+ }),
138
+ timeout: 60000,
139
+ formData: form,
140
+ qs,
141
+ jar,
142
+ gzip: true
143
+ }
144
+
145
+ request.post(url, op, callback);
146
+
147
+ return returnPromise;
148
+ }
149
+
150
+
151
+ function padZeros(val, len) {
152
+ val = String(val);
153
+ len = len || 2;
154
+ while (val.length < len) val = "0" + val;
155
+ return val;
156
+ }
157
+
158
+ function generateThreadingID(clientID) {
159
+ const k = Date.now();
160
+ const l = Math.floor(Math.random() * 4294967295);
161
+ const m = clientID;
162
+ return "<" + k + ":" + l + "-" + m + "@mail.projektitan.com>";
163
+ }
164
+
165
+ function binaryToDecimal(data) {
166
+ let ret = "";
167
+ while (data !== "0") {
168
+ let end = 0;
169
+ let fullName = "";
170
+ let i = 0;
171
+ for (; i < data.length; i++) {
172
+ end = 2 * end + parseInt(data[i], 10);
173
+ if (end >= 10) {
174
+ fullName += "1";
175
+ end -= 10;
176
+ }
177
+ else {
178
+ fullName += "0";
179
+ }
180
+ }
181
+ ret = end.toString() + ret;
182
+ data = fullName.slice(fullName.indexOf("1"));
183
+ }
184
+ return ret;
185
+ }
186
+
187
+ function generateOfflineThreadingID() {
188
+ const ret = Date.now();
189
+ const value = Math.floor(Math.random() * 4294967295);
190
+ const str = ("0000000000000000000000" + value.toString(2)).slice(-22);
191
+ const msgs = ret.toString(2) + str;
192
+ return binaryToDecimal(msgs);
193
+ }
194
+
195
+ let h;
196
+ const i = {};
197
+ const j = {
198
+ _: "%",
199
+ A: "%2",
200
+ B: "000",
201
+ C: "%7d",
202
+ D: "%7b%22",
203
+ E: "%2c%22",
204
+ F: "%22%3a",
205
+ G: "%2c%22ut%22%3a1",
206
+ H: "%2c%22bls%22%3a",
207
+ I: "%2c%22n%22%3a%22%",
208
+ J: "%22%3a%7b%22i%22%3a0%7d",
209
+ K: "%2c%22pt%22%3a0%2c%22vis%22%3a",
210
+ L: "%2c%22ch%22%3a%7b%22h%22%3a%22",
211
+ M: "%7b%22v%22%3a2%2c%22time%22%3a1",
212
+ N: ".channel%22%2c%22sub%22%3a%5b",
213
+ O: "%2c%22sb%22%3a1%2c%22t%22%3a%5b",
214
+ P: "%2c%22ud%22%3a100%2c%22lc%22%3a0",
215
+ Q: "%5d%2c%22f%22%3anull%2c%22uct%22%3a",
216
+ R: ".channel%22%2c%22sub%22%3a%5b1%5d",
217
+ S: "%22%2c%22m%22%3a0%7d%2c%7b%22i%22%3a",
218
+ T: "%2c%22blc%22%3a1%2c%22snd%22%3a1%2c%22ct%22%3a",
219
+ U: "%2c%22blc%22%3a0%2c%22snd%22%3a1%2c%22ct%22%3a",
220
+ V: "%2c%22blc%22%3a0%2c%22snd%22%3a0%2c%22ct%22%3a",
221
+ W: "%2c%22s%22%3a0%2c%22blo%22%3a0%7d%2c%22bl%22%3a%7b%22ac%22%3a",
222
+ X: "%2c%22ri%22%3a0%7d%2c%22state%22%3a%7b%22p%22%3a0%2c%22ut%22%3a1",
223
+ Y: "%2c%22pt%22%3a0%2c%22vis%22%3a1%2c%22bls%22%3a0%2c%22blc%22%3a0%2c%22snd%22%3a1%2c%22ct%22%3a",
224
+ Z: "%2c%22sb%22%3a1%2c%22t%22%3a%5b%5d%2c%22f%22%3anull%2c%22uct%22%3a0%2c%22s%22%3a0%2c%22blo%22%3a0%7d%2c%22bl%22%3a%7b%22ac%22%3a"
225
+ };
226
+ (function() {
227
+ const l = [];
228
+ for (const m in j) {
229
+ i[j[m]] = m;
230
+ l.push(j[m]);
231
+ }
232
+ l.reverse();
233
+ h = new RegExp(l.join("|"), "g");
234
+ })();
235
+
236
+ function presenceEncode(str) {
237
+ return encodeURIComponent(str)
238
+ .replace(/([_A-Z])|%../g, function(m, n) {
239
+ return n ? "%" + n.charCodeAt(0).toString(16) : m;
240
+ })
241
+ .toLowerCase()
242
+ .replace(h, function(m) {
243
+ return i[m];
244
+ });
245
+ }
246
+
247
+ // eslint-disable-next-line no-unused-vars
248
+ function presenceDecode(str) {
249
+ return decodeURIComponent(
250
+ str.replace(/[_A-Z]/g, function(m) {
251
+ return j[m];
252
+ })
253
+ );
254
+ }
255
+
256
+ function generatePresence(userID) {
257
+ const time = Date.now();
258
+ return (
259
+ "E" +
260
+ presenceEncode(
261
+ JSON.stringify({
262
+ v: 3,
263
+ time: parseInt(time / 1000, 10),
264
+ user: userID,
265
+ state: {
266
+ ut: 0,
267
+ t2: [],
268
+ lm2: null,
269
+ uct2: time,
270
+ tr: null,
271
+ tw: Math.floor(Math.random() * 4294967295) + 1,
272
+ at: time
273
+ },
274
+ ch: {
275
+ ["p_" + userID]: 0
276
+ }
277
+ })
278
+ )
279
+ );
280
+ }
281
+
282
+ function generateAccessiblityCookie() {
283
+ const time = Date.now();
284
+ return encodeURIComponent(
285
+ JSON.stringify({
286
+ sr: 0,
287
+ "sr-ts": time,
288
+ jk: 0,
289
+ "jk-ts": time,
290
+ kb: 0,
291
+ "kb-ts": time,
292
+ hcm: 0,
293
+ "hcm-ts": time
294
+ })
295
+ );
296
+ }
297
+
298
+ function getGUID() {
299
+ /** @type {number} */
300
+ let sectionLength = Date.now();
301
+ /** @type {string} */
302
+ const id = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
303
+ /** @type {number} */
304
+ const r = Math.floor((sectionLength + Math.random() * 16) % 16);
305
+ /** @type {number} */
306
+ sectionLength = Math.floor(sectionLength / 16);
307
+ /** @type {string} */
308
+ const _guid = (c == "x" ? r : (r & 7) | 8).toString(16);
309
+ return _guid;
310
+ });
311
+ return id;
312
+ }
313
+
314
+ function getExtension(original_extension, fullFileName = "") {
315
+ if (original_extension) {
316
+ return original_extension;
317
+ }
318
+ else {
319
+ const extension = fullFileName.split(".").pop();
320
+ if (extension === fullFileName) {
321
+ return "";
322
+ }
323
+ else {
324
+ return extension;
325
+ }
326
+ }
327
+ }
328
+
329
+ function _formatAttachment(attachment1, attachment2) {
330
+ // TODO: THIS IS REALLY BAD
331
+ // This is an attempt at fixing Facebook's inconsistencies. Sometimes they give us
332
+ // two attachment objects, but sometimes only one. They each contain part of the
333
+ // data that you'd want so we merge them for convenience.
334
+ // Instead of having a bunch of if statements guarding every access to image_data,
335
+ // we set it to empty object and use the fact that it'll return undefined.
336
+ const fullFileName = attachment1.filename;
337
+ const fileSize = Number(attachment1.fileSize || 0);
338
+ const durationVideo = attachment1.genericMetadata ? Number(attachment1.genericMetadata.videoLength) : undefined;
339
+ const durationAudio = attachment1.genericMetadata ? Number(attachment1.genericMetadata.duration) : undefined;
340
+ const mimeType = attachment1.mimeType;
341
+
342
+ attachment2 = attachment2 || { id: "", image_data: {} };
343
+ attachment1 = attachment1.mercury || attachment1;
344
+ let blob = attachment1.blob_attachment || attachment1.sticker_attachment;
345
+ let type =
346
+ blob && blob.__typename ? blob.__typename : attachment1.attach_type;
347
+ if (!type && attachment1.sticker_attachment) {
348
+ type = "StickerAttachment";
349
+ blob = attachment1.sticker_attachment;
350
+ }
351
+ else if (!type && attachment1.extensible_attachment) {
352
+ if (
353
+ attachment1.extensible_attachment.story_attachment &&
354
+ attachment1.extensible_attachment.story_attachment.target &&
355
+ attachment1.extensible_attachment.story_attachment.target.__typename &&
356
+ attachment1.extensible_attachment.story_attachment.target.__typename === "MessageLocation"
357
+ ) {
358
+ type = "MessageLocation";
359
+ }
360
+ else {
361
+ type = "ExtensibleAttachment";
362
+ }
363
+
364
+ blob = attachment1.extensible_attachment;
365
+ }
366
+ // TODO: Determine whether "sticker", "photo", "file" etc are still used
367
+ // KEEP IN SYNC WITH getThreadHistory
368
+ switch (type) {
369
+ case "sticker":
370
+ return {
371
+ type: "sticker",
372
+ ID: attachment1.metadata.stickerID.toString(),
373
+ url: attachment1.url,
374
+
375
+ packID: attachment1.metadata.packID.toString(),
376
+ spriteUrl: attachment1.metadata.spriteURI,
377
+ spriteUrl2x: attachment1.metadata.spriteURI2x,
378
+ width: attachment1.metadata.width,
379
+ height: attachment1.metadata.height,
380
+
381
+ caption: attachment2.caption,
382
+ description: attachment2.description,
383
+
384
+ frameCount: attachment1.metadata.frameCount,
385
+ frameRate: attachment1.metadata.frameRate,
386
+ framesPerRow: attachment1.metadata.framesPerRow,
387
+ framesPerCol: attachment1.metadata.framesPerCol,
388
+
389
+ stickerID: attachment1.metadata.stickerID.toString(), // @Legacy
390
+ spriteURI: attachment1.metadata.spriteURI, // @Legacy
391
+ spriteURI2x: attachment1.metadata.spriteURI2x // @Legacy
392
+ };
393
+ case "file":
394
+ return {
395
+ type: "file",
396
+ ID: attachment2.id.toString(),
397
+ fullFileName: fullFileName,
398
+ filename: attachment1.name,
399
+ fileSize: fileSize,
400
+ original_extension: getExtension(attachment1.original_extension, fullFileName),
401
+ mimeType: mimeType,
402
+ url: attachment1.url,
403
+
404
+ isMalicious: attachment2.is_malicious,
405
+ contentType: attachment2.mime_type,
406
+
407
+ name: attachment1.name // @Legacy
408
+ };
409
+ case "photo":
410
+ return {
411
+ type: "photo",
412
+ ID: attachment1.metadata.fbid.toString(),
413
+ filename: attachment1.fileName,
414
+ fullFileName: fullFileName,
415
+ fileSize: fileSize,
416
+ original_extension: getExtension(attachment1.original_extension, fullFileName),
417
+ mimeType: mimeType,
418
+ thumbnailUrl: attachment1.thumbnail_url,
419
+
420
+ previewUrl: attachment1.preview_url,
421
+ previewWidth: attachment1.preview_width,
422
+ previewHeight: attachment1.preview_height,
423
+
424
+ largePreviewUrl: attachment1.large_preview_url,
425
+ largePreviewWidth: attachment1.large_preview_width,
426
+ largePreviewHeight: attachment1.large_preview_height,
427
+
428
+ url: attachment1.metadata.url, // @Legacy
429
+ width: attachment1.metadata.dimensions.split(",")[0], // @Legacy
430
+ height: attachment1.metadata.dimensions.split(",")[1], // @Legacy
431
+ name: fullFileName // @Legacy
432
+ };
433
+ case "animated_image":
434
+ return {
435
+ type: "animated_image",
436
+ ID: attachment2.id.toString(),
437
+ filename: attachment2.filename,
438
+ fullFileName: fullFileName,
439
+ original_extension: getExtension(attachment2.original_extension, fullFileName),
440
+ mimeType: mimeType,
441
+
442
+ previewUrl: attachment1.preview_url,
443
+ previewWidth: attachment1.preview_width,
444
+ previewHeight: attachment1.preview_height,
445
+
446
+ url: attachment2.image_data.url,
447
+ width: attachment2.image_data.width,
448
+ height: attachment2.image_data.height,
449
+
450
+ name: attachment1.name, // @Legacy
451
+ facebookUrl: attachment1.url, // @Legacy
452
+ thumbnailUrl: attachment1.thumbnail_url, // @Legacy
453
+ rawGifImage: attachment2.image_data.raw_gif_image, // @Legacy
454
+ rawWebpImage: attachment2.image_data.raw_webp_image, // @Legacy
455
+ animatedGifUrl: attachment2.image_data.animated_gif_url, // @Legacy
456
+ animatedGifPreviewUrl: attachment2.image_data.animated_gif_preview_url, // @Legacy
457
+ animatedWebpUrl: attachment2.image_data.animated_webp_url, // @Legacy
458
+ animatedWebpPreviewUrl: attachment2.image_data.animated_webp_preview_url // @Legacy
459
+ };
460
+ case "share":
461
+ return {
462
+ type: "share",
463
+ ID: attachment1.share.share_id.toString(),
464
+ url: attachment2.href,
465
+
466
+ title: attachment1.share.title,
467
+ description: attachment1.share.description,
468
+ source: attachment1.share.source,
469
+
470
+ image: attachment1.share.media.image,
471
+ width: attachment1.share.media.image_size.width,
472
+ height: attachment1.share.media.image_size.height,
473
+ playable: attachment1.share.media.playable,
474
+ duration: attachment1.share.media.duration,
475
+
476
+ subattachments: attachment1.share.subattachments,
477
+ properties: {},
478
+
479
+ animatedImageSize: attachment1.share.media.animated_image_size, // @Legacy
480
+ facebookUrl: attachment1.share.uri, // @Legacy
481
+ target: attachment1.share.target, // @Legacy
482
+ styleList: attachment1.share.style_list // @Legacy
483
+ };
484
+ case "video":
485
+ return {
486
+ type: "video",
487
+ ID: attachment1.metadata.fbid.toString(),
488
+ filename: attachment1.name,
489
+ fullFileName: fullFileName,
490
+ original_extension: getExtension(attachment1.original_extension, fullFileName),
491
+ mimeType: mimeType,
492
+ duration: durationVideo,
493
+
494
+ previewUrl: attachment1.preview_url,
495
+ previewWidth: attachment1.preview_width,
496
+ previewHeight: attachment1.preview_height,
497
+
498
+ url: attachment1.url,
499
+ width: attachment1.metadata.dimensions.width,
500
+ height: attachment1.metadata.dimensions.height,
501
+
502
+ videoType: "unknown",
503
+
504
+ thumbnailUrl: attachment1.thumbnail_url // @Legacy
505
+ };
506
+ case "error":
507
+ return {
508
+ type: "error",
509
+
510
+ // Save error attachments because we're unsure of their format,
511
+ // and whether there are cases they contain something useful for debugging.
512
+ attachment1: attachment1,
513
+ attachment2: attachment2
514
+ };
515
+ case "MessageImage":
516
+ return {
517
+ type: "photo",
518
+ ID: blob.legacy_attachment_id,
519
+ filename: blob.filename,
520
+ fullFileName: fullFileName,
521
+ fileSize: fileSize,
522
+ original_extension: getExtension(blob.original_extension, fullFileName),
523
+ mimeType: mimeType,
524
+ thumbnailUrl: blob.thumbnail.uri,
525
+
526
+ previewUrl: blob.preview.uri,
527
+ previewWidth: blob.preview.width,
528
+ previewHeight: blob.preview.height,
529
+
530
+ largePreviewUrl: blob.large_preview.uri,
531
+ largePreviewWidth: blob.large_preview.width,
532
+ largePreviewHeight: blob.large_preview.height,
533
+
534
+ url: blob.large_preview.uri, // @Legacy
535
+ width: blob.original_dimensions.x, // @Legacy
536
+ height: blob.original_dimensions.y, // @Legacy
537
+ name: blob.filename // @Legacy
538
+ };
539
+ case "MessageAnimatedImage":
540
+ return {
541
+ type: "animated_image",
542
+ ID: blob.legacy_attachment_id,
543
+ filename: blob.filename,
544
+ fullFileName: fullFileName,
545
+ original_extension: getExtension(blob.original_extension, fullFileName),
546
+ mimeType: mimeType,
547
+
548
+ previewUrl: blob.preview_image.uri,
549
+ previewWidth: blob.preview_image.width,
550
+ previewHeight: blob.preview_image.height,
551
+
552
+ url: blob.animated_image.uri,
553
+ width: blob.animated_image.width,
554
+ height: blob.animated_image.height,
555
+
556
+ thumbnailUrl: blob.preview_image.uri, // @Legacy
557
+ name: blob.filename, // @Legacy
558
+ facebookUrl: blob.animated_image.uri, // @Legacy
559
+ rawGifImage: blob.animated_image.uri, // @Legacy
560
+ animatedGifUrl: blob.animated_image.uri, // @Legacy
561
+ animatedGifPreviewUrl: blob.preview_image.uri, // @Legacy
562
+ animatedWebpUrl: blob.animated_image.uri, // @Legacy
563
+ animatedWebpPreviewUrl: blob.preview_image.uri // @Legacy
564
+ };
565
+ case "MessageVideo":
566
+ return {
567
+ type: "video",
568
+ ID: blob.legacy_attachment_id,
569
+ filename: blob.filename,
570
+ fullFileName: fullFileName,
571
+ original_extension: getExtension(blob.original_extension, fullFileName),
572
+ fileSize: fileSize,
573
+ duration: durationVideo,
574
+ mimeType: mimeType,
575
+
576
+ previewUrl: blob.large_image.uri,
577
+ previewWidth: blob.large_image.width,
578
+ previewHeight: blob.large_image.height,
579
+
580
+ url: blob.playable_url,
581
+ width: blob.original_dimensions.x,
582
+ height: blob.original_dimensions.y,
583
+
584
+ videoType: blob.video_type.toLowerCase(),
585
+
586
+ thumbnailUrl: blob.large_image.uri // @Legacy
587
+ };
588
+ case "MessageAudio":
589
+ return {
590
+ type: "audio",
591
+ ID: blob.url_shimhash,
592
+ filename: blob.filename,
593
+ fullFileName: fullFileName,
594
+ fileSize: fileSize,
595
+ duration: durationAudio,
596
+ original_extension: getExtension(blob.original_extension, fullFileName),
597
+ mimeType: mimeType,
598
+
599
+ audioType: blob.audio_type,
600
+ url: blob.playable_url,
601
+
602
+ isVoiceMail: blob.is_voicemail
603
+ };
604
+ case "StickerAttachment":
605
+ case "Sticker":
606
+ return {
607
+ type: "sticker",
608
+ ID: blob.id,
609
+ url: blob.url,
610
+
611
+ packID: blob.pack ? blob.pack.id : null,
612
+ spriteUrl: blob.sprite_image,
613
+ spriteUrl2x: blob.sprite_image_2x,
614
+ width: blob.width,
615
+ height: blob.height,
616
+
617
+ caption: blob.label,
618
+ description: blob.label,
619
+
620
+ frameCount: blob.frame_count,
621
+ frameRate: blob.frame_rate,
622
+ framesPerRow: blob.frames_per_row,
623
+ framesPerCol: blob.frames_per_column,
624
+
625
+ stickerID: blob.id, // @Legacy
626
+ spriteURI: blob.sprite_image, // @Legacy
627
+ spriteURI2x: blob.sprite_image_2x // @Legacy
628
+ };
629
+ case "MessageLocation":
630
+ var urlAttach = blob.story_attachment.url;
631
+ var mediaAttach = blob.story_attachment.media;
632
+
633
+ var u = querystring.parse(url.parse(urlAttach).query).u;
634
+ var where1 = querystring.parse(url.parse(u).query).where1;
635
+ var address = where1.split(", ");
636
+
637
+ var latitude;
638
+ var longitude;
639
+
640
+ try {
641
+ latitude = Number.parseFloat(address[0]);
642
+ longitude = Number.parseFloat(address[1]);
643
+ } catch (err) {
644
+ /* empty */
645
+ }
646
+
647
+ var imageUrl;
648
+ var width;
649
+ var height;
650
+
651
+ if (mediaAttach && mediaAttach.image) {
652
+ imageUrl = mediaAttach.image.uri;
653
+ width = mediaAttach.image.width;
654
+ height = mediaAttach.image.height;
655
+ }
656
+
657
+ return {
658
+ type: "location",
659
+ ID: blob.legacy_attachment_id,
660
+ latitude: latitude,
661
+ longitude: longitude,
662
+ image: imageUrl,
663
+ width: width,
664
+ height: height,
665
+ url: u || urlAttach,
666
+ address: where1,
667
+
668
+ facebookUrl: blob.story_attachment.url, // @Legacy
669
+ target: blob.story_attachment.target, // @Legacy
670
+ styleList: blob.story_attachment.style_list // @Legacy
671
+ };
672
+ case "ExtensibleAttachment":
673
+ return {
674
+ type: "share",
675
+ ID: blob.legacy_attachment_id,
676
+ url: blob.story_attachment.url,
677
+
678
+ title: blob.story_attachment.title_with_entities.text,
679
+ description:
680
+ blob.story_attachment.description &&
681
+ blob.story_attachment.description.text,
682
+ source: blob.story_attachment.source ?
683
+ blob.story_attachment.source.text :
684
+ null,
685
+
686
+ image:
687
+ blob.story_attachment.media &&
688
+ blob.story_attachment.media.image &&
689
+ blob.story_attachment.media.image.uri,
690
+ width:
691
+ blob.story_attachment.media &&
692
+ blob.story_attachment.media.image &&
693
+ blob.story_attachment.media.image.width,
694
+ height:
695
+ blob.story_attachment.media &&
696
+ blob.story_attachment.media.image &&
697
+ blob.story_attachment.media.image.height,
698
+ playable:
699
+ blob.story_attachment.media &&
700
+ blob.story_attachment.media.is_playable,
701
+ duration:
702
+ blob.story_attachment.media &&
703
+ blob.story_attachment.media.playable_duration_in_ms,
704
+ playableUrl:
705
+ blob.story_attachment.media == null ?
706
+ null :
707
+ blob.story_attachment.media.playable_url,
708
+
709
+ subattachments: blob.story_attachment.subattachments,
710
+ properties: blob.story_attachment.properties.reduce(function(obj, cur) {
711
+ obj[cur.key] = cur.value.text;
712
+ return obj;
713
+ }, {}),
714
+
715
+ facebookUrl: blob.story_attachment.url, // @Legacy
716
+ target: blob.story_attachment.target, // @Legacy
717
+ styleList: blob.story_attachment.style_list // @Legacy
718
+ };
719
+ case "MessageFile":
720
+ return {
721
+ type: "file",
722
+ ID: blob.message_file_fbid,
723
+ fullFileName: fullFileName,
724
+ filename: blob.filename,
725
+ fileSize: fileSize,
726
+ mimeType: blob.mimetype,
727
+ original_extension: blob.original_extension || fullFileName.split(".").pop(),
728
+
729
+ url: blob.url,
730
+ isMalicious: blob.is_malicious,
731
+ contentType: blob.content_type,
732
+
733
+ name: blob.filename
734
+ };
735
+ default:
736
+ throw new Error(
737
+ "unrecognized attach_file of type " +
738
+ type +
739
+ "`" +
740
+ JSON.stringify(attachment1, null, 4) +
741
+ " attachment2: " +
742
+ JSON.stringify(attachment2, null, 4) +
743
+ "`"
744
+ );
745
+ }
746
+ }
747
+
748
+ function formatAttachment(attachments, attachmentIds, attachmentMap, shareMap) {
749
+ attachmentMap = shareMap || attachmentMap;
750
+ return attachments ?
751
+ attachments.map(function(val, i) {
752
+ if (
753
+ !attachmentMap ||
754
+ !attachmentIds ||
755
+ !attachmentMap[attachmentIds[i]]
756
+ ) {
757
+ return _formatAttachment(val);
758
+ }
759
+ return _formatAttachment(val, attachmentMap[attachmentIds[i]]);
760
+ }) : [];
761
+ }
762
+
763
+ function formatDeltaMessage(m) {
764
+ const md = m.delta.messageMetadata;
765
+
766
+ const mdata =
767
+ m.delta.data === undefined ? [] :
768
+ m.delta.data.prng === undefined ? [] :
769
+ JSON.parse(m.delta.data.prng);
770
+ const m_id = mdata.map(u => u.i);
771
+ const m_offset = mdata.map(u => u.o);
772
+ const m_length = mdata.map(u => u.l);
773
+ const mentions = {};
774
+ for (let i = 0; i < m_id.length; i++) {
775
+ mentions[m_id[i]] = m.delta.body.substring(
776
+ m_offset[i],
777
+ m_offset[i] + m_length[i]
778
+ );
779
+ }
780
+
781
+ return {
782
+ type: "message",
783
+ senderID: formatID(md.actorFbId.toString()),
784
+ body: m.delta.body || "",
785
+ threadID: formatID(
786
+ (md.threadKey.threadFbId || md.threadKey.otherUserFbId).toString()
787
+ ),
788
+ messageID: md.messageId,
789
+ attachments: (m.delta.attachments || []).map(v => _formatAttachment(v)),
790
+ mentions: mentions,
791
+ timestamp: md.timestamp,
792
+ isGroup: !!md.threadKey.threadFbId,
793
+ participantIDs: m.delta.participants
794
+ };
795
+ }
796
+
797
+ function formatID(id) {
798
+ if (id != undefined && id != null) {
799
+ return id.replace(/(fb)?id[:.]/, "");
800
+ }
801
+ else {
802
+ return id;
803
+ }
804
+ }
805
+
806
+ function formatMessage(m) {
807
+ const originalMessage = m.message ? m.message : m;
808
+ const obj = {
809
+ type: "message",
810
+ senderName: originalMessage.sender_name,
811
+ senderID: formatID(originalMessage.sender_fbid.toString()),
812
+ participantNames: originalMessage.group_thread_info ?
813
+ originalMessage.group_thread_info.participant_names : [originalMessage.sender_name.split(" ")[0]],
814
+ participantIDs: originalMessage.group_thread_info ?
815
+ originalMessage.group_thread_info.participant_ids.map(function(v) {
816
+ return formatID(v.toString());
817
+ }) : [formatID(originalMessage.sender_fbid)],
818
+ body: originalMessage.body || "",
819
+ threadID: formatID(
820
+ (
821
+ originalMessage.thread_fbid || originalMessage.other_user_fbid
822
+ ).toString()
823
+ ),
824
+ threadName: originalMessage.group_thread_info ?
825
+ originalMessage.group_thread_info.name : originalMessage.sender_name,
826
+ location: originalMessage.coordinates ? originalMessage.coordinates : null,
827
+ messageID: originalMessage.mid ?
828
+ originalMessage.mid.toString() : originalMessage.message_id,
829
+ attachments: formatAttachment(
830
+ originalMessage.attachments,
831
+ originalMessage.attachmentIds,
832
+ originalMessage.attachment_map,
833
+ originalMessage.share_map
834
+ ),
835
+ timestamp: originalMessage.timestamp,
836
+ timestampAbsolute: originalMessage.timestamp_absolute,
837
+ timestampRelative: originalMessage.timestamp_relative,
838
+ timestampDatetime: originalMessage.timestamp_datetime,
839
+ tags: originalMessage.tags,
840
+ reactions: originalMessage.reactions ? originalMessage.reactions : [],
841
+ isUnread: originalMessage.is_unread
842
+ };
843
+
844
+ if (m.type === "pages_messaging")
845
+ obj.pageID = m.realtime_viewer_fbid.toString();
846
+ obj.isGroup = obj.participantIDs.length > 2;
847
+
848
+ return obj;
849
+ }
850
+
851
+ function formatEvent(m) {
852
+ const originalMessage = m.message ? m.message : m;
853
+ let logMessageType = originalMessage.log_message_type;
854
+ let logMessageData;
855
+ if (logMessageType === "log:generic-admin-text") {
856
+ logMessageData = originalMessage.log_message_data.untypedData;
857
+ logMessageType = getAdminTextMessageType(
858
+ originalMessage.log_message_data.message_type
859
+ );
860
+ }
861
+ else {
862
+ logMessageData = originalMessage.log_message_data;
863
+ }
864
+
865
+ return Object.assign(formatMessage(originalMessage), {
866
+ type: "event",
867
+ logMessageType: logMessageType,
868
+ logMessageData: logMessageData,
869
+ logMessageBody: originalMessage.log_message_body
870
+ });
871
+ }
872
+
873
+ function formatHistoryMessage(m) {
874
+ switch (m.action_type) {
875
+ case "ma-type:log-message":
876
+ return formatEvent(m);
877
+ default:
878
+ return formatMessage(m);
879
+ }
880
+ }
881
+
882
+ // Get a more readable message type for AdminTextMessages
883
+ function getAdminTextMessageType(type) {
884
+ switch (type) {
885
+ case 'unpin_messages_v2':
886
+ return 'log:unpin-message';
887
+ case 'pin_messages_v2':
888
+ return 'log:pin-message';
889
+ case "change_thread_theme":
890
+ return "log:thread-color";
891
+ case "change_thread_icon":
892
+ case 'change_thread_quick_reaction':
893
+ return "log:thread-icon";
894
+ case "change_thread_nickname":
895
+ return "log:user-nickname";
896
+ case "change_thread_admins":
897
+ return "log:thread-admins";
898
+ case "group_poll":
899
+ return "log:thread-poll";
900
+ case "change_thread_approval_mode":
901
+ return "log:thread-approval-mode";
902
+ case "messenger_call_log":
903
+ case "participant_joined_group_call":
904
+ return "log:thread-call";
905
+ default:
906
+ return type;
907
+ }
908
+ }
909
+
910
+ function formatDeltaEvent(m) {
911
+ let logMessageType;
912
+ let logMessageData;
913
+
914
+ // log:thread-color => {theme_color}
915
+ // log:user-nickname => {participant_id, nickname}
916
+ // log:thread-icon => {thread_icon}
917
+ // log:thread-name => {name}
918
+ // log:subscribe => {addedParticipants - [Array]}
919
+ // log:unsubscribe => {leftParticipantFbId}
920
+
921
+ switch (m.class) {
922
+ case "AdminTextMessage":
923
+ logMessageData = m.untypedData;
924
+ logMessageType = getAdminTextMessageType(m.type);
925
+ break;
926
+ case "ThreadName":
927
+ logMessageType = "log:thread-name";
928
+ logMessageData = { name: m.name };
929
+ break;
930
+ case "ParticipantsAddedToGroupThread":
931
+ logMessageType = "log:subscribe";
932
+ logMessageData = { addedParticipants: m.addedParticipants };
933
+ break;
934
+ case "ParticipantLeftGroupThread":
935
+ logMessageType = "log:unsubscribe";
936
+ logMessageData = { leftParticipantFbId: m.leftParticipantFbId };
937
+ break;
938
+ case "ApprovalQueue":
939
+ logMessageType = "log:approval-queue";
940
+ logMessageData = {
941
+ approvalQueue: {
942
+ action: m.action,
943
+ recipientFbId: m.recipientFbId,
944
+ requestSource: m.requestSource,
945
+ ...m.messageMetadata
946
+ }
947
+ };
948
+ }
949
+ return {
950
+ type: "event",
951
+ threadID: formatID(
952
+ (
953
+ m.messageMetadata.threadKey.threadFbId ||
954
+ m.messageMetadata.threadKey.otherUserFbId
955
+ ).toString()
956
+ ),
957
+ messageID: m.messageMetadata.messageId.toString(),
958
+ logMessageType,
959
+ logMessageData,
960
+ logMessageBody: m.messageMetadata.adminText,
961
+ timestamp: m.messageMetadata.timestamp,
962
+ author: m.messageMetadata.actorFbId,
963
+ participantIDs: m.participants
964
+ };
965
+ }
966
+
967
+ function formatTyp(event) {
968
+ return {
969
+ isTyping: !!event.st,
970
+ from: event.from.toString(),
971
+ threadID: formatID(
972
+ (event.to || event.thread_fbid || event.from).toString()
973
+ ),
974
+ // When receiving typ indication from mobile, `from_mobile` isn't set.
975
+ // If it is, we just use that value.
976
+ fromMobile: event.hasOwnProperty("from_mobile") ? event.from_mobile : true,
977
+ userID: (event.realtime_viewer_fbid || event.from).toString(),
978
+ type: "typ"
979
+ };
980
+ }
981
+
982
+ function formatDeltaReadReceipt(delta) {
983
+ // otherUserFbId seems to be used as both the readerID and the threadID in a 1-1 chat.
984
+ // In a group chat actorFbId is used for the reader and threadFbId for the thread.
985
+ return {
986
+ reader: (delta.threadKey.otherUserFbId || delta.actorFbId).toString(),
987
+ time: delta.actionTimestampMs,
988
+ threadID: formatID(
989
+ (delta.threadKey.otherUserFbId || delta.threadKey.threadFbId).toString()
990
+ ),
991
+ type: "read_receipt"
992
+ };
993
+ }
994
+
995
+ function formatReadReceipt(event) {
996
+ return {
997
+ reader: event.reader.toString(),
998
+ time: event.time,
999
+ threadID: formatID((event.thread_fbid || event.reader).toString()),
1000
+ type: "read_receipt"
1001
+ };
1002
+ }
1003
+
1004
+ function formatRead(event) {
1005
+ return {
1006
+ threadID: formatID(
1007
+ (
1008
+ (event.chat_ids && event.chat_ids[0]) ||
1009
+ (event.thread_fbids && event.thread_fbids[0])
1010
+ ).toString()
1011
+ ),
1012
+ time: event.timestamp,
1013
+ type: "read"
1014
+ };
1015
+ }
1016
+
1017
+ function getFrom(str, startToken, endToken) {
1018
+ const start = str.indexOf(startToken) + startToken.length;
1019
+ if (start < startToken.length) return "";
1020
+
1021
+ const lastHalf = str.substring(start);
1022
+ const end = lastHalf.indexOf(endToken);
1023
+ if (end === -1) {
1024
+ throw Error(
1025
+ "Could not find endTime `" + endToken + "` in the given string."
1026
+ );
1027
+ }
1028
+ return lastHalf.substring(0, end);
1029
+ }
1030
+
1031
+ function makeParsable(html) {
1032
+ const withoutForLoop = html.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, "");
1033
+
1034
+ // (What the fuck FB, why windows style newlines?)
1035
+ // So sometimes FB will send us base multiple objects in the same response.
1036
+ // They're all valid JSON, one after the other, at the top level. We detect
1037
+ // that and make it parse-able by JSON.parse.
1038
+ // Ben - July 15th 2017
1039
+ //
1040
+ // It turns out that Facebook may insert random number of spaces before
1041
+ // next object begins (issue #616)
1042
+ // rav_kr - 2018-03-19
1043
+ const maybeMultipleObjects = withoutForLoop.split(/\}\r\n *\{/);
1044
+ if (maybeMultipleObjects.length === 1) return maybeMultipleObjects;
1045
+
1046
+ return "[" + maybeMultipleObjects.join("},{") + "]";
1047
+ }
1048
+
1049
+ function arrToForm(form) {
1050
+ return arrayToObject(
1051
+ form,
1052
+ function(v) {
1053
+ return v.name;
1054
+ },
1055
+ function(v) {
1056
+ return v.val;
1057
+ }
1058
+ );
1059
+ }
1060
+
1061
+ function arrayToObject(arr, getKey, getValue) {
1062
+ return arr.reduce(function(acc, val) {
1063
+ acc[getKey(val)] = getValue(val);
1064
+ return acc;
1065
+ }, {});
1066
+ }
1067
+
1068
+ function getSignatureID() {
1069
+ return Math.floor(Math.random() * 2147483648).toString(16);
1070
+ }
1071
+
1072
+ function generateTimestampRelative() {
1073
+ const d = new Date();
1074
+ return d.getHours() + ":" + padZeros(d.getMinutes());
1075
+ }
1076
+
1077
+ function makeDefaults(html, userID, ctx) {
1078
+ let reqCounter = 1;
1079
+ const fb_dtsg = getFrom(html, 'name="fb_dtsg" value="', '"');
1080
+
1081
+ let ttstamp = "2";
1082
+ for (let i = 0; i < fb_dtsg.length; i++) {
1083
+ ttstamp += fb_dtsg.charCodeAt(i);
1084
+ }
1085
+ const revision = getFrom(html, 'revision":', ",");
1086
+
1087
+ function mergeWithDefaults(obj) {
1088
+ const newObj = {
1089
+ av: userID,
1090
+ __user: userID,
1091
+ __req: (reqCounter++).toString(36),
1092
+ __rev: revision,
1093
+ __a: 1,
1094
+ fb_dtsg: ctx.fb_dtsg || fb_dtsg,
1095
+ jazoest: ctx.ttstamp || ttstamp
1096
+ }
1097
+
1098
+ if (!obj) return newObj;
1099
+
1100
+ for (var prop in obj) {
1101
+ if (obj.hasOwnProperty(prop)) {
1102
+ if (!newObj[prop])
1103
+ newObj[prop] = obj[prop];
1104
+ }
1105
+ }
1106
+
1107
+ return newObj;
1108
+ }
1109
+
1110
+ return {
1111
+ get: (url, jar, qs, ctxx, customHeader = {}) => get(url, jar, mergeWithDefaults(qs), ctx.globalOptions, ctxx || ctx, customHeader),
1112
+ post: (url, jar, form, ctxx, customHeader = {}) => post(url, jar, mergeWithDefaults(form), ctx.globalOptions, ctxx || ctx, customHeader),
1113
+ postFormData: (url, jar, form, qs, ctxx) => postFormData(url, jar, mergeWithDefaults(form), mergeWithDefaults(qs), ctx.globalOptions, ctxx || ctx)
1114
+ };
1115
+ }
1116
+
1117
+ function parseAndCheckLogin(ctx, http, retryCount) {
1118
+ var delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
1119
+ var _try = (tryData) => new Promise(function(resolve, reject) {
1120
+ try {
1121
+ resolve(tryData());
1122
+ } catch (error) {
1123
+ reject(error);
1124
+ }
1125
+ });
1126
+ if (retryCount == undefined) retryCount = 0;
1127
+
1128
+ return function(data) {
1129
+ function any() {
1130
+ if (data.statusCode >= 500 && data.statusCode < 600) {
1131
+ if (retryCount >= 5) {
1132
+ const err = new Error("Request retry failed. Check the `res` and `statusCode` property on this error.");
1133
+ err.statusCode = data.statusCode;
1134
+ err.res = data.body;
1135
+ err.error = "Request retry failed. Check the `res` and `statusCode` property on this error.";
1136
+ throw err;
1137
+ }
1138
+ retryCount++;
1139
+ const retryTime = Math.floor(Math.random() * 5000);
1140
+ console.warn("parseAndCheckLogin", "Got status code " + data.statusCode + " - " + retryCount + ". attempt to retry in " + retryTime + " milliseconds...");
1141
+ const url = data.request.uri.protocol + "//" + data.request.uri.hostname + data.request.uri.pathname;
1142
+ if (data.request.headers["content-type"].split(";")[0] === "multipart/form-data") {
1143
+ return delay(retryTime)
1144
+ .then(function() {
1145
+ return http
1146
+ .postFormData(url, ctx.jar, data.request.formData);
1147
+ })
1148
+ .then(parseAndCheckLogin(ctx, http, retryCount));
1149
+ }
1150
+ else {
1151
+ return delay(retryTime)
1152
+ .then(function() {
1153
+ return http
1154
+ .post(url, ctx.jar, data.request.formData);
1155
+ })
1156
+ .then(parseAndCheckLogin(ctx, http, retryCount));
1157
+ }
1158
+ }
1159
+
1160
+ if (data.statusCode === 404) return;
1161
+
1162
+ if (data.statusCode !== 200)
1163
+ throw new Error("parseAndCheckLogin got status code: " + data.statusCode + ". Bailing out of trying to parse response.");
1164
+
1165
+ let res = null;
1166
+ try {
1167
+ res = JSON.parse(makeParsable(data.body));
1168
+ } catch (e) {
1169
+ const err = new Error("JSON.parse error. Check the `detail` property on this error.");
1170
+ err.error = "JSON.parse error. Check the `detail` property on this error.";
1171
+ err.detail = e;
1172
+ err.res = data.body;
1173
+ throw err;
1174
+ }
1175
+
1176
+ // In some cases the response contains only a redirect URL which should be followed
1177
+ if (res.redirect && data.request.method === "GET") {
1178
+ return http
1179
+ .get(res.redirect, ctx.jar)
1180
+ .then(parseAndCheckLogin(ctx, http));
1181
+ }
1182
+
1183
+ // TODO: handle multiple cookies?
1184
+ if (res.jsmods && res.jsmods.require && Array.isArray(res.jsmods.require[0]) && res.jsmods.require[0][0] === "Cookie") {
1185
+ res.jsmods.require[0][3][0] = res.jsmods.require[0][3][0].replace("_js_", "");
1186
+ const requireCookie = res.jsmods.require[0][3];
1187
+ ctx.jar.setCookie(formatCookie(requireCookie, "facebook"), "https://www.facebook.com");
1188
+ ctx.jar.setCookie(formatCookie(requireCookie, "messenger"), "https://www.messenger.com");
1189
+ }
1190
+
1191
+ // On every request we check if we got a DTSG and we mutate the context so that we use the latest
1192
+ // one for the next requests.
1193
+ if (res.jsmods && Array.isArray(res.jsmods.require)) {
1194
+ const arr = res.jsmods.require;
1195
+ for (const i in arr) {
1196
+ if (arr[i][0] === "DTSG" && arr[i][1] === "setToken") {
1197
+ ctx.fb_dtsg = arr[i][3][0];
1198
+
1199
+ // Update ttstamp since that depends on fb_dtsg
1200
+ ctx.ttstamp = "2";
1201
+ for (let j = 0; j < ctx.fb_dtsg.length; j++) {
1202
+ ctx.ttstamp += ctx.fb_dtsg.charCodeAt(j);
1203
+ }
1204
+ }
1205
+ }
1206
+ }
1207
+
1208
+ if (res.error === 1357001) {
1209
+ const err = new Error('Facebook blocked the login');
1210
+ err.error = "Not logged in.";
1211
+ throw err;
1212
+ }
1213
+ return res;
1214
+ }
1215
+ return _try(any);
1216
+ };
1217
+ }
1218
+
1219
+ function saveCookies(jar) {
1220
+ return function(res) {
1221
+ const cookies = res.headers["set-cookie"] || [];
1222
+ cookies.forEach(function(c) {
1223
+ if (c.indexOf(".facebook.com") > -1) {
1224
+ jar.setCookie(c, "https://www.facebook.com");
1225
+ }
1226
+ const c2 = c.replace(/domain=\.facebook\.com/, "domain=.messenger.com");
1227
+ jar.setCookie(c2, "https://www.messenger.com");
1228
+ });
1229
+ return res;
1230
+ };
1231
+ }
1232
+
1233
+ const NUM_TO_MONTH = [
1234
+ "Jan",
1235
+ "Feb",
1236
+ "Mar",
1237
+ "Apr",
1238
+ "May",
1239
+ "Jun",
1240
+ "Jul",
1241
+ "Aug",
1242
+ "Sep",
1243
+ "Oct",
1244
+ "Nov",
1245
+ "Dec"
1246
+ ];
1247
+ const NUM_TO_DAY = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
1248
+
1249
+ function formatDate(date) {
1250
+ let d = date.getUTCDate();
1251
+ d = d >= 10 ? d : "0" + d;
1252
+ let h = date.getUTCHours();
1253
+ h = h >= 10 ? h : "0" + h;
1254
+ let m = date.getUTCMinutes();
1255
+ m = m >= 10 ? m : "0" + m;
1256
+ let s = date.getUTCSeconds();
1257
+ s = s >= 10 ? s : "0" + s;
1258
+ return (
1259
+ NUM_TO_DAY[date.getUTCDay()] +
1260
+ ", " +
1261
+ d +
1262
+ " " +
1263
+ NUM_TO_MONTH[date.getUTCMonth()] +
1264
+ " " +
1265
+ date.getUTCFullYear() +
1266
+ " " +
1267
+ h +
1268
+ ":" +
1269
+ m +
1270
+ ":" +
1271
+ s +
1272
+ " GMT"
1273
+ );
1274
+ }
1275
+
1276
+ function formatCookie(arr, url) {
1277
+ return (
1278
+ arr[0] + "=" + arr[1] + "; Path=" + arr[3] + "; Domain=" + url + ".com"
1279
+ );
1280
+ }
1281
+
1282
+ function formatThread(data) {
1283
+ return {
1284
+ threadID: formatID(data.thread_fbid.toString()),
1285
+ participants: data.participants.map(formatID),
1286
+ participantIDs: data.participants.map(formatID),
1287
+ name: data.name,
1288
+ nicknames: data.custom_nickname,
1289
+ snippet: data.snippet,
1290
+ snippetAttachments: data.snippet_attachments,
1291
+ snippetSender: formatID((data.snippet_sender || "").toString()),
1292
+ unreadCount: data.unread_count,
1293
+ messageCount: data.message_count,
1294
+ imageSrc: data.image_src,
1295
+ timestamp: data.timestamp,
1296
+ serverTimestamp: data.server_timestamp, // what is this?
1297
+ muteUntil: data.mute_until,
1298
+ isCanonicalUser: data.is_canonical_user,
1299
+ isCanonical: data.is_canonical,
1300
+ isSubscribed: data.is_subscribed,
1301
+ folder: data.folder,
1302
+ isArchived: data.is_archived,
1303
+ recipientsLoadable: data.recipients_loadable,
1304
+ hasEmailParticipant: data.has_email_participant,
1305
+ readOnly: data.read_only,
1306
+ canReply: data.can_reply,
1307
+ cannotReplyReason: data.cannot_reply_reason,
1308
+ lastMessageTimestamp: data.last_message_timestamp,
1309
+ lastReadTimestamp: data.last_read_timestamp,
1310
+ lastMessageType: data.last_message_type,
1311
+ emoji: data.custom_like_icon,
1312
+ color: data.custom_color,
1313
+ adminIDs: data.admin_ids,
1314
+ threadType: data.thread_type
1315
+ };
1316
+ }
1317
+
1318
+ function getType(obj) {
1319
+ return Object.prototype.toString.call(obj).slice(8, -1);
1320
+ }
1321
+
1322
+ function formatProxyPresence(presence, userID) {
1323
+ if (presence.lat === undefined || presence.p === undefined) return null;
1324
+ return {
1325
+ type: "presence",
1326
+ timestamp: presence.lat * 1000,
1327
+ userID: userID,
1328
+ statuses: presence.p
1329
+ };
1330
+ }
1331
+
1332
+ function formatPresence(presence, userID) {
1333
+ return {
1334
+ type: "presence",
1335
+ timestamp: presence.la * 1000,
1336
+ userID: userID,
1337
+ statuses: presence.a
1338
+ };
1339
+ }
1340
+
1341
+ function decodeClientPayload(payload) {
1342
+ /*
1343
+ Special function which Client using to "encode" clients JSON payload
1344
+ */
1345
+ return JSON.parse(String.fromCharCode.apply(null, payload));
1346
+ }
1347
+
1348
+ function getAppState(jar) {
1349
+ return jar
1350
+ .getCookies("https://www.facebook.com")
1351
+ .concat(jar.getCookies("https://www.messenger.com"));
1352
+ }
1353
+
1354
+ function getAccessFromBusiness(jar, Options) {
1355
+ return function(res) {
1356
+ var html = res ? res.body : null;
1357
+ return get('https://business.facebook.com/content_management', jar, null, Options, null, { noRef: true })
1358
+ .then(function(res) {
1359
+ var token = /"accessToken":"([^.]+)","clientID":/g.exec(res.body)[1];
1360
+ return [html, token];
1361
+ })
1362
+ .catch(function() {
1363
+ return [html, null];
1364
+ });
1365
+ }
1366
+ }
1367
+
1368
+ const meta = prop => new RegExp(`<meta property="${prop}" content="([^"]*)"`);
1369
+
1370
+ module.exports = {
1371
+ isReadableStream,
1372
+ get,
1373
+ post,
1374
+ postFormData,
1375
+ generateThreadingID,
1376
+ generateOfflineThreadingID,
1377
+ getGUID,
1378
+ getFrom,
1379
+ makeParsable,
1380
+ arrToForm,
1381
+ getSignatureID,
1382
+ getJar: request.jar,
1383
+ generateTimestampRelative,
1384
+ makeDefaults,
1385
+ parseAndCheckLogin,
1386
+ saveCookies,
1387
+ getType,
1388
+ _formatAttachment,
1389
+ formatHistoryMessage,
1390
+ formatID,
1391
+ formatMessage,
1392
+ formatDeltaEvent,
1393
+ formatDeltaMessage,
1394
+ formatProxyPresence,
1395
+ formatPresence,
1396
+ formatTyp,
1397
+ formatDeltaReadReceipt,
1398
+ formatCookie,
1399
+ formatThread,
1400
+ formatReadReceipt,
1401
+ formatRead,
1402
+ generatePresence,
1403
+ generateAccessiblityCookie,
1404
+ formatDate,
1405
+ decodeClientPayload,
1406
+ getAppState,
1407
+ getAdminTextMessageType,
1408
+ setProxy,
1409
+ getAccessFromBusiness,
1410
+ presenceDecode,
1411
+ presenceEncode,
1412
+ headers,
1413
+ defaultUserAgent,
1414
+ randomUserAgent,
1415
+ meta
1416
+ };