fca-kenlie-plays 0.0.1-security → 1.0.1

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

Potentially problematic release.


This version of fca-kenlie-plays might be problematic. Click here for more details.

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