@vangbanlanhat/fca-unofficial 1.4.2

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 (115) hide show
  1. package/.gitattributes +2 -0
  2. package/.github/workflows/nodejs.yml +26 -0
  3. package/.github/workflows/npmpublish.yml +30 -0
  4. package/.travis.yml +6 -0
  5. package/CHANGELOG.md +2 -0
  6. package/DOCS.md +1932 -0
  7. package/LICENSE-MIT +21 -0
  8. package/README.md +198 -0
  9. package/jest.config.js +10 -0
  10. package/package.json +86 -0
  11. package/pnpm-workspace.yaml +3 -0
  12. package/src/actions/addExternalModule.js +34 -0
  13. package/src/actions/addUserToGroup.js +113 -0
  14. package/src/actions/changeAdminStatus.js +79 -0
  15. package/src/actions/changeArchivedStatus.js +55 -0
  16. package/src/actions/changeBio.js +77 -0
  17. package/src/actions/changeBlockedStatus.js +47 -0
  18. package/src/actions/changeGroupImage.js +129 -0
  19. package/src/actions/changeNickname.js +59 -0
  20. package/src/actions/changeThreadColor.js +71 -0
  21. package/src/actions/changeThreadEmoji.js +55 -0
  22. package/src/actions/createNewGroup.js +86 -0
  23. package/src/actions/createPoll.js +71 -0
  24. package/src/actions/deleteMessage.js +56 -0
  25. package/src/actions/deleteThread.js +56 -0
  26. package/src/actions/editMessage.js +81 -0
  27. package/src/actions/forwardAttachment.js +60 -0
  28. package/src/actions/getAvatarUser.js +77 -0
  29. package/src/actions/getCurrentUserID.js +11 -0
  30. package/src/actions/getEmojiUrl.js +37 -0
  31. package/src/actions/getFriendsList.js +84 -0
  32. package/src/actions/getMessage.js +833 -0
  33. package/src/actions/getRegion.js +11 -0
  34. package/src/actions/getThreadHistory.js +702 -0
  35. package/src/actions/getThreadHistoryDeprecated.js +93 -0
  36. package/src/actions/getThreadInfo.js +265 -0
  37. package/src/actions/getThreadInfoDeprecated.js +80 -0
  38. package/src/actions/getThreadList.js +274 -0
  39. package/src/actions/getThreadListDeprecated.js +91 -0
  40. package/src/actions/getThreadPictures.js +79 -0
  41. package/src/actions/getUserID.js +66 -0
  42. package/src/actions/getUserInfo.js +92 -0
  43. package/src/actions/handleFriendRequest.js +61 -0
  44. package/src/actions/handleMessageRequest.js +65 -0
  45. package/src/actions/httpGet.js +70 -0
  46. package/src/actions/httpPost.js +70 -0
  47. package/src/actions/index.js +69 -0
  48. package/src/actions/listenMqtt.js +818 -0
  49. package/src/actions/logout.js +136 -0
  50. package/src/actions/markAsDelivered.js +58 -0
  51. package/src/actions/markAsRead.js +92 -0
  52. package/src/actions/markAsReadAll.js +50 -0
  53. package/src/actions/markAsSeen.js +59 -0
  54. package/src/actions/muteThread.js +52 -0
  55. package/src/actions/pinMessage.js +86 -0
  56. package/src/actions/refreshFb_dtsg.js +89 -0
  57. package/src/actions/removeUserFromGroup.js +79 -0
  58. package/src/actions/resolvePhotoUrl.js +45 -0
  59. package/src/actions/searchForThread.js +53 -0
  60. package/src/actions/searchStickers.js +53 -0
  61. package/src/actions/sendMessage.js +490 -0
  62. package/src/actions/sendMessageMqtt.js +235 -0
  63. package/src/actions/sendTypingIndicator.js +59 -0
  64. package/src/actions/setMessageReaction.js +140 -0
  65. package/src/actions/setMessageReactionMqtt.js +72 -0
  66. package/src/actions/setPostReaction.js +76 -0
  67. package/src/actions/setTitle.js +86 -0
  68. package/src/actions/stopListenMqtt.js +63 -0
  69. package/src/actions/threadColors.js +57 -0
  70. package/src/actions/unfriend.js +52 -0
  71. package/src/actions/unsendMessage.js +61 -0
  72. package/src/index.js +659 -0
  73. package/src/service/uploadAttachment.js +318 -0
  74. package/src/utils/base-parts/auth.js +286 -0
  75. package/src/utils/base-parts/formatters.js +751 -0
  76. package/src/utils/base-parts/identity.js +169 -0
  77. package/src/utils/base-parts/network.js +159 -0
  78. package/src/utils/base-parts/parsing.js +53 -0
  79. package/src/utils/base-parts/type.js +9 -0
  80. package/src/utils/base.js +18 -0
  81. package/src/utils/defaults.js +10 -0
  82. package/src/utils/format-attachments.js +7 -0
  83. package/src/utils/format-core.js +8 -0
  84. package/src/utils/format-events.js +11 -0
  85. package/src/utils/format-messages.js +10 -0
  86. package/src/utils/format-presence.js +9 -0
  87. package/src/utils/format-threads.js +8 -0
  88. package/src/utils/formatters.js +18 -0
  89. package/src/utils/identity.js +12 -0
  90. package/src/utils/index.js +15 -0
  91. package/src/utils/network.js +12 -0
  92. package/src/utils/parsing.js +11 -0
  93. package/src/utils.js +3 -0
  94. package/test/config.env.example +30 -0
  95. package/test/data/shareAttach.js +146 -0
  96. package/test/data/something.mov +0 -0
  97. package/test/data/test.png +0 -0
  98. package/test/data/test.txt +7 -0
  99. package/test/example-appstate.txt +11 -0
  100. package/test/integration/actions.appstate.integration.test.js +233 -0
  101. package/test/integration/api.integration.test.js +387 -0
  102. package/test/integration/env-test-config.js +46 -0
  103. package/test/integration/login.appstate.integration.test.js +47 -0
  104. package/test/integration/page.integration.test.js +139 -0
  105. package/test/jest.setup.js +54 -0
  106. package/test/unit/actions/actions.basic.test.js +116 -0
  107. package/test/unit/actions/actions.registry.test.js +36 -0
  108. package/test/unit/index/index.test.js +109 -0
  109. package/test/unit/utils/base-parts/auth.test.js +92 -0
  110. package/test/unit/utils/base-parts/formatters.test.js +53 -0
  111. package/test/unit/utils/base-parts/identity.test.js +43 -0
  112. package/test/unit/utils/base-parts/parsing.test.js +38 -0
  113. package/test/unit/utils/base-parts/type.test.js +23 -0
  114. package/test/unit/utils/base.test.js +35 -0
  115. package/vangbanlanhat-fca-unofficial-1.4.2.tgz +0 -0
package/src/index.js ADDED
@@ -0,0 +1,659 @@
1
+ "use strict";
2
+
3
+ var utils = require("./utils");
4
+ var cheerio = require("cheerio");
5
+ var log = require("npmlog");
6
+ var actions = require("./actions");
7
+
8
+ var checkVerified = null;
9
+
10
+ var defaultLogRecordSize = 100;
11
+ log.maxRecordSize = defaultLogRecordSize;
12
+
13
+ function normalizeAppState(appState) {
14
+ if (utils.getType(appState) === "String") {
15
+ return appState
16
+ .split(";")
17
+ .map(function (cookie) {
18
+ var kv = cookie.split("=");
19
+ var key = (kv[0] || "").trim();
20
+ var value = (kv[1] || "").trim();
21
+ if (!key) return null;
22
+ return {
23
+ key: key,
24
+ value: value,
25
+ domain: ".facebook.com",
26
+ path: "/",
27
+ expires: Date.now() + 1000 * 60 * 60 * 24 * 365
28
+ };
29
+ })
30
+ .filter(Boolean);
31
+ }
32
+
33
+ if (utils.getType(appState) === "Array") {
34
+ return appState.map(function (cookie) {
35
+ var c = Object.assign({}, cookie);
36
+ if (!c.key && c.name) c.key = c.name;
37
+ if (!c.domain) c.domain = ".facebook.com";
38
+ if (!c.path) c.path = "/";
39
+ return c;
40
+ });
41
+ }
42
+
43
+ return appState;
44
+ }
45
+
46
+ function getRegionFromEndpoint(mqttEndpoint) {
47
+ if (!mqttEndpoint) return null;
48
+ try {
49
+ var region = new URL(mqttEndpoint).searchParams.get("region");
50
+ return region ? region.toUpperCase() : null;
51
+ } catch (_) {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ function setOptions(globalOptions, options) {
57
+ Object.keys(options).map(function (key) {
58
+ switch (key) {
59
+ case 'online':
60
+ globalOptions.online = Boolean(options.online);
61
+ break;
62
+ case 'logLevel':
63
+ log.level = options.logLevel;
64
+ globalOptions.logLevel = options.logLevel;
65
+ break;
66
+ case 'logRecordSize':
67
+ log.maxRecordSize = options.logRecordSize;
68
+ globalOptions.logRecordSize = options.logRecordSize;
69
+ break;
70
+ case 'selfListen':
71
+ globalOptions.selfListen = Boolean(options.selfListen);
72
+ break;
73
+ case 'listenEvents':
74
+ globalOptions.listenEvents = Boolean(options.listenEvents);
75
+ break;
76
+ case 'pageID':
77
+ globalOptions.pageID = options.pageID.toString();
78
+ break;
79
+ case 'updatePresence':
80
+ globalOptions.updatePresence = Boolean(options.updatePresence);
81
+ break;
82
+ case 'forceLogin':
83
+ globalOptions.forceLogin = Boolean(options.forceLogin);
84
+ break;
85
+ case 'userAgent':
86
+ globalOptions.userAgent = options.userAgent;
87
+ break;
88
+ case 'autoMarkDelivery':
89
+ globalOptions.autoMarkDelivery = Boolean(options.autoMarkDelivery);
90
+ break;
91
+ case 'autoMarkRead':
92
+ globalOptions.autoMarkRead = Boolean(options.autoMarkRead);
93
+ break;
94
+ case 'listenTyping':
95
+ globalOptions.listenTyping = Boolean(options.listenTyping);
96
+ break;
97
+ case 'proxy':
98
+ if (typeof options.proxy != "string") {
99
+ delete globalOptions.proxy;
100
+ utils.setProxy();
101
+ } else {
102
+ globalOptions.proxy = options.proxy;
103
+ utils.setProxy(globalOptions.proxy);
104
+ }
105
+ break;
106
+ case 'autoReconnect':
107
+ globalOptions.autoReconnect = Boolean(options.autoReconnect);
108
+ break;
109
+ case 'emitReady':
110
+ globalOptions.emitReady = Boolean(options.emitReady);
111
+ break;
112
+
113
+ default:
114
+ log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
115
+ break;
116
+ }
117
+ });
118
+ }
119
+
120
+ function buildAPI(globalOptions, html, jar) {
121
+ var fbDtsgMatch = html.match(/DTSGInitialData.*?token":"(.*?)"/);
122
+ var initialFbDtsg = fbDtsgMatch ? fbDtsgMatch[1] : null;
123
+ var lsdMatch = html.match(/\["LSD",\[\],\{"token":"(.*?)"\}/);
124
+ var initialLsd = lsdMatch ? lsdMatch[1] : null;
125
+ var initialTtstamp = null;
126
+ if (initialFbDtsg) {
127
+ initialTtstamp = "2";
128
+ for (var idx = 0; idx < initialFbDtsg.length; idx++) {
129
+ initialTtstamp += initialFbDtsg.charCodeAt(idx);
130
+ }
131
+ }
132
+
133
+ var maybeCookie = jar.getCookies("https://www.facebook.com").filter(function (val) {
134
+ return val.cookieString().split("=")[0] === "c_user";
135
+ });
136
+
137
+ if (maybeCookie.length === 0) {
138
+ maybeCookie = jar.getCookies("https://www.facebook.com").filter(function (val) {
139
+ return val.cookieString().split("=")[0] === "i_user";
140
+ });
141
+ }
142
+
143
+ if (maybeCookie.length === 0) {
144
+ throw { error: "Error retrieving userID. This can be caused by a lot of things, including getting blocked by Facebook for logging in from an unknown location. Try logging in with a browser to verify." };
145
+ }
146
+
147
+ if (html.indexOf("/checkpoint/block/?next") > -1) {
148
+ log.warn("login", "Checkpoint detected. Please log in with a browser to verify.");
149
+ }
150
+
151
+ var userID = maybeCookie[0].cookieString().split("=")[1].toString();
152
+ log.info("login", `Logged in as ${userID}`);
153
+
154
+ try {
155
+ clearInterval(checkVerified);
156
+ } catch (_) { }
157
+
158
+ var clientID = (Math.random() * 2147483648 | 0).toString(16);
159
+
160
+
161
+ let oldFBMQTTMatch = html.match(/irisSeqID:"(.+?)",appID:219994525426954,endpoint:"(.+?)"/);
162
+ let mqttEndpoint = null;
163
+ let region = null;
164
+ let irisSeqID = null;
165
+ var noMqttData = null;
166
+
167
+ if (oldFBMQTTMatch) {
168
+ irisSeqID = oldFBMQTTMatch[1];
169
+ mqttEndpoint = oldFBMQTTMatch[2];
170
+ region = getRegionFromEndpoint(mqttEndpoint);
171
+ if (region) {
172
+ log.info("login", `Got this account's message region: ${region}`);
173
+ }
174
+ } else {
175
+ let newFBMQTTMatch = html.match(/{"app_id":"219994525426954","endpoint":"(.+?)","iris_seq_id":"(.+?)"}/);
176
+ if (newFBMQTTMatch) {
177
+ irisSeqID = newFBMQTTMatch[2];
178
+ mqttEndpoint = newFBMQTTMatch[1].replace(/\\\//g, "/");
179
+ region = getRegionFromEndpoint(mqttEndpoint);
180
+ if (region) {
181
+ log.info("login", `Got this account's message region: ${region}`);
182
+ }
183
+ } else {
184
+ let legacyFBMQTTMatch = html.match(/(\["MqttWebConfig",\[\],{fbid:")(.+?)(",appID:219994525426954,endpoint:")(.+?)(",pollingEndpoint:")(.+?)(3790])/);
185
+ if (legacyFBMQTTMatch) {
186
+ mqttEndpoint = legacyFBMQTTMatch[4];
187
+ region = getRegionFromEndpoint(mqttEndpoint);
188
+ log.warn("login", `Cannot get sequence ID with new RegExp. Fallback to old RegExp (without seqID)...`);
189
+ if (region) {
190
+ log.info("login", `Got this account's message region: ${region}`);
191
+ }
192
+ log.info("login", `[Unused] Polling endpoint: ${legacyFBMQTTMatch[6]}`);
193
+ } else {
194
+ log.warn("login", "Cannot get MQTT region & sequence ID.");
195
+ noMqttData = html;
196
+ }
197
+ }
198
+ }
199
+
200
+ // All data available to api functions
201
+ var ctx = {
202
+ userID: userID,
203
+ jar: jar,
204
+ clientID: clientID,
205
+ globalOptions: globalOptions,
206
+ loggedIn: true,
207
+ access_token: 'NONE',
208
+ clientMutationId: 0,
209
+ mqttClient: undefined,
210
+ lastSeqId: irisSeqID,
211
+ syncToken: undefined,
212
+ mqttEndpoint,
213
+ region,
214
+ firstListen: true,
215
+ wsReqNumber: 0,
216
+ wsTaskNumber: 0,
217
+ fb_dtsg: initialFbDtsg,
218
+ ttstamp: initialTtstamp,
219
+ lsd: initialLsd,
220
+
221
+ };
222
+
223
+ var api = {
224
+ setOptions: setOptions.bind(null, globalOptions),
225
+ getAppState: function getAppState() {
226
+ return utils.getAppState(jar);
227
+ },
228
+ isFullyReady: function isFullyReady() {
229
+ return !!(ctx.mqttClient && ctx.mqttClient.connected);
230
+ }
231
+ };
232
+
233
+ if (noMqttData) {
234
+ api["htmlData"] = noMqttData;
235
+ }
236
+
237
+ var apiFuncNames = Object.keys(actions);
238
+
239
+ var defaultFuncs = utils.makeDefaults(html, userID, ctx);
240
+
241
+ // Load all api functions in a loop
242
+ apiFuncNames.map(function (v) {
243
+ api[v] = actions[v](defaultFuncs, api, ctx);
244
+ });
245
+
246
+ //Removing original `listen` that uses pull.
247
+ //Map it to listenMqtt instead for backward compatibly.
248
+ api.listen = api.listenMqtt;
249
+ if (typeof api.sendMessageMqtt !== "function") {
250
+ api.sendMessageMqtt = api.sendMessage;
251
+ }
252
+ if (typeof api.setMessageReactionMqtt !== "function") {
253
+ api.setMessageReactionMqtt = api.setMessageReaction;
254
+ }
255
+ // Keep fb_dtsg/jazoest fresh to reduce long-session send failures.
256
+ if (ctx.refreshDtsgTimer) {
257
+ clearInterval(ctx.refreshDtsgTimer);
258
+ }
259
+ if (typeof api.refreshFb_dtsg === "function") {
260
+ ctx.refreshDtsgTimer = setInterval(function () {
261
+ api.refreshFb_dtsg(function () {});
262
+ }, 2 * 60 * 60 * 1000);
263
+ if (ctx.refreshDtsgTimer && typeof ctx.refreshDtsgTimer.unref === "function") {
264
+ ctx.refreshDtsgTimer.unref();
265
+ }
266
+ }
267
+
268
+ return [ctx, defaultFuncs, api];
269
+ }
270
+
271
+ function makeLogin(jar, email, password, loginOptions, callback, prCallback) {
272
+ return function (res) {
273
+ var html = res.body;
274
+ var $ = cheerio.load(html);
275
+ var arr = [];
276
+
277
+ // This will be empty, but just to be sure we leave it
278
+ $("#login_form input").map(function (i, v) {
279
+ arr.push({ val: $(v).val(), name: $(v).attr("name") });
280
+ });
281
+
282
+ arr = arr.filter(function (v) {
283
+ return v.val && v.val.length;
284
+ });
285
+
286
+ var form = utils.arrToForm(arr);
287
+ form.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
288
+ form.lgndim = Buffer.from("{\"w\":1440,\"h\":900,\"aw\":1440,\"ah\":834,\"c\":24}").toString('base64');
289
+ form.email = email;
290
+ form.pass = password;
291
+ form.default_persistent = '0';
292
+ form.lgnrnd = utils.getFrom(html, "name=\"lgnrnd\" value=\"", "\"");
293
+ form.locale = 'en_US';
294
+ form.timezone = '240';
295
+ form.lgnjs = ~~(Date.now() / 1000);
296
+
297
+
298
+ // Getting cookies from the HTML page... (kill me now plz)
299
+ // we used to get a bunch of cookies in the headers of the response of the
300
+ // request, but FB changed and they now send those cookies inside the JS.
301
+ // They run the JS which then injects the cookies in the page.
302
+ // The "solution" is to parse through the html and find those cookies
303
+ // which happen to be conveniently indicated with a _js_ in front of their
304
+ // variable name.
305
+ //
306
+ // ---------- Very Hacky Part Starts -----------------
307
+ var willBeCookies = html.split("\"_js_");
308
+ willBeCookies.slice(1).map(function (val) {
309
+ var cookieData = JSON.parse("[\"" + utils.getFrom(val, "", "]") + "]");
310
+ jar.setCookie(utils.formatCookie(cookieData, "facebook"), "https://www.facebook.com");
311
+ });
312
+ // ---------- Very Hacky Part Ends -----------------
313
+
314
+ log.info("login", "Logging in...");
315
+ return utils
316
+ .post("https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110", jar, form, loginOptions)
317
+ .then(utils.saveCookies(jar))
318
+ .then(function (res) {
319
+ var headers = res.headers;
320
+ if (!headers.location) {
321
+ throw { error: "Wrong username/password." };
322
+ }
323
+
324
+ // This means the account has login approvals turned on.
325
+ if (headers.location.indexOf('https://www.facebook.com/checkpoint/') > -1) {
326
+ log.info("login", "You have login approvals turned on.");
327
+ var nextURL = 'https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php';
328
+
329
+ return utils
330
+ .get(headers.location, jar, null, loginOptions)
331
+ .then(utils.saveCookies(jar))
332
+ .then(function (res) {
333
+ var html = res.body;
334
+ // Make the form in advance which will contain the fb_dtsg and nh
335
+ var $ = cheerio.load(html);
336
+ var arr = [];
337
+ $("form input").map(function (i, v) {
338
+ arr.push({ val: $(v).val(), name: $(v).attr("name") });
339
+ });
340
+
341
+ arr = arr.filter(function (v) {
342
+ return v.val && v.val.length;
343
+ });
344
+
345
+ var form = utils.arrToForm(arr);
346
+ if (html.indexOf("checkpoint/?next") > -1) {
347
+ setTimeout(() => {
348
+ checkVerified = setInterval((_form) => {
349
+ /* utils
350
+ .post("https://www.facebook.com/login/approvals/approved_machine_check/", jar, form, loginOptions, null, {
351
+ "Referer": "https://www.facebook.com/checkpoint/?next"
352
+ })
353
+ .then(utils.saveCookies(jar))
354
+ .then(res => {
355
+ try {
356
+ JSON.parse(res.body.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*()/, ""));
357
+ } catch (ex) {
358
+ clearInterval(checkVerified);
359
+ log.info("login", "Verified from browser. Logging in...");
360
+ return loginHelper(utils.getAppState(jar), email, password, loginOptions, callback);
361
+ }
362
+ })
363
+ .catch(ex => {
364
+ log.error("login", ex);
365
+ }); */
366
+ }, 5000, {
367
+ fb_dtsg: form.fb_dtsg,
368
+ jazoest: form.jazoest,
369
+ dpr: 1
370
+ });
371
+ }, 2500);
372
+ throw {
373
+ error: 'login-approval',
374
+ continue: function submit2FA(code) {
375
+ form.approvals_code = code;
376
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html(); //'Continue';
377
+ var prResolve = null;
378
+ var prReject = null;
379
+ var rtPromise = new Promise(function (resolve, reject) {
380
+ prResolve = resolve;
381
+ prReject = reject;
382
+ });
383
+ if (typeof code == "string") {
384
+ utils
385
+ .post(nextURL, jar, form, loginOptions)
386
+ .then(utils.saveCookies(jar))
387
+ .then(function (res) {
388
+ var $ = cheerio.load(res.body);
389
+ var error = $("#approvals_code").parent().attr("data-xui-error");
390
+ if (error) {
391
+ throw {
392
+ error: 'login-approval',
393
+ errordesc: "Invalid 2FA code.",
394
+ lerror: error,
395
+ continue: submit2FA
396
+ };
397
+ }
398
+ })
399
+ .then(function () {
400
+ // Use the same form (safe I hope)
401
+ delete form.no_fido;
402
+ delete form.approvals_code;
403
+ form.name_action_selected = 'dont_save'; //'save_device';
404
+
405
+ return utils
406
+ .post(nextURL, jar, form, loginOptions)
407
+ .then(utils.saveCookies(jar));
408
+ })
409
+ .then(function (res) {
410
+ var headers = res.headers;
411
+ if (!headers.location && res.body.indexOf('Review Recent Login') > -1) {
412
+ throw { error: "Something went wrong with login approvals." };
413
+ }
414
+
415
+ var appState = utils.getAppState(jar);
416
+
417
+ if (callback === prCallback) {
418
+ callback = function (err, api) {
419
+ if (err) {
420
+ return prReject(err);
421
+ }
422
+ return prResolve(api);
423
+ };
424
+ }
425
+
426
+ // Simply call loginHelper because all it needs is the jar
427
+ // and will then complete the login process
428
+ return loginHelper(appState, email, password, loginOptions, callback);
429
+ })
430
+ .catch(function (err) {
431
+ // Check if using Promise instead of callback
432
+ if (callback === prCallback) {
433
+ prReject(err);
434
+ } else {
435
+ callback(err);
436
+ }
437
+ });
438
+ } else {
439
+ utils
440
+ .post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions, null, {
441
+ "Referer": "https://www.facebook.com/checkpoint/?next"
442
+ })
443
+ .then(utils.saveCookies(jar))
444
+ .then(res => {
445
+ try {
446
+ JSON.parse(res.body.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, ""));
447
+ } catch (ex) {
448
+ clearInterval(checkVerified);
449
+ log.info("login", "Verified from browser. Logging in...");
450
+ if (callback === prCallback) {
451
+ callback = function (err, api) {
452
+ if (err) {
453
+ return prReject(err);
454
+ }
455
+ return prResolve(api);
456
+ };
457
+ }
458
+ return loginHelper(utils.getAppState(jar), email, password, loginOptions, callback);
459
+ }
460
+ })
461
+ .catch(ex => {
462
+ log.error("login", ex);
463
+ if (callback === prCallback) {
464
+ prReject(ex);
465
+ } else {
466
+ callback(ex);
467
+ }
468
+ });
469
+ }
470
+ return rtPromise;
471
+ }
472
+ };
473
+ } else {
474
+ if (!loginOptions.forceLogin) {
475
+ throw { error: "Couldn't login. Facebook might have blocked this account. Please login with a browser or enable the option 'forceLogin' and try again." };
476
+ }
477
+ if (html.indexOf("Suspicious Login Attempt") > -1) {
478
+ form['submit[This was me]'] = "This was me";
479
+ } else {
480
+ form['submit[This Is Okay]'] = "This Is Okay";
481
+ }
482
+
483
+ return utils
484
+ .post(nextURL, jar, form, loginOptions)
485
+ .then(utils.saveCookies(jar))
486
+ .then(function () {
487
+ // Use the same form (safe I hope)
488
+ form.name_action_selected = 'save_device';
489
+
490
+ return utils
491
+ .post(nextURL, jar, form, loginOptions)
492
+ .then(utils.saveCookies(jar));
493
+ })
494
+ .then(function (res) {
495
+ var headers = res.headers;
496
+
497
+ if (!headers.location && res.body.indexOf('Review Recent Login') > -1) {
498
+ throw { error: "Something went wrong with review recent login." };
499
+ }
500
+
501
+ var appState = utils.getAppState(jar);
502
+
503
+ // Simply call loginHelper because all it needs is the jar
504
+ // and will then complete the login process
505
+ return loginHelper(appState, email, password, loginOptions, callback);
506
+ })
507
+ .catch(function (e) {
508
+ callback(e);
509
+ });
510
+ }
511
+ });
512
+ }
513
+
514
+ return utils
515
+ .get('https://www.facebook.com/', jar, null, loginOptions)
516
+ .then(utils.saveCookies(jar));
517
+ });
518
+ };
519
+ }
520
+
521
+ // Helps the login
522
+ function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
523
+ var mainPromise = null;
524
+ var jar = utils.getJar();
525
+
526
+ // If we're given an appState we loop through it and save each cookie
527
+ // back into the jar.
528
+ if (appState) {
529
+ appState = normalizeAppState(appState);
530
+
531
+ appState.map(function (c) {
532
+ if (!c || !c.key) return;
533
+ var str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";";
534
+ jar.setCookie(str, "http://" + c.domain);
535
+ });
536
+
537
+ // Load the main page.
538
+ mainPromise = utils
539
+ .get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true })
540
+ .then(utils.saveCookies(jar));
541
+ } else {
542
+ // Open the main page, then we login with the given credentials and finally
543
+ // load the main page again (it'll give us some IDs that we need)
544
+ mainPromise = utils
545
+ .get("https://www.facebook.com/", null, null, globalOptions, { noRef: true })
546
+ .then(utils.saveCookies(jar))
547
+ .then(makeLogin(jar, email, password, globalOptions, callback, prCallback))
548
+ .then(function () {
549
+ return utils
550
+ .get('https://www.facebook.com/', jar, null, globalOptions)
551
+ .then(utils.saveCookies(jar));
552
+ });
553
+ }
554
+
555
+ var ctx = null;
556
+ var _defaultFuncs = null;
557
+ var api = null;
558
+
559
+ mainPromise = mainPromise
560
+ .then(function (res) {
561
+ // Hacky check for the redirection that happens on some ISPs, which doesn't return statusCode 3xx
562
+ var reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
563
+ var redirect = reg.exec(res.body);
564
+ if (redirect && redirect[1]) {
565
+ return utils
566
+ .get(redirect[1], jar, null, globalOptions)
567
+ .then(utils.saveCookies(jar));
568
+ }
569
+ return res;
570
+ })
571
+ .then(function () {
572
+ // ws3 flow stabilizes appstate sessions by loading /home.php before building API.
573
+ return utils
574
+ .get("https://www.facebook.com/home.php", jar, null, globalOptions)
575
+ .then(utils.saveCookies(jar));
576
+ })
577
+ .then(function (res) {
578
+ var html = res.body;
579
+ var stuff = buildAPI(globalOptions, html, jar);
580
+ ctx = stuff[0];
581
+ _defaultFuncs = stuff[1];
582
+ api = stuff[2];
583
+ return res;
584
+ });
585
+
586
+ // given a pageID we log in as a page
587
+ if (globalOptions.pageID) {
588
+ mainPromise = mainPromise
589
+ .then(function () {
590
+ return utils
591
+ .get('https://www.facebook.com/' + ctx.globalOptions.pageID + '/messages/?section=messages&subsection=inbox', ctx.jar, null, globalOptions);
592
+ })
593
+ .then(function (resData) {
594
+ var url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
595
+ url = url.substring(0, url.length - 1);
596
+
597
+ return utils
598
+ .get('https://www.facebook.com' + url, ctx.jar, null, globalOptions);
599
+ });
600
+ }
601
+
602
+ // At the end we call the callback or catch an exception
603
+ mainPromise
604
+ .then(function () {
605
+ log.info("login", 'Done logging in.');
606
+ return callback(null, api);
607
+ })
608
+ .catch(function (e) {
609
+ log.error("login", e.error || e);
610
+ callback(e);
611
+ });
612
+ }
613
+
614
+ function login(loginData, options, callback) {
615
+ if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
616
+ callback = options;
617
+ options = {};
618
+ }
619
+
620
+ var globalOptions = {
621
+ selfListen: false,
622
+ listenEvents: false,
623
+ listenTyping: false,
624
+ updatePresence: false,
625
+ forceLogin: false,
626
+ autoMarkDelivery: true,
627
+ autoMarkRead: false,
628
+ autoReconnect: true,
629
+
630
+ logRecordSize: defaultLogRecordSize,
631
+ online: true,
632
+ emitReady: false,
633
+ userAgent: "facebookexternalhit/1.1"
634
+ };
635
+
636
+ setOptions(globalOptions, options);
637
+
638
+ var prCallback = null;
639
+ if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
640
+ var rejectFunc = null;
641
+ var resolveFunc = null;
642
+ var returnPromise = new Promise(function (resolve, reject) {
643
+ resolveFunc = resolve;
644
+ rejectFunc = reject;
645
+ });
646
+ prCallback = function (error, api) {
647
+ if (error) {
648
+ return rejectFunc(error);
649
+ }
650
+ return resolveFunc(api);
651
+ };
652
+ callback = prCallback;
653
+ }
654
+ loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
655
+ return returnPromise;
656
+ }
657
+
658
+ module.exports = login;
659
+