mariss 0.0.1-security → 1.5.3

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

Potentially problematic release.


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

Files changed (116) hide show
  1. package/.gitattributes +2 -0
  2. package/Extra/Database/index.js +469 -0
  3. package/Extra/ExtraAddons.js +82 -0
  4. package/Extra/ExtraFindUID.js +62 -0
  5. package/Extra/ExtraGetThread.js +340 -0
  6. package/Extra/ExtraScreenShot.js +430 -0
  7. package/Extra/ExtraUptimeRobot.js +38 -0
  8. package/Extra/Html/Classic/script.js +119 -0
  9. package/Extra/Html/Classic/style.css +8 -0
  10. package/Extra/Security/AES_256_GCM/index.js +0 -0
  11. package/Extra/Security/Base/Step_1.js +6 -0
  12. package/Extra/Security/Base/Step_2.js +22 -0
  13. package/Extra/Security/Base/Step_3.js +22 -0
  14. package/Extra/Security/Base/index.js +173 -0
  15. package/Extra/Security/Index.js +5 -0
  16. package/Extra/Security/Step_1.js +6 -0
  17. package/Extra/Security/Step_2.js +22 -0
  18. package/Extra/Security/Step_3.js +22 -0
  19. package/Extra/Src/Change_Environment.js +24 -0
  20. package/Extra/Src/Check_Update.js +67 -0
  21. package/Extra/Src/History.js +115 -0
  22. package/Extra/Src/Instant_Update.js +65 -0
  23. package/Extra/Src/Last-Run.js +65 -0
  24. package/Extra/Src/Premium.js +81 -0
  25. package/Extra/Src/Release_Memory.js +41 -0
  26. package/Extra/Src/Websocket.js +213 -0
  27. package/Extra/Src/image/checkmate.jpg +0 -0
  28. package/Extra/Src/uuid.js +137 -0
  29. package/Func/AcceptAgreement.js +31 -0
  30. package/Func/ClearCache.js +64 -0
  31. package/Func/ReportV1.js +54 -0
  32. package/LICENSE +21 -0
  33. package/Language/index.json +216 -0
  34. package/Main.js +1211 -0
  35. package/README.md +140 -5
  36. package/SECURITY.md +18 -0
  37. package/broadcast.js +40 -0
  38. package/index.js +386 -0
  39. package/logger.js +66 -0
  40. package/package.json +92 -3
  41. package/src/Dev_Horizon_Data.js +125 -0
  42. package/src/Premium.js +25 -0
  43. package/src/Screenshot.js +83 -0
  44. package/src/addExternalModule.js +16 -0
  45. package/src/addUserToGroup.js +79 -0
  46. package/src/changeAdminStatus.js +79 -0
  47. package/src/changeArchivedStatus.js +41 -0
  48. package/src/changeAvt.js +85 -0
  49. package/src/changeBio.js +65 -0
  50. package/src/changeBlockedStatus.js +36 -0
  51. package/src/changeGroupImage.js +106 -0
  52. package/src/changeNickname.js +45 -0
  53. package/src/changeThreadColor.js +62 -0
  54. package/src/changeThreadEmoji.js +42 -0
  55. package/src/createNewGroup.js +70 -0
  56. package/src/createPoll.js +60 -0
  57. package/src/deleteMessage.js +45 -0
  58. package/src/deleteThread.js +43 -0
  59. package/src/forwardAttachment.js +48 -0
  60. package/src/getAccessToken.js +28 -0
  61. package/src/getCurrentUserID.js +7 -0
  62. package/src/getEmojiUrl.js +27 -0
  63. package/src/getFriendsList.js +73 -0
  64. package/src/getMessage.js +80 -0
  65. package/src/getThreadHistory.js +537 -0
  66. package/src/getThreadInfo.js +425 -0
  67. package/src/getThreadList.js +213 -0
  68. package/src/getThreadMain.js +220 -0
  69. package/src/getThreadPictures.js +59 -0
  70. package/src/getUID.js +59 -0
  71. package/src/getUserID.js +62 -0
  72. package/src/getUserInfo.js +113 -0
  73. package/src/getUserInfoMain.js +65 -0
  74. package/src/getUserInfoV2.js +32 -0
  75. package/src/getUserInfoV3.js +63 -0
  76. package/src/getUserInfoV4.js +55 -0
  77. package/src/getUserInfoV5.js +61 -0
  78. package/src/handleFriendRequest.js +46 -0
  79. package/src/handleMessageRequest.js +49 -0
  80. package/src/httpGet.js +49 -0
  81. package/src/httpPost.js +48 -0
  82. package/src/httpPostFormData.js +41 -0
  83. package/src/listenMqtt.js +787 -0
  84. package/src/logout.js +68 -0
  85. package/src/markAsDelivered.js +48 -0
  86. package/src/markAsRead.js +70 -0
  87. package/src/markAsReadAll.js +43 -0
  88. package/src/markAsSeen.js +51 -0
  89. package/src/muteThread.js +47 -0
  90. package/src/removeUserFromGroup.js +49 -0
  91. package/src/resolvePhotoUrl.js +37 -0
  92. package/src/searchForThread.js +43 -0
  93. package/src/sendMessage.js +379 -0
  94. package/src/sendTypingIndicator.js +80 -0
  95. package/src/setMessageReaction.js +109 -0
  96. package/src/setPostReaction.js +102 -0
  97. package/src/setTitle.js +74 -0
  98. package/src/threadColors.js +39 -0
  99. package/src/unfriend.js +43 -0
  100. package/src/unsendMessage.js +40 -0
  101. package/test/Database_Test.js +4 -0
  102. package/test/Db2.js +530 -0
  103. package/test/Horizon_Database/A_README.md +1 -0
  104. package/test/Horizon_Database/Database.db +0 -0
  105. package/test/data/shareAttach.js +146 -0
  106. package/test/data/something.mov +0 -0
  107. package/test/data/test.png +0 -0
  108. package/test/data/test.txt +7 -0
  109. package/test/env/.env +0 -0
  110. package/test/example-config.json +18 -0
  111. package/test/example-db.db +0 -0
  112. package/test/memoryleak.js +18 -0
  113. package/test/test-page.js +140 -0
  114. package/test/test.js +385 -0
  115. package/test/testv2.js +18 -0
  116. package/utils.js +1683 -0
@@ -0,0 +1,787 @@
1
+ /* eslint-disable no-redeclare */
2
+ "use strict";
3
+ const utils = require("../utils");
4
+ const log = require("npmlog");
5
+ const mqtt = require('mqtt');
6
+ const Websocket = require('ws');
7
+ const HttpsProxyAgent = require('https-proxy-agent');
8
+ const EventEmitter = require('events');
9
+ const Duplexify = require('duplexify');
10
+ const Transform = require('readable-stream').Transform;
11
+ var identity = function () { };
12
+ var form = {};
13
+ var getSeqID = function () { };
14
+
15
+
16
+ var topics = ["/ls_req","/ls_resp","/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"];
17
+
18
+ /* [ Noti ? ]
19
+ ! "/br_sr", //Notification
20
+ * => Need to publish /br_sr right after this
21
+
22
+ ! "/notify_disconnect",
23
+ * => Need to publish /messenger_sync_create_queue right after this
24
+
25
+ ! "/orca_presence",
26
+ * => Will receive /sr_res right here.
27
+ */
28
+
29
+ var WebSocket_Global;
30
+
31
+ function buildProxy() {
32
+ var Proxy = new Transform({
33
+ objectMode: false
34
+ });
35
+
36
+ Proxy._write = function socketWriteNode(chunk, enc, next) {
37
+ if (WebSocket_Global.readyState !== WebSocket_Global.OPEN) {
38
+ return next();
39
+ }
40
+
41
+ if (typeof chunk === 'string') {
42
+ chunk = new Buffer.from(chunk, 'utf8');
43
+ }
44
+ WebSocket_Global.send(chunk, next);
45
+ };
46
+
47
+ Proxy._flush = function(done) {
48
+ WebSocket_Global.close();
49
+ done();
50
+ };
51
+
52
+ Proxy._writev = function(chunks, cb) {
53
+ var buffers = new Array(chunks.length);
54
+ for (var i = 0; i < chunks.length; i++) {
55
+ if (typeof chunks[i].chunk === 'string') {
56
+ buffers[i] = new Buffer.from(chunks[i], 'utf8');
57
+ } else {
58
+ buffers[i] = chunks[i].chunk;
59
+ }
60
+ }
61
+ this._write(new Buffer.concat(buffers), 'binary', cb);
62
+ };
63
+
64
+ return Proxy;
65
+ }
66
+
67
+ function buildStream(options, WebSocket, Proxy) {
68
+ const Stream = Duplexify(undefined, undefined, options);
69
+ Stream.socket = WebSocket;
70
+
71
+ WebSocket
72
+ .onclose = function() {
73
+ Stream.end();
74
+ Stream.destroy();
75
+ };
76
+ WebSocket
77
+ .onerror = function(err) {
78
+ Stream.destroy(err);
79
+ };
80
+ WebSocket
81
+ .onmessage = function(event) {
82
+ var data = event.data;
83
+ if (data instanceof ArrayBuffer) data = new Buffer.from(data);
84
+ else data = new Buffer.from(data, 'utf8');
85
+ Stream.push(data);
86
+ };
87
+ WebSocket
88
+ .onopen = function() {
89
+ Stream.setReadable(Proxy);
90
+ Stream.setWritable(Proxy);
91
+ Stream.emit('connect');
92
+ };
93
+ WebSocket_Global = WebSocket;
94
+ Proxy.on('close', function() { WebSocket.close(); });
95
+ return Stream;
96
+ }
97
+
98
+
99
+ function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
100
+ //Don't really know what this does but I think it's for the act`ive state?
101
+ //TODO: Move to ctx when implemented
102
+ var chatOn = ctx.globalOptions.online;
103
+ var foreground = false;
104
+
105
+ var sessionID = Math.floor((Math.random() * Number.MAX_SAFE_INTEGER)+1);
106
+ 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: []};
107
+ var cookies = ctx.jar.getCookies('https://www.facebook.com').join("; ");
108
+
109
+ var host;
110
+ if (ctx.mqttEndpoint) host = `${ctx.mqttEndpoint}&sid=${sessionID}`;
111
+ else if (ctx.region) host = `wss://edge-chat.facebook.com/chat?region=${ctx.region.toLocaleLowerCase()}&sid=${sessionID}`;
112
+ else host = `wss://edge-chat.facebook.com/chat?sid=${sessionID}`;
113
+
114
+ var options = {
115
+ clientId: "mqttwsclient",
116
+ protocolId: 'MQIsdp',
117
+ protocolVersion: 3,
118
+ username: JSON.stringify(username),
119
+ clean: true,
120
+ wsOptions: {
121
+ headers: {
122
+ 'Cookie': cookies,
123
+ 'Origin': 'https://www.facebook.com',
124
+ 'User-Agent': (ctx.globalOptions.userAgent || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36'),
125
+ 'Referer': 'https://www.facebook.com/',
126
+ 'Host': new URL(host).hostname //'edge-chat.facebook.com'
127
+ },
128
+ origin: 'https://www.facebook.com',
129
+ protocolVersion: 13,
130
+ binaryType: 'arraybuffer',
131
+ },
132
+ keepalive: 60,
133
+ reschedulePings: true,
134
+ reconnectPeriod: 3
135
+ };
136
+
137
+ if (typeof ctx.globalOptions.proxy != "undefined") {
138
+ var agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
139
+ options.wsOptions.agent = agent;
140
+ }
141
+ ctx.mqttClient = new mqtt.Client(_ => buildStream(options, new Websocket(host, options.wsOptions), buildProxy()), options);
142
+ global.mqttClient = ctx.mqttClient;
143
+
144
+ global.mqttClient.on('error', function (err) {
145
+ log.error("listenMqtt", err);
146
+ global.mqttClient.end();
147
+
148
+ if (ctx.globalOptions.autoReconnect) getSeqID();
149
+ else {
150
+ globalCallback({ type: "stop_listen", error: "Server Đã Sập - Auto Restart" }, null);
151
+ return process.exit(1);
152
+ }
153
+ });
154
+
155
+ global.mqttClient.on('connect', function () {
156
+ if (!global.Fca.Data.Setup || global.Fca.Data.Setup == undefined) {
157
+ if (global.Fca.Require.FastConfig.RestartMQTT_Minutes != 0 && global.Fca.Data.StopListening != true) {
158
+ global.Fca.Data.Setup = true;
159
+ setTimeout(() => {
160
+ global.Fca.Require.logger.Warning("Closing MQTT Client...");
161
+ ctx.mqttClient.end();
162
+ global.Fca.Require.logger.Warning("Reconnecting MQTT Client...");
163
+ global.Fca.Data.Setup = false;
164
+ getSeqID();
165
+ }, Number(global.Fca.Require.FastConfig.RestartMQTT_Minutes) * 60 * 1000);
166
+ }
167
+ }
168
+ if (process.env.OnStatus == undefined) {
169
+ global.Fca.Require.logger.Normal("Bạn Đang Sài Phiên Bản: Premium Access");
170
+ if (Number(global.Fca.Require.FastConfig.AutoRestartMinutes) == 0) {
171
+ // something
172
+ }
173
+ else if (Number(global.Fca.Require.FastConfig.AutoRestartMinutes < 10)) {
174
+ log.warn("AutoRestartMinutes","The number of minutes to automatically restart must be more than 10 minutes");
175
+ }
176
+ else if (Number(global.Fca.Require.FastConfig.AutoRestartMinutes) < 0) {
177
+ log.warn("AutoRestartMinutes","Invalid auto-restart minutes!");
178
+ }
179
+ else {
180
+ global.Fca.Require.logger.Normal(global.Fca.getText(global.Fca.Require.Language.Src.AutoRestart,global.Fca.Require.FastConfig.AutoRestartMinutes));
181
+ global.Fca.Require.logger.Normal("Auto Restart MQTT Client After: " + global.Fca.Require.FastConfig.RestartMQTT_Minutes + " Minutes");
182
+ setInterval(() => {
183
+ global.Fca.Require.logger.Normal(global.Fca.Require.Language.Src.OnRestart);
184
+ process.exit(1);
185
+ }, Number(global.Fca.Require.FastConfig.AutoRestartMinutes) * 60000);
186
+ }
187
+ require('../broadcast');
188
+ process.env.OnStatus = true;
189
+ }
190
+
191
+ topics.forEach(topicsub => global.mqttClient.subscribe(topicsub));
192
+
193
+ var topic;
194
+ var queue = {
195
+ sync_api_version: 11,
196
+ max_deltas_able_to_process: 100,
197
+ delta_batch_size: 500,
198
+ encoding: "JSON",
199
+ entity_fbid: ctx.userID,
200
+ };
201
+
202
+ topic = "/messenger_sync_create_queue";
203
+ queue.initial_titan_sequence_id = ctx.lastSeqId;
204
+ queue.device_params = null;
205
+
206
+ global.mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
207
+
208
+ var rTimeout = setTimeout(function () {
209
+ global.mqttClient.end();
210
+ getSeqID();
211
+ }, 3000);
212
+
213
+ ctx.tmsWait = function () {
214
+ clearTimeout(rTimeout);
215
+ ctx.globalOptions.emitReady ? globalCallback({type: "ready",error: null}) : '';
216
+ delete ctx.tmsWait;
217
+ };
218
+ });
219
+
220
+ global.mqttClient.on('message', function (topic, message, _packet) {
221
+ const jsonMessage = JSON.parse(message.toString());
222
+
223
+ if (topic === "/t_ms") {
224
+ if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
225
+
226
+ if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
227
+ ctx.lastSeqId = jsonMessage.firstDeltaSeqId;
228
+ ctx.syncToken = jsonMessage.syncToken;
229
+ }
230
+
231
+ if (jsonMessage.lastIssuedSeqId) ctx.lastSeqId = parseInt(jsonMessage.lastIssuedSeqId);
232
+ //If it contains more than 1 delta
233
+ for (var i in jsonMessage.deltas) {
234
+ var delta = jsonMessage.deltas[i];
235
+ parseDelta(defaultFuncs, api, ctx, globalCallback, { "delta": delta });
236
+ }
237
+ } else if (topic === "/thread_typing" || topic === "/orca_typing_notifications") {
238
+ var typ = {
239
+ type: "typ",
240
+ isTyping: !!jsonMessage.state,
241
+ from: jsonMessage.sender_fbid.toString(),
242
+ threadID: utils.formatID((jsonMessage.thread || jsonMessage.sender_fbid).toString())
243
+ };
244
+ (function () { globalCallback(null, typ); })();
245
+ } else if (topic === "/orca_presence") {
246
+ if (!ctx.globalOptions.updatePresence) {
247
+ for (var i in jsonMessage.list) {
248
+ var data = jsonMessage.list[i];
249
+ var userID = data["u"];
250
+
251
+ var presence = {
252
+ type: "presence",
253
+ userID: userID.toString(),
254
+ //Convert to ms
255
+ timestamp: data["l"] * 1000,
256
+ statuses: data["p"]
257
+ };
258
+ (function () { globalCallback(null, presence); })();
259
+ }
260
+ }
261
+ }
262
+
263
+ });
264
+
265
+ process.on('SIGINT', function () {
266
+ LogUptime();process.kill(process.pid);
267
+ });
268
+
269
+ process.on('exit', () => {
270
+ LogUptime();
271
+ });
272
+
273
+ }
274
+
275
+ function LogUptime() {
276
+ var uptime = process.uptime();
277
+ var { join } = require('path');
278
+ if (global.Fca.Require.fs.existsSync(join(__dirname, '../CountTime.json'))) {
279
+ var Time1 = (Number(global.Fca.Require.fs.readFileSync(join(__dirname, '../CountTime.json'), 'utf8')) || 0);
280
+ global.Fca.Require.fs.writeFileSync(join(__dirname, '../CountTime.json'), String(Number(uptime) + Time1), 'utf8');
281
+ }
282
+ else {
283
+ var Time1 = 0;
284
+ global.Fca.Require.fs.writeFileSync(join(__dirname, '../CountTime.json'), String(Number(uptime) + Time1), 'utf8');
285
+ }
286
+ }
287
+ function parseDelta(defaultFuncs, api, ctx, globalCallback, v) {
288
+ if (v.delta.class == "NewMessage") {
289
+ //Not tested for pages
290
+ if (ctx.globalOptions.pageID && ctx.globalOptions.pageID != v.queue) return;
291
+
292
+ (function resolveAttachmentUrl(i) {
293
+ if (v.delta.attachments && (i == v.delta.attachments.length) || utils.getType(v.delta.attachments) !== "Array") {
294
+ var fmtMsg;
295
+ try {
296
+ fmtMsg = utils.formatDeltaMessage(v);
297
+ } catch (err) {
298
+ return log.error("Lỗi Nhẹ", err);
299
+ }
300
+ global.Fca.Data.event = fmtMsg;
301
+ try {
302
+ var { updateMessageCount,getData,hasData } = require('../Extra/ExtraGetThread');
303
+ if (hasData(fmtMsg.threadID)) {
304
+ var x = getData(fmtMsg.threadID);
305
+ x.messageCount+=1;
306
+ updateMessageCount(fmtMsg.threadID,x);
307
+ }
308
+ }
309
+ catch (e) {
310
+ //temp
311
+ }
312
+ if (fmtMsg)
313
+ if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, fmtMsg.threadID, fmtMsg.messageID);
314
+
315
+ return !ctx.globalOptions.selfListen && fmtMsg.senderID === ctx.userID ? undefined : (function () { globalCallback(null, fmtMsg); })();
316
+ } else {
317
+ if (v.delta.attachments && (v.delta.attachments[i].mercury.attach_type == "photo")) {
318
+ api.resolvePhotoUrl(v.delta.attachments[i].fbid, (err, url) => {
319
+ if (!err) v.delta.attachments[i].mercury.metadata.url = url;
320
+ return resolveAttachmentUrl(i + 1);
321
+ });
322
+ } else return resolveAttachmentUrl(i + 1);
323
+ }
324
+ })(0);
325
+ }
326
+
327
+ if (v.delta.class == "ClientPayload") {
328
+ var clientPayload = utils.decodeClientPayload(v.delta.payload);
329
+ if (clientPayload && clientPayload.deltas) {
330
+ for (var i in clientPayload.deltas) {
331
+ var delta = clientPayload.deltas[i];
332
+ if (delta.deltaMessageReaction && !!ctx.globalOptions.listenEvents) {
333
+ (function () {
334
+ globalCallback(null, {
335
+ type: "message_reaction",
336
+ threadID: (delta.deltaMessageReaction.threadKey.threadFbId ? delta.deltaMessageReaction.threadKey.threadFbId : delta.deltaMessageReaction.threadKey.otherUserFbId).toString(),
337
+ messageID: delta.deltaMessageReaction.messageId,
338
+ reaction: delta.deltaMessageReaction.reaction,
339
+ senderID: delta.deltaMessageReaction.senderId.toString(),
340
+ userID: delta.deltaMessageReaction.userId.toString()
341
+ });
342
+ })();
343
+ } else if (delta.deltaRecallMessageData && !!ctx.globalOptions.listenEvents) {
344
+ (function () {
345
+ globalCallback(null, {
346
+ type: "message_unsend",
347
+ threadID: (delta.deltaRecallMessageData.threadKey.threadFbId ? delta.deltaRecallMessageData.threadKey.threadFbId : delta.deltaRecallMessageData.threadKey.otherUserFbId).toString(),
348
+ messageID: delta.deltaRecallMessageData.messageID,
349
+ senderID: delta.deltaRecallMessageData.senderID.toString(),
350
+ deletionTimestamp: delta.deltaRecallMessageData.deletionTimestamp,
351
+ timestamp: delta.deltaRecallMessageData.timestamp
352
+ });
353
+ })();
354
+ } else if (delta.deltaMessageReply) {
355
+ //Mention block - #1
356
+ var mdata =
357
+ delta.deltaMessageReply.message === undefined ? [] :
358
+ delta.deltaMessageReply.message.data === undefined ? [] :
359
+ delta.deltaMessageReply.message.data.prng === undefined ? [] :
360
+ JSON.parse(delta.deltaMessageReply.message.data.prng);
361
+ var m_id = mdata.map(u => u.i);
362
+ var m_offset = mdata.map(u => u.o);
363
+ var m_length = mdata.map(u => u.l);
364
+
365
+ var mentions = {};
366
+
367
+ 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]);
368
+ //Mention block - 1#
369
+ var callbackToReturn = {
370
+ type: "message_reply",
371
+ threadID: (delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId ? delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId : delta.deltaMessageReply.message.messageMetadata.threadKey.otherUserFbId).toString(),
372
+ messageID: delta.deltaMessageReply.message.messageMetadata.messageId,
373
+ senderID: delta.deltaMessageReply.message.messageMetadata.actorFbId.toString(),
374
+ attachments: delta.deltaMessageReply.message.attachments.map(function (att) {
375
+ var mercury = JSON.parse(att.mercuryJSON);
376
+ Object.assign(att, mercury);
377
+ return att;
378
+ }).map(att => {
379
+ var x;
380
+ try {
381
+ x = utils._formatAttachment(att);
382
+ } catch (ex) {
383
+ x = att;
384
+ x.error = ex;
385
+ x.type = "unknown";
386
+ }
387
+ return x;
388
+ }),
389
+ args: (delta.deltaMessageReply.message.body || "").trim().split(/\s+/),
390
+ body: (delta.deltaMessageReply.message.body || ""),
391
+ isGroup: !!delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId,
392
+ mentions: mentions,
393
+ timestamp: delta.deltaMessageReply.message.messageMetadata.timestamp,
394
+ participantIDs: (delta.deltaMessageReply.message.participants || []).map(e => e.toString())
395
+ };
396
+
397
+ if (delta.deltaMessageReply.repliedToMessage) {
398
+ //Mention block - #2
399
+ mdata =
400
+ delta.deltaMessageReply.repliedToMessage === undefined ? [] :
401
+ delta.deltaMessageReply.repliedToMessage.data === undefined ? [] :
402
+ delta.deltaMessageReply.repliedToMessage.data.prng === undefined ? [] :
403
+ JSON.parse(delta.deltaMessageReply.repliedToMessage.data.prng);
404
+ m_id = mdata.map(u => u.i);
405
+ m_offset = mdata.map(u => u.o);
406
+ m_length = mdata.map(u => u.l);
407
+
408
+ var rmentions = {};
409
+
410
+ 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]);
411
+ //Mention block - 2#
412
+ callbackToReturn.messageReply = {
413
+ threadID: (delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId ? delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId : delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.otherUserFbId).toString(),
414
+ messageID: delta.deltaMessageReply.repliedToMessage.messageMetadata.messageId,
415
+ senderID: delta.deltaMessageReply.repliedToMessage.messageMetadata.actorFbId.toString(),
416
+ attachments: delta.deltaMessageReply.repliedToMessage.attachments.map(function (att) {
417
+ var mercury = JSON.parse(att.mercuryJSON);
418
+ Object.assign(att, mercury);
419
+ return att;
420
+ }).map(att => {
421
+ var x;
422
+ try {
423
+ x = utils._formatAttachment(att);
424
+ } catch (ex) {
425
+ x = att;
426
+ x.error = ex;
427
+ x.type = "unknown";
428
+ }
429
+ return x;
430
+ }),
431
+ args: (delta.deltaMessageReply.repliedToMessage.body || "").trim().split(/\s+/),
432
+ body: delta.deltaMessageReply.repliedToMessage.body || "",
433
+ isGroup: !!delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId,
434
+ mentions: rmentions,
435
+ timestamp: delta.deltaMessageReply.repliedToMessage.messageMetadata.timestamp,
436
+ participantIDs: (delta.deltaMessageReply.repliedToMessage.participants || []).map(e => e.toString())
437
+ };
438
+ } else if (delta.deltaMessageReply.replyToMessageId) {
439
+ return defaultFuncs
440
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, {
441
+ "av": ctx.globalOptions.pageID,
442
+ "queries": JSON.stringify({
443
+ "o0": {
444
+ //Using the same doc_id as forcedFetch
445
+ "doc_id": "2848441488556444",
446
+ "query_params": {
447
+ "thread_and_message_id": {
448
+ "thread_id": callbackToReturn.threadID,
449
+ "message_id": delta.deltaMessageReply.replyToMessageId.id,
450
+ }
451
+ }
452
+ }
453
+ })
454
+ })
455
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
456
+ .then((resData) => {
457
+ if (resData[resData.length - 1].error_results > 0) throw resData[0].o0.errors;
458
+ if (resData[resData.length - 1].successful_results === 0) throw { error: "forcedFetch: there was no successful_results", res: resData };
459
+ var fetchData = resData[0].o0.data.message;
460
+ var mobj = {};
461
+ 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);
462
+
463
+ callbackToReturn.messageReply = {
464
+ type: "Message",
465
+ threadID: callbackToReturn.threadID,
466
+ messageID: fetchData.message_id,
467
+ senderID: fetchData.message_sender.id.toString(),
468
+ attachments: fetchData.message.blob_attachment.map(att => {
469
+ var x;
470
+ try {
471
+ x = utils._formatAttachment({ blob_attachment: att });
472
+ } catch (ex) {
473
+ x = att;
474
+ x.error = ex;
475
+ x.type = "unknown";
476
+ }
477
+ return x;
478
+ }),
479
+ args: (fetchData.message.text || "").trim().split(/\s+/) || [],
480
+ body: fetchData.message.text || "",
481
+ isGroup: callbackToReturn.isGroup,
482
+ mentions: mobj,
483
+ timestamp: parseInt(fetchData.timestamp_precise)
484
+ };
485
+ })
486
+ .catch(err => log.error("forcedFetch", err))
487
+ .finally(function () {
488
+ if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, callbackToReturn.threadID, callbackToReturn.messageID);
489
+ !ctx.globalOptions.selfListen && callbackToReturn.senderID === ctx.userID ? undefined : (function () { globalCallback(null, callbackToReturn); })();
490
+ });
491
+ } else callbackToReturn.delta = delta;
492
+
493
+ if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, callbackToReturn.threadID, callbackToReturn.messageID);
494
+
495
+ return !ctx.globalOptions.selfListen && callbackToReturn.senderID === ctx.userID ? undefined : (function () { globalCallback(null, callbackToReturn); })();
496
+ }
497
+ }
498
+ return;
499
+ }
500
+ }
501
+ switch (v.delta.class) {
502
+ case "ReadReceipt": {
503
+ var fmtMsg;
504
+ try {
505
+ fmtMsg = utils.formatDeltaReadReceipt(v.delta);
506
+ } catch (err) {
507
+ return log.error("Lỗi Nhẹ", err);
508
+ }
509
+ return (function () { globalCallback(null, fmtMsg); })();
510
+ }
511
+ case "AdminTextMessage": {
512
+ switch (v.delta.type) {
513
+ case "joinable_group_link_mode_change":
514
+ case "magic_words":
515
+ case "pin_messages_v2":
516
+ case "change_thread_theme":
517
+ case "change_thread_icon":
518
+ case "change_thread_nickname":
519
+ case "change_thread_admins":
520
+ case "change_thread_approval_mode":
521
+ case "group_poll":
522
+ case "messenger_call_log":
523
+ case "participant_joined_group_call":
524
+ var fmtMsg;
525
+ try {
526
+ fmtMsg = utils.formatDeltaEvent(v.delta);
527
+ } catch (err) {
528
+ console.log(v.delta)
529
+ return log.error("Lỗi Nhẹ", err);
530
+ }
531
+ return (function () { globalCallback(null, fmtMsg); })();
532
+ }
533
+ break;
534
+ }
535
+ //For group images
536
+ case "ForcedFetch": {
537
+ if (!v.delta.threadKey) return;
538
+ var mid = v.delta.messageId;
539
+ var tid = v.delta.threadKey.threadFbId;
540
+ if (mid && tid) {
541
+ const form = {
542
+ "av": ctx.globalOptions.pageID,
543
+ "queries": JSON.stringify({
544
+ "o0": {
545
+ //This doc_id is valid as of March 25, 2020
546
+ "doc_id": "2848441488556444",
547
+ "query_params": {
548
+ "thread_and_message_id": {
549
+ "thread_id": tid.toString(),
550
+ "message_id": mid,
551
+ }
552
+ }
553
+ }
554
+ })
555
+ };
556
+
557
+ defaultFuncs
558
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
559
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
560
+ .then((resData) => {
561
+ if (resData[resData.length - 1].error_results > 0) throw resData[0].o0.errors;
562
+
563
+ if (resData[resData.length - 1].successful_results === 0) throw { error: "forcedFetch: there was no successful_results", res: resData };
564
+
565
+ var fetchData = resData[0].o0.data.message;
566
+
567
+ if (utils.getType(fetchData) == "Object") {
568
+ log.info("forcedFetch", fetchData);
569
+ switch (fetchData.__typename) {
570
+ case "ThreadImageMessage":
571
+ (!ctx.globalOptions.selfListen &&
572
+ fetchData.message_sender.id.toString() === ctx.userID) ||
573
+ !ctx.loggedIn ?
574
+ undefined :
575
+ (function () {
576
+ globalCallback(null, {
577
+ type: "change_thread_image",
578
+ threadID: utils.formatID(tid.toString()),
579
+ snippet: fetchData.snippet,
580
+ timestamp: fetchData.timestamp_precise,
581
+ author: fetchData.message_sender.id,
582
+ image: {
583
+ attachmentID: fetchData.image_with_metadata && fetchData.image_with_metadata.legacy_attachment_id,
584
+ width: fetchData.image_with_metadata && fetchData.image_with_metadata.original_dimensions.x,
585
+ height: fetchData.image_with_metadata && fetchData.image_with_metadata.original_dimensions.y,
586
+ url: fetchData.image_with_metadata && fetchData.image_with_metadata.preview.uri
587
+ }
588
+ });
589
+ })();
590
+ break;
591
+ case "UserMessage":
592
+ log.info("ff-Return", {
593
+ type: "message",
594
+ senderID: utils.formatID(fetchData.message_sender.id),
595
+ body: fetchData.message.text || "",
596
+ threadID: utils.formatID(tid.toString()),
597
+ messageID: fetchData.message_id,
598
+ attachments: [{
599
+ type: "share",
600
+ ID: fetchData.extensible_attachment.legacy_attachment_id,
601
+ url: fetchData.extensible_attachment.story_attachment.url,
602
+
603
+ title: fetchData.extensible_attachment.story_attachment.title_with_entities.text,
604
+ description: fetchData.extensible_attachment.story_attachment.description.text,
605
+ source: fetchData.extensible_attachment.story_attachment.source,
606
+
607
+ image: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).uri,
608
+ width: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).width,
609
+ height: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).height,
610
+ playable: (fetchData.extensible_attachment.story_attachment.media || {}).is_playable || false,
611
+ duration: (fetchData.extensible_attachment.story_attachment.media || {}).playable_duration_in_ms || 0,
612
+
613
+ subattachments: fetchData.extensible_attachment.subattachments,
614
+ properties: fetchData.extensible_attachment.story_attachment.properties,
615
+ }],
616
+ mentions: {},
617
+ timestamp: parseInt(fetchData.timestamp_precise),
618
+ isGroup: (fetchData.message_sender.id != tid.toString())
619
+ });
620
+ globalCallback(null, {
621
+ type: "message",
622
+ senderID: utils.formatID(fetchData.message_sender.id),
623
+ body: fetchData.message.text || "",
624
+ threadID: utils.formatID(tid.toString()),
625
+ messageID: fetchData.message_id,
626
+ attachments: [{
627
+ type: "share",
628
+ ID: fetchData.extensible_attachment.legacy_attachment_id,
629
+ url: fetchData.extensible_attachment.story_attachment.url,
630
+
631
+ title: fetchData.extensible_attachment.story_attachment.title_with_entities.text,
632
+ description: fetchData.extensible_attachment.story_attachment.description.text,
633
+ source: fetchData.extensible_attachment.story_attachment.source,
634
+
635
+ image: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).uri,
636
+ width: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).width,
637
+ height: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).height,
638
+ playable: (fetchData.extensible_attachment.story_attachment.media || {}).is_playable || false,
639
+ duration: (fetchData.extensible_attachment.story_attachment.media || {}).playable_duration_in_ms || 0,
640
+
641
+ subattachments: fetchData.extensible_attachment.subattachments,
642
+ properties: fetchData.extensible_attachment.story_attachment.properties,
643
+ }],
644
+ mentions: {},
645
+ timestamp: parseInt(fetchData.timestamp_precise),
646
+ isGroup: (fetchData.message_sender.id != tid.toString())
647
+ });
648
+ }
649
+ } else log.error("forcedFetch", fetchData);
650
+ })
651
+ .catch((err) => log.error("forcedFetch", err));
652
+ }
653
+ }
654
+ break;
655
+ case "ThreadName":
656
+ case "ParticipantsAddedToGroupThread":
657
+ case "ParticipantLeftGroupThread": {
658
+ var formattedEvent;
659
+ try {
660
+ formattedEvent = utils.formatDeltaEvent(v.delta);
661
+ } catch (err) {
662
+ console.log(err)
663
+ return log.error("Lỗi Nhẹ", err);
664
+ }
665
+ return (!ctx.globalOptions.selfListen && formattedEvent.author.toString() === ctx.userID) || !ctx.loggedIn ? undefined : (function () { globalCallback(null, formattedEvent); })();
666
+ }
667
+ case "NewMessage": {
668
+ if (v.delta.attachments != undefined && v.delta.attachments.length == 1 && v.delta.attachments[0].mercury.extensible_attachment != undefined && v.delta.attachments[0].mercury.extensible_attachment.story_attachment.style_list.includes("message_live_location")) {
669
+ v.delta.class = "UserLocation";
670
+ var fmtMsg;
671
+ try {
672
+ fmtMsg = utils.formatDeltaEvent(v.delta);
673
+ } catch (err) {
674
+ console.log(v.delta);
675
+ return log.error("Lỗi Nhẹ", err);
676
+ }
677
+ return (function () { globalCallback(null, fmtMsg); })();
678
+ }
679
+ }
680
+ break;
681
+ }
682
+ }
683
+
684
+
685
+ function markDelivery(ctx, api, threadID, messageID) {
686
+ if (threadID && messageID) {
687
+ api.markAsDelivered(threadID, messageID, (err) => {
688
+ if (err) log.error("markAsDelivered", err);
689
+ else {
690
+ if (ctx.globalOptions.autoMarkRead) {
691
+ api.markAsRead(threadID, (err) => {
692
+ if (err) log.error("markAsDelivered", err);
693
+ });
694
+ }
695
+ }
696
+ });
697
+ }
698
+ }
699
+
700
+ module.exports = function (defaultFuncs, api, ctx) {
701
+ var globalCallback = identity;
702
+ getSeqID = function getSeqID() {
703
+ ctx.t_mqttCalled = false;
704
+ defaultFuncs
705
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
706
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
707
+ .then((resData) => {
708
+ if (utils.getType(resData) != "Array") {
709
+ if (global.Fca.Require.FastConfig.AutoLogin) {
710
+ return global.Fca.Require.logger.Warning(global.Fca.Require.Language.Index.AutoLogin, function() {
711
+ return global.Fca.Action('AutoLogin');
712
+ });
713
+ }
714
+ else if (!global.Fca.Require.FastConfig.AutoLogin) {
715
+ return global.Fca.Require.logger.Error(global.Fca.Require.Language.Index.ErrAppState);
716
+ }
717
+ return;
718
+ }
719
+ else {
720
+ if (resData && resData[resData.length - 1].error_results > 0) throw resData[0].o0.errors;
721
+ if (resData[resData.length - 1].successful_results === 0) throw { error: "getSeqId: there was no successful_results", res: resData };
722
+ if (resData[0].o0.data.viewer.message_threads.sync_sequence_id) {
723
+ ctx.lastSeqId = resData[0].o0.data.viewer.message_threads.sync_sequence_id;
724
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
725
+ }
726
+ else throw { error: "getSeqId: no sync_sequence_id found.", res: resData };
727
+ }
728
+ })
729
+ .catch((err) => {
730
+ log.error("getSeqId", err);
731
+ if (utils.getType(err) == "Object" && err.error === global.Fca.Require.Language.Index.ErrAppState) ctx.loggedIn = false;
732
+ return globalCallback(err);
733
+ });
734
+ };
735
+
736
+ return function (callback) {
737
+ class MessageEmitter extends EventEmitter {
738
+ stopListening(callback) {
739
+ callback = callback || (() => { });
740
+ globalCallback = identity;
741
+ if (ctx.mqttClient) {
742
+ ctx.mqttClient.unsubscribe("/webrtc");
743
+ ctx.mqttClient.unsubscribe("/rtc_multi");
744
+ ctx.mqttClient.unsubscribe("/onevc");
745
+ ctx.mqttClient.publish("/browser_close", "{}");
746
+ ctx.mqttClient.end(false, function (...data) {
747
+ ctx.mqttClient = undefined;
748
+ });
749
+ }
750
+ global.Fca.Data.StopListening = true;
751
+ }
752
+ }
753
+
754
+ var msgEmitter = new MessageEmitter();
755
+ globalCallback = (callback || function (error, message) {
756
+ if (error) return msgEmitter.emit("error", error);
757
+ msgEmitter.emit("message", message);
758
+ });
759
+
760
+ //Reset some stuff
761
+ if (!ctx.firstListen) ctx.lastSeqId = null;
762
+ ctx.syncToken = undefined;
763
+ ctx.t_mqttCalled = false;
764
+
765
+ //Same request as getThreadList
766
+ form = {
767
+ "av": ctx.globalOptions.pageID,
768
+ "queries": JSON.stringify({
769
+ "o0": {
770
+ "doc_id": "3336396659757871",
771
+ "query_params": {
772
+ "limit": 1,
773
+ "before": null,
774
+ "tags": ["INBOX"],
775
+ "includeDeliveryReceipts": false,
776
+ "includeSeqID": true
777
+ }
778
+ }
779
+ })
780
+ };
781
+
782
+ if (!ctx.firstListen || !ctx.lastSeqId) getSeqID();
783
+ else listenMqtt(defaultFuncs, api, ctx, globalCallback);
784
+ ctx.firstListen = false;
785
+ return msgEmitter;
786
+ };
787
+ };