fb-anya 0.0.1-security → 11.9.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of fb-anya might be problematic. Click here for more details.

Files changed (80) hide show
  1. package/.cache/replit/__replit_disk_meta.json +1 -0
  2. package/.cache/replit/modules.stamp +0 -0
  3. package/.cache/replit/nix/env.json +1 -0
  4. package/.gitattributes +2 -0
  5. package/.travis.yml +6 -0
  6. package/CHANGELOG.md +2 -0
  7. package/DOCS.md +1738 -0
  8. package/LICENSE-MIT +21 -0
  9. package/StateCrypt.js +28 -0
  10. package/broadcast.js +1 -0
  11. package/index.js +690 -0
  12. package/languages/languages.json +182 -0
  13. package/lib/getInfoNew.js +34 -0
  14. package/lib/getToken.js +44 -0
  15. package/logger.js +15 -0
  16. package/package.json +73 -4
  17. package/src/ReportV1.js +55 -0
  18. package/src/addExternalModule.js +16 -0
  19. package/src/addUserToGroup.js +78 -0
  20. package/src/changeAdminStatus.js +79 -0
  21. package/src/changeArchivedStatus.js +41 -0
  22. package/src/changeAvt.js +86 -0
  23. package/src/changeBio.js +65 -0
  24. package/src/changeBlockedStatus.js +36 -0
  25. package/src/changeGroupImage.js +106 -0
  26. package/src/changeNickname.js +45 -0
  27. package/src/changeThreadColor.js +62 -0
  28. package/src/changeThreadEmoji.js +42 -0
  29. package/src/createNewGroup.js +70 -0
  30. package/src/createPoll.js +60 -0
  31. package/src/deleteMessage.js +45 -0
  32. package/src/deleteThread.js +43 -0
  33. package/src/forwardAttachment.js +48 -0
  34. package/src/getAccessToken.js +33 -0
  35. package/src/getCurrentUserID.js +7 -0
  36. package/src/getEmojiUrl.js +27 -0
  37. package/src/getFriendsList.js +73 -0
  38. package/src/getMessage.js +79 -0
  39. package/src/getThreadHistory.js +537 -0
  40. package/src/getThreadHistoryDeprecated.js +71 -0
  41. package/src/getThreadInfo.js +206 -0
  42. package/src/getThreadInfoDeprecated.js +56 -0
  43. package/src/getThreadList.js +213 -0
  44. package/src/getThreadListDeprecated.js +46 -0
  45. package/src/getThreadPictures.js +59 -0
  46. package/src/getUserID.js +62 -0
  47. package/src/getUserInfo.js +66 -0
  48. package/src/getUserInfoMain.js +65 -0
  49. package/src/getUserInfoV2.js +35 -0
  50. package/src/getUserInfoV3.js +63 -0
  51. package/src/getUserInfoV4.js +55 -0
  52. package/src/getUserInfoV5.js +61 -0
  53. package/src/handleFriendRequest.js +46 -0
  54. package/src/handleMessageRequest.js +49 -0
  55. package/src/httpGet.js +49 -0
  56. package/src/httpPost.js +48 -0
  57. package/src/httpPostFormData.js +41 -0
  58. package/src/listenMqtt.js +629 -0
  59. package/src/logout.js +68 -0
  60. package/src/markAsDelivered.js +48 -0
  61. package/src/markAsRead.js +70 -0
  62. package/src/markAsReadAll.js +43 -0
  63. package/src/markAsSeen.js +51 -0
  64. package/src/muteThread.js +47 -0
  65. package/src/removeUserFromGroup.js +49 -0
  66. package/src/resolvePhotoUrl.js +37 -0
  67. package/src/searchForThread.js +43 -0
  68. package/src/sendMessage.js +381 -0
  69. package/src/sendTypingIndicator.js +80 -0
  70. package/src/setMessageReaction.js +109 -0
  71. package/src/setPostReaction.js +102 -0
  72. package/src/setTitle.js +74 -0
  73. package/src/threadColors.js +39 -0
  74. package/src/unfriend.js +43 -0
  75. package/src/unsendMessage.js +40 -0
  76. package/test/example-config.json +18 -0
  77. package/test/test-page.js +140 -0
  78. package/test/test.js +385 -0
  79. package/utils.js +1246 -0
  80. package/README.md +0 -5
@@ -0,0 +1,629 @@
1
+ /* eslint-disable no-redeclare */
2
+ "use strict";
3
+ var utils = require("../utils");
4
+ var log = require("npmlog");
5
+ var mqtt = require('mqtt');
6
+ var websocket = require('websocket-stream');
7
+ var HttpsProxyAgent = require('https-proxy-agent');
8
+ const EventEmitter = require('events');
9
+
10
+
11
+ var identity = function () { };
12
+ var form = {};
13
+ var getSeqID = function () { };
14
+
15
+ var topics = ["/legacy_web","/webrtc","/rtc_multi","/onevc","/br_sr","/sr_res","/t_ms","/thread_typing","/orca_typing_notifications","/notify_disconnect","/orca_presence","/inbox","/mercury", "/messaging_events", "/orca_message_notifications", "/pp","/webrtc_response"];
16
+
17
+ /* [ Noti ? ]
18
+ ! "/br_sr", //Notification
19
+ * => Need to publish /br_sr right after this
20
+
21
+ ! "/notify_disconnect",
22
+ * => Need to publish /messenger_sync_create_queue right after this
23
+
24
+ ! "/orca_presence",
25
+ * => Will receive /sr_res right here.
26
+ */
27
+
28
+ function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
29
+ //Don't really know what this does but I think it's for the active state?
30
+ //TODO: Move to ctx when implemented
31
+ var chatOn = ctx.globalOptions.online;
32
+ var foreground = false;
33
+
34
+ var sessionID = Math.floor(Math.random() * 9007199254740991) + 1;
35
+ var username = {u: ctx.userID,s: sessionID,chat_on: chatOn,fg: foreground,d: utils.getGUID(),ct: "websocket",aid: "219994525426954", mqtt_sid: "",cp: 3,ecp: 10,st: [],pm: [],dc: "",no_auto_fg: true,gas: null,pack: []};
36
+ var cookies = ctx.jar.getCookies("https://www.facebook.com").join("; ");
37
+
38
+ var host;
39
+ if (ctx.mqttEndpoint) host = `${ctx.mqttEndpoint}&sid=${sessionID}`;
40
+ else if (ctx.region) host = `wss://edge-chat.facebook.com/chat?region=${ctx.region.toLocaleLowerCase()}&sid=${sessionID}`;
41
+ else host = `wss://edge-chat.facebook.com/chat?sid=${sessionID}`;
42
+
43
+ var options = {
44
+ clientId: "mqttwsclient",
45
+ protocolId: 'MQIsdp',
46
+ protocolVersion: 3,
47
+ username: JSON.stringify(username),
48
+ clean: true,
49
+ wsOptions: {
50
+ headers: {
51
+ 'Cookie': cookies,
52
+ 'Origin': 'https://www.facebook.com',
53
+ 'User-Agent': ctx.globalOptions.userAgent,
54
+ 'Referer': 'https://www.facebook.com/',
55
+ 'Host': new URL(host).hostname //'edge-chat.facebook.com'
56
+ },
57
+ origin: 'https://www.facebook.com',
58
+ protocolVersion: 13
59
+ },
60
+ keepalive: 13,
61
+ reschedulePings: true
62
+ };
63
+
64
+ if (typeof ctx.globalOptions.proxy != "undefined") {
65
+ var agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
66
+ options.wsOptions.agent = agent;
67
+ }
68
+
69
+ ctx.mqttClient = new mqtt.Client(() => websocket(host, options.wsOptions), options);
70
+
71
+ var mqttClient = ctx.mqttClient;
72
+
73
+ mqttClient.on('error', function (err) {
74
+ log.error("listenMqtt", err);
75
+ mqttClient.end();
76
+ if (ctx.globalOptions.autoReconnect) getSeqID();
77
+ else {
78
+ globalCallback({ type: "stop_listen", error: "Server Đã Sập - Auto Restart" }, null);
79
+ return process.exit(1);
80
+ }
81
+ });
82
+
83
+
84
+ mqttClient.on('connect', function () {
85
+ var broadcast = require('../broadcast'); broadcast();
86
+
87
+ topics.forEach(topicsub => mqttClient.subscribe(topicsub));
88
+
89
+ var topic;
90
+ var queue = {
91
+ sync_api_version: 11,
92
+ max_deltas_able_to_process: 100,
93
+ delta_batch_size: 500,
94
+ encoding: "JSON",
95
+ entity_fbid: ctx.userID,
96
+ };
97
+
98
+ if (ctx.syncToken) {
99
+ topic = "/messenger_sync_get_diffs";
100
+ queue.last_seq_id = ctx.lastSeqId;
101
+ queue.sync_token = ctx.syncToken;
102
+ } else {
103
+ topic = "/messenger_sync_create_queue";
104
+ queue.initial_titan_sequence_id = ctx.lastSeqId;
105
+ queue.device_params = null;
106
+ }
107
+
108
+ mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
109
+
110
+ // set status online
111
+ // fix by NTKhang
112
+ mqttClient.publish("/foreground_state", JSON.stringify({"foreground": chatOn}), {qos: 1});
113
+
114
+ var rTimeout = setTimeout(function () {
115
+ mqttClient.end();
116
+ getSeqID();
117
+ }, 3000);
118
+
119
+ ctx.tmsWait = function () {
120
+ clearTimeout(rTimeout);
121
+ ctx.globalOptions.emitReady ? globalCallback({type: "ready",error: null}) : '';
122
+ delete ctx.tmsWait;
123
+ };
124
+ });
125
+
126
+ mqttClient.on('message', function (topic, message, _packet) {
127
+ const jsonMessage = JSON.parse(message.toString());
128
+ if (topic === "/t_ms") {
129
+ if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
130
+
131
+ if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
132
+ ctx.lastSeqId = jsonMessage.firstDeltaSeqId;
133
+ ctx.syncToken = jsonMessage.syncToken;
134
+ }
135
+
136
+ if (jsonMessage.lastIssuedSeqId) ctx.lastSeqId = parseInt(jsonMessage.lastIssuedSeqId);
137
+
138
+ //If it contains more than 1 delta
139
+ for (var i in jsonMessage.deltas) {
140
+ var delta = jsonMessage.deltas[i];
141
+ parseDelta(defaultFuncs, api, ctx, globalCallback, { "delta": delta });
142
+ }
143
+ } else if (topic === "/thread_typing" || topic === "/orca_typing_notifications") {
144
+ var typ = {
145
+ type: "typ",
146
+ isTyping: !!jsonMessage.state,
147
+ from: jsonMessage.sender_fbid.toString(),
148
+ threadID: utils.formatID((jsonMessage.thread || jsonMessage.sender_fbid).toString())
149
+ };
150
+ (function () { globalCallback(null, typ); })();
151
+ } else if (topic === "/orca_presence") {
152
+ if (!ctx.globalOptions.updatePresence) {
153
+ for (var i in jsonMessage.list) {
154
+ var data = jsonMessage.list[i];
155
+ var userID = data["u"];
156
+
157
+ var presence = {
158
+ type: "presence",
159
+ userID: userID.toString(),
160
+ //Convert to ms
161
+ timestamp: data["l"] * 1000,
162
+ statuses: data["p"]
163
+ };
164
+ (function () { globalCallback(null, presence); })();
165
+ }
166
+ }
167
+ }
168
+
169
+ });
170
+
171
+ mqttClient.on('close', function () {
172
+ });
173
+ }
174
+
175
+ function parseDelta(defaultFuncs, api, ctx, globalCallback, v) {
176
+ if (v.delta.class == "NewMessage") {
177
+ //Not tested for pages
178
+ if (ctx.globalOptions.pageID && ctx.globalOptions.pageID != v.queue) return;
179
+
180
+ (function resolveAttachmentUrl(i) {
181
+ if (v.delta.attachments && (i == v.delta.attachments.length)) {
182
+ var fmtMsg;
183
+ try {
184
+ fmtMsg = utils.formatDeltaMessage(v);
185
+ } catch (err) {
186
+ return log.error("Lỗi Nhẹ", null);
187
+ }
188
+ if (fmtMsg)
189
+ if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, fmtMsg.threadID, fmtMsg.messageID);
190
+
191
+ return !ctx.globalOptions.selfListen && fmtMsg.senderID === ctx.userID ? undefined : (function () { globalCallback(null, fmtMsg); })();
192
+ } else {
193
+ if (v.delta.attachments && (v.delta.attachments[i].mercury.attach_type == "photo")) {
194
+ api.resolvePhotoUrl(v.delta.attachments[i].fbid, (err, url) => {
195
+ if (!err) v.delta.attachments[i].mercury.metadata.url = url;
196
+ return resolveAttachmentUrl(i + 1);
197
+ });
198
+ } else return resolveAttachmentUrl(i + 1);
199
+ }
200
+ })(0);
201
+ }
202
+
203
+ if (v.delta.class == "ClientPayload") {
204
+ var clientPayload = utils.decodeClientPayload(v.delta.payload);
205
+ if (clientPayload && clientPayload.deltas) {
206
+ for (var i in clientPayload.deltas) {
207
+ var delta = clientPayload.deltas[i];
208
+ if (delta.deltaMessageReaction && !!ctx.globalOptions.listenEvents) {
209
+ (function () {
210
+ globalCallback(null, {
211
+ type: "message_reaction",
212
+ threadID: (delta.deltaMessageReaction.threadKey.threadFbId ? delta.deltaMessageReaction.threadKey.threadFbId : delta.deltaMessageReaction.threadKey.otherUserFbId).toString(),
213
+ messageID: delta.deltaMessageReaction.messageId,
214
+ reaction: delta.deltaMessageReaction.reaction,
215
+ senderID: delta.deltaMessageReaction.senderId.toString(),
216
+ userID: delta.deltaMessageReaction.userId.toString()
217
+ });
218
+ })();
219
+ } else if (delta.deltaRecallMessageData && !!ctx.globalOptions.listenEvents) {
220
+ (function () {
221
+ globalCallback(null, {
222
+ type: "message_unsend",
223
+ threadID: (delta.deltaRecallMessageData.threadKey.threadFbId ? delta.deltaRecallMessageData.threadKey.threadFbId : delta.deltaRecallMessageData.threadKey.otherUserFbId).toString(),
224
+ messageID: delta.deltaRecallMessageData.messageID,
225
+ senderID: delta.deltaRecallMessageData.senderID.toString(),
226
+ deletionTimestamp: delta.deltaRecallMessageData.deletionTimestamp,
227
+ timestamp: delta.deltaRecallMessageData.timestamp
228
+ });
229
+ })();
230
+ } else if (delta.deltaMessageReply) {
231
+ //Mention block - #1
232
+ var mdata =
233
+ delta.deltaMessageReply.message === undefined ? [] :
234
+ delta.deltaMessageReply.message.data === undefined ? [] :
235
+ delta.deltaMessageReply.message.data.prng === undefined ? [] :
236
+ JSON.parse(delta.deltaMessageReply.message.data.prng);
237
+ var m_id = mdata.map(u => u.i);
238
+ var m_offset = mdata.map(u => u.o);
239
+ var m_length = mdata.map(u => u.l);
240
+
241
+ var mentions = {};
242
+
243
+ for (var i = 0; i < m_id.length; i++) mentions[m_id[i]] = (delta.deltaMessageReply.message.body || "").substring(m_offset[i], m_offset[i] + m_length[i]);
244
+ //Mention block - 1#
245
+ var callbackToReturn = {
246
+ type: "message_reply",
247
+ threadID: (delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId ? delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId : delta.deltaMessageReply.message.messageMetadata.threadKey.otherUserFbId).toString(),
248
+ messageID: delta.deltaMessageReply.message.messageMetadata.messageId,
249
+ senderID: delta.deltaMessageReply.message.messageMetadata.actorFbId.toString(),
250
+ attachments: delta.deltaMessageReply.message.attachments.map(function (att) {
251
+ var mercury = JSON.parse(att.mercuryJSON);
252
+ Object.assign(att, mercury);
253
+ return att;
254
+ }).map(att => {
255
+ var x;
256
+ try {
257
+ x = utils._formatAttachment(att);
258
+ } catch (ex) {
259
+ x = att;
260
+ x.error = ex;
261
+ x.type = "unknown";
262
+ }
263
+ return x;
264
+ }),
265
+ args: (delta.deltaMessageReply.message.body || "").trim().split(/\s+/),
266
+ body: (delta.deltaMessageReply.message.body || ""),
267
+ isGroup: !!delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId,
268
+ mentions: mentions,
269
+ timestamp: delta.deltaMessageReply.message.messageMetadata.timestamp,
270
+ participantIDs: (delta.deltaMessageReply.message.participants || []).map(e => e.toString())
271
+ };
272
+
273
+ if (delta.deltaMessageReply.repliedToMessage) {
274
+ //Mention block - #2
275
+ mdata =
276
+ delta.deltaMessageReply.repliedToMessage === undefined ? [] :
277
+ delta.deltaMessageReply.repliedToMessage.data === undefined ? [] :
278
+ delta.deltaMessageReply.repliedToMessage.data.prng === undefined ? [] :
279
+ JSON.parse(delta.deltaMessageReply.repliedToMessage.data.prng);
280
+ m_id = mdata.map(u => u.i);
281
+ m_offset = mdata.map(u => u.o);
282
+ m_length = mdata.map(u => u.l);
283
+
284
+ var rmentions = {};
285
+
286
+ for (var i = 0; i < m_id.length; i++) rmentions[m_id[i]] = (delta.deltaMessageReply.repliedToMessage.body || "").substring(m_offset[i], m_offset[i] + m_length[i]);
287
+ //Mention block - 2#
288
+ callbackToReturn.messageReply = {
289
+ threadID: (delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId ? delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId : delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.otherUserFbId).toString(),
290
+ messageID: delta.deltaMessageReply.repliedToMessage.messageMetadata.messageId,
291
+ senderID: delta.deltaMessageReply.repliedToMessage.messageMetadata.actorFbId.toString(),
292
+ attachments: delta.deltaMessageReply.repliedToMessage.attachments.map(function (att) {
293
+ var mercury = JSON.parse(att.mercuryJSON);
294
+ Object.assign(att, mercury);
295
+ return att;
296
+ }).map(att => {
297
+ var x;
298
+ try {
299
+ x = utils._formatAttachment(att);
300
+ } catch (ex) {
301
+ x = att;
302
+ x.error = ex;
303
+ x.type = "unknown";
304
+ }
305
+ return x;
306
+ }),
307
+ args: (delta.deltaMessageReply.repliedToMessage.body || "").trim().split(/\s+/),
308
+ body: delta.deltaMessageReply.repliedToMessage.body || "",
309
+ isGroup: !!delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId,
310
+ mentions: rmentions,
311
+ timestamp: delta.deltaMessageReply.repliedToMessage.messageMetadata.timestamp,
312
+ participantIDs: (delta.deltaMessageReply.repliedToMessage.participants || []).map(e => e.toString())
313
+ };
314
+ } else if (delta.deltaMessageReply.replyToMessageId) {
315
+ return defaultFuncs
316
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, {
317
+ "av": ctx.globalOptions.pageID,
318
+ "queries": JSON.stringify({
319
+ "o0": {
320
+ //Using the same doc_id as forcedFetch
321
+ "doc_id": "2848441488556444",
322
+ "query_params": {
323
+ "thread_and_message_id": {
324
+ "thread_id": callbackToReturn.threadID,
325
+ "message_id": delta.deltaMessageReply.replyToMessageId.id,
326
+ }
327
+ }
328
+ }
329
+ })
330
+ })
331
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
332
+ .then((resData) => {
333
+ if (resData[resData.length - 1].error_results > 0) throw resData[0].o0.errors;
334
+ if (resData[resData.length - 1].successful_results === 0) throw { error: "forcedFetch: there was no successful_results", res: resData };
335
+ var fetchData = resData[0].o0.data.message;
336
+ var mobj = {};
337
+ for (var n in fetchData.message.ranges) mobj[fetchData.message.ranges[n].entity.id] = (fetchData.message.text || "").substr(fetchData.message.ranges[n].offset, fetchData.message.ranges[n].length);
338
+
339
+ callbackToReturn.messageReply = {
340
+ threadID: callbackToReturn.threadID,
341
+ messageID: fetchData.message_id,
342
+ senderID: fetchData.message_sender.id.toString(),
343
+ attachments: fetchData.message.blob_attachment.map(att => {
344
+ var x;
345
+ try {
346
+ x = utils._formatAttachment({ blob_attachment: att });
347
+ } catch (ex) {
348
+ x = att;
349
+ x.error = ex;
350
+ x.type = "unknown";
351
+ }
352
+ return x;
353
+ }),
354
+ args: (fetchData.message.text || "").trim().split(/\s+/) || [],
355
+ body: fetchData.message.text || "",
356
+ isGroup: callbackToReturn.isGroup,
357
+ mentions: mobj,
358
+ timestamp: parseInt(fetchData.timestamp_precise)
359
+ };
360
+ })
361
+ .catch(err => log.error("forcedFetch", err))
362
+ .finally(function () {
363
+ if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, callbackToReturn.threadID, callbackToReturn.messageID);
364
+ !ctx.globalOptions.selfListen && callbackToReturn.senderID === ctx.userID ? undefined : (function () { globalCallback(null, callbackToReturn); })();
365
+ });
366
+ } else callbackToReturn.delta = delta;
367
+
368
+ if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, callbackToReturn.threadID, callbackToReturn.messageID);
369
+
370
+ return !ctx.globalOptions.selfListen && callbackToReturn.senderID === ctx.userID ? undefined : (function () { globalCallback(null, callbackToReturn); })();
371
+ }
372
+ }
373
+ return;
374
+ }
375
+ }
376
+
377
+ if (v.delta.class !== "NewMessage" && !ctx.globalOptions.listenEvents) return;
378
+ switch (v.delta.class) {
379
+ case "ReadReceipt":
380
+ var fmtMsg;
381
+ try {
382
+ fmtMsg = utils.formatDeltaReadReceipt(v.delta);
383
+ } catch (err) {
384
+ return log.error("Lỗi Nhẹ", null)
385
+ }
386
+ return (function () { globalCallback(null, fmtMsg); })();
387
+ case "AdminTextMessage":
388
+ switch (v.delta.type) {
389
+ case "change_thread_theme":
390
+ case "change_thread_icon":
391
+ case "change_thread_nickname":
392
+ case "change_thread_admins":
393
+ case "change_thread_approval_mode":
394
+ case "group_poll":
395
+ case "messenger_call_log":
396
+ case "participant_joined_group_call":
397
+ var fmtMsg;
398
+ try {
399
+ fmtMsg = utils.formatDeltaEvent(v.delta);
400
+ } catch (err) {
401
+ return log.error("Lỗi Nhẹ", null)
402
+ }
403
+ return (function () { globalCallback(null, fmtMsg); })();
404
+ default:
405
+ return;
406
+ }
407
+ break;
408
+ //For group images
409
+ case "ForcedFetch":
410
+ if (!v.delta.threadKey) return;
411
+ var mid = v.delta.messageId;
412
+ var tid = v.delta.threadKey.threadFbId;
413
+ if (mid && tid) {
414
+ const form = {
415
+ "av": ctx.globalOptions.pageID,
416
+ "queries": JSON.stringify({
417
+ "o0": {
418
+ //This doc_id is valid as of March 25, 2020
419
+ "doc_id": "2848441488556444",
420
+ "query_params": {
421
+ "thread_and_message_id": {
422
+ "thread_id": tid.toString(),
423
+ "message_id": mid,
424
+ }
425
+ }
426
+ }
427
+ })
428
+ };
429
+
430
+ defaultFuncs
431
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
432
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
433
+ .then((resData) => {
434
+ if (resData[resData.length - 1].error_results > 0) throw resData[0].o0.errors;
435
+
436
+ if (resData[resData.length - 1].successful_results === 0) throw { error: "forcedFetch: there was no successful_results", res: resData };
437
+
438
+ var fetchData = resData[0].o0.data.message;
439
+
440
+ if (utils.getType(fetchData) == "Object") {
441
+ log.info("forcedFetch", fetchData);
442
+ switch (fetchData.__typename) {
443
+ case "ThreadImageMessage":
444
+ (!ctx.globalOptions.selfListen &&
445
+ fetchData.message_sender.id.toString() === ctx.userID) ||
446
+ !ctx.loggedIn ?
447
+ undefined :
448
+ (function () {
449
+ globalCallback(null, {
450
+ type: "change_thread_image",
451
+ threadID: utils.formatID(tid.toString()),
452
+ snippet: fetchData.snippet,
453
+ timestamp: fetchData.timestamp_precise,
454
+ author: fetchData.message_sender.id,
455
+ image: {
456
+ attachmentID: fetchData.image_with_metadata && fetchData.image_with_metadata.legacy_attachment_id,
457
+ width: fetchData.image_with_metadata && fetchData.image_with_metadata.original_dimensions.x,
458
+ height: fetchData.image_with_metadata && fetchData.image_with_metadata.original_dimensions.y,
459
+ url: fetchData.image_with_metadata && fetchData.image_with_metadata.preview.uri
460
+ }
461
+ });
462
+ })();
463
+ break;
464
+ case "UserMessage":
465
+ log.info("ff-Return", {
466
+ type: "message",
467
+ senderID: utils.formatID(fetchData.message_sender.id),
468
+ body: fetchData.message.text || "",
469
+ threadID: utils.formatID(tid.toString()),
470
+ messageID: fetchData.message_id,
471
+ attachments: [{
472
+ type: "share",
473
+ ID: fetchData.extensible_attachment.legacy_attachment_id,
474
+ url: fetchData.extensible_attachment.story_attachment.url,
475
+
476
+ title: fetchData.extensible_attachment.story_attachment.title_with_entities.text,
477
+ description: fetchData.extensible_attachment.story_attachment.description.text,
478
+ source: fetchData.extensible_attachment.story_attachment.source,
479
+
480
+ image: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).uri,
481
+ width: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).width,
482
+ height: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).height,
483
+ playable: (fetchData.extensible_attachment.story_attachment.media || {}).is_playable || false,
484
+ duration: (fetchData.extensible_attachment.story_attachment.media || {}).playable_duration_in_ms || 0,
485
+
486
+ subattachments: fetchData.extensible_attachment.subattachments,
487
+ properties: fetchData.extensible_attachment.story_attachment.properties,
488
+ }],
489
+ mentions: {},
490
+ timestamp: parseInt(fetchData.timestamp_precise),
491
+ isGroup: (fetchData.message_sender.id != tid.toString())
492
+ });
493
+ globalCallback(null, {
494
+ type: "message",
495
+ senderID: utils.formatID(fetchData.message_sender.id),
496
+ body: fetchData.message.text || "",
497
+ threadID: utils.formatID(tid.toString()),
498
+ messageID: fetchData.message_id,
499
+ attachments: [{
500
+ type: "share",
501
+ ID: fetchData.extensible_attachment.legacy_attachment_id,
502
+ url: fetchData.extensible_attachment.story_attachment.url,
503
+
504
+ title: fetchData.extensible_attachment.story_attachment.title_with_entities.text,
505
+ description: fetchData.extensible_attachment.story_attachment.description.text,
506
+ source: fetchData.extensible_attachment.story_attachment.source,
507
+
508
+ image: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).uri,
509
+ width: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).width,
510
+ height: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).height,
511
+ playable: (fetchData.extensible_attachment.story_attachment.media || {}).is_playable || false,
512
+ duration: (fetchData.extensible_attachment.story_attachment.media || {}).playable_duration_in_ms || 0,
513
+
514
+ subattachments: fetchData.extensible_attachment.subattachments,
515
+ properties: fetchData.extensible_attachment.story_attachment.properties,
516
+ }],
517
+ mentions: {},
518
+ timestamp: parseInt(fetchData.timestamp_precise),
519
+ isGroup: (fetchData.message_sender.id != tid.toString())
520
+ });
521
+ }
522
+ } else log.error("forcedFetch", fetchData);
523
+ })
524
+ .catch((err) => log.error("forcedFetch", err));
525
+ }
526
+ break;
527
+ case "ThreadName":
528
+ case "ParticipantsAddedToGroupThread":
529
+ case "ParticipantLeftGroupThread":
530
+ var formattedEvent;
531
+ try {
532
+ formattedEvent = utils.formatDeltaEvent(v.delta);
533
+ } catch (err) {
534
+ return log.error("Lỗi Nhẹ", null)
535
+ }
536
+ return (!ctx.globalOptions.selfListen && formattedEvent.author.toString() === ctx.userID) || !ctx.loggedIn ? undefined : (function () { globalCallback(null, formattedEvent); })();
537
+ }
538
+ }
539
+
540
+ function markDelivery(ctx, api, threadID, messageID) {
541
+ if (threadID && messageID) {
542
+ api.markAsDelivered(threadID, messageID, (err) => {
543
+ if (err) log.error("markAsDelivered", err);
544
+ else {
545
+ if (ctx.globalOptions.autoMarkRead) {
546
+ api.markAsRead(threadID, (err) => {
547
+ if (err) log.error("markAsDelivered", err);
548
+ });
549
+ }
550
+ }
551
+ });
552
+ }
553
+ }
554
+
555
+ module.exports = function (defaultFuncs, api, ctx) {
556
+ var globalCallback = identity;
557
+ getSeqID = function getSeqID() {
558
+ ctx.t_mqttCalled = false;
559
+ defaultFuncs
560
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
561
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
562
+ .then((resData) => {
563
+ if (utils.getType(resData) != "Array") throw { error: "Chưa Đăng Nhập Được - Appstate Đã Bị Lỗi", res: resData };
564
+ if (resData && resData[resData.length - 1].error_results > 0) throw resData[0].o0.errors;
565
+ if (resData[resData.length - 1].successful_results === 0) throw { error: "getSeqId: there was no successful_results", res: resData };
566
+ if (resData[0].o0.data.viewer.message_threads.sync_sequence_id) {
567
+ ctx.lastSeqId = resData[0].o0.data.viewer.message_threads.sync_sequence_id;
568
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
569
+ } else throw { error: "getSeqId: no sync_sequence_id found.", res: resData };
570
+ })
571
+ .catch((err) => {
572
+ log.error("getSeqId", err);
573
+ if (utils.getType(err) == "Object" && err.error === "Chưa Đăng Nhập Được - Appstate Đã Bị Lỗi") ctx.loggedIn = false;
574
+ return globalCallback(err);
575
+ });
576
+ };
577
+
578
+ return function (callback) {
579
+ class MessageEmitter extends EventEmitter {
580
+ stopListening(callback) {
581
+ callback = callback || (() => { });
582
+ globalCallback = identity;
583
+ if (ctx.mqttClient) {
584
+ ctx.mqttClient.unsubscribe("/webrtc");
585
+ ctx.mqttClient.unsubscribe("/rtc_multi");
586
+ ctx.mqttClient.unsubscribe("/onevc");
587
+ ctx.mqttClient.publish("/browser_close", "{}");
588
+ ctx.mqttClient.end(false, function (...data) {
589
+ callback(data);
590
+ ctx.mqttClient = undefined;
591
+ });
592
+ }
593
+ }
594
+ }
595
+
596
+ var msgEmitter = new MessageEmitter();
597
+ globalCallback = (callback || function (error, message) {
598
+ if (error) return msgEmitter.emit("error", error);
599
+ msgEmitter.emit("message", message);
600
+ });
601
+
602
+ //Reset some stuff
603
+ if (!ctx.firstListen) ctx.lastSeqId = null;
604
+ ctx.syncToken = undefined;
605
+ ctx.t_mqttCalled = false;
606
+
607
+ //Same request as getThreadList
608
+ form = {
609
+ "av": ctx.globalOptions.pageID,
610
+ "queries": JSON.stringify({
611
+ "o0": {
612
+ "doc_id": "3336396659757871",
613
+ "query_params": {
614
+ "limit": 1,
615
+ "before": null,
616
+ "tags": ["INBOX"],
617
+ "includeDeliveryReceipts": false,
618
+ "includeSeqID": true
619
+ }
620
+ }
621
+ })
622
+ };
623
+
624
+ if (!ctx.firstListen || !ctx.lastSeqId) getSeqID();
625
+ else listenMqtt(defaultFuncs, api, ctx, globalCallback);
626
+ ctx.firstListen = false;
627
+ return msgEmitter;
628
+ };
629
+ };