fca-shankar-bot 20.2.0 → 20.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/.replit +14 -1
  2. package/Extra/Balancer.js +49 -0
  3. package/Extra/ExtraAddons.js +4 -4
  4. package/Extra/ExtraGetThread.js +27 -27
  5. package/Extra/ExtraScreenShot.js +3 -3
  6. package/Extra/ExtraUptimeRobot.js +4 -4
  7. package/Extra/Src/Change_Environment.js +2 -2
  8. package/Extra/Src/Check_Update.js +3 -3
  9. package/Extra/Src/Instant_Update.js +2 -2
  10. package/Extra/Src/Premium.js +7 -7
  11. package/Extra/Src/Release_Memory.js +7 -7
  12. package/Extra/Src/Websocket.js +12 -12
  13. package/Func/ClearCache.js +2 -2
  14. package/LICENSE +21 -0
  15. package/Language/index.json +22 -16
  16. package/Main.js +515 -349
  17. package/README.md +198 -0
  18. package/SECURITY.md +17 -0
  19. package/broadcast.js +44 -0
  20. package/index.js +215 -31
  21. package/logger.js +51 -122
  22. package/package.json +17 -15
  23. package/src/Dev_Horizon_Data.js +2 -2
  24. package/src/editMessage.js +45 -38
  25. package/src/listenMqtt.js +395 -373
  26. package/src/listenMqttV1.js +11 -11
  27. package/src/sendMessage.js +2 -2
  28. package/src/sendMqttMessage.js +51 -251
  29. package/src/setMessageReaction.js +64 -66
  30. package/src/shareContact.js +50 -75
  31. package/src/unsendMessage.js +32 -126
  32. package/src/unsendMqttMessage.js +66 -0
  33. package/test/data/shareAttach.js +146 -0
  34. package/test/data/something.mov +0 -0
  35. package/test/data/test.png +0 -0
  36. package/test/data/test.txt +7 -0
  37. package/test/example-config.json +18 -0
  38. package/test/test-page.js +140 -0
  39. package/test/test.js +385 -0
  40. package/test/testv2.js +3 -0
  41. package/utils.js +50 -11
  42. package/.cache/replit/env/latest +0 -49
  43. package/.cache/replit/env/latest.json +0 -1
  44. package/.cache/replit/modules/nodejs-20.res +0 -1
  45. package/.cache/replit/modules/replit.res +0 -1
  46. package/.cache/replit/modules.stamp +0 -0
  47. package/.cache/replit/toolchain.json +0 -1
  48. package/CountTime.json +0 -1
  49. package/src/followUser.js +0 -171
  50. package/src/getFacebookInfo.js +0 -69
  51. package/src/listenMqtt.jk +0 -732
  52. package/src/postStory.js +0 -122
  53. package/src/refreshFb_dtsg.js +0 -81
package/src/listenMqtt.js CHANGED
@@ -8,8 +8,9 @@ const WebSocket = require('ws');
8
8
  const HttpsProxyAgent = require('https-proxy-agent');
9
9
  const EventEmitter = require('events');
10
10
  const Duplexify = require('duplexify');
11
- const { Transform } = require('stream');
12
-
11
+ const {
12
+ Transform
13
+ } = require('stream');
13
14
  var identity = function() {};
14
15
  var form = {};
15
16
  var getSeqID = function() {};
@@ -19,326 +20,396 @@ global.Fca.Data.event = new Map();
19
20
  const 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'];
20
21
 
21
22
  let WebSocket_Global;
22
- let mqttReconnectCount = 0;
23
- const maxReconnectAttempts = 5;
24
- const reconnectBackoff = 2000;
25
23
 
26
24
  function buildProxy() {
27
- const Proxy = new Transform({
28
- objectMode: false,
29
- transform(chunk, enc, next) {
30
- if (WebSocket_Global.readyState !== WebSocket_Global.OPEN) {
31
- return next();
32
- }
25
+ const Proxy = new Transform({
26
+ objectMode: false,
27
+ transform(chunk, enc, next) {
28
+ if (WebSocket_Global.readyState !== WebSocket_Global.OPEN) {
29
+ return next();
30
+ }
33
31
 
34
- let data;
35
- if (typeof chunk === 'string') {
36
- data = Buffer.from(chunk, 'utf8');
37
- } else {
38
- data = chunk;
39
- }
32
+ let data;
33
+ if (typeof chunk === 'string') {
34
+ data = Buffer.from(chunk, 'utf8');
35
+ } else {
36
+ data = chunk;
37
+ }
40
38
 
41
- WebSocket_Global.send(data);
42
- next();
43
- },
44
- flush(done) {
45
- WebSocket_Global.close();
46
- done();
47
- },
48
- writev(chunks, cb) {
49
- const buffers = chunks.map(({ chunk }) => {
50
- if (typeof chunk === 'string') {
51
- return Buffer.from(chunk, 'utf8');
52
- }
53
- return chunk;
54
- });
55
- this._write(Buffer.concat(buffers), 'binary', cb);
56
- },
57
- });
58
- return Proxy;
39
+ WebSocket_Global.send(data);
40
+ next();
41
+ },
42
+ flush(done) {
43
+ WebSocket_Global.close();
44
+ done();
45
+ },
46
+ writev(chunks, cb) {
47
+ const buffers = chunks.map(({ chunk }) => {
48
+ if (typeof chunk === 'string') {
49
+ return Buffer.from(chunk, 'utf8');
50
+ }
51
+ return chunk;
52
+ });
53
+ this._write(Buffer.concat(buffers), 'binary', cb);
54
+ },
55
+ });
56
+ return Proxy;
59
57
  }
60
58
 
61
59
  function buildStream(options, WebSocket, Proxy) {
62
- const Stream = Duplexify(undefined, undefined, options);
63
- Stream.socket = WebSocket;
60
+ const Stream = Duplexify(undefined, undefined, options);
61
+ Stream.socket = WebSocket;
64
62
 
65
- let pingInterval;
66
- let reconnectTimeout;
63
+ WebSocket.onclose = () => {
64
+ Stream.end();
65
+ Stream.destroy();
66
+ };
67
67
 
68
- const clearTimers = () => {
69
- clearInterval(pingInterval);
70
- clearTimeout(reconnectTimeout);
71
- };
68
+ WebSocket.onerror = (err) => {
69
+ Stream.destroy(err);
70
+ };
72
71
 
73
- WebSocket.onclose = () => {
74
- clearTimers();
75
- Stream.end();
76
- Stream.destroy();
77
- };
72
+ WebSocket.onmessage = (event) => {
73
+ const data = event.data instanceof ArrayBuffer ? Buffer.from(event.data) : Buffer.from(event.data, 'utf8');
74
+ Stream.push(data);
75
+ };
78
76
 
79
- WebSocket.onerror = (err) => {
80
- clearTimers();
81
- Stream.destroy(err);
82
- };
77
+ WebSocket.onopen = () => {
78
+ Stream.setReadable(Proxy);
79
+ Stream.setWritable(Proxy);
80
+ Stream.emit('connect');
81
+ };
83
82
 
84
- WebSocket.onmessage = (event) => {
85
- clearTimeout(reconnectTimeout);
86
- const data = event.data instanceof ArrayBuffer ? Buffer.from(event.data) : Buffer.from(event.data, 'utf8');
87
- Stream.push(data);
88
- };
83
+ WebSocket_Global = WebSocket;
84
+ Proxy.on('close', () => WebSocket.close());
89
85
 
90
- WebSocket.onopen = () => {
91
- Stream.setReadable(Proxy);
92
- Stream.setWritable(Proxy);
93
- Stream.emit('connect');
86
+ return Stream;
87
+ }
94
88
 
95
- // Ping mỗi 30s để giữ kết nối
96
- pingInterval = setInterval(() => {
97
- if (WebSocket.readyState === WebSocket.OPEN) {
98
- WebSocket.ping();
99
- }
100
- }, 30000);
101
-
102
- // Timeout 60s nếu không nhận được response
103
- reconnectTimeout = setTimeout(() => {
104
- if (WebSocket.readyState === WebSocket.OPEN) {
105
- WebSocket.close();
106
- Stream.end();
107
- Stream.destroy();
108
- }
109
- }, 60000);
110
- };
89
+ function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
90
+ const chatOn = ctx.globalOptions.online;
91
+ const foreground = false;
92
+
93
+ const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
94
+ const GUID = utils.getGUID()
95
+ const username = {
96
+ u: ctx.userID,
97
+ s: sessionID,
98
+ chat_on: chatOn,
99
+ fg: foreground,
100
+ d: GUID,
101
+ ct: 'websocket',
102
+ aid: '219994525426954',
103
+ aids: null,
104
+ mqtt_sid: '',
105
+ cp: 3,
106
+ ecp: 10,
107
+ st: [],
108
+ pm: [],
109
+ dc: '',
110
+ no_auto_fg: true,
111
+ gas: null,
112
+ pack: [],
113
+ p: null,
114
+ php_override: ""
115
+ };
111
116
 
112
- WebSocket_Global = WebSocket;
113
- Proxy.on('close', () => {
114
- clearTimers();
115
- WebSocket.close();
116
- });
117
+ const cookies = ctx.jar.getCookies('https://www.facebook.com').join('; ');
117
118
 
118
- return Stream;
119
- }
120
- function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
121
- const chatOn = ctx.globalOptions.online;
122
- const foreground = false;
123
-
124
- const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
125
- const GUID = utils.getGUID()
126
- const username = {
127
- u: ctx.userID,
128
- s: sessionID,
129
- chat_on: chatOn,
130
- fg: foreground,
131
- d: GUID,
132
- ct: 'websocket',
133
- aid: '219994525426954',
134
- aids: null,
135
- mqtt_sid: '',
136
- cp: 3,
137
- ecp: 10,
138
- st: [],
139
- pm: [],
140
- dc: '',
141
- no_auto_fg: true,
142
- gas: null,
143
- pack: [],
144
- p: null,
145
- php_override: ""
146
- };
119
+ let host;
120
+ if (ctx.mqttEndpoint) {
121
+ host = `${ctx.mqttEndpoint}&sid=${sessionID}&cid=${GUID}`;
122
+ } else if (ctx.region) {
123
+ host = `wss://edge-chat.facebook.com/chat?region=${ctx.region.toLowerCase()}&sid=${sessionID}&cid=${GUID}`;
124
+ } else {
125
+ host = `wss://edge-chat.facebook.com/chat?sid=${sessionID}&cid=${GUID}`;
126
+ }
127
+
128
+ const options = {
129
+ clientId: 'mqttwsclient',
130
+ protocolId: 'MQIsdp',
131
+ protocolVersion: 3,
132
+ username: JSON.stringify(username),
133
+ clean: true,
134
+ wsOptions: {
135
+ headers: {
136
+ Cookie: cookies,
137
+ Origin: 'https://www.facebook.com',
138
+ 'User-Agent': ctx.globalOptions.userAgent,
139
+ Referer: 'https://www.facebook.com/',
140
+ Host: new URL(host).hostname,
141
+ },
142
+ origin: 'https://www.facebook.com',
143
+ protocolVersion: 13,
144
+ binaryType: 'arraybuffer',
145
+ },
146
+ keepalive: 60,
147
+ reschedulePings: true,
148
+ reconnectPeriod: 3,
149
+ };
150
+
151
+ if (ctx.globalOptions.proxy !== undefined) {
152
+ const agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
153
+ options.wsOptions.agent = agent;
154
+ }
147
155
 
148
- const cookies = ctx.jar.getCookies('https://www.facebook.com').join('; ');
156
+ ctx.mqttClient = new mqtt.Client(() => buildStream(options, new WebSocket(host, options.wsOptions), buildProxy()), options);
157
+ global.mqttClient = ctx.mqttClient;
149
158
 
150
- let host;
151
- if (ctx.mqttEndpoint) {
152
- host = `${ctx.mqttEndpoint}&sid=${sessionID}&cid=${GUID}`;
153
- } else if (ctx.region) {
154
- host = `wss://edge-chat.facebook.com/chat?region=${ctx.region.toLowerCase()}&sid=${sessionID}&cid=${GUID}`;
159
+ global.mqttClient.on('error', (err) => {
160
+ log.error('listenMqtt', err);
161
+ global.mqttClient.end();
162
+
163
+ if (ctx.globalOptions.autoReconnect) {
164
+ getSeqID();
155
165
  } else {
156
- host = `wss://edge-chat.facebook.com/chat?sid=${sessionID}&cid=${GUID}`;
166
+ globalCallback({
167
+ type: 'stop_listen',
168
+ error: 'Server Đã Sập - Auto Restart'
169
+ }, null);
170
+ return process.exit(1);
171
+ }
172
+ });
173
+
174
+ global.mqttClient.on('connect', () => {
175
+ if (!global.Fca.Data.Setup || global.Fca.Data.Setup === undefined) {
176
+ if (global.Fca.Require.Shankar.RestartMQTT_Minutes !== 0 && global.Fca.Data.StopListening !== true) {
177
+ global.Fca.Data.Setup = true;
178
+ setTimeout(() => {
179
+ global.Fca.Require.logger.Warning('Closing MQTT Client...');
180
+ ctx.mqttClient.end();
181
+ global.Fca.Require.logger.Warning('Reconnecting MQTT Client...');
182
+ global.Fca.Data.Setup = false;
183
+ getSeqID();
184
+ }, Number(global.Fca.Require.Shankar.RestartMQTT_Minutes) * 60 * 1000);
185
+ }
157
186
  }
158
187
 
159
- const options = {
160
- clientId: 'mqttwsclient',
161
- protocolId: 'MQIsdp',
162
- protocolVersion: 3,
163
- username: JSON.stringify(username),
164
- clean: true,
165
- wsOptions: {
166
- headers: {
167
- Cookie: cookies,
168
- Origin: 'https://www.facebook.com',
169
- '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',
170
- Referer: 'https://www.facebook.com/',
171
- Host: new URL(host).hostname,
172
- },
173
- origin: 'https://www.facebook.com',
174
- protocolVersion: 13,
175
- binaryType: 'arraybuffer',
176
- },
177
- keepalive: 60,
178
- reschedulePings: true,
179
- reconnectPeriod: 2000,
180
- connectTimeout: 10000,
181
- };
188
+ if (process.env.OnStatus === undefined) {
189
+ global.Fca.Require.logger.Normal('Bạn Đang Sài Phiên Bản: Premium Access');
190
+
191
+ if (Number(global.Fca.Require.Shankar.AutoRestartMinutes) === 0) {
192
+ // something
193
+ } else if (Number(global.Fca.Require.Shankar.AutoRestartMinutes) < 10) {
194
+ log.warn('AutoRestartMinutes', 'The number of minutes to automatically restart must be more than 10 minutes');
195
+ } else if (Number(global.Fca.Require.Shankar.AutoRestartMinutes) < 0) {
196
+ log.warn('AutoRestartMinutes', 'Invalid auto-restart minutes!');
197
+ } else {
198
+ global.Fca.Require.logger.Normal(global.Fca.getText(global.Fca.Require.Language.Src.AutoRestart, global.Fca.Require.Shankar.AutoRestartMinutes));
199
+ global.Fca.Require.logger.Normal(`Auto Restart MQTT Client After: ${global.Fca.Require.Shankar.RestartMQTT_Minutes} Minutes`);
200
+ setTimeout(() => {
201
+ global.Fca.Require.logger.Normal(global.Fca.Require.Language.Src.OnRestart);
202
+ process.exit(1);
203
+ }, Number(global.Fca.Require.Shankar.AutoRestartMinutes) * 60000);
204
+ }
205
+ require('../broadcast').startBroadcasting();
206
+ const MemoryManager = require('../Extra/Src/Release_Memory');
207
+ const path = require('path');
208
+
209
+ const SettingMemoryManager = {
210
+ warningThreshold: 0.7,
211
+ releaseThreshold: 0.8,
212
+ maxThreshold: 0.9,
213
+ interval: 300 * 1000,
214
+ logLevel: 'warn',
215
+ logFile: path.join(process.cwd(), 'Shankar_Database' ,'memory.log'),
216
+ smartReleaseEnabled: true,
217
+ allowLog: (global.Fca.Require.Shankar.AntiStuckAndMemoryLeak.LogFile.Use || false)
218
+ };
219
+
220
+ const memoryManager = new MemoryManager(SettingMemoryManager);
221
+
222
+ memoryManager.autoStart(60 * 60 * 1000);
182
223
 
183
- if (ctx.globalOptions.proxy !== undefined) {
184
- const agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
185
- options.wsOptions.agent = agent;
224
+ if (global.Fca.Require.Shankar.AntiStuckAndMemoryLeak.AutoRestart.Use) {
225
+ memoryManager.onMaxMemory(function() {
226
+ global.Fca.Require.logger.Warning('Memory Usage >= 90% - Auto Restart Avoid Crash');
227
+ process.exit(1);
228
+ });
229
+ }
230
+ process.env.OnStatus = true;
186
231
  }
187
232
 
188
- ctx.mqttClient = new mqtt.Client(() => buildStream(options, new WebSocket(host, options.wsOptions), buildProxy()), options);
189
- global.mqttClient = ctx.mqttClient;
233
+ topics.forEach((topicsub) => global.mqttClient.subscribe(topicsub));
190
234
 
191
- global.mqttClient.on('error', (err) => {
192
- log.error('listenMqtt', err);
193
- global.mqttClient.end();
194
-
195
- if (mqttReconnectCount < maxReconnectAttempts) {
196
- mqttReconnectCount++;
197
- const backoffTime = reconnectBackoff * Math.pow(2, mqttReconnectCount - 1);
198
- setTimeout(() => {
199
- if (ctx.globalOptions.autoReconnect) {
200
- getSeqID();
201
- }
202
- }, backoffTime);
203
- } else {
204
- globalCallback({
205
- type: 'stop_listen',
206
- error: 'Server Đã Sập - Auto Restart'
207
- }, null);
208
- return process.exit(1);
209
- }
235
+
236
+ let topic;
237
+ const queue = {
238
+ sync_api_version: 11,
239
+ max_deltas_able_to_process: 100,
240
+ delta_batch_size: 500,
241
+ encoding: 'JSON',
242
+ entity_fbid: ctx.userID,
243
+ };
244
+
245
+ topic = "/messenger_sync_create_queue";
246
+ queue.initial_titan_sequence_id = ctx.lastSeqId;
247
+ queue.device_params = null;
248
+
249
+ global.mqttClient.publish(topic, JSON.stringify(queue), {
250
+ qos: 1,
251
+ retain: false
210
252
  });
211
253
 
212
- global.mqttClient.on('connect', () => {
213
- mqttReconnectCount = 0;
214
-
215
- if (!global.Fca.Data.Setup || global.Fca.Data.Setup === undefined) {
216
- if (global.Fca.Require.ShankarConfig.RestartMQTT_Minutes !== 0 && global.Fca.Data.StopListening !== true) {
217
- global.Fca.Data.Setup = true;
218
- setTimeout(() => {
219
- global.Fca.Require.logger.Warning('Closing MQTT Client...');
220
- ctx.mqttClient.end();
221
- global.Fca.Require.logger.Warning('Reconnecting MQTT Client...');
222
- global.Fca.Data.Setup = false;
223
- getSeqID();
224
- }, Number(global.Fca.Require.ShankarConfig.RestartMQTT_Minutes) * 60 * 1000);
225
- }
226
- }
254
+ var rTimeout = setTimeout(function() {
255
+ global.mqttClient.end();
256
+ getSeqID();
257
+ }, 3000);
258
+
259
+ ctx.tmsWait = function() {
260
+ clearTimeout(rTimeout);
261
+ ctx.globalOptions.emitReady ? globalCallback({
262
+ type: "ready",
263
+ error: null
264
+ }) : '';
265
+ delete ctx.tmsWait;
266
+ };
267
+ });
227
268
 
228
- if (process.env.OnStatus === undefined) {
229
- global.Fca.Require.logger.Normal('Horizon Prime');
230
-
231
- const MemoryManager = require('../Extra/Src/Release_Memory');
232
- const path = require('path');
233
-
234
- const SettingMemoryManager = {
235
- warningThreshold: 0.7,
236
- releaseThreshold: 0.8,
237
- maxThreshold: 0.9,
238
- interval: 60 * 1000,
239
- logLevel: 'warn',
240
- logFile: path.join(process.cwd(), 'Shankar_Database', 'memory.log'),
241
- smartReleaseEnabled: true,
242
- allowLog: (global.Fca.Require.ShankarConfig.AntiStuckAndMemoryLeak.LogFile.Use || false)
243
- };
269
+ const HandleMessage = function(topic, message, _packet) {
270
+ const jsonMessage = JSON.parse(message.toString());
271
+ if (topic === "/t_ms") {
272
+ if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
244
273
 
245
- const memoryManager = new MemoryManager(SettingMemoryManager);
246
- memoryManager.autoStart(60 * 60 * 1000);
274
+ if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
275
+ ctx.lastSeqId = jsonMessage.firstDeltaSeqId;
276
+ ctx.syncToken = jsonMessage.syncToken;
277
+ }
247
278
 
248
- if (global.Fca.Require.ShankarConfig.AntiStuckAndMemoryLeak.AutoRestart.Use) {
249
- memoryManager.onMaxMemory(function() {
250
- global.Fca.Require.logger.Warning('Memory Usage >= 90% - Auto Restart Avoid Crash');
251
- process.exit(1);
252
- });
253
- }
254
- process.env.OnStatus = true;
279
+ if (jsonMessage.lastIssuedSeqId) ctx.lastSeqId = parseInt(jsonMessage.lastIssuedSeqId);
280
+ //If it contains more than 1 delta
281
+ for (var i in jsonMessage.deltas) {
282
+ var delta = jsonMessage.deltas[i];
283
+ parseDelta(defaultFuncs, api, ctx, globalCallback, {
284
+ "delta": delta
285
+ });
286
+ }
287
+ } else if (topic === "/ls_resp") {
288
+ const payload = JSON.parse(jsonMessage.payload); //'{"name":null,"step":[1,[1,[4,0,1,[5,"taskExists",[19,"415"]]],[23,[2,0],[1,[5,"replaceOptimsiticMessage","7192532113093667880","mid.$gABfX5li9LA6VdUymnWPRAdlkiawo"]]]],[1,[4,0,1,[5,"taskExists",[19,"415"]]],[23,[2,0],[1,[5,"mailboxTaskCompletionApiOnTaskCompletion",[19,"415"],true]]]],[1,[4,0,1,[5,"taskExists",[19,"415"]]],[23,[2,0],[1,[5,"removeTask",[19,"415"],[9]]]]]]}'
289
+ const request_ID = jsonMessage.request_id;
290
+
291
+ if (ctx.callback_Task[request_ID] != undefined && ctx.callback_Task[request_ID].type != undefined) {
292
+ const {
293
+ callback,
294
+ type
295
+ } = ctx.callback_Task[request_ID];
296
+ const Data = new getRespData(type, payload);
297
+ if (!callback) {
298
+ return;
299
+ }
300
+ else if (!Data) {
301
+ callback("Something went wrong 🐳", null);
302
+ } else {
303
+ callback(null, Data);
304
+ }
305
+ }
306
+ } else if (topic === "/thread_typing" || topic === "/orca_typing_notifications") {
307
+ var typ = {
308
+ type: "typ",
309
+ isTyping: !!jsonMessage.state,
310
+ from: jsonMessage.sender_fbid.toString(),
311
+ threadID: utils.formatID((jsonMessage.thread || jsonMessage.sender_fbid).toString())
312
+ };
313
+ (function() {
314
+ globalCallback(null, typ);
315
+ })();
316
+ } else if (topic === "/orca_presence") {
317
+ if (!ctx.globalOptions.updatePresence) {
318
+ for (var i in jsonMessage.list) {
319
+ var data = jsonMessage.list[i];
320
+ var userID = data["u"];
321
+
322
+ var presence = {
323
+ type: "presence",
324
+ userID: userID.toString(),
325
+ //Convert to ms
326
+ timestamp: data["l"] * 1000,
327
+ statuses: data["p"]
328
+ };
329
+ (function() {
330
+ globalCallback(null, presence);
331
+ })();
255
332
  }
333
+ }
334
+ }
256
335
 
257
- topics.forEach((topicsub) => global.mqttClient.subscribe(topicsub));
336
+ };
258
337
 
259
- const queue = {
260
- sync_api_version: 11,
261
- max_deltas_able_to_process: 100,
262
- delta_batch_size: 500,
263
- encoding: 'JSON',
264
- entity_fbid: ctx.userID,
265
- initial_titan_sequence_id: ctx.lastSeqId,
266
- device_params: null
267
- };
338
+ global.mqttClient.on('message', HandleMessage);
268
339
 
269
- global.mqttClient.publish("/messenger_sync_create_queue", JSON.stringify(queue), {
270
- qos: 1,
271
- retain: false
272
- });
340
+ process.on('SIGINT', () => {
341
+ LogUptime();
342
+ process.kill(process.pid);
343
+ });
273
344
 
274
- var rTimeout = setTimeout(function() {
275
- global.mqttClient.end();
276
- getSeqID();
277
- }, 3000);
278
-
279
- ctx.tmsWait = function() {
280
- clearTimeout(rTimeout);
281
- ctx.globalOptions.emitReady ? globalCallback({
282
- type: "ready",
283
- error: null
284
- }) : '';
285
- delete ctx.tmsWait;
345
+ process.on('exit', LogUptime);
346
+
347
+
348
+ }
349
+
350
+ function getRespData(Type, payload) {
351
+ try {
352
+ switch (Type) {
353
+ case "sendMqttMessage": {
354
+ return {
355
+ type: Type,
356
+ threadID: payload.step[1][2][2][1][2], //this is sick bro
357
+ messageID: payload.step[1][2][2][1][3],
358
+ payload: payload.step[1][2]
286
359
  };
287
- });
360
+ }
361
+ default: { //!very LAZY :> cook yourself
362
+ return {
363
+ Data: payload.step[1][2][2][1],
364
+ type: Type,
365
+ payload: payload.step[1][2]
366
+ };
367
+ }
368
+ }
369
+ } catch (e) {
370
+ return null;
371
+ }
372
+ }
288
373
 
289
- global.mqttClient.on('message', (topic, message, _packet) => {
290
- const jsonMessage = JSON.parse(message.toString());
291
- if (topic === "/t_ms") {
292
- if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
374
+ function LogUptime() {
375
+ const uptime = process.uptime();
376
+ const {
377
+ join
378
+ } = require('path');
379
+ const filePath = join(__dirname, '../CountTime.json');
293
380
 
294
- if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
295
- ctx.lastSeqId = jsonMessage.firstDeltaSeqId;
296
- ctx.syncToken = jsonMessage.syncToken;
297
- }
381
+ let time1;
382
+ if (global.Fca.Require.fs.existsSync(filePath)) {
383
+ time1 = Number(global.Fca.Require.fs.readFileSync(filePath, 'utf8')) || 0;
384
+ } else {
385
+ time1 = 0;
386
+ }
298
387
 
299
- if (jsonMessage.lastIssuedSeqId) ctx.lastSeqId = parseInt(jsonMessage.lastIssuedSeqId);
388
+ global.Fca.Require.fs.writeFileSync(filePath, String(Number(uptime) + time1), 'utf8');
389
+ }
300
390
 
301
- for (var i in jsonMessage.deltas) {
302
- var delta = jsonMessage.deltas[i];
303
- parseDelta(defaultFuncs, api, ctx, globalCallback, {
304
- delta: delta
305
- });
306
- }
307
- } else if (topic === '/thread_typing' || topic === '/orca_typing_notifications') {
308
- var typ = {
309
- type: "typ",
310
- isTyping: !!jsonMessage.state,
311
- from: jsonMessage.sender_fbid.toString(),
312
- threadID: utils.formatID((jsonMessage.thread || jsonMessage.sender_fbid).toString())
313
- };
314
- (function() {
315
- globalCallback(null, typ);
316
- })();
317
- } else if (topic === '/orca_presence' && !ctx.globalOptions.updatePresence) {
318
- for (var i in jsonMessage.list) {
319
- var data = jsonMessage.list[i];
320
- var userID = data["u"];
321
-
322
- var presence = {
323
- type: "presence",
324
- userID: userID.toString(),
325
- timestamp: data["l"] * 1000,
326
- statuses: data["p"]
327
- };
328
- (function() {
329
- globalCallback(null, presence);
330
- })();
391
+ if (global.Fca.Require.Shankar.AntiGetInfo.AntiGetThreadInfo) {
392
+ setInterval(() => {
393
+ try {
394
+ const { updateMessageCount, getData, hasData } = require('../Extra/ExtraGetThread');
395
+ const Data = global.Fca.Data.MsgCount;
396
+ const Arr = Array.from(Data.keys());
397
+ for (let i of Arr) {
398
+ const Count = parseInt(Data.get(i));
399
+ if (hasData(i)) {
400
+ let x = getData(i);
401
+ x.messageCount += Count;
402
+ updateMessageCount(i, x);
403
+ Data.delete(i);
404
+ }
331
405
  }
406
+
407
+ } catch (e) {
408
+ console.log(e);
332
409
  }
333
- });
334
-
335
- process.on('SIGINT', () => {
336
- LogUptime();
337
- process.kill(process.pid);
338
- });
339
-
340
- process.on('exit', LogUptime);
410
+ }, 30 * 1000);
341
411
  }
412
+
342
413
  function parseDelta(defaultFuncs, api, ctx, globalCallback, {
343
414
  delta
344
415
  }) {
@@ -365,7 +436,7 @@ function parseDelta(defaultFuncs, api, ctx, globalCallback, {
365
436
  messageID
366
437
  });
367
438
 
368
- if (global.Fca.Require.ShankarConfig.AntiGetInfo.AntiGetThreadInfo) {
439
+ if (global.Fca.Require.Shankar.AntiGetInfo.AntiGetThreadInfo) {
369
440
  global.Fca.Data.MsgCount.set(fmtMsg.threadID, ((global.Fca.Data.MsgCount.get(fmtMsg.threadID)) + 1 || 1));
370
441
  }
371
442
 
@@ -487,22 +558,27 @@ function parseDelta(defaultFuncs, api, ctx, globalCallback, {
487
558
  messageID: delta.deltaMessageReply.repliedToMessage.messageMetadata.messageId,
488
559
  senderID: delta.deltaMessageReply.repliedToMessage.messageMetadata.actorFbId.toString(),
489
560
  attachments: delta.deltaMessageReply.repliedToMessage.attachments
490
- .map((att) => {
491
- const mercury = JSON.parse(att.mercuryJSON);
561
+ .map((att) => {
562
+ let mercury;
563
+ try {
564
+ mercury = JSON.parse(att.mercuryJSON);
492
565
  Object.assign(att, mercury);
493
- return att;
494
- })
495
- .map((att) => {
496
- let x;
497
- try {
498
- x = utils._formatAttachment(att);
499
- } catch (ex) {
500
- x = att;
501
- x.error = ex;
502
- x.type = 'unknown';
503
- }
504
- return x;
505
- }),
566
+ } catch (ex) {
567
+ mercury = {};
568
+ }
569
+ return att;
570
+ })
571
+ .map((att) => {
572
+ let x;
573
+ try {
574
+ x = utils._formatAttachment(att);
575
+ } catch (ex) {
576
+ x = att;
577
+ x.error = ex;
578
+ x.type = 'unknown';
579
+ }
580
+ return x;
581
+ }),
506
582
  args: (delta.deltaMessageReply.repliedToMessage.body || '').trim().split(/\s+/),
507
583
  body: delta.deltaMessageReply.repliedToMessage.body || '',
508
584
  isGroup: !!delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId,
@@ -693,7 +769,7 @@ function parseDelta(defaultFuncs, api, ctx, globalCallback, {
693
769
  duration: (fetchData.extensible_attachment.story_attachment.media || {}).playable_duration_in_ms || 0,
694
770
  subattachments: fetchData.extensible_attachment.subattachments,
695
771
  properties: fetchData.extensible_attachment.story_attachment.properties,
696
- }],
772
+ }],
697
773
  mentions: {},
698
774
  timestamp: parseInt(fetchData.timestamp_precise),
699
775
  isGroup: (fetchData.message_sender.id !== tid.toString()),
@@ -768,81 +844,32 @@ function markDelivery(ctx, api, threadID, messageID) {
768
844
  }
769
845
  }
770
846
 
771
- function getRespData(Type, payload) {
772
- try {
773
- switch (Type) {
774
- case "sendMqttMessage": {
775
- return {
776
- type: Type,
777
- threadID: payload.step[1][2][2][1][2],
778
- messageID: payload.step[1][2][2][1][3],
779
- payload: payload.step[1][2]
780
- };
781
- }
782
- default: {
783
- return {
784
- Data: payload.step[1][2][2][1],
785
- type: Type,
786
- payload: payload.step[1][2]
787
- };
788
- }
789
- }
790
- } catch (e) {
791
- return null;
792
- }
793
- }
794
-
795
- function LogUptime() {
796
- const uptime = process.uptime();
797
- const { join } = require('path');
798
- const filePath = join(__dirname, '../CountTime.json');
799
-
800
- let time1;
801
- if (global.Fca.Require.fs.existsSync(filePath)) {
802
- time1 = Number(global.Fca.Require.fs.readFileSync(filePath, 'utf8')) || 0;
803
- } else {
804
- time1 = 0;
805
- }
806
847
 
807
- global.Fca.Require.fs.writeFileSync(filePath, String(Number(uptime) + time1), 'utf8');
808
- }
809
-
810
- if (global.Fca.Require.ShankarConfig.AntiGetInfo.AntiGetThreadInfo) {
811
- setInterval(() => {
812
- try {
813
- const { updateMessageCount, getData, hasData } = require('../Extra/ExtraGetThread');
814
- const Data = global.Fca.Data.MsgCount;
815
- const Arr = Array.from(Data.keys());
816
- for (let i of Arr) {
817
- const Count = parseInt(Data.get(i));
818
- if (hasData(i)) {
819
- let x = getData(i);
820
- x.messageCount += Count;
821
- updateMessageCount(i, x);
822
- Data.delete(i);
823
- }
824
- }
825
- } catch (e) {
826
- console.log(e);
827
- }
828
- }, 30 * 1000);
829
- }
830
848
 
831
849
  module.exports = function(defaultFuncs, api, ctx) {
832
850
  var globalCallback = identity;
833
-
834
- getSeqID = function() {
851
+ var okeoke;
852
+ getSeqID = function getSeqID() {
835
853
  ctx.t_mqttCalled = false;
836
854
  defaultFuncs
837
855
  .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
856
+ .then(res => {
857
+ okeoke = res;
858
+ return res;
859
+ })
838
860
  .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
839
861
  .then((resData) => {
840
862
  if (utils.getType(resData) != "Array") {
841
- if (global.Fca.Require.ShankarConfig.AutoLogin) {
863
+ if (okeoke.request.uri && okeoke.request.uri.href.includes("https://www.facebook.com/checkpoint/")) {
864
+ if (okeoke.request.uri.href.includes('601051028565049')) {
865
+ return global.Fca.BypassAutomationNotification(undefined, ctx.jar, ctx.globalOptions, undefined ,process.env.UID)
866
+ }
867
+ }
868
+ if (global.Fca.Require.Shankar.AutoLogin) {
842
869
  return global.Fca.Require.logger.Warning(global.Fca.Require.Language.Index.AutoLogin, function() {
843
870
  return global.Fca.Action('AutoLogin');
844
871
  });
845
- } else if (!global.Fca.Require.ShankarConfig.AutoLogin) {
872
+ } else if (!global.Fca.Require.Shankar.AutoLogin) {
846
873
  return global.Fca.Require.logger.Error(global.Fca.Require.Language.Index.ErrAppState);
847
874
  }
848
875
  return;
@@ -863,7 +890,12 @@ module.exports = function(defaultFuncs, api, ctx) {
863
890
  })
864
891
  .catch((err) => {
865
892
  log.error("getSeqId", err);
866
- if (utils.getType(err) == "Object" && err.error === "getSeqId: no sync_sequence_id found.") ctx.loggedIn = false;
893
+ if (okeoke.request.uri && okeoke.request.uri.href.includes("https://www.facebook.com/checkpoint/")) {
894
+ if (okeoke.request.uri.href.includes('601051028565049')) {
895
+ return global.Fca.BypassAutomationNotification(undefined, ctx.jar, ctx.globalOptions, undefined ,process.env.UID)
896
+ }
897
+ }
898
+ if (utils.getType(err) == "Object" && err.error === global.Fca.Require.Language.Index.ErrAppState) ctx.loggedIn = false;
867
899
  return globalCallback(err);
868
900
  });
869
901
  };
@@ -880,7 +912,6 @@ module.exports = function(defaultFuncs, api, ctx) {
880
912
  ctx.mqttClient.publish("/browser_close", "{}");
881
913
  ctx.mqttClient.end(false, function(...data) {
882
914
  ctx.mqttClient = undefined;
883
- callback(data);
884
915
  });
885
916
  }
886
917
  global.Fca.Data.StopListening = true;
@@ -910,11 +941,12 @@ module.exports = function(defaultFuncs, api, ctx) {
910
941
  tags: ['INBOX'],
911
942
  includeDeliveryReceipts: false,
912
943
  includeSeqID: true,
913
- }
914
- }
915
- })
944
+ },
945
+ },
946
+ }),
916
947
  };
917
948
 
949
+
918
950
  if (!ctx.firstListen || !ctx.lastSeqId) getSeqID();
919
951
  else listenMqtt(defaultFuncs, api, ctx, globalCallback);
920
952
  ctx.firstListen = false;
@@ -922,13 +954,3 @@ module.exports = function(defaultFuncs, api, ctx) {
922
954
  return msgEmitter;
923
955
  };
924
956
  };
925
-
926
- process.on('SIGINT', () => {
927
- if (global.mqttClient) {
928
- global.mqttClient.end();
929
- }
930
- LogUptime();
931
- process.exit();
932
- });
933
-
934
- process.on('exit', LogUptime);