meta-horizon 0.0.1-security → 1.0.5

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

Potentially problematic release.


This version of meta-horizon might be problematic. Click here for more details.

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