fca-neokex-fix 1.0.1

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 (114) hide show
  1. package/CHANGELOG.md +220 -0
  2. package/LICENSE +26 -0
  3. package/README.md +346 -0
  4. package/THEME_FEATURES.md +137 -0
  5. package/examples/README.md +131 -0
  6. package/examples/apply-ai-theme.js +127 -0
  7. package/examples/check-current-theme.js +74 -0
  8. package/examples/simple-bot.js +114 -0
  9. package/examples/test-bot.js +752 -0
  10. package/examples/test-logging.js +85 -0
  11. package/examples/theme-usage-example.js +53 -0
  12. package/index.js +2 -0
  13. package/package.json +105 -0
  14. package/src/apis/addExternalModule.js +24 -0
  15. package/src/apis/addUserToGroup.js +108 -0
  16. package/src/apis/changeAdminStatus.js +148 -0
  17. package/src/apis/changeArchivedStatus.js +61 -0
  18. package/src/apis/changeAvatar.js +103 -0
  19. package/src/apis/changeBio.js +69 -0
  20. package/src/apis/changeBlockedStatus.js +54 -0
  21. package/src/apis/changeGroupImage.js +136 -0
  22. package/src/apis/changeThreadColor.js +116 -0
  23. package/src/apis/comment.js +207 -0
  24. package/src/apis/createAITheme.js +129 -0
  25. package/src/apis/createNewGroup.js +79 -0
  26. package/src/apis/createPoll.js +73 -0
  27. package/src/apis/deleteMessage.js +44 -0
  28. package/src/apis/deleteThread.js +52 -0
  29. package/src/apis/editMessage.js +70 -0
  30. package/src/apis/emoji.js +124 -0
  31. package/src/apis/fetchThemeData.js +65 -0
  32. package/src/apis/follow.js +81 -0
  33. package/src/apis/forwardMessage.js +52 -0
  34. package/src/apis/friend.js +243 -0
  35. package/src/apis/gcmember.js +122 -0
  36. package/src/apis/gcname.js +123 -0
  37. package/src/apis/gcrule.js +119 -0
  38. package/src/apis/getAccess.js +111 -0
  39. package/src/apis/getBotInfo.js +88 -0
  40. package/src/apis/getBotInitialData.js +43 -0
  41. package/src/apis/getFriendsList.js +79 -0
  42. package/src/apis/getMessage.js +423 -0
  43. package/src/apis/getTheme.js +104 -0
  44. package/src/apis/getThemeInfo.js +96 -0
  45. package/src/apis/getThreadHistory.js +239 -0
  46. package/src/apis/getThreadInfo.js +257 -0
  47. package/src/apis/getThreadList.js +222 -0
  48. package/src/apis/getThreadPictures.js +58 -0
  49. package/src/apis/getUserID.js +83 -0
  50. package/src/apis/getUserInfo.js +495 -0
  51. package/src/apis/getUserInfoV2.js +146 -0
  52. package/src/apis/handleMessageRequest.js +50 -0
  53. package/src/apis/httpGet.js +63 -0
  54. package/src/apis/httpPost.js +89 -0
  55. package/src/apis/httpPostFormData.js +69 -0
  56. package/src/apis/listenMqtt.js +796 -0
  57. package/src/apis/listenSpeed.js +170 -0
  58. package/src/apis/logout.js +63 -0
  59. package/src/apis/markAsDelivered.js +47 -0
  60. package/src/apis/markAsRead.js +95 -0
  61. package/src/apis/markAsReadAll.js +41 -0
  62. package/src/apis/markAsSeen.js +70 -0
  63. package/src/apis/mqttDeltaValue.js +330 -0
  64. package/src/apis/muteThread.js +45 -0
  65. package/src/apis/nickname.js +132 -0
  66. package/src/apis/notes.js +163 -0
  67. package/src/apis/pinMessage.js +141 -0
  68. package/src/apis/produceMetaTheme.js +180 -0
  69. package/src/apis/realtime.js +161 -0
  70. package/src/apis/removeUserFromGroup.js +117 -0
  71. package/src/apis/resolvePhotoUrl.js +58 -0
  72. package/src/apis/searchForThread.js +154 -0
  73. package/src/apis/sendMessage.js +281 -0
  74. package/src/apis/sendMessageMqtt.js +188 -0
  75. package/src/apis/sendTypingIndicator.js +41 -0
  76. package/src/apis/setMessageReaction.js +27 -0
  77. package/src/apis/setMessageReactionMqtt.js +61 -0
  78. package/src/apis/setThreadTheme.js +260 -0
  79. package/src/apis/setThreadThemeMqtt.js +94 -0
  80. package/src/apis/share.js +107 -0
  81. package/src/apis/shareContact.js +66 -0
  82. package/src/apis/stickers.js +257 -0
  83. package/src/apis/story.js +181 -0
  84. package/src/apis/theme.js +233 -0
  85. package/src/apis/unfriend.js +47 -0
  86. package/src/apis/unsendMessage.js +17 -0
  87. package/src/database/appStateBackup.js +189 -0
  88. package/src/database/models/index.js +56 -0
  89. package/src/database/models/thread.js +31 -0
  90. package/src/database/models/user.js +32 -0
  91. package/src/database/threadData.js +101 -0
  92. package/src/database/userData.js +90 -0
  93. package/src/engine/client.js +91 -0
  94. package/src/engine/models/buildAPI.js +109 -0
  95. package/src/engine/models/loginHelper.js +326 -0
  96. package/src/engine/models/setOptions.js +53 -0
  97. package/src/utils/auth-helpers.js +149 -0
  98. package/src/utils/autoReLogin.js +169 -0
  99. package/src/utils/axios.js +290 -0
  100. package/src/utils/clients.js +270 -0
  101. package/src/utils/constants.js +396 -0
  102. package/src/utils/formatters/data/formatAttachment.js +370 -0
  103. package/src/utils/formatters/data/formatDelta.js +153 -0
  104. package/src/utils/formatters/index.js +159 -0
  105. package/src/utils/formatters/value/formatCookie.js +91 -0
  106. package/src/utils/formatters/value/formatDate.js +36 -0
  107. package/src/utils/formatters/value/formatID.js +16 -0
  108. package/src/utils/formatters.js +1067 -0
  109. package/src/utils/headers.js +199 -0
  110. package/src/utils/index.js +151 -0
  111. package/src/utils/monitoring.js +358 -0
  112. package/src/utils/rateLimiter.js +380 -0
  113. package/src/utils/tokenRefresh.js +311 -0
  114. package/src/utils/user-agents.js +238 -0
@@ -0,0 +1,1067 @@
1
+ /* eslint-disable no-prototype-builtins */
2
+ "use strict";
3
+ const url = require("url");
4
+
5
+ const querystring = require("querystring");
6
+
7
+ const stream = require("stream");
8
+
9
+ const { getType, padZeros, NUM_TO_MONTH, NUM_TO_DAY } = require("./constants");
10
+ function isReadableStream(obj) {
11
+ return obj instanceof stream.Stream && typeof obj._read == "function" && getType(obj._readableState) == "Object";
12
+ }
13
+
14
+ function getExtension(original_extension, fullFileName = "") {
15
+ if (original_extension) {
16
+ return original_extension;
17
+ } else {
18
+ const extension = fullFileName.split(".").pop();
19
+ if (extension === fullFileName) {
20
+ return "";
21
+ } else {
22
+ return extension;
23
+ }
24
+ }
25
+ }
26
+
27
+ /**
28
+ * A function for formatting incoming attachments.
29
+ * @param {Object} attachment1 - The main attachment object.
30
+ * @param {Object} attachment2 - A secondary attachment object that sometimes contains additional data.
31
+ * @returns {Object} A formatted attachment object.
32
+ */
33
+ function _formatAttachment(attachment1, attachment2) {
34
+ const blob_attachment = attachment1.mercury || attachment1.blob_attachment || attachment1.sticker_attachment;
35
+ const type_attachment = blob_attachment && blob_attachment.__typename ? blob_attachment.__typename : attachment1.attach_type;
36
+ if (type_attachment == null && attachment1.id != null && attachment1.extensible_attachment == null) {
37
+ return {
38
+ type: "share",
39
+ ID: attachment1.id,
40
+ url: attachment1.href,
41
+ title: "Shared Content",
42
+ description: "Unsupported shared content.",
43
+ source: null,
44
+ isUnrecognized: true
45
+ };
46
+ }
47
+
48
+ if (!attachment1.attach_type && attachment1.imageMetadata) {
49
+ return {
50
+ type: 'photo',
51
+ ID: attachment1.fbid,
52
+ filename: attachment1.filename,
53
+ fileSize: Number(attachment1.fileSize || 0),
54
+ mimeType: attachment1.mimeType,
55
+ width: attachment1.imageMetadata.width,
56
+ height: attachment1.imageMetadata.height,
57
+ url: null,
58
+ thumbnailUrl: null,
59
+ previewUrl: null,
60
+ largePreviewUrl: null,
61
+ name: attachment1.filename
62
+ };
63
+ }
64
+
65
+
66
+ attachment2 = attachment2 || {
67
+ id: "",
68
+ image_data: {}
69
+ };
70
+ attachment1 = attachment1.mercury || attachment1;
71
+ let blob = attachment1.blob_attachment || attachment1.sticker_attachment;
72
+ let type =
73
+ blob && blob.__typename ? blob.__typename: attachment1.attach_type;
74
+ if (!type && attachment1.sticker_attachment) {
75
+ type = "StickerAttachment";
76
+ blob = attachment1.sticker_attachment;
77
+ } else if (!type && attachment1.extensible_attachment) {
78
+ if (
79
+ attachment1.extensible_attachment.story_attachment &&
80
+ attachment1.extensible_attachment.story_attachment.target &&
81
+ attachment1.extensible_attachment.story_attachment.target.__typename &&
82
+ attachment1.extensible_attachment.story_attachment.target.__typename === "MessageLocation"
83
+ ) {
84
+ type = "MessageLocation";
85
+ } else {
86
+ type = "ExtensibleAttachment";
87
+ }
88
+
89
+ blob = attachment1.extensible_attachment;
90
+ }
91
+
92
+ const fullFileName = attachment1.filename;
93
+ const fileSize = Number(attachment1.fileSize || 0);
94
+ const durationVideo = attachment1.genericMetadata ? Number(attachment1.genericMetadata.videoLength): undefined;
95
+ const durationAudio = attachment1.genericMetadata ? Number(attachment1.genericMetadata.duration): undefined;
96
+ const mimeType = attachment1.mimeType;
97
+
98
+ switch (type) {
99
+ case "sticker":
100
+ return {
101
+ type: "sticker",
102
+ ID: attachment1.metadata.stickerID.toString(),
103
+ url: attachment1.url,
104
+ packID: attachment1.metadata.packID.toString(),
105
+ spriteUrl: attachment1.metadata.spriteURI,
106
+ spriteUrl2x: attachment1.metadata.spriteURI2x,
107
+ width: attachment1.metadata.width,
108
+ height: attachment1.metadata.height,
109
+ caption: attachment2.caption,
110
+ description: attachment2.description,
111
+ frameCount: attachment1.metadata.frameCount,
112
+ frameRate: attachment1.metadata.frameRate,
113
+ framesPerRow: attachment1.metadata.framesPerRow,
114
+ framesPerCol: attachment1.metadata.framesPerCol,
115
+ stickerID: attachment1.metadata.stickerID.toString(),
116
+ spriteURI: attachment1.metadata.spriteURI,
117
+ spriteURI2x: attachment1.metadata.spriteURI2x
118
+ };
119
+ case "file":
120
+ return {
121
+ type: "file",
122
+ ID: attachment2.id.toString(),
123
+ fullFileName: fullFileName,
124
+ filename: attachment1.name,
125
+ fileSize: fileSize,
126
+ original_extension: getExtension(attachment1.original_extension, fullFileName),
127
+ mimeType: mimeType,
128
+ url: attachment1.url,
129
+ isMalicious: attachment2.is_malicious,
130
+ contentType: attachment2.mime_type,
131
+ name: attachment1.name
132
+ };
133
+ case "photo":
134
+ return {
135
+ type: "photo",
136
+ ID: attachment1.metadata.fbid.toString(),
137
+ filename: attachment1.fileName,
138
+ fullFileName: fullFileName,
139
+ fileSize: fileSize,
140
+ original_extension: getExtension(attachment1.original_extension, fullFileName),
141
+ mimeType: mimeType,
142
+ thumbnailUrl: attachment1.thumbnail_url,
143
+ previewUrl: attachment1.preview_url,
144
+ previewWidth: attachment1.preview_width,
145
+ previewHeight: attachment1.preview_height,
146
+ largePreviewUrl: attachment1.large_preview_url,
147
+ largePreviewWidth: attachment1.large_preview_width,
148
+ largePreviewHeight: attachment1.large_preview_height,
149
+ url: attachment1.metadata.url,
150
+ width: attachment1.metadata.dimensions.split(",")[0],
151
+ height: attachment1.metadata.dimensions.split(",")[1],
152
+ name: fullFileName
153
+ };
154
+ case "animated_image":
155
+ return {
156
+ type: "animated_image",
157
+ ID: attachment2.id.toString(),
158
+ filename: attachment2.filename,
159
+ fullFileName: fullFileName,
160
+ original_extension: getExtension(attachment2.original_extension, fullFileName),
161
+ mimeType: mimeType,
162
+ previewUrl: attachment1.preview_url,
163
+ previewWidth: attachment1.preview_width,
164
+ previewHeight: attachment1.preview_height,
165
+ url: attachment2.image_data.url,
166
+ width: attachment2.image_data.width,
167
+ height: attachment2.image_data.height,
168
+ name: attachment1.name,
169
+ facebookUrl: attachment1.url,
170
+ thumbnailUrl: attachment1.thumbnail_url,
171
+ rawGifImage: attachment2.image_data.raw_gif_image,
172
+ rawWebpImage: attachment2.image_data.raw_webp_image,
173
+ animatedGifUrl: attachment2.image_data.animated_gif_url,
174
+ animatedGifPreviewUrl: attachment2.image_data.animated_gif_preview_url,
175
+ animatedWebpUrl: attachment2.image_data.animated_webp_url,
176
+ animatedWebpPreviewUrl: attachment2.image_data.animated_webp_preview_url
177
+ };
178
+ case "share":
179
+ return {
180
+ type: "share",
181
+ ID: attachment1.share.share_id.toString(),
182
+ url: attachment2.href,
183
+ title: attachment1.share.title,
184
+ description: attachment1.share.description,
185
+ source: attachment1.share.source,
186
+ image: attachment1.share.media.image,
187
+ width: attachment1.share.media.image_slicewidth,
188
+ height: attachment1.share.media.image_size.height,
189
+ playable: attachment1.share.media.playable,
190
+ duration: attachment1.share.media.duration,
191
+ subattachments: attachment1.share.subattachments,
192
+ properties: {},
193
+ animatedImageSize: attachment1.share.media.animated_image_size,
194
+ facebookUrl: attachment1.share.uri,
195
+ target: attachment1.share.target,
196
+ styleList: attachment1.share.style_list
197
+ };
198
+ case "video":
199
+ return {
200
+ type: "video",
201
+ ID: attachment1.metadata.fbid.toString(),
202
+ filename: attachment1.name,
203
+ fullFileName: fullFileName,
204
+ original_extension: getExtension(attachment1.original_extension, fullFileName),
205
+ mimeType: mimeType,
206
+ duration: durationVideo,
207
+ previewUrl: attachment1.preview_url,
208
+ previewWidth: attachment1.preview_width,
209
+ previewHeight: attachment1.preview_height,
210
+ url: attachment1.url,
211
+ width: attachment1.metadata.dimensions.width,
212
+ height: attachment1.metadata.dimensions.height,
213
+ videoType: "unknown",
214
+ thumbnailUrl: attachment1.thumbnail_url
215
+ };
216
+ case "error":
217
+ return {
218
+ type: "error",
219
+ attachment1: attachment1,
220
+ attachment2: attachment2
221
+ };
222
+ case "MessageImage":
223
+ return {
224
+ type: "photo",
225
+ ID: blob.legacy_attachment_id,
226
+ filename: blob.filename,
227
+ fullFileName: fullFileName,
228
+ fileSize: fileSize,
229
+ original_extension: getExtension(blob.original_extension, fullFileName),
230
+ mimeType: mimeType,
231
+ thumbnailUrl: blob.thumbnail.uri,
232
+ previewUrl: blob.preview.uri,
233
+ previewWidth: blob.preview.width,
234
+ previewHeight: blob.preview.height,
235
+ largePreviewUrl: blob.large_preview.uri,
236
+ largePreviewWidth: blob.large_preview.width,
237
+ largePreviewHeight: blob.large_preview.height,
238
+ url: blob.large_preview.uri,
239
+ width: blob.original_dimensions.x,
240
+ height: blob.original_dimensions.y,
241
+ name: blob.filename
242
+ };
243
+ case "MessageAnimatedImage":
244
+ return {
245
+ type: "animated_image",
246
+ ID: blob.legacy_attachment_id,
247
+ filename: blob.filename,
248
+ fullFileName: fullFileName,
249
+ original_extension: getExtension(blob.original_extension, fullFileName),
250
+ mimeType: mimeType,
251
+ previewUrl: blob.preview_image.uri,
252
+ previewWidth: blob.preview_image.width,
253
+ previewHeight: blob.preview_image.height,
254
+ url: blob.animated_image.uri,
255
+ width: blob.animated_image.width,
256
+ height: blob.animated_image.height,
257
+ thumbnailUrl: blob.preview_image.uri,
258
+ name: blob.filename,
259
+ facebookUrl: blob.animated_image.uri,
260
+ rawGifImage: blob.animated_image.uri,
261
+ animatedGifUrl: blob.animated_image.uri,
262
+ animatedGifPreviewUrl: blob.preview_image.uri,
263
+ animatedWebpUrl: blob.animated_image.uri,
264
+ animatedWebpPreviewUrl: blob.preview_image.uri
265
+ };
266
+ case "MessageVideo":
267
+ return {
268
+ type: "video",
269
+ ID: blob.legacy_attachment_id,
270
+ filename: blob.filename,
271
+ fullFileName: fullFileName,
272
+ original_extension: getExtension(blob.original_extension, fullFileName),
273
+ fileSize: fileSize,
274
+ duration: durationVideo,
275
+ mimeType: mimeType,
276
+ previewUrl: blob.large_image.uri,
277
+ previewWidth: blob.large_image.width,
278
+ previewHeight: blob.large_image.height,
279
+ url: blob.playable_url,
280
+ width: blob.original_dimensions.x,
281
+ height: blob.original_dimensions.y,
282
+ videoType: blob.video_type.toLowerCase(),
283
+ thumbnailUrl: blob.large_image.uri
284
+ };
285
+ case "MessageAudio":
286
+ return {
287
+ type: "audio",
288
+ ID: blob.url_shimhash,
289
+ filename: blob.filename,
290
+ fullFileName: fullFileName,
291
+ fileSize: fileSize,
292
+ duration: durationAudio,
293
+ original_extension: getExtension(blob.original_extension, fullFileName),
294
+ mimeType: mimeType,
295
+ audioType: blob.audio_type,
296
+ url: blob.playable_url,
297
+ isVoiceMail: blob.is_voicemail
298
+ };
299
+ case "StickerAttachment":
300
+ case "Sticker":
301
+ return {
302
+ type: "sticker",
303
+ ID: blob.id,
304
+ url: blob.url,
305
+ packID: blob.pack ? blob.pack.id: null,
306
+ spriteUrl: blob.sprite_image,
307
+ spriteUrl2x: blob.sprite_image_2x,
308
+ width: blob.width,
309
+ height: blob.height,
310
+ caption: blob.label,
311
+ description: blob.label,
312
+ frameCount: blob.frame_count,
313
+ frameRate: blob.frame_rate,
314
+ framesPerRow: blob.frames_per_row,
315
+ framesPerCol: blob.frames_per_column,
316
+ stickerID: blob.id,
317
+ spriteURI: blob.sprite_image,
318
+ spriteURI2x: blob.sprite_image_2x
319
+ };
320
+ case "MessageLocation":
321
+ var urlAttach = blob.story_attachment.url;
322
+ var mediaAttach = blob.story_attachment.media;
323
+
324
+ var u = querystring.parse(url.parse(urlAttach).query).u;
325
+ var where1 = querystring.parse(url.parse(u).query).where1;
326
+ var address = where1.split(", ");
327
+
328
+ var latitude;
329
+ var longitude;
330
+
331
+ try {
332
+ latitude = Number.parseFloat(address[0]);
333
+ longitude = Number.parseFloat(address[1]);
334
+ } catch (err) {
335
+ /* empty */
336
+ }
337
+ var imageUrl;
338
+ var width;
339
+ var height;
340
+ if (mediaAttach && mediaAttach.image) {
341
+ imageUrl = mediaAttach.image.uri;
342
+ width = mediaAttach.image.width;
343
+ height = mediaAttach.image.height;
344
+ }
345
+
346
+ return {
347
+ type: "location",
348
+ ID: blob.legacy_attachment_id,
349
+ latitude: latitude,
350
+ longitude: longitude,
351
+ image: imageUrl,
352
+ width: width,
353
+ height: height,
354
+ url: u || urlAttach,
355
+ address: where1,
356
+ facebookUrl: blob.story_attachment.url,
357
+ target: blob.story_attachment.target,
358
+ styleList: blob.story_attachment.style_list
359
+ };
360
+ case "ExtensibleAttachment":
361
+ return {
362
+ type: "share",
363
+ ID: blob.legacy_attachment_id,
364
+ url: blob.story_attachment.url,
365
+ title: blob.story_attachment.title_with_entities.text,
366
+ description:
367
+ blob.story_attachment.description &&
368
+ blob.story_attachment.description.text,
369
+ source: blob.story_attachment.source ? blob.story_attachment.source.text: null,
370
+ image:
371
+ blob.story_attachment.media &&
372
+ blob.story_attachment.media.image &&
373
+ blob.story_attachment.media.image.uri,
374
+ width:
375
+ blob.story_attachment.media &&
376
+ blob.story_attachment.media.image &&
377
+ blob.story_attachment.media.image.width,
378
+ height:
379
+ blob.story_attachment.media &&
380
+ blob.story_attachment.media.image &&
381
+ blob.story_attachment.media.image.height,
382
+ playable:
383
+ blob.story_attachment.media &&
384
+ blob.story_attachment.media.is_playable,
385
+ duration:
386
+ blob.story_attachment.media &&
387
+ blob.story_attachment.media.playable_duration_in_ms,
388
+ playableUrl:
389
+ blob.story_attachment.media == null ? null:
390
+ blob.story_attachment.media.playable_url,
391
+ subattachments: blob.story_attachment.subattachments,
392
+ properties: blob.story_attachment.properties.reduce(function(obj, cur) {
393
+ obj[cur.key] = cur.value.text;
394
+ return obj;
395
+ }, {}),
396
+ facebookUrl: blob.story_attachment.url,
397
+ target: blob.story_attachment.target,
398
+ styleList: blob.story_attachment.style_list
399
+ };
400
+ case "MessageFile":
401
+ return {
402
+ type: "file",
403
+ ID: blob.message_file_fbid,
404
+ fullFileName: fullFileName,
405
+ filename: blob.filename,
406
+ fileSize: fileSize,
407
+ mimeType: blob.mimetype,
408
+ original_extension: blob.original_extension || fullFileName.split(".").pop(),
409
+ url: blob.url,
410
+ isMalicious: blob.is_malicious,
411
+ contentType: blob.content_type,
412
+ name: blob.filename
413
+ };
414
+ default:
415
+ throw new Error(
416
+ "unrecognized attach_file of type " +
417
+ type +
418
+ "`" +
419
+ JSON.stringify(attachment1, null, 4) +
420
+ " attachment2: " +
421
+ JSON.stringify(attachment2, null, 4) +
422
+ "`"
423
+ );
424
+ }
425
+ } function formatAttachment(attachments, attachmentIds, attachmentMap, shareMap) {
426
+ attachmentMap = shareMap || attachmentMap;
427
+ return attachments ?
428
+ attachments.map(function(val, i) {
429
+ if (
430
+ !attachmentMap ||
431
+ !attachmentIds ||
432
+ !attachmentMap[attachmentIds[i]]
433
+ ) {
434
+ return _formatAttachment(val);
435
+ }
436
+ return _formatAttachment(val, attachmentMap[attachmentIds[i]]);
437
+ }): [];
438
+ }
439
+
440
+ /**
441
+ * file: ws3-fca/exocore/datas/formatters.js
442
+ * Hanapin ang function na ito at palitan ng version na ito.
443
+ */
444
+ function formatDeltaMessage(m) {
445
+ const md = m.delta.messageMetadata;
446
+ const mdata =
447
+ m.delta.data === undefined ?
448
+ [] :
449
+ m.delta.data.prng === undefined ?
450
+ [] :
451
+ JSON.parse(m.delta.data.prng);
452
+ const m_id = mdata.map(u => u.i);
453
+ const m_offset = mdata.map(u => u.o);
454
+ const m_length = mdata.map(u => u.l);
455
+ const mentions = {};
456
+ for (let i = 0; i < m_id.length; i++) {
457
+ mentions[m_id[i]] = m.delta.body.substring(
458
+ m_offset[i],
459
+ m_offset[i] + m_length[i]
460
+ );
461
+ }
462
+
463
+ return {
464
+ type: "message",
465
+ senderID: formatID(md.actorFbId.toString()),
466
+ body: m.delta.body || "",
467
+ threadID: formatID(
468
+ (md.threadKey.threadFbId || md.threadKey.otherUserFbId).toString()
469
+ ),
470
+ messageID: md.messageId,
471
+ offlineThreadingId: md.offlineThreadingId,
472
+ attachments: (m.delta.attachments || []).map(v => _formatAttachment(v)),
473
+ mentions: mentions,
474
+ timestamp: md.timestamp,
475
+ isGroup: !!md.threadKey.threadFbId,
476
+ participantIDs: m.delta.participants
477
+ };
478
+ } function formatID(id) {
479
+ if (id != undefined && id != null) {
480
+ return id.replace(/(fb)?id[:.]/, "");
481
+ } else {
482
+ return id;
483
+ }
484
+ }
485
+
486
+ function formatMessage(m) {
487
+ const originalMessage = m.message ? m.message: m;
488
+ const obj = {
489
+ type: "message",
490
+ senderName: originalMessage.sender_name,
491
+ senderID: formatID(originalMessage.sender_fbid.toString()),
492
+ participantNames: originalMessage.group_thread_info ?
493
+ originalMessage.group_thread_info.participant_names: [originalMessage.sender_name.split(" ")[0]],
494
+ participantIDs: originalMessage.group_thread_info ?
495
+ originalMessage.group_thread_info.participant_ids.map(function(v) {
496
+ return formatID(v.toString());
497
+ }): [formatID(originalMessage.sender_fbid)],
498
+ body: originalMessage.body || "",
499
+ threadID: formatID(
500
+ (
501
+ originalMessage.thread_fbid || originalMessage.other_user_fbid
502
+ ).toString()
503
+ ),
504
+ threadName: originalMessage.group_thread_info ?
505
+ originalMessage.group_thread_info.name: originalMessage.sender_name,
506
+ location: originalMessage.coordinates ? originalMessage.coordinates: null,
507
+ messageID: originalMessage.mid ?
508
+ originalMessage.mid.toString(): originalMessage.message_id,
509
+ attachments: formatAttachment(
510
+ originalMessage.attachments,
511
+ originalMessage.attachmentIds,
512
+ originalMessage.attachment_map,
513
+ originalMessage.share_map
514
+ ),
515
+ timestamp: originalMessage.timestamp,
516
+ timestampAbsolute: originalMessage.timestamp_absolute,
517
+ timestampRelative: originalMessage.timestamp_relative,
518
+ timestampDatetime: originalMessage.timestamp_datetime,
519
+ tags: originalMessage.tags,
520
+ reactions: originalMessage.reactions ? originalMessage.reactions: [],
521
+ isUnread: originalMessage.is_unread
522
+ };
523
+
524
+ if (m.type === "pages_messaging")
525
+ obj.pageID = m.realtime_viewer_fbid.toString();
526
+ obj.isGroup = obj.participantIDs.length > 2;
527
+
528
+ return obj;
529
+ }
530
+
531
+ function formatEvent(m) {
532
+ const originalMessage = m.message ? m.message: m;
533
+ let logMessageType = originalMessage.log_message_type;
534
+ let logMessageData;
535
+ if (logMessageType === "log:generic-admin-text") {
536
+ logMessageData = originalMessage.log_message_data.untypedData;
537
+ logMessageType = getAdminTextMessageType(
538
+ originalMessage.log_message_data.message_type
539
+ );
540
+ } else {
541
+ logMessageData = originalMessage.log_message_data;
542
+ }
543
+
544
+ return Object.assign(formatMessage(originalMessage), {
545
+ type: "event",
546
+ logMessageType: logMessageType,
547
+ logMessageData: logMessageData,
548
+ logMessageBody: originalMessage.log_message_body
549
+ });
550
+ }
551
+
552
+ function formatHistoryMessage(m) {
553
+ switch (m.action_type) {
554
+ case "ma-type:log-message":
555
+ return formatEvent(m);
556
+ default:
557
+ return formatMessage(m);
558
+ }
559
+ }
560
+
561
+
562
+ function getAdminTextMessageType(type) {
563
+ switch (type) {
564
+ case 'unpin_messages_v2':
565
+ return 'log:unpin-message';
566
+ case 'pin_messages_v2':
567
+ return 'log:pin-message';
568
+ case "change_thread_theme":
569
+ return "log:thread-color";
570
+ case "change_thread_icon":
571
+ case 'change_thread_quick_reaction':
572
+ return "log:thread-icon";
573
+ case "change_thread_nickname":
574
+ return "log:user-nickname";
575
+ case "change_thread_admins":
576
+ return "log:thread-admins";
577
+ case "group_poll":
578
+ return "log:thread-poll";
579
+ case "change_thread_approval_mode":
580
+ return "log:thread-approval-mode";
581
+ case "messenger_call_log":
582
+ case "participant_joined_group_call":
583
+ return "log:thread-call";
584
+ default:
585
+ return type;
586
+ }
587
+ }
588
+
589
+ function formatDeltaEvent(m) {
590
+ let logMessageType;
591
+ let logMessageData;
592
+
593
+
594
+
595
+
596
+
597
+
598
+
599
+
600
+ switch (m.class) {
601
+ case "AdminTextMessage":
602
+ logMessageData = m.untypedData;
603
+ logMessageType = getAdminTextMessageType(m.type);
604
+ break;
605
+ case "ThreadName":
606
+ logMessageType = "log:thread-name";
607
+ logMessageData = {
608
+ name: m.name
609
+ };
610
+ break;
611
+ case "ParticipantsAddedToGroupThread":
612
+ logMessageType = "log:subscribe";
613
+ logMessageData = {
614
+ addedParticipants: m.addedParticipants
615
+ };
616
+ break;
617
+ case "ParticipantLeftGroupThread":
618
+ logMessageType = "log:unsubscribe";
619
+ logMessageData = {
620
+ leftParticipantFbId: m.leftParticipantFbId
621
+ };
622
+ break;
623
+ case "ApprovalQueue":
624
+ logMessageType = "log:approval-queue";
625
+ logMessageData = {
626
+ approvalQueue: {
627
+ action: m.action,
628
+ recipientFbId: m.recipientFbId,
629
+ requestSource: m.requestSource,
630
+ ...m.messageMetadata
631
+ }
632
+ };
633
+ }
634
+ return {
635
+ type: "event",
636
+ threadID: formatID(
637
+ (
638
+ m.messageMetadata.threadKey.threadFbId ||
639
+ m.messageMetadata.threadKey.otherUserFbId
640
+ ).toString()
641
+ ),
642
+ messageID: m.messageMetadata.messageId.toString(),
643
+ logMessageType,
644
+ logMessageData,
645
+ logMessageBody: m.messageMetadata.adminText,
646
+ timestamp: m.messageMetadata.timestamp,
647
+ author: m.messageMetadata.actorFbId,
648
+ participantIDs: m.participants
649
+ };
650
+ }
651
+
652
+ function formatTyp(event) {
653
+ return {
654
+ isTyping: !!event.st,
655
+ from: event.from.toString(),
656
+ threadID: formatID(
657
+ (event.to || event.thread_fbid || event.from).toString()
658
+ ),
659
+
660
+
661
+ fromMobile: event.hasOwnProperty("from_mobile") ? event.from_mobile: true,
662
+ userID: (event.realtime_viewer_fbid || event.from).toString(),
663
+ type: "typ"
664
+ };
665
+ }
666
+
667
+ function formatDeltaReadReceipt(delta) {
668
+
669
+
670
+ return {
671
+ reader: (delta.threadKey.otherUserFbId || delta.actorFbId).toString(),
672
+ time: delta.actionTimestampMs,
673
+ threadID: formatID(
674
+ (delta.threadKey.otherUserFbId || delta.threadKey.threadFbId).toString()
675
+ ),
676
+ type: "read_receipt"
677
+ };
678
+ }
679
+
680
+ function formatReadReceipt(event) {
681
+ return {
682
+ reader: event.reader.toString(),
683
+ time: event.time,
684
+ threadID: formatID((event.thread_fbid || event.reader).toString()),
685
+ type: "read_receipt"
686
+ };
687
+ }
688
+
689
+ function formatRead(event) {
690
+ return {
691
+ threadID: formatID(
692
+ (
693
+ (event.chat_ids && event.chat_ids[0]) ||
694
+ (event.thread_fbids && event.thread_fbids[0])
695
+ ).toString()
696
+ ),
697
+ time: event.timestamp,
698
+ type: "read"
699
+ };
700
+ }
701
+
702
+ function getFrom(str, startToken, endToken) {
703
+ const start = str.indexOf(startToken) + startToken.length;
704
+ if (start < startToken.length) return "";
705
+
706
+ const lastHalf = str.substring(start);
707
+ const end = lastHalf.indexOf(endToken);
708
+ if (end === -1) {
709
+ throw Error(
710
+ "Could not find endTime `" + endToken + "` in the given string."
711
+ );
712
+ }
713
+ return lastHalf.substring(0, end);
714
+ }
715
+
716
+ function makeParsable(html) {
717
+ const withoutForLoop = html.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, "");
718
+
719
+
720
+
721
+
722
+
723
+
724
+
725
+
726
+
727
+
728
+ const maybeMultipleObjects = withoutForLoop.split(/\}\r\n *\{/);
729
+ if (maybeMultipleObjects.length === 1) return maybeMultipleObjects;
730
+
731
+ return "[" + maybeMultipleObjects.join("},{") + "]";
732
+ }
733
+
734
+ function arrToForm(form) {
735
+ return arrayToObject(
736
+ form,
737
+ function(v) {
738
+ return v.name;
739
+ },
740
+ function(v) {
741
+ return v.val;
742
+ }
743
+ );
744
+ }
745
+
746
+ function arrayToObject(arr, getKey, getValue) {
747
+ return arr.reduce(function(acc, val) {
748
+ acc[getKey(val)] = getValue(val);
749
+ return acc;
750
+ }, {});
751
+ }
752
+
753
+ function getSignatureID() {
754
+ return Math.floor(Math.random() * 2147483648).toString(16);
755
+ }
756
+
757
+ function generateTimestampRelative() {
758
+ const d = new Date();
759
+ return d.getHours() + ":" + padZeros(d.getMinutes());
760
+ }
761
+
762
+ function makeDefaults(html, userID, ctx) {
763
+ let reqCounter = 1;
764
+ const revision = getFrom(html, 'revision":', ",");
765
+ function mergeWithDefaults(obj) {
766
+ const newObj = {
767
+ av: userID,
768
+ __user: userID,
769
+ __req: (reqCounter++).toString(36),
770
+ __rev: revision,
771
+ __a: 1,
772
+ ...(ctx && {
773
+ fb_dtsg: ctx.fb_dtsg,
774
+ jazoest: ctx.jazoest
775
+ })
776
+ }
777
+
778
+ if (!obj) return newObj;
779
+
780
+ for (var prop in obj) {
781
+ if (obj.hasOwnProperty(prop)) {
782
+ if (!newObj[prop])
783
+ newObj[prop] = obj[prop];
784
+ }
785
+ }
786
+
787
+ return newObj;
788
+ }
789
+
790
+ return {
791
+ get: (url, jar, qs, ctxx, customHeader = {}) => get(url, jar, mergeWithDefaults(qs), ctx.globalOptions, ctxx || ctx, customHeader),
792
+ post: (url, jar, form, ctxx, customHeader = {}) => post(url, jar, mergeWithDefaults(form), ctx.globalOptions, ctxx || ctx, customHeader),
793
+ postFormData: (url, jar, form, qs, ctxx) => postFormData(url, jar, mergeWithDefaults(form), mergeWithDefaults(qs), ctx.globalOptions, ctxx || ctx)
794
+ };
795
+ }
796
+
797
+ function parseAndCheckLogin(ctx, http, retryCount) {
798
+ var delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
799
+ var _try = (tryData) => new Promise(function(resolve, reject) {
800
+ try {
801
+ resolve(tryData());
802
+ } catch (error) {
803
+ reject(error);
804
+ }
805
+ });
806
+ if (retryCount == undefined) retryCount = 0;
807
+
808
+ return function(data) {
809
+ function any() {
810
+ if (data.statusCode >= 500 && data.statusCode < 600) {
811
+ if (retryCount >= 5) {
812
+ const err = new Error("Request retry failed. Check the `res` and `statusCode` property on this error.");
813
+ err.statusCode = data.statusCode;
814
+ err.res = data.body;
815
+ err.error = "Request retry failed. Check the `res` and `statusCode` property on this error.";
816
+ throw err;
817
+ }
818
+ retryCount++;
819
+ const retryTime = Math.floor(Math.random() * 5000);
820
+ console.warn("parseAndCheckLogin", "Got status code " + data.statusCode + " - " + retryCount + ". attempt to retry in " + retryTime + " milliseconds...");
821
+ const url = data.request.uri.protocol + "//" + data.request.uri.hostname + data.request.uri.pathname;
822
+ if (data.request.headers["content-type"].split(";")[0] === "multipart/form-data") {
823
+ return delay(retryTime)
824
+ .then(function() {
825
+ return http
826
+ .postFormData(url, ctx.jar, data.request.formData);
827
+ })
828
+ .then(parseAndCheckLogin(ctx, http, retryCount));
829
+ } else {
830
+ return delay(retryTime)
831
+ .then(function() {
832
+ return http
833
+ .post(url, ctx.jar, data.request.formData);
834
+ })
835
+ .then(parseAndCheckLogin(ctx, http, retryCount));
836
+ }
837
+ }
838
+
839
+ if (data.statusCode === 404) return;
840
+
841
+ if (data.statusCode !== 200)
842
+ throw new Error("parseAndCheckLogin got status code: " + data.statusCode + ". Bailing out of trying to parse response.");
843
+
844
+ let res = null;
845
+ try {
846
+ res = JSON.parse(makeParsable(data.body));
847
+ } catch (e) {
848
+ const err = new Error("JSON.parse error. Check the `detail` property on this error.");
849
+ err.error = "JSON.parse error. Check the `detail` property on this error.";
850
+ err.detail = e;
851
+ err.res = data.body;
852
+ throw err;
853
+ }
854
+
855
+
856
+ if (res.redirect && data.request.method === "GET") {
857
+ return http
858
+ .get(res.redirect, ctx.jar)
859
+ .then(parseAndCheckLogin(ctx, http));
860
+ }
861
+
862
+
863
+ if (res.jsmods && res.jsmods.require && Array.isArray(res.jsmods.require[0]) && res.jsmods.require[0][0] === "Cookie") {
864
+ res.jsmods.require[0][3][0] = res.jsmods.require[0][3][0].replace("_js_", "");
865
+ const requireCookie = res.jsmods.require[0][3];
866
+ ctx.jar.setCookie(formatCookie(requireCookie, "facebook"), "https://www.facebook.com");
867
+ ctx.jar.setCookie(formatCookie(requireCookie, "messenger"), "https://www.messenger.com");
868
+ }
869
+
870
+
871
+
872
+ if (res.jsmods && Array.isArray(res.jsmods.require)) {
873
+ const arr = res.jsmods.require;
874
+ for (const i in arr) {
875
+ if (arr[i][0] === "DTSG" && arr[i][1] === "setToken") {
876
+ ctx.fb_dtsg = arr[i][3][0];
877
+
878
+
879
+ ctx.ttstamp = "2";
880
+ for (let j = 0; j < ctx.fb_dtsg.length; j++) {
881
+ ctx.ttstamp += ctx.fb_dtsg.charCodeAt(j);
882
+ }
883
+ }
884
+ }
885
+ }
886
+
887
+ if (res.error === 1357001 || res.error === 1357004) {
888
+ const errMsg = res.error === 1357004 ? 'Account temporarily locked or blocked' : 'Facebook blocked the login';
889
+ const err = new Error(errMsg);
890
+ err.error = "Not logged in.";
891
+ err.requiresReLogin = true;
892
+ err.loginBlocked = res.error === 1357004;
893
+ throw err;
894
+ }
895
+
896
+ if (res.errors && Array.isArray(res.errors)) {
897
+ for (const errorObj of res.errors) {
898
+ const errorMsg = errorObj.message || errorObj.description || '';
899
+ if (/Not logged in|blocked the login|401|403/.test(errorMsg)) {
900
+ const err = new Error('Authentication error: ' + errorMsg);
901
+ err.error = "Not logged in.";
902
+ err.requiresReLogin = true;
903
+ err.loginBlocked = /blocked/.test(errorMsg);
904
+ throw err;
905
+ }
906
+ }
907
+ }
908
+ return res;
909
+ }
910
+ return _try(any);
911
+ };
912
+ }
913
+
914
+ function saveCookies(jar) {
915
+ return function(res) {
916
+ const cookies = res.headers["set-cookie"] || [];
917
+ cookies.forEach(function(c) {
918
+ if (c.indexOf(".facebook.com") > -1) {
919
+ jar.setCookie(c, "https://www.facebook.com");
920
+ }
921
+ const c2 = c.replace(/domain=\.facebook\.com/, "domain=.messenger.com");
922
+ jar.setCookie(c2, "https://www.messenger.com");
923
+ });
924
+ return res;
925
+ };
926
+ }
927
+
928
+ function formatThread(data) {
929
+ return {
930
+ threadID: formatID(data.thread_fbid.toString()),
931
+ participants: data.participants.map(formatID),
932
+ participantIDs: data.participants.map(formatID),
933
+ name: data.name,
934
+ nicknames: data.custom_nickname,
935
+ snippet: data.snippet,
936
+ snippetAttachments: data.snippet_attachments,
937
+ snippetSender: formatID((data.snippet_sender || "").toString()),
938
+ unreadCount: data.unread_count,
939
+ messageCount: data.message_count,
940
+ imageSrc: data.image_src,
941
+ timestamp: data.timestamp,
942
+ serverTimestamp: data.server_timestamp,
943
+ muteUntil: data.mute_until,
944
+ isCanonicalUser: data.is_canonical_user,
945
+ isCanonical: data.is_canonical,
946
+ isSubscribed: data.is_subscribed,
947
+ folder: data.folder,
948
+ isArchived: data.is_archived,
949
+ recipientsLoadable: data.recipients_loadable,
950
+ hasEmailParticipant: data.has_email_participant,
951
+ readOnly: data.read_only,
952
+ canReply: data.can_reply,
953
+ cannotReplyReason: data.cannot_reply_reason,
954
+ lastMessageTimestamp: data.last_message_timestamp,
955
+ lastReadTimestamp: data.last_read_timestamp,
956
+ lastMessageType: data.last_message_type,
957
+ emoji: data.custom_like_icon,
958
+ color: data.custom_color,
959
+ adminIDs: data.admin_ids,
960
+ threadType: data.thread_type
961
+ };
962
+ }
963
+
964
+ function formatDate(date) {
965
+ let d = date.getUTCDate();
966
+ d = d >= 10 ? d : "0" + d;
967
+ let h = date.getUTCHours();
968
+ h = h >= 10 ? h : "0" + h;
969
+ let m = date.getUTCMinutes();
970
+ m = m >= 10 ? m : "0" + m;
971
+ let s = date.getUTCSeconds();
972
+ s = s >= 10 ? s : "0" + s;
973
+ return (
974
+ NUM_TO_DAY[date.getUTCDay()] +
975
+ ", " +
976
+ d +
977
+ " " +
978
+ NUM_TO_MONTH[date.getUTCMonth()] +
979
+ " " +
980
+ date.getUTCFullYear() +
981
+ " " +
982
+ h +
983
+ ":" +
984
+ m +
985
+ ":" +
986
+ s +
987
+ " GMT"
988
+ );
989
+ }
990
+
991
+ function formatCookie(arr, url) {
992
+ return (
993
+ arr[0] + "=" + arr[1] + "; Path=" + arr[3] + "; Domain=" + url + ".com"
994
+ );
995
+ }
996
+
997
+ function formatProxyPresence(presence, userID) {
998
+ if (presence.lat === undefined || presence.p === undefined) return null;
999
+ return {
1000
+ type: "presence",
1001
+ timestamp: presence.lat * 1000,
1002
+ userID: userID,
1003
+ statuses: presence.p
1004
+ };
1005
+ }
1006
+
1007
+ function formatPresence(presence, userID) {
1008
+ return {
1009
+ type: "presence",
1010
+ timestamp: presence.la * 1000,
1011
+ userID: userID,
1012
+ statuses: presence.a
1013
+ };
1014
+ }
1015
+
1016
+ function decodeClientPayload(payload) {
1017
+ /*
1018
+ Special function which Client using to "encode" clients JSON payload
1019
+ */
1020
+ return JSON.parse(String.fromCharCode.apply(null, payload));
1021
+ }
1022
+
1023
+
1024
+ module.exports = {
1025
+
1026
+ isReadableStream,
1027
+
1028
+ getExtension,
1029
+
1030
+ _formatAttachment,
1031
+
1032
+ formatAttachment,
1033
+
1034
+ formatDeltaMessage,
1035
+
1036
+ formatID,
1037
+
1038
+ formatMessage,
1039
+
1040
+ formatEvent,
1041
+
1042
+ formatHistoryMessage,
1043
+
1044
+ getAdminTextMessageType,
1045
+
1046
+ formatDeltaEvent,
1047
+
1048
+ formatTyp,
1049
+
1050
+ formatDeltaReadReceipt,
1051
+
1052
+ formatReadReceipt,
1053
+
1054
+ formatRead,
1055
+
1056
+ formatDate,
1057
+
1058
+ formatCookie,
1059
+
1060
+ formatThread,
1061
+
1062
+ formatProxyPresence,
1063
+
1064
+ formatPresence,
1065
+
1066
+ decodeClientPayload,
1067
+ };