fb-chatify 1.5.7

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 (101) hide show
  1. package/.gitattributes +2 -0
  2. package/.github/workflows/publish.yml +20 -0
  3. package/Extra/Database/index.js +360 -0
  4. package/Extra/ExtraAddons.js +78 -0
  5. package/Extra/ExtraFindUID.js +60 -0
  6. package/Extra/ExtraGetThread.js +118 -0
  7. package/Extra/ExtraScreenShot.js +430 -0
  8. package/Extra/ExtraUptimeRobot.js +26 -0
  9. package/Extra/Html/Classic/script.js +119 -0
  10. package/Extra/Html/Classic/style.css +8 -0
  11. package/Extra/Security/Index.js +146 -0
  12. package/Extra/Security/Step_1.js +11 -0
  13. package/Extra/Security/Step_2.js +20 -0
  14. package/Extra/Security/Step_3.js +20 -0
  15. package/Extra/Src/History.js +115 -0
  16. package/Extra/Src/Last-Run.js +65 -0
  17. package/Extra/Src/Premium.js +84 -0
  18. package/Extra/Src/uuid.js +137 -0
  19. package/Func/AcceptAgreement.js +32 -0
  20. package/Func/ClearCache.js +64 -0
  21. package/Func/ReportV1.js +54 -0
  22. package/LICENSE +24 -0
  23. package/Language/index.json +177 -0
  24. package/README.md +1 -0
  25. package/SECURITY.md +20 -0
  26. package/broadcast.js +38 -0
  27. package/gitattributes +2 -0
  28. package/gitignore.txt +10 -0
  29. package/index.js +1371 -0
  30. package/logger.js +66 -0
  31. package/package.json +92 -0
  32. package/src/Dev_Horizon_Data.js +125 -0
  33. package/src/Premium.js +30 -0
  34. package/src/Screenshot.js +85 -0
  35. package/src/addExternalModule.js +16 -0
  36. package/src/addUserToGroup.js +79 -0
  37. package/src/changeAdminStatus.js +79 -0
  38. package/src/changeArchivedStatus.js +41 -0
  39. package/src/changeAvt.js +85 -0
  40. package/src/changeBio.js +65 -0
  41. package/src/changeBlockedStatus.js +36 -0
  42. package/src/changeGroupImage.js +106 -0
  43. package/src/changeNickname.js +45 -0
  44. package/src/changeThreadColor.js +62 -0
  45. package/src/changeThreadEmoji.js +42 -0
  46. package/src/createNewGroup.js +70 -0
  47. package/src/createPoll.js +60 -0
  48. package/src/deleteMessage.js +45 -0
  49. package/src/deleteThread.js +43 -0
  50. package/src/forwardAttachment.js +48 -0
  51. package/src/getAccessToken.js +32 -0
  52. package/src/getCurrentUserID.js +7 -0
  53. package/src/getEmojiUrl.js +27 -0
  54. package/src/getFriendsList.js +73 -0
  55. package/src/getMessage.js +80 -0
  56. package/src/getThreadHistory.js +537 -0
  57. package/src/getThreadInfo.js +348 -0
  58. package/src/getThreadList.js +213 -0
  59. package/src/getThreadMain.js +220 -0
  60. package/src/getThreadPictures.js +59 -0
  61. package/src/getUID.js +59 -0
  62. package/src/getUserID.js +62 -0
  63. package/src/getUserInfo.js +129 -0
  64. package/src/getUserInfoMain.js +65 -0
  65. package/src/getUserInfoV2.js +36 -0
  66. package/src/getUserInfoV3.js +63 -0
  67. package/src/getUserInfoV4.js +55 -0
  68. package/src/getUserInfoV5.js +61 -0
  69. package/src/handleFriendRequest.js +46 -0
  70. package/src/handleMessageRequest.js +49 -0
  71. package/src/httpGet.js +49 -0
  72. package/src/httpPost.js +48 -0
  73. package/src/httpPostFormData.js +41 -0
  74. package/src/listenMqtt.js +676 -0
  75. package/src/logout.js +68 -0
  76. package/src/markAsDelivered.js +48 -0
  77. package/src/markAsRead.js +70 -0
  78. package/src/markAsReadAll.js +43 -0
  79. package/src/markAsSeen.js +51 -0
  80. package/src/muteThread.js +47 -0
  81. package/src/removeUserFromGroup.js +49 -0
  82. package/src/resolvePhotoUrl.js +37 -0
  83. package/src/searchForThread.js +43 -0
  84. package/src/sendMessage.js +334 -0
  85. package/src/sendTypingIndicator.js +80 -0
  86. package/src/setMessageReaction.js +109 -0
  87. package/src/setPostReaction.js +102 -0
  88. package/src/setTitle.js +74 -0
  89. package/src/threadColors.js +39 -0
  90. package/src/unfriend.js +43 -0
  91. package/src/unsendMessage.js +40 -0
  92. package/test/data/shareAttach.js +146 -0
  93. package/test/data/something.mov +0 -0
  94. package/test/data/test.png +0 -0
  95. package/test/data/test.txt +7 -0
  96. package/test/env/.env +0 -0
  97. package/test/example-config.json +18 -0
  98. package/test/test-page.js +140 -0
  99. package/test/test.js +385 -0
  100. package/test/testv2.js +3 -0
  101. package/utils.js +1648 -0
package/index.js ADDED
@@ -0,0 +1,1371 @@
1
+ 'use strict';
2
+
3
+ // Unofficial Fb Chat Api By Ñaughty+Priyansh
4
+
5
+ /!-[ Global Set ]-!/
6
+
7
+ global.Fca = new Object({
8
+ isThread: new Array(),
9
+ isUser: new Array(),
10
+ startTime: Date.now(),
11
+ Setting: new Map(),
12
+ Version: require('./package.json').version,
13
+ Require: new Object({
14
+ fs: require("fs"),
15
+ Fetch: require('got'),
16
+ log: require("npmlog"),
17
+ utils: require("./utils"),
18
+ logger: require('./logger'),
19
+ languageFile: require('./Language/index.json'),
20
+ Database: require("./Extra/Database"),
21
+ Security: require('./Extra/Src/uuid')
22
+ }),
23
+ getText: function(/** @type {any[]} */...Data) {
24
+ var Main = (Data.splice(0,1)).toString();
25
+ for (let i = 0; i < Data.length; i++) Main = Main.replace(RegExp(`%${i + 1}`, 'g'), Data[i]);
26
+ return Main;
27
+ },
28
+ Data: new Object({
29
+ ObjFastConfig: {
30
+ "Language": "en",
31
+ "PreKey": "",
32
+ "AutoUpdate": false,
33
+ "MainColor": "#00FFFF",
34
+ "MainName": "[ FCA-ÑAUGHTY ]",
35
+ "Logo": true,
36
+ "Uptime": true,
37
+ "Config": "default",
38
+ "Login2Fa": false,
39
+ "AutoLogin": false,
40
+ "BroadCast": true,
41
+ "AuthString": "SD4S XQ32 O2JA WXB3 FUX2 OPJ7 Q7JZ 4R6Z | https://i.imgur.com/RAg3rvw.png Please remove this !, Recommend If You Using getUserInfoV2",
42
+ "EncryptFeature": false,
43
+ "ResetDataLogin": false,
44
+ "AutoRestartMinutes": 0,
45
+ "HTML": {
46
+ "HTML": true,
47
+ "UserName": "Guest",
48
+ "MusicLink": "https://drive.google.com/uc?id=1zlAALlxk1TnO7jXtEP_O6yvemtzA2ukA&export=download"
49
+ }
50
+ },
51
+ CountTime: function() {
52
+ var fs = global.Fca.Require.fs;
53
+ if (fs.existsSync(__dirname + '/CountTime.json')) {
54
+ try {
55
+ var data = Number(fs.readFileSync(__dirname + '/CountTime.json', 'utf8')),
56
+ hours = Math.floor(data / (60 * 60));
57
+ }
58
+ catch (e) {
59
+ fs.writeFileSync(__dirname + '/CountTime.json', 0);
60
+ hours = 0;
61
+ }
62
+ }
63
+ else {
64
+ hours = 0;
65
+ }
66
+ return `${hours} Hours`;
67
+ }
68
+ }),
69
+ AutoLogin: async function () {
70
+ var Database = global.Fca.Require.Database;
71
+ var logger = global.Fca.Require.logger;
72
+ var Email = (await global.Fca.Require.Database.get('Account')).replace(RegExp('"', 'g'), ''); //hmm IDK
73
+ var PassWord = (await global.Fca.Require.Database.get('Password')).replace(RegExp('"', 'g'), '');
74
+ login({ email: Email, password: PassWord},async (error, api) => {
75
+ if (error) {
76
+ logger.Error(JSON.stringify(error,null,2), function() { logger.Error("AutoLogin Failed!", function() { process.exit(0); }) });
77
+ }
78
+ try {
79
+ await Database.set("TempState", api.getAppState());
80
+ }
81
+ catch(e) {
82
+ logger.Warning(global.Fca.Require.Language.Index.ErrDatabase);
83
+ logger.Error();
84
+ process.exit(0);
85
+ }
86
+ process.exit(1);
87
+ });
88
+ }
89
+ });
90
+
91
+ /!-[ Check File To Run Process ]-!/
92
+ console.log(`┌────────────────────────────────────────────────────────────────────────────────┐
93
+ │ │
94
+ │ │
95
+ │ │
96
+ │ ███╗ ██╗ █████╗ ██╗ ██╗ ██████╗ ██╗ ██╗████████╗██╗ ██╗ │
97
+ │ ████╗ ██║██╔══██╗██║ ██║██╔════╝ ██║ ██║╚══██╔══╝╚██╗ ██╔╝ │
98
+ │ ██╔██╗ ██║███████║██║ ██║██║ ███╗███████║ ██║ ╚████╔╝ │
99
+ │ ██║╚██╗██║██╔══██║██║ ██║██║ ██║██╔══██║ ██║ ╚██╔╝ │
100
+ │ ██║ ╚████║██║ ██║╚██████╔╝╚██████╔╝██║ ██║ ██║ ██║ │
101
+ │ ╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ │
102
+ │ │
103
+ │ │
104
+ │ fb-chatify │
105
+ │ Version: 1.5.7 │
106
+ └────────────────────────────────────────────────────────────────────────────────┘`);
107
+ let Boolean_Fca = ["AutoUpdate","Uptime","BroadCast","EncryptFeature","AutoLogin","ResetDataLogin","Login2Fa","Logo"];
108
+ let String_Fca = ["MainName","PreKey","Language","AuthString","Config"]
109
+ let Number_Fca = ["AutoRestartMinutes"];
110
+ let All_Variable = Boolean_Fca.concat(String_Fca,Number_Fca);
111
+
112
+ try {
113
+ if (!global.Fca.Require.fs.existsSync(process.cwd() + '/FastConfigFca.json')) {
114
+ global.Fca.Require.fs.writeFileSync(process.cwd() + "/FastConfigFca.json", JSON.stringify(global.Fca.Data.ObjFastConfig, null, "\t"));
115
+ process.exit(1);
116
+ }
117
+
118
+ try {
119
+ var DataLanguageSetting = require(process.cwd() + "/FastConfigFca.json");
120
+ }
121
+ catch (e) {
122
+ global.Fca.Require.logger.Error('Detect Your FastConfigFca Settings Invalid!, Carry out default restoration');
123
+ global.Fca.Require.fs.writeFileSync(process.cwd() + "/FastConfigFca.json", JSON.stringify(global.Fca.Data.ObjFastConfig, null, "\t"));
124
+ process.exit(1)
125
+ }
126
+ if (global.Fca.Require.fs.existsSync(process.cwd() + '/FastConfigFca.json')) {
127
+ try {
128
+ if (DataLanguageSetting.Logo != undefined) {
129
+ delete DataLanguageSetting.Logo
130
+ global.Fca.Require.fs.writeFileSync(process.cwd() + "/FastConfigFca.json", JSON.stringify(DataLanguageSetting, null, "\t"));
131
+ }
132
+ }
133
+ catch (e) {
134
+ console.log(e);
135
+ }
136
+ if (!global.Fca.Require.languageFile.some((/** @type {{ Language: string; }} */i) => i.Language == DataLanguageSetting.Language)) {
137
+ global.Fca.Require.logger.Warning("Not Support Language: " + DataLanguageSetting.Language + " Only 'en' and 'vi'");
138
+ process.exit(0);
139
+ }
140
+ var Language = global.Fca.Require.languageFile.find((/** @type {{ Language: string; }} */i) => i.Language == DataLanguageSetting.Language).Folder.Index;
141
+ global.Fca.Require.Language = global.Fca.Require.languageFile.find((/** @type {{ Language: string; }} */i) => i.Language == DataLanguageSetting.Language).Folder;
142
+ } else process.exit(1);
143
+ for (let i in DataLanguageSetting) {
144
+ if (Boolean_Fca.includes(i)) {
145
+ if (global.Fca.Require.utils.getType(DataLanguageSetting[i]) != "Boolean") return logger.Error(i + " Is Not A Boolean, Need To Be true Or false !", function() { process.exit(0) });
146
+ else continue;
147
+ }
148
+ else if (String_Fca.includes(i)) {
149
+ if (global.Fca.Require.utils.getType(DataLanguageSetting[i]) != "String") return logger.Error(i + " Is Not A String, Need To Be String!", function() { process.exit(0) });
150
+ else continue;
151
+ }
152
+ else if (Number_Fca.includes(i)) {
153
+ if (global.Fca.Require.utils.getType(DataLanguageSetting[i]) != "Number") return logger.Error(i + " Is Not A Number, Need To Be Number !", function() { process.exit(0) });
154
+ else continue;
155
+ }
156
+ }
157
+ for (let i of All_Variable) {
158
+ if (!DataLanguageSetting[All_Variable[i]] == undefined) {
159
+ DataLanguageSetting[All_Variable[i]] = global.Fca.Data.ObjFastConfig[All_Variable[i]];
160
+ global.Fca.Require.fs.writeFileSync(process.cwd() + "/FastConfigFca.json", JSON.stringify(DataLanguageSetting, null, "\t"));
161
+ }
162
+ else continue;
163
+ }
164
+ global.Fca.Require.FastConfig = DataLanguageSetting;
165
+ }
166
+ catch (e) {
167
+ console.log(e);
168
+ global.Fca.Require.logger.Error();
169
+ }
170
+
171
+ /!-[ Require config and use ]-!/
172
+
173
+ if (global.Fca.Require.FastConfig.Config != 'default') {
174
+ //do ssth
175
+ }
176
+
177
+ /!-[ Require All Package Need Use ]-!/
178
+
179
+ var utils = global.Fca.Require.utils,
180
+ logger = global.Fca.Require.logger,
181
+ fs = global.Fca.Require.fs,
182
+ getText = global.Fca.getText,
183
+ log = global.Fca.Require.log,
184
+ Fetch = global.Fca.Require.Fetch,
185
+ express = require("express")(),
186
+ { join, resolve } = require('path'),
187
+ cheerio = require("cheerio"),
188
+ StateCrypt = {},
189
+ { readFileSync } = require('fs-extra'),
190
+ Database = require("./Extra/Database"),
191
+ readline = require("readline"),
192
+ chalk = require("chalk"),
193
+ figlet = require("figlet"),
194
+ os = require("os"),
195
+ Security = require("./Extra/Security/Index");
196
+
197
+ /!-[ Set Variable For Process ]-!/
198
+
199
+ log.maxRecordSize = 100;
200
+ var checkVerified = null;
201
+ var Boolean_Option = ['online','selfListen','listenEvents','updatePresence','forceLogin','autoMarkDelivery','autoMarkRead','listenTyping','autoReconnect','emitReady'];
202
+
203
+ /!-[ Set And Check Template HTML ]-!/
204
+
205
+ var css = readFileSync(join(__dirname, 'Extra', 'Html', 'Classic', 'style.css'));
206
+ var js = readFileSync(join(__dirname, 'Extra', 'Html', 'Classic', 'script.js'));
207
+
208
+ /!-[ Function Generate HTML Template ]-!/
209
+
210
+ /**
211
+ * It returns a string of HTML code.
212
+ * @param UserName - The username of the user
213
+ * @param Type - The type of user, either "Free" or "Premium"
214
+ * @param link - The link to the music you want to play
215
+ * @returns A HTML file
216
+ */
217
+
218
+ function ClassicHTML(UserName,Type,link) {
219
+ return `<!DOCTYPE html>
220
+ <html lang="en" >
221
+ <head>
222
+ <meta charset="UTF-8">
223
+ <title>Horizon</title>
224
+ <link rel="stylesheet" href="./style.css">
225
+ </head>
226
+ <body>
227
+ <center>
228
+ <marquee><b>waiting for u :d</b></marquee>
229
+ <h2>Horizon User Infomation</h2>
230
+ <h3>UserName: ${UserName} | Type: ${Type}</h3>
231
+ <canvas id="myCanvas"></canvas>
232
+ <script src="./script.js"></script>
233
+ <footer class="footer">
234
+ <div id="music">
235
+ <audio autoplay="false" controls="true" loop="true" src="${link}" __idm_id__="5070849">Your browser does not support the audio element.</audio>
236
+ <br><b>Session ID:</b> ${global.Fca.Require.Security.create().uuid}<br>
237
+ <br>Thanks For Using <b>team.atf</b> - From <b>Kanzu</b> <3<br>
238
+ </div>
239
+ </footer>
240
+ </div>
241
+ </center>
242
+ </html>
243
+ </body>`
244
+ //lazy to change
245
+ }
246
+
247
+ /!-[ Stating Http Infomation ]-!/
248
+
249
+ express.set('DFP', (process.env.PORT || process.env.port || 1932));
250
+ express.use(function(req, res, next) {
251
+ switch (req.url.split('?')[0]) {
252
+ case '/script.js': {
253
+ res.writeHead(200, { 'Content-Type': 'text/javascript' });
254
+ res.write(js);
255
+ break;
256
+ }
257
+ case '/style.css': {
258
+ res.writeHead(200, { 'Content-Type': 'text/css' });
259
+ res.write(css);
260
+ break;
261
+ }
262
+ // case '/History': {
263
+ // if (req.query.PassWord == process.env.REPL_OWNER) {
264
+ // res.writeHead(200, { 'Content-Type': 'application/json charset=utf-8' });
265
+ // res.write(JSON.stringify(console.history,null,2),'utf8');
266
+ // res.end();
267
+ // }
268
+ // else res.json({
269
+ // Status: false,
270
+ // Error: "Thiếu Params ?PassWord=PassWordCuaBan =))"
271
+ // });
272
+ // break;
273
+ // }
274
+ default: {
275
+ res.writeHead(200, "OK", { "Content-Type": "text/html" });
276
+ res.write(ClassicHTML(global.Fca.Require.FastConfig.HTML.UserName, global.Fca.Data.PremText.includes("Premium") ? "Premium": "Free", global.Fca.Require.FastConfig.HTML.MusicLink));
277
+ }
278
+ }
279
+ res.end();
280
+ })
281
+
282
+ global.Fca.Require.Web = express;
283
+
284
+ /!-[ Function setOptions ]-!/
285
+
286
+ /**
287
+ * @param {{ [x: string]: boolean; selfListen?: boolean; listenEvents?: boolean; listenTyping?: boolean; updatePresence?: boolean; forceLogin?: boolean; autoMarkDelivery?: boolean; autoMarkRead?: boolean; autoReconnect?: boolean; logRecordSize: any; online?: boolean; emitReady?: boolean; userAgent: any; logLevel?: any; pageID?: any; proxy?: any; }} globalOptions
288
+ * @param {{ [x: string]: any; logLevel?: any; forceLogin?: boolean; userAgent?: any; pauseLog?: any; logRecordSize?: any; pageID?: any; proxy?: any; }} options
289
+ */
290
+
291
+ function setOptions(globalOptions, options) {
292
+ Object.keys(options).map(function(key) {
293
+ switch (Boolean_Option.includes(key)) {
294
+ case true: {
295
+ globalOptions[key] = Boolean(options[key]);
296
+ break;
297
+ }
298
+ case false: {
299
+ switch (key) {
300
+ case 'pauseLog': {
301
+ if (options.pauseLog) log.pause();
302
+ else log.resume();
303
+ break;
304
+ }
305
+ case 'logLevel': {
306
+ log.level = options.logLevel;
307
+ globalOptions.logLevel = options.logLevel;
308
+ break;
309
+ }
310
+ case 'logRecordSize': {
311
+ log.maxRecordSize = options.logRecordSize;
312
+ globalOptions.logRecordSize = options.logRecordSize;
313
+ break;
314
+ }
315
+ case 'pageID': {
316
+ globalOptions.pageID = options.pageID.toString();
317
+ break;
318
+ }
319
+ case 'userAgent': {
320
+ globalOptions.userAgent = (options.userAgent || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36');
321
+ break;
322
+ }
323
+ case 'proxy': {
324
+ if (typeof options.proxy != "string") {
325
+ delete globalOptions.proxy;
326
+ utils.setProxy();
327
+ } else {
328
+ globalOptions.proxy = options.proxy;
329
+ utils.setProxy(globalOptions.proxy);
330
+ }
331
+ break;
332
+ }
333
+ default: {
334
+ log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
335
+ break;
336
+ }
337
+ }
338
+ break;
339
+ }
340
+ }
341
+ });
342
+ }
343
+
344
+ /!-[ Function BuildAPI ]-!/
345
+
346
+ /**
347
+ * @param {any} globalOptions
348
+ * @param {string} html
349
+ * @param {{ getCookies: (arg0: string) => any[]; }} jar
350
+ */
351
+
352
+ function buildAPI(globalOptions, html, jar) {
353
+ var maybeCookie = jar.getCookies("https://www.facebook.com").filter(function(/** @type {{ cookieString: () => string; }} */val) { return val.cookieString().split("=")[0] === "c_user"; });
354
+
355
+ if (maybeCookie.length === 0) {
356
+ switch (global.Fca.Require.FastConfig.AutoLogin) {
357
+ case true: {
358
+ global.Fca.Require.logger.Warning(global.Fca.Require.Language.Index.AutoLogin, function() {
359
+ return global.Fca.AutoLogin();
360
+ });
361
+ break;
362
+ }
363
+ case false: {
364
+ throw { error: global.Fca.Require.Language.Index.ErrAppState };
365
+
366
+ }
367
+ }
368
+ }
369
+
370
+ if (html.indexOf("/checkpoint/block/?next") > -1) log.warn("login", Language.CheckPointLevelI);
371
+
372
+ var userID = maybeCookie[0].cookieString().split("=")[1].toString();
373
+ process.env['UID'] = logger.Normal(getText(Language.UID,userID), userID);
374
+
375
+ try {
376
+ clearInterval(checkVerified);
377
+ } catch (e) {
378
+ console.log(e);
379
+ }
380
+
381
+ var clientID = (Math.random() * 2147483648 | 0).toString(16);
382
+
383
+ var CHECK_MQTT = {
384
+ oldFBMQTTMatch: html.match(/irisSeqID:"(.+?)",appID:219994525426954,endpoint:"(.+?)"/),
385
+ newFBMQTTMatch: html.match(/{"app_id":"219994525426954","endpoint":"(.+?)","iris_seq_id":"(.+?)"}/),
386
+ legacyFBMQTTMatch: html.match(/(\["MqttWebConfig",\[\],{fbid:")(.+?)(",appID:219994525426954,endpoint:")(.+?)(",pollingEndpoint:")(.+?)(3790])/)
387
+ }
388
+
389
+ let Slot = Object.keys(CHECK_MQTT);
390
+
391
+ var mqttEndpoint,region,irisSeqID;
392
+ Object.keys(CHECK_MQTT).map(function(MQTT) {
393
+ if (CHECK_MQTT[MQTT] && !region) {
394
+ switch (Slot.indexOf(MQTT)) {
395
+ case 0: {
396
+ irisSeqID = CHECK_MQTT[MQTT][1];
397
+ mqttEndpoint = CHECK_MQTT[MQTT][2];
398
+ region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
399
+ return;
400
+ }
401
+ case 1: {
402
+ irisSeqID = CHECK_MQTT[MQTT][2];
403
+ mqttEndpoint = CHECK_MQTT[MQTT][1].replace(/\\\//g, "/");
404
+ region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
405
+ return;
406
+ }
407
+ case 2: {
408
+ mqttEndpoint = CHECK_MQTT[MQTT][4];
409
+ region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
410
+ return;
411
+ }
412
+ }
413
+ return;
414
+ }
415
+ });
416
+
417
+ var ctx = {
418
+ userID: userID,
419
+ jar: jar,
420
+ clientID: clientID,
421
+ globalOptions: globalOptions,
422
+ loggedIn: true,
423
+ access_token: 'NONE',
424
+ clientMutationId: 0,
425
+ mqttClient: undefined,
426
+ lastSeqId: irisSeqID,
427
+ syncToken: undefined,
428
+ mqttEndpoint: mqttEndpoint,
429
+ region: region,
430
+ firstListen: true
431
+ };
432
+
433
+ var api = {
434
+ setOptions: setOptions.bind(null, globalOptions),
435
+ getAppState: function getAppState() {
436
+ return utils.getAppState(jar);
437
+ }
438
+ };
439
+
440
+ if (region && mqttEndpoint) {
441
+ //do sth
442
+ }
443
+ else {
444
+ log.warn("login", getText(Language.NoAreaData));
445
+ api["htmlData"] = html;
446
+ }
447
+
448
+ var defaultFuncs = utils.makeDefaults(html, userID, ctx);
449
+
450
+ fs.readdirSync(__dirname + "/src").filter((/** @type {string} */File) => File.endsWith(".js") && !File.includes('Dev_')).map((/** @type {string} */File) => api[File.split('.').slice(0, -1).join('.')] = require('./src/' + File)(defaultFuncs, api, ctx));
451
+
452
+ return {
453
+ ctx,
454
+ defaultFuncs,
455
+ api
456
+ };
457
+ }
458
+
459
+ /!-[ Function makeLogin ]-!/
460
+
461
+ /**
462
+ * @param {{ setCookie: (arg0: any, arg1: string) => void; }} jar
463
+ * @param {any} email
464
+ * @param {any} password
465
+ * @param {{ forceLogin: any; }} loginOptions
466
+ * @param {(err: any, api: any) => any} callback
467
+ * @param {any} prCallback
468
+ */
469
+
470
+ function makeLogin(jar, email, password, loginOptions, callback, prCallback) {
471
+ return function(/** @type {{ body: any; }} */res) {
472
+ var html = res.body,$ = cheerio.load(html),arr = [];
473
+
474
+ $("#login_form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
475
+
476
+ arr = arr.filter(function(v) {
477
+ return v.val && v.val.length;
478
+ });
479
+
480
+ var form = utils.arrToForm(arr);
481
+ form.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
482
+ form.lgndim = Buffer.from("{\"w\":1440,\"h\":900,\"aw\":1440,\"ah\":834,\"c\":24}").toString('base64');
483
+ form.email = email;
484
+ form.pass = password;
485
+ form.default_persistent = '0';
486
+ form.locale = 'en_US';
487
+ form.timezone = '240';
488
+ form.lgnjs = ~~(Date.now() / 1000);
489
+
490
+ html.split("\"_js_").slice(1).map((/** @type {any} */val) => {
491
+ jar.setCookie(utils.formatCookie(JSON.parse("[\"" + utils.getFrom(val, "", "]") + "]"), "facebook"),"https://www.facebook.com")
492
+ });
493
+
494
+ logger.Normal(Language.OnLogin);
495
+ return utils
496
+ .post("https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110", jar, form, loginOptions)
497
+ .then(utils.saveCookies(jar))
498
+ .then(function(/** @type {{ headers: any; }} */res) {
499
+ var headers = res.headers;
500
+ if (!headers.location) throw { error: Language.InvaildAccount };
501
+
502
+ // This means the account has login approvals turned on.
503
+ if (headers.location.indexOf('https://www.facebook.com/checkpoint/') > -1) {
504
+ logger.Warning(Language.TwoAuth);
505
+ var nextURL = 'https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php';
506
+
507
+ return utils
508
+ .get(headers.location, jar, null, loginOptions)
509
+ .then(utils.saveCookies(jar))
510
+ .then(async function(/** @type {{ body: any; }} */res) {
511
+ if (!await Database.get('ThroughAcc')) {
512
+ await Database.set('ThroughAcc', email);
513
+ }
514
+ else {
515
+ if (String((await Database.get('ThroughAcc'))).replace(RegExp('"','g'), '') != String(email).replace(RegExp('"','g'), '')) {
516
+ await Database.set('ThroughAcc', email);
517
+ if (await Database.get('Through2Fa')) {
518
+ await Database.delete('Through2Fa');
519
+ }
520
+ }
521
+ }
522
+ var html = res.body,$ = cheerio.load(html), arr = [];
523
+ $("form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
524
+ arr = arr.filter(v => { return v.val && v.val.length });
525
+ var form = utils.arrToForm(arr);
526
+ if (html.indexOf("checkpoint/?next") > -1) {
527
+ setTimeout(() => {
528
+ checkVerified = setInterval((_form) => {}, 5000, {
529
+ fb_dtsg: form.fb_dtsg,
530
+ jazoest: form.jazoest,
531
+ dpr: 1
532
+ });
533
+ }, 2500);
534
+ switch (global.Fca.Require.FastConfig.Login2Fa) {
535
+ case true: {
536
+ try {
537
+ const question = question => {
538
+ const rl = readline.createInterface({
539
+ input: process.stdin,
540
+ output: process.stdout
541
+ });
542
+ return new Promise(resolve => {
543
+ rl.question(question, answer => {
544
+ rl.close();
545
+ return resolve(answer);
546
+ });
547
+ });
548
+ };
549
+ async function EnterSecurityCode() {
550
+ try {
551
+ var Through2Fa = await Database.get('Through2Fa');
552
+ if (Through2Fa) {
553
+ Through2Fa.map(function(/** @type {{ key: string; value: string; expires: string; domain: string; path: string; }} */c) {
554
+ let str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";";
555
+ jar.setCookie(str, "http://" + c.domain);
556
+ })
557
+ var from2 = utils.arrToForm(arr);
558
+ from2.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
559
+ from2.lgndim = Buffer.from("{\"w\":1440,\"h\":900,\"aw\":1440,\"ah\":834,\"c\":24}").toString('base64');
560
+ from2.email = email;
561
+ from2.pass = password;
562
+ from2.default_persistent = '0';
563
+ from2.locale = 'en_US';
564
+ from2.timezone = '240';
565
+ from2.lgnjs = ~~(Date.now() / 1000);
566
+ return utils
567
+ .post("https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110", jar, from2, loginOptions)
568
+ .then(utils.saveCookies(jar))
569
+ .then(function(/** @type {{ headers: any; }} */res) {
570
+ var headers = res.headers;
571
+ if (!headers['set-cookie'][0].includes('deleted')) {
572
+ logger.Warning(Language.ErrThroughCookies, async function() {
573
+ await Database.delete('Through2Fa');
574
+ });
575
+ process.exit(1);
576
+ }
577
+ if (headers.location && headers.location.indexOf('https://www.facebook.com/checkpoint/') > -1) {
578
+ return utils
579
+ .get(headers.location, jar, null, loginOptions)
580
+ .then(utils.saveCookies(jar))
581
+ .then(function(/** @type {{ body: any; }} */res) {
582
+ var html = res.body,$ = cheerio.load(html), arr = [];
583
+ $("form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
584
+ arr = arr.filter(v => { return v.val && v.val.length });
585
+ var from2 = utils.arrToForm(arr);
586
+
587
+ if (html.indexOf("checkpoint/?next") > -1) {
588
+ setTimeout(() => {
589
+ checkVerified = setInterval((_form) => {}, 5000, {
590
+ fb_dtsg: from2.fb_dtsg,
591
+ jazoest: from2.jazoest,
592
+ dpr: 1
593
+ });
594
+ }, 2500);
595
+ if (!res.headers.location && res.headers['set-cookie'][0].includes('checkpoint')) {
596
+ try {
597
+ delete from2.name_action_selected;
598
+ from2['submit[Continue]'] = $("#checkpointSubmitButton").html();
599
+ return utils
600
+ .post(nextURL, jar, from2, loginOptions)
601
+ .then(utils.saveCookies(jar))
602
+ .then(function() {
603
+ from2['submit[This was me]'] = "This was me";
604
+ return utils.post(nextURL, jar, from2, loginOptions).then(utils.saveCookies(jar));
605
+ })
606
+ .then(function() {
607
+ delete from2['submit[This was me]'];
608
+ from2.name_action_selected = 'save_device';
609
+ from2['submit[Continue]'] = $("#checkpointSubmitButton").html();
610
+ return utils.post(nextURL, jar, from2, loginOptions).then(utils.saveCookies(jar));
611
+ })
612
+ .then(async function(/** @type {{ headers: any; body: string | string[]; }} */res) {
613
+ var headers = res.headers;
614
+ if (!headers.location && res.headers['set-cookie'][0].includes('checkpoint')) throw { error: "wtf ??:D" };
615
+ var appState = utils.getAppState(jar,false);
616
+ await Database.set('Through2Fa', appState);
617
+ return loginHelper(appState, email, password, loginOptions, callback);
618
+ })
619
+ .catch((/** @type {any} */e) => callback(e));
620
+ }
621
+ catch (e) {
622
+ console.log(e)
623
+ }
624
+ }
625
+ }
626
+ })
627
+ }
628
+ return utils.get('https://www.facebook.com/', jar, null, loginOptions).then(utils.saveCookies(jar));
629
+ }).catch((/** @type {any} */e) => console.log(e));
630
+ }
631
+ }
632
+ catch (e) {
633
+ await Database.delete('Through2Fa');
634
+ }
635
+ var code = await question(Language.EnterSecurityCode);
636
+ try {
637
+ form.approvals_code = code;
638
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html();
639
+ var prResolve,prReject;
640
+ var rtPromise = new Promise((resolve, reject) => { prResolve = resolve; prReject = reject; });
641
+ if (typeof code == "string") { //always strings
642
+ utils
643
+ .post(nextURL, jar, form, loginOptions)
644
+ .then(utils.saveCookies(jar))
645
+ .then(function(/** @type {{ body: string | Buffer; }} */res) {
646
+ var $ = cheerio.load(res.body);
647
+ var error = $("#approvals_code").parent().attr("data-xui-error");
648
+ if (error) {
649
+ logger.Warning(Language.InvaildTwoAuthCode,function() { EnterSecurityCode(); }); //bruh loop
650
+ };
651
+ })
652
+ .then(function() {
653
+ delete form.no_fido;delete form.approvals_code;
654
+ form.name_action_selected = 'save_device'; //'save_device' || 'dont_save;
655
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
656
+ })
657
+ .then(async function(/** @type {{ headers: any; body: string | string[]; }} */res) {
658
+ var headers = res.headers;
659
+ if (!headers.location && res.headers['set-cookie'][0].includes('checkpoint')) {
660
+ try {
661
+ delete form.name_action_selected;
662
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html();
663
+ return utils
664
+ .post(nextURL, jar, form, loginOptions)
665
+ .then(utils.saveCookies(jar))
666
+ .then(function() {
667
+ form['submit[This was me]'] = "This was me";
668
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
669
+ })
670
+ .then(function() {
671
+ delete form['submit[This was me]'];
672
+ form.name_action_selected = 'save_device';
673
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html();
674
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
675
+ })
676
+ .then(async function(/** @type {{ headers: any; body: string | string[]; }} */res) {
677
+ var headers = res.headers;
678
+ if (!headers.location && res.headers['set-cookie'][0].includes('checkpoint')) throw { error: "wtf ??:D" };
679
+ var appState = utils.getAppState(jar,false);
680
+ await Database.set('Through2Fa', appState);
681
+ return loginHelper(appState, email, password, loginOptions, callback);
682
+ })
683
+ .catch((/** @type {any} */e) => callback(e));
684
+ }
685
+ catch (e) {
686
+ console.log(e)
687
+ }
688
+ }
689
+ var appState = utils.getAppState(jar,false);
690
+ if (callback === prCallback) {
691
+ callback = function(/** @type {any} */err, /** @type {any} */api) {
692
+ if (err) return prReject(err);
693
+ return prResolve(api);
694
+ };
695
+ }
696
+ await Database.set('Through2Fa', appState);
697
+ return loginHelper(appState, email, password, loginOptions, callback);
698
+ })
699
+ .catch(function(/** @type {any} */err) {
700
+ if (callback === prCallback) prReject(err);
701
+ else callback(err);
702
+ });
703
+ } else {
704
+ utils
705
+ .post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions, null, { "Referer": "https://www.facebook.com/checkpoint/?next" })
706
+ .then(utils.saveCookies(jar))
707
+ .then(async function(/** @type {{ body: string; }} */res) {
708
+ try {
709
+ JSON.parse(res.body.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, ""));
710
+ } catch (ex) {
711
+ clearInterval(checkVerified);
712
+ logger.Warning(Language.VerifiedCheck);
713
+ if (callback === prCallback) {
714
+ callback = function(/** @type {any} */err, /** @type {any} */api) {
715
+ if (err) return prReject(err);
716
+ return prResolve(api);
717
+ };
718
+ }
719
+ let appState = utils.getAppState(jar,false);
720
+ return loginHelper(appState, email, password, loginOptions, callback);
721
+ }
722
+ })
723
+ .catch((/** @type {any} */ex) => {
724
+ log.error("login", ex);
725
+ if (callback === prCallback) prReject(ex);
726
+ else callback(ex);
727
+ });
728
+ }
729
+ return rtPromise;
730
+ }
731
+ catch (e) {
732
+ logger.Error(e)
733
+ logger.Error()
734
+ process.exit(0)
735
+ }
736
+ }
737
+ await EnterSecurityCode()
738
+ }
739
+ catch (e) {
740
+ logger.Error(e)
741
+ logger.Error();
742
+ process.exit(0);
743
+ }
744
+ }
745
+ break;
746
+ case false: {
747
+ throw {
748
+ error: 'login-approval',
749
+ continue: function submit2FA(/** @type {any} */code) {
750
+ form.approvals_code = code;
751
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html(); //'Continue';
752
+ var prResolve,prReject;
753
+ var rtPromise = new Promise((resolve, reject) => { prResolve = resolve; prReject = reject; });
754
+ if (typeof code == "string") {
755
+ utils
756
+ .post(nextURL, jar, form, loginOptions)
757
+ .then(utils.saveCookies(jar))
758
+ .then(function(/** @type {{ body: string | Buffer; }} */res) {
759
+ var $ = cheerio.load(res.body);
760
+ var error = $("#approvals_code").parent().attr("data-xui-error");
761
+ if (error) {
762
+ throw {
763
+ error: 'login-approval',
764
+ errordesc: Language.InvaildTwoAuthCode,
765
+ lerror: error,
766
+ continue: submit2FA
767
+ };
768
+ }
769
+ })
770
+ .then(function() {
771
+ delete form.no_fido;delete form.approvals_code;
772
+ form.name_action_selected = 'dont_save'; //'save_device' || 'dont_save;
773
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
774
+ })
775
+ .then(function(/** @type {{ headers: any; body: string | string[]; }} */res) {
776
+ var headers = res.headers;
777
+ if (!headers.location && res.headers['set-cookie'][0].includes('checkpoint')) throw { error: Language.ApprovalsErr };
778
+ var appState = utils.getAppState(jar,false);
779
+ if (callback === prCallback) {
780
+ callback = function(/** @type {any} */err, /** @type {any} */api) {
781
+ if (err) return prReject(err);
782
+ return prResolve(api);
783
+ };
784
+ }
785
+ return loginHelper(appState, email, password, loginOptions, callback);
786
+ })
787
+ .catch(function(/** @type {any} */err) {
788
+ if (callback === prCallback) prReject(err);
789
+ else callback(err);
790
+ });
791
+ } else {
792
+ utils
793
+ .post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions, null, { "Referer": "https://www.facebook.com/checkpoint/?next" })
794
+ .then(utils.saveCookies(jar))
795
+ .then((/** @type {{ body: string; }} */res) => {
796
+ try {
797
+ JSON.parse(res.body.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, ""));
798
+ } catch (ex) {
799
+ clearInterval(checkVerified);
800
+ logger.Warning(Language.VerifiedCheck);
801
+ if (callback === prCallback) {
802
+ callback = function(/** @type {any} */err, /** @type {any} */api) {
803
+ if (err) return prReject(err);
804
+ return prResolve(api);
805
+ };
806
+ }
807
+ return loginHelper(utils.getAppState(jar,false), email, password, loginOptions, callback);
808
+ }
809
+ })
810
+ .catch((/** @type {any} */ex) => {
811
+ log.error("login", ex);
812
+ if (callback === prCallback) prReject(ex);
813
+ else callback(ex);
814
+ });
815
+ }
816
+ return rtPromise;
817
+ }
818
+ };
819
+ }
820
+ }
821
+ } else {
822
+ if (!loginOptions.forceLogin) throw { error: Language.ForceLoginNotEnable };
823
+
824
+ if (html.indexOf("Suspicious Login Attempt") > -1) form['submit[This was me]'] = "This was me";
825
+ else form['submit[This Is Okay]'] = "This Is Okay";
826
+
827
+ return utils
828
+ .post(nextURL, jar, form, loginOptions)
829
+ .then(utils.saveCookies(jar))
830
+ .then(function() {
831
+ form.name_action_selected = 'dont_save';
832
+
833
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
834
+ })
835
+ .then(function(/** @type {{ headers: any; body: string | string[]; }} */res) {
836
+ var headers = res.headers;
837
+
838
+ if (!headers.location && res.body.indexOf('Review Recent Login') > -1) throw { error: "Something went wrong with review recent login." };
839
+
840
+ var appState = utils.getAppState(jar,false);
841
+
842
+ return loginHelper(appState, email, password, loginOptions, callback);
843
+ })
844
+ .catch((/** @type {any} */e) => callback(e));
845
+ }
846
+ });
847
+ }
848
+ return utils.get('https://www.facebook.com/', jar, null, loginOptions).then(utils.saveCookies(jar));
849
+ });
850
+ };
851
+ }
852
+
853
+ /!-[ Function backup ]-!/
854
+
855
+ /**
856
+ * @param {string} data
857
+ * @param {any} globalOptions
858
+ * @param {any} callback
859
+ * @param {any} prCallback
860
+ */
861
+
862
+ function backup(data,globalOptions, callback, prCallback) {
863
+ try {
864
+ var appstate;
865
+ try {
866
+ appstate = JSON.parse(data)
867
+ }
868
+ catch(e) {
869
+ appstate = data;
870
+ }
871
+ logger.Warning(Language.BackupNoti);
872
+ try {
873
+ loginHelper(appstate,null,null,globalOptions, callback, prCallback)
874
+ }
875
+ catch (e) {
876
+ logger.Error(Language.ErrBackup);
877
+ process.exit(0);
878
+ }
879
+ }
880
+ catch (e) {
881
+ return logger.Error();
882
+ }
883
+ }
884
+
885
+ /!-[ async function loginHelper ]-!/
886
+
887
+ /**
888
+ * @param {string | any[]} appState
889
+ * @param {any} email
890
+ * @param {any} password
891
+ * @param {{ selfListen?: boolean; listenEvents?: boolean; listenTyping?: boolean; updatePresence?: boolean; forceLogin?: boolean; autoMarkDelivery?: boolean; autoMarkRead?: boolean; autoReconnect?: boolean; logRecordSize?: number; online?: boolean; emitReady?: boolean; userAgent?: string; pageID?: any; }} globalOptions
892
+ * @param {(arg0: any, arg1: undefined) => void} callback
893
+ * @param {(error: any, api: any) => any} [prCallback]
894
+ */
895
+
896
+ async function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
897
+ var mainPromise = null;
898
+ var jar = utils.getJar();
899
+
900
+ if (fs.existsSync('./backupappstate.json')) {
901
+ fs.unlinkSync('./backupappstate.json');
902
+ }
903
+
904
+ try {
905
+ if (appState) {
906
+ logger.Normal(Language.OnProcess);
907
+ switch (await Database.has("FBKEY")) {
908
+ case true: {
909
+ process.env.FBKEY = await Database.get("FBKEY");
910
+ }
911
+ break;
912
+ case false: {
913
+ const SecurityKey = global.Fca.Require.Security.create().apiKey;
914
+ process.env['FBKEY'] = SecurityKey;
915
+ await Database.set('FBKEY', SecurityKey);
916
+ }
917
+ break;
918
+ default: {
919
+ const SecurityKey = global.Fca.Require.Security.create().apiKey;
920
+ process.env['FBKEY'] = SecurityKey;
921
+ await Database.set('FBKEY', SecurityKey);
922
+ }
923
+ }
924
+ try {
925
+ switch (global.Fca.Require.FastConfig.EncryptFeature) {
926
+ case true: {
927
+ appState = JSON.parse(JSON.stringify(appState, null, "\t"));
928
+ switch (utils.getType(appState)) {
929
+ case "Array": {
930
+ switch (utils.getType(appState[0])) {
931
+ case "Object": {
932
+ logger.Normal(Language.NotReadyToDecrypt);
933
+ }
934
+ break;
935
+ case "String": {
936
+ appState = Security(appState,process.env['FBKEY'],'Decrypt');
937
+ logger.Normal(Language.DecryptSuccess);
938
+ }
939
+ }
940
+ }
941
+ break;
942
+ case "Object": {
943
+ try {
944
+ appState = StateCrypt.decryptState(appState, process.env['FBKEY']);
945
+ logger.Normal(Language.DecryptSuccess);
946
+ }
947
+ catch (e) {
948
+ if (process.env.Backup != undefined && process.env.Backup) {
949
+ await backup(process.env.Backup,globalOptions, callback, prCallback);
950
+ }
951
+ else {
952
+ try {
953
+ if (await Database.has('Backup')) {
954
+ return await backup(await Database.get('Backup'),globalOptions, callback, prCallback);
955
+ }
956
+ else {
957
+ logger.Normal(Language.ErrBackup);
958
+ process.exit(0);
959
+ }
960
+ }
961
+ catch (e) {
962
+ logger.Warning(Language.ErrBackup);
963
+ logger.Error();
964
+ process.exit(0);
965
+ }
966
+ }
967
+ logger.Warning(Language.DecryptFailed);
968
+ return logger.Error();
969
+ }
970
+ }
971
+ break;
972
+ case "String": {
973
+ try {
974
+ appState = StateCrypt.decryptState(appState, process.env['FBKEY']);
975
+ logger.Normal(Language.DecryptSuccess);
976
+ }
977
+ catch (e) {
978
+ if (process.env.Backup != undefined && process.env.Backup) {
979
+ await backup(process.env.Backup,globalOptions, callback, prCallback);
980
+ }
981
+ else {
982
+ try {
983
+ if (await Database.has('Backup')) {
984
+ return await backup(await Database.get('Backup'),globalOptions, callback, prCallback);
985
+ }
986
+ else {
987
+ logger.Normal(Language.ErrBackup);
988
+ process.exit(0);
989
+ }
990
+ }
991
+ catch (e) {
992
+ logger.Warning(Language.ErrBackup);
993
+ logger.Error();
994
+ process.exit(0);
995
+ }
996
+ }
997
+ logger.Warning(Language.DecryptFailed);
998
+ return logger.Error();
999
+ }
1000
+ }
1001
+ break;
1002
+ default: {
1003
+ logger.Warning(Language.InvaildAppState);
1004
+ process.exit(0)
1005
+ }
1006
+ }
1007
+ }
1008
+ break;
1009
+ case false: {
1010
+ switch (utils.getType(appState)) {
1011
+ case "Array": {
1012
+ logger.Normal(Language.EncryptStateOff);
1013
+ }
1014
+ break;
1015
+ case "Object": {
1016
+ logger.Normal(Language.EncryptStateOff);
1017
+ try {
1018
+ appState = StateCrypt.decryptState(appState, process.env['FBKEY']);
1019
+ logger.Normal(Language.DecryptSuccess);
1020
+ }
1021
+ catch (e) {
1022
+ if (process.env.Backup != undefined && process.env.Backup) {
1023
+ await backup(process.env.Backup,globalOptions, callback, prCallback);
1024
+ }
1025
+ else {
1026
+ try {
1027
+ if (await Database.has('Backup')) {
1028
+ return await backup(await Database.get('Backup'),globalOptions, callback, prCallback);
1029
+ }
1030
+ else {
1031
+ logger.Warning(Language.ErrBackup);
1032
+ process.exit(0);
1033
+ }
1034
+ }
1035
+ catch (e) {
1036
+ logger.Warning(Language.ErrBackup);
1037
+ logger.Error();
1038
+ process.exit(0);
1039
+ }
1040
+ }
1041
+ logger.Warning(Language.DecryptFailed);
1042
+ return logger.Error();
1043
+ }
1044
+ }
1045
+ break;
1046
+ default: {
1047
+ logger.Warning(Language.InvaildAppState);
1048
+ process.exit(0)
1049
+ }
1050
+ }
1051
+ }
1052
+ break;
1053
+ default: {
1054
+ logger.Warning(getText(Language.IsNotABoolean,global.Fca.Require.FastConfig.EncryptFeature))
1055
+ process.exit(0);
1056
+ }
1057
+ }
1058
+ }
1059
+ catch (e) {
1060
+ console.log(e);
1061
+ }
1062
+
1063
+ try {
1064
+ appState = JSON.parse(appState);
1065
+ }
1066
+ catch (e) {
1067
+ try {
1068
+ appState = appState;
1069
+ }
1070
+ catch (e) {
1071
+ return logger.Error();
1072
+ }
1073
+ }
1074
+ try {
1075
+ global.Fca.Data.AppState = appState;
1076
+ appState.map(function(/** @type {{ key: string; value: string; expires: string; domain: string; path: string; }} */c) {
1077
+ var str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";";
1078
+ jar.setCookie(str, "http://" + c.domain);
1079
+ });
1080
+ process.env.Backup = appState;
1081
+ await Database.set('Backup', appState);
1082
+ mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
1083
+ } catch (e) {
1084
+ console.log(e)
1085
+ if (process.env.Backup != undefined && process.env.Backup) {
1086
+ return await backup(process.env.Backup,globalOptions, callback, prCallback);
1087
+ }
1088
+ try {
1089
+ if (await Database.has('Backup')) {
1090
+ return await backup(await Database.get('Backup'),globalOptions, callback, prCallback);
1091
+ }
1092
+ else {
1093
+ logger.Warning(Language.ErrBackup);
1094
+ process.exit(0);
1095
+ }
1096
+ }
1097
+ catch (e) {
1098
+ logger.Warning(Language.ErrBackup);
1099
+ process.exit(0);
1100
+ }
1101
+ return logger.Warning(Language.ErrBackup); // unreachable 👑
1102
+ }
1103
+ } else {
1104
+ mainPromise = utils
1105
+ .get("https://www.facebook.com/", null, null, globalOptions, { noRef: true })
1106
+ .then(utils.saveCookies(jar))
1107
+ .then(makeLogin(jar, email, password, globalOptions, callback, prCallback))
1108
+ .then(function() {
1109
+ return utils.get('https://www.facebook.com/', jar, null, globalOptions).then(utils.saveCookies(jar));
1110
+ });
1111
+ }
1112
+ } catch (e) {
1113
+ console.log(e);
1114
+ }
1115
+ var ctx,api;
1116
+ mainPromise = mainPromise
1117
+ .then(function(/** @type {{ body: string; }} */res) {
1118
+ var reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/,redirect = reg.exec(res.body);
1119
+ if (redirect && redirect[1]) return utils.get(redirect[1], jar, null, globalOptions).then(utils.saveCookies(jar));
1120
+ return res;
1121
+ })
1122
+ .then(function(/** @type {{ body: any; }} */res) {
1123
+ var html = res.body,Obj = buildAPI(globalOptions, html, jar);
1124
+ ctx = Obj.ctx;
1125
+ api = Obj.api;
1126
+ process.env.api = Obj.api;
1127
+ return res;
1128
+ });
1129
+ if (globalOptions.pageID) {
1130
+ mainPromise = mainPromise
1131
+ .then(function() {
1132
+ return utils.get('https://www.facebook.com/' + ctx.globalOptions.pageID + '/messages/?section=messages&subsection=inbox', ctx.jar, null, globalOptions);
1133
+ })
1134
+ .then(function(/** @type {{ body: any; }} */resData) {
1135
+ var url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
1136
+ url = url.substring(0, url.length - 1);
1137
+ return utils.get('https://www.facebook.com' + url, ctx.jar, null, globalOptions);
1138
+ });
1139
+ }
1140
+ mainPromise
1141
+ .then(function() {
1142
+ const { execSync } = require('child_process');
1143
+ Fetch('https://raw.githubusercontent.com/corazoncary/fca/main/package.json').then(async (/** @type {{ body: { toString: () => string; }; }} */res) => {
1144
+ const localVersion = global.Fca.Version;
1145
+ if (Number(localVersion.replace(/\./g,"")) < Number(JSON.parse(res.body.toString()).version.replace(/\./g,"")) ) {
1146
+ log.warn("[ FCA-PRIYANSH ] •",getText(Language.NewVersionFound,global.Fca.Version,JSON.parse(res.body.toString()).version));
1147
+ if (global.Fca.Require.FastConfig.AutoUpdate == true) {
1148
+ log.warn("[ FCA-PRIYANSH ] •",Language.AutoUpdate);
1149
+ try {
1150
+ execSync('npm install team.atf@latest', { stdio: 'inherit' });
1151
+ logger.Success(Language.UpdateSuccess)
1152
+ logger.Normal(Language.RestartAfterUpdate);
1153
+ await new Promise(resolve => setTimeout(resolve,5*1000));
1154
+ console.clear();process.exit(1);
1155
+ }
1156
+ catch (err) {
1157
+ log.warn('Error Update: ' + err);
1158
+ logger.Normal(Language.UpdateFailed);
1159
+ try {
1160
+ const fs = require('fs-extra')
1161
+ try {
1162
+ logger.Error('succeess Package');
1163
+ execSync('npm cache clean --force', { stdio: 'ignore'})
1164
+ await new Promise(resolve => setTimeout(resolve, 2*1000))
1165
+ fs.removeSync('../team.atf');
1166
+ // why stdio is not studio :v
1167
+ await new Promise(resolve => setTimeout(resolve, 2*1000))
1168
+ execSync('npm i team.atf@latest', { stdio: 'inherit'})
1169
+ logger.Success("success Restart");
1170
+ process.exit(1);
1171
+ }
1172
+ catch (e) {
1173
+ logger.Warning("Error Please Enter The Following Code In Console To Fix !");
1174
+ logger.Warning("rmdir -rf ./node_modules/fca-priyansh && npm i fca-priyansh@latest && npm start");
1175
+ logger.Warning("Please Copy All The Above Words, Need To Do It 100% Correctly Otherwise Your File Will Be Discolored ✨")
1176
+ process.exit(0);
1177
+ }
1178
+ }
1179
+ catch (e) {
1180
+ logger.Error(Language.NotiAfterUseToolFail)
1181
+ logger.Warning("rmdir ./node_modules after type npm i && npm start");
1182
+ process.exit(0);
1183
+ }
1184
+ }
1185
+ }
1186
+ }
1187
+ else {
1188
+ logger.Normal(getText(Language.LocalVersion,localVersion));
1189
+ logger.Normal(getText(Language.CountTime,global.Fca.Data.CountTime()))
1190
+ logger.Normal(Language.WishMessage[Math.floor(Math.random()*Language.WishMessage.length)]);
1191
+ require('./Extra/ExtraUptimeRobot')();
1192
+ DataLanguageSetting.HTML.HTML==true? global.Fca.Require.Web.listen(global.Fca.Require.Web.get('DFP')) : global.Fca.Require.Web = null;
1193
+ callback(null, api);
1194
+ };
1195
+ }).catch(async function(e) {
1196
+ console.log(e)
1197
+ logger.Warning(Language.AutoCheckUpdateFailure)
1198
+ logger.Normal(getText(Language.LocalVersion,global.Fca.Version));
1199
+ logger.Normal(getText(Language.CountTime,global.Fca.Data.CountTime()))
1200
+ logger.Normal(Language.WishMessage[Math.floor(Math.random()*Language.WishMessage.length)]);
1201
+ require('./Extra/ExtraUptimeRobot')();
1202
+ DataLanguageSetting.HTML.HTML==true? global.Fca.Require.Web.listen(global.Fca.Require.Web.get('DFP')) : global.Fca.Require.Web = null;
1203
+ callback(null, api);
1204
+ });
1205
+ }).catch(function(/** @type {{ error: any; }} */e) {
1206
+ log.error("login", e.error || e);
1207
+ callback(e);
1208
+ });
1209
+ }
1210
+
1211
+ /**
1212
+ * It asks the user for their account and password, and then saves it to the database.
1213
+ */
1214
+
1215
+ function setUserNameAndPassWord() {
1216
+ let rl = readline.createInterface({
1217
+ input: process.stdin,
1218
+ output: process.stdout
1219
+ });
1220
+ let localbrand2 = global.Fca.Version
1221
+ console.clear();
1222
+ console.log(figlet.textSync('Horizon', {font: 'ANSI Shadow',horizontalLayout: 'default',verticalLayout: 'default',width: 0,whitespaceBreak: true }));
1223
+ console.log(chalk.bold.hex('#9900FF')("[</>]") + chalk.bold.yellow(' => ') + "Operating System: " + chalk.bold.red(os.type()));
1224
+ console.log(chalk.bold.hex('#9900FF')("[</>]") + chalk.bold.yellow(' => ') + "Machine Version: " + chalk.bold.red(os.version()));
1225
+ console.log(chalk.bold.hex('#9900FF')("[</>]") + chalk.bold.yellow(' => ') + "Fca Version: " + chalk.bold.red(localbrand2) + '\n');
1226
+ try {
1227
+ rl.question(Language.TypeAccount, (Account) => {
1228
+ if (!Account.includes("@") && global.Fca.Require.utils.getType(parseInt(Account)) != "Number") return logger.Normal(Language.TypeAccountError, function () { process.exit(1) }); //Very Human
1229
+ else rl.question(Language.TypePassword,async function (Password) {
1230
+ rl.close();
1231
+ try {
1232
+ await Database.set("Account", Account);
1233
+ await Database.set("Password", Password);
1234
+ }
1235
+ catch (e) {
1236
+ logger.Warning(Language.ErrDataBase);
1237
+ logger.Error();
1238
+ process.exit(0);
1239
+ }
1240
+ if (global.Fca.Require.FastConfig.ResetDataLogin) {
1241
+ global.Fca.Require.FastConfig.ResetDataLogin = false;
1242
+ global.Fca.Require.fs.writeFileSync(process.cwd() + '/FastConfigFca.json', JSON.stringify(global.Fca.Require.FastConfig, null, 4));
1243
+ }
1244
+ logger.Success(Language.SuccessSetData);
1245
+ process.exit(1);
1246
+ });
1247
+ })
1248
+ }
1249
+ catch (e) {
1250
+ logger.Error(e)
1251
+ }
1252
+ }
1253
+
1254
+ /**
1255
+ * @param {{ email: any; password: any; appState: any; }} loginData
1256
+ * @param {{}} options
1257
+ * @param {(error: any, api: any) => any} callback
1258
+ */
1259
+
1260
+ function login(loginData, options, callback) {
1261
+
1262
+ if (utils.getType(loginData) == "Array") {
1263
+ if (loginData.length == 3) {
1264
+ options = loginData[1];
1265
+ callback = loginData[2];
1266
+ loginData = loginData[0]
1267
+ }
1268
+ else if (loginData.length == 2) {
1269
+ options = loginData[1];
1270
+ loginData = loginData[0]
1271
+ }
1272
+ else {
1273
+ loginData = loginData[0]
1274
+ }
1275
+ }
1276
+
1277
+ if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
1278
+ callback = options;
1279
+ options = {};
1280
+ }
1281
+
1282
+ var globalOptions = {
1283
+ selfListen: true,
1284
+ listenEvents: true,
1285
+ listenTyping: true,
1286
+ updatePresence: false,
1287
+ forceLogin: false,
1288
+ autoMarkDelivery: true,
1289
+ autoMarkRead: true,
1290
+ autoReconnect: true,
1291
+ logRecordSize: 100,
1292
+ online: true,
1293
+ emitReady: false,
1294
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8"
1295
+ };
1296
+
1297
+ if (loginData.email && loginData.password) {
1298
+ setOptions(globalOptions, {
1299
+ logLevel: "silent",
1300
+ forceLogin: true,
1301
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36"
1302
+ });
1303
+ }
1304
+ else if (loginData.appState) {
1305
+ setOptions(globalOptions, options);
1306
+ }
1307
+
1308
+ var prCallback = null;
1309
+ if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
1310
+ var rejectFunc = null;
1311
+ var resolveFunc = null;
1312
+ var returnPromise = new Promise(function(resolve, reject) {
1313
+ resolveFunc = resolve;
1314
+ rejectFunc = reject;
1315
+ });
1316
+ prCallback = function(/** @type {any} */error, /** @type {any} */api) {
1317
+ if (error) return rejectFunc(error);
1318
+ return resolveFunc(api);
1319
+ };
1320
+ callback = prCallback;
1321
+ }
1322
+
1323
+ (async function() {
1324
+ var Premium = require("./Extra/Src/Premium");
1325
+ global.Fca.Data.PremText = await Premium(global.Fca.Require.Security.create().uuid) || "Bạn Đang Sài Phiên Bản: Free !";
1326
+ if (!loginData.email && !loginData.password) {
1327
+ switch (global.Fca.Require.FastConfig.AutoLogin) {
1328
+ case true: {
1329
+ if (global.Fca.Require.FastConfig.ResetDataLogin) return setUserNameAndPassWord();
1330
+ else {
1331
+ try {
1332
+ if (await Database.get("TempState")) {
1333
+ try {
1334
+ loginData.appState = JSON.parse(await Database.get("TempState"));
1335
+ }
1336
+ catch (_) {
1337
+ loginData.appState = await Database.get("TempState");
1338
+ }
1339
+ await Database.delete("TempState");
1340
+ }
1341
+ }
1342
+ catch (e) {
1343
+ console.log(e)
1344
+ await Database.delete("TempState");
1345
+ logger.Warning(Language.ErrDataBase);
1346
+ logger.Error();
1347
+ process.exit(0);
1348
+ }
1349
+ try {
1350
+ if (await Database.has('Account') && await Database.has('Password')) return loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
1351
+ else return setUserNameAndPassWord();
1352
+ }
1353
+ catch (e) {
1354
+ console.log(e)
1355
+ logger.Warning(Language.ErrDataBase);
1356
+ logger.Error();
1357
+ process.exit(0);
1358
+ }
1359
+ }
1360
+ }
1361
+ case false: {
1362
+ loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
1363
+ }
1364
+ }
1365
+ }
1366
+ else loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
1367
+ })()
1368
+ return returnPromise;
1369
+ }
1370
+
1371
+ module.exports = login;