metacord 0.0.1-security → 1.1.5-Beta

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

Potentially problematic release.


This version of metacord might be problematic. Click here for more details.

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