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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import * as utils from "./utils";
|
2 |
+
import * as fs from "fs";
|
3 |
+
import cron from "node-cron";
|
4 |
+
import logger from "./logger";
|
5 |
+
import { CookieJar } from "tough-cookie";
|
6 |
+
|
7 |
+
interface GlobalOptions {
|
8 |
+
online: boolean;
|
9 |
+
selfListen: boolean;
|
10 |
+
selfListenEvent: boolean;
|
11 |
+
listenEvents: boolean;
|
12 |
+
pageID?: string;
|
13 |
+
updatePresence: boolean;
|
14 |
+
forceLogin: boolean;
|
15 |
+
userAgent?: string;
|
16 |
+
autoMarkDelivery: boolean;
|
17 |
+
autoMarkRead: boolean;
|
18 |
+
listenTyping: boolean;
|
19 |
+
proxy?: string;
|
20 |
+
autoReconnect: boolean;
|
21 |
+
emitReady: boolean;
|
22 |
+
randomUserAgent: boolean;
|
23 |
+
bypassRegion?: string;
|
24 |
+
FCAOption?: any;
|
25 |
+
}
|
26 |
+
|
27 |
+
interface Context {
|
28 |
+
userID: string;
|
29 |
+
jar: CookieJar;
|
30 |
+
clientID: string;
|
31 |
+
globalOptions: GlobalOptions;
|
32 |
+
loggedIn: boolean;
|
33 |
+
access_token: string;
|
34 |
+
clientMutationId: number;
|
35 |
+
mqttClient: any;
|
36 |
+
lastSeqId?: string;
|
37 |
+
syncToken?: string;
|
38 |
+
mqttEndpoint: string;
|
39 |
+
wsReqNumber: number;
|
40 |
+
wsTaskNumber: number;
|
41 |
+
reqCallbacks: {};
|
42 |
+
region: string;
|
43 |
+
firstListen: boolean;
|
44 |
+
fb_dtsg?: string;
|
45 |
+
userName?: string;
|
46 |
+
}
|
47 |
+
|
48 |
+
let globalOptions: GlobalOptions = {
|
49 |
+
selfListen: false,
|
50 |
+
selfListenEvent: false,
|
51 |
+
listenEvents: true,
|
52 |
+
listenTyping: false,
|
53 |
+
updatePresence: false,
|
54 |
+
forceLogin: false,
|
55 |
+
autoMarkDelivery: false,
|
56 |
+
autoMarkRead: false,
|
57 |
+
autoReconnect: true,
|
58 |
+
online: true,
|
59 |
+
emitReady: false,
|
60 |
+
randomUserAgent: false,
|
61 |
+
};
|
62 |
+
let ctx: Context | null = null;
|
63 |
+
let _defaultFuncs: any = null;
|
64 |
+
let api: any = null;
|
65 |
+
let region: string | undefined;
|
66 |
+
|
67 |
+
const errorRetrieving = "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.";
|
68 |
+
|
69 |
+
export async function setOptions(options: Partial<GlobalOptions>) {
|
70 |
+
Object.keys(options).map((key) => {
|
71 |
+
switch (key) {
|
72 |
+
case 'online':
|
73 |
+
globalOptions.online = Boolean((options as any).online);
|
74 |
+
break;
|
75 |
+
case 'selfListen':
|
76 |
+
globalOptions.selfListen = Boolean((options as any).selfListen);
|
77 |
+
break;
|
78 |
+
case 'selfListenEvent':
|
79 |
+
globalOptions.selfListenEvent = (options as any).selfListenEvent;
|
80 |
+
break;
|
81 |
+
case 'listenEvents':
|
82 |
+
globalOptions.listenEvents = Boolean((options as any).listenEvents);
|
83 |
+
break;
|
84 |
+
case 'pageID':
|
85 |
+
globalOptions.pageID = String((options as any).pageID);
|
86 |
+
break;
|
87 |
+
case 'updatePresence':
|
88 |
+
globalOptions.updatePresence = Boolean((options as any).updatePresence);
|
89 |
+
break;
|
90 |
+
case 'forceLogin':
|
91 |
+
globalOptions.forceLogin = Boolean((options as any).forceLogin);
|
92 |
+
break;
|
93 |
+
case 'userAgent':
|
94 |
+
globalOptions.userAgent = (options as any).userAgent;
|
95 |
+
break;
|
96 |
+
case 'autoMarkDelivery':
|
97 |
+
globalOptions.autoMarkDelivery = Boolean((options as any).autoMarkDelivery);
|
98 |
+
break;
|
99 |
+
case 'autoMarkRead':
|
100 |
+
globalOptions.autoMarkRead = Boolean((options as any).autoMarkRead);
|
101 |
+
break;
|
102 |
+
case 'listenTyping':
|
103 |
+
globalOptions.listenTyping = Boolean((options as any).listenTyping);
|
104 |
+
break;
|
105 |
+
case 'proxy':
|
106 |
+
if (typeof (options as any).proxy !== "string") {
|
107 |
+
delete globalOptions.proxy;
|
108 |
+
utils.setProxy();
|
109 |
+
} else {
|
110 |
+
globalOptions.proxy = (options as any).proxy;
|
111 |
+
utils.setProxy(globalOptions.proxy);
|
112 |
+
}
|
113 |
+
break;
|
114 |
+
case 'autoReconnect':
|
115 |
+
globalOptions.autoReconnect = Boolean((options as any).autoReconnect);
|
116 |
+
break;
|
117 |
+
case 'emitReady':
|
118 |
+
globalOptions.emitReady = Boolean((options as any).emitReady);
|
119 |
+
break;
|
120 |
+
case 'randomUserAgent':
|
121 |
+
globalOptions.randomUserAgent = Boolean((options as any).randomUserAgent);
|
122 |
+
if (globalOptions.randomUserAgent) {
|
123 |
+
globalOptions.userAgent = utils.randomUserAgent();
|
124 |
+
console.warn("login", "Random user agent enabled. This is an EXPERIMENTAL feature and I think this won't on some accounts. turn it on at your own risk. Contact the owner for more information about experimental features.");
|
125 |
+
console.warn("randomUserAgent", "UA selected:", globalOptions.userAgent);
|
126 |
+
}
|
127 |
+
break;
|
128 |
+
case 'bypassRegion':
|
129 |
+
globalOptions.bypassRegion = (options as any).bypassRegion;
|
130 |
+
break;
|
131 |
+
default:
|
132 |
+
break;
|
133 |
+
}
|
134 |
+
});
|
135 |
+
}
|
136 |
+
|
137 |
+
async function updateDTSG(res: any, appstate: any[], userId?: string) {
|
138 |
+
try {
|
139 |
+
const appstateCUser = (appstate.find(i => i.key === 'i_user') || appstate.find(i => i.key === 'c_user'));
|
140 |
+
const UID = userId || appstateCUser?.value;
|
141 |
+
if (!res || !res.body) {
|
142 |
+
throw new Error("Invalid response: Response body is missing.");
|
143 |
+
}
|
144 |
+
const fb_dtsg = utils.getFrom(res.body, '["DTSGInitData",[],{"token":"', '","');
|
145 |
+
const jazoest = utils.getFrom(res.body, 'jazoest=', '",');
|
146 |
+
if (fb_dtsg && jazoest) {
|
147 |
+
const filePath = 'fb_dtsg_data.json';
|
148 |
+
let existingData: { [key: string]: { fb_dtsg: string; jazoest: string } } = {};
|
149 |
+
if (fs.existsSync(filePath)) {
|
150 |
+
const fileContent = fs.readFileSync(filePath, 'utf8');
|
151 |
+
existingData = JSON.parse(fileContent);
|
152 |
+
}
|
153 |
+
if (UID) {
|
154 |
+
existingData[UID] = {
|
155 |
+
fb_dtsg,
|
156 |
+
jazoest
|
157 |
+
};
|
158 |
+
fs.writeFileSync(filePath, JSON.stringify(existingData, null, 2), 'utf8');
|
159 |
+
}
|
160 |
+
}
|
161 |
+
return res;
|
162 |
+
} catch (error: any) {
|
163 |
+
logger(`Error during update fb_dtsg for account ${userId} : ${error.message}`, 'error');
|
164 |
+
return;
|
165 |
+
}
|
166 |
+
}
|
167 |
+
|
168 |
+
let isBehavior = false;
|
169 |
+
async function bypassAutoBehavior(resp: any, jar: CookieJar, appstate: any[], ID?: string) {
|
170 |
+
try {
|
171 |
+
const appstateCUser = (appstate.find(i => i.key === 'c_user') || appstate.find(i => i.key === 'i_user'));
|
172 |
+
const UID = ID || appstateCUser?.value;
|
173 |
+
const FormBypass = {
|
174 |
+
av: UID,
|
175 |
+
fb_api_caller_class: "RelayModern",
|
176 |
+
fb_api_req_friendly_name: "FBScrapingWarningMutation",
|
177 |
+
variables: JSON.stringify({}),
|
178 |
+
server_timestamps: true,
|
179 |
+
doc_id: 6339492849481770
|
180 |
+
};
|
181 |
+
const kupal = () => {
|
182 |
+
logger(`Suspect automatic behavoir on account ${UID}.`, 'warn');
|
183 |
+
if (!isBehavior) isBehavior = true;
|
184 |
+
};
|
185 |
+
if (resp) {
|
186 |
+
if (resp.request.uri && resp.request.uri.href.includes("https://www.facebook.com/checkpoint/")) {
|
187 |
+
if (resp.request.uri.href.includes('601051028565049')) {
|
188 |
+
const fb_dtsg = utils.getFrom(resp.body, '["DTSGInitData",[],{"token":"', '","');
|
189 |
+
const jazoest = utils.getFrom(resp.body, 'jazoest=', '",');
|
190 |
+
const lsd = utils.getFrom(resp.body, "[\"LSD\",[],{\"token\":\"", "\"}");
|
191 |
+
return utils.post("https://www.facebook.com/api/graphql/", jar, {
|
192 |
+
...FormBypass,
|
193 |
+
fb_dtsg,
|
194 |
+
jazoest,
|
195 |
+
lsd
|
196 |
+
}, globalOptions).then(utils.saveCookies(jar)).then((res: any) => {
|
197 |
+
kupal();
|
198 |
+
return res;
|
199 |
+
});
|
200 |
+
} else return resp;
|
201 |
+
} else return resp;
|
202 |
+
}
|
203 |
+
} catch (e: any) {
|
204 |
+
logger("error" + e, 'error');
|
205 |
+
}
|
206 |
+
}
|
207 |
+
|
208 |
+
async function checkIfSuspended(resp: any, appstate: any[]) {
|
209 |
+
try {
|
210 |
+
const appstateCUser = (appstate.find(i => i.key === 'c_user') || appstate.find(i => i.key === 'i_user'));
|
211 |
+
const UID = appstateCUser?.value;
|
212 |
+
if (resp) {
|
213 |
+
if (resp.request.uri && resp.request.uri.href.includes("https://www.facebook.com/checkpoint/")) {
|
214 |
+
if (resp.request.uri.href.includes('1501092823525282')) {
|
215 |
+
logger(`Alert on ${UID}: ` + `Your account has been suspended, error code is 282!`, 'error');
|
216 |
+
}
|
217 |
+
|
218 |
+
ctx = null;
|
219 |
+
return {
|
220 |
+
suspended: true
|
221 |
+
};
|
222 |
+
}
|
223 |
+
} else return;
|
224 |
+
} catch (error) {
|
225 |
+
return;
|
226 |
+
}
|
227 |
+
}
|
228 |
+
|
229 |
+
async function checkIfLocked(resp: any, appstate: any[]) {
|
230 |
+
try {
|
231 |
+
const appstateCUser = (appstate.find(i => i.key === 'c_user') || appstate.find(i => i.key === 'i_user'));
|
232 |
+
const UID = appstateCUser?.value;
|
233 |
+
if (resp) {
|
234 |
+
if (resp.request.uri && resp.request.uri.href.includes("https://www.facebook.com/checkpoint/")) {
|
235 |
+
if (resp.request.uri.href.includes('828281030927956')) {
|
236 |
+
logger(`Alert on ${UID}: ` + `Your account has been suspended, error code is 956!`, 'error');
|
237 |
+
ctx = null;
|
238 |
+
return {
|
239 |
+
locked: true
|
240 |
+
};
|
241 |
+
}
|
242 |
+
} else return;
|
243 |
+
}
|
244 |
+
} catch (e) {
|
245 |
+
console.error("error", e);
|
246 |
+
}
|
247 |
+
}
|
248 |
+
|
249 |
+
function buildAPI(html: string, jar: CookieJar) {
|
250 |
+
let fb_dtsg: string | undefined;
|
251 |
+
let userID: string;
|
252 |
+
const tokenMatch = html.match(/DTSGInitialData.*?token":"(.*?)"/);
|
253 |
+
if (tokenMatch) {
|
254 |
+
fb_dtsg = tokenMatch[1];
|
255 |
+
}
|
256 |
+
let cookie = jar.getCookies("https://www.facebook.com");
|
257 |
+
let primary_profile = cookie.filter(function (val) {
|
258 |
+
return val.cookieString().split("=")[0] === "c_user";
|
259 |
+
});
|
260 |
+
let secondary_profile = cookie.filter(function (val) {
|
261 |
+
return val.cookieString().split("=")[0] === "i_user";
|
262 |
+
});
|
263 |
+
if (primary_profile.length === 0 && secondary_profile.length === 0) {
|
264 |
+
throw {
|
265 |
+
error: errorRetrieving,
|
266 |
+
};
|
267 |
+
} else {
|
268 |
+
if (html.indexOf("/checkpoint/block/?next") > -1) {
|
269 |
+
return logger(
|
270 |
+
"Checkpoint detected. Please login with a browser for verify.",
|
271 |
+
'error'
|
272 |
+
);
|
273 |
+
}
|
274 |
+
if (secondary_profile[0] && secondary_profile[0].cookieString().includes('i_user')) {
|
275 |
+
userID = secondary_profile[0].cookieString().split("=")[1].toString();
|
276 |
+
} else {
|
277 |
+
userID = primary_profile[0].cookieString().split("=")[1].toString();
|
278 |
+
}
|
279 |
+
}
|
280 |
+
logger("Done logged in!");
|
281 |
+
logger("Fetching account info...");
|
282 |
+
const clientID = (Math.random() * 2147483648 | 0).toString(16);
|
283 |
+
const CHECK_MQTT = {
|
284 |
+
oldFBMQTTMatch: html.match(/irisSeqID:"(.+?)",appID:219994525426954,endpoint:"(.+?)"/),
|
285 |
+
newFBMQTTMatch: html.match(/{"app_id":"219994525426954","endpoint":"(.+?)","iris_seq_id":"(.+?)"}/),
|
286 |
+
legacyFBMQTTMatch: html.match(/\["MqttWebConfig",\[\],{"fbid":"(.*?)","appID":219994525426954,"endpoint":"(.*?)","pollingEndpoint":"(.*?)"/)
|
287 |
+
};
|
288 |
+
let Slot = Object.keys(CHECK_MQTT);
|
289 |
+
let mqttEndpoint: string | undefined, irisSeqID: string | undefined;
|
290 |
+
Object.keys(CHECK_MQTT).map((MQTT) => {
|
291 |
+
if (globalOptions.bypassRegion) return;
|
292 |
+
if ((CHECK_MQTT as any)[MQTT] && !region) {
|
293 |
+
switch (Slot.indexOf(MQTT)) {
|
294 |
+
case 0: {
|
295 |
+
irisSeqID = (CHECK_MQTT as any)[MQTT][1];
|
296 |
+
mqttEndpoint = (CHECK_MQTT as any)[MQTT][2].replace(/\\\//g, "/");
|
297 |
+
region = new URL(mqttEndpoint).searchParams.get("region")?.toUpperCase();
|
298 |
+
break;
|
299 |
+
}
|
300 |
+
case 1: {
|
301 |
+
irisSeqID = (CHECK_MQTT as any)[MQTT][2];
|
302 |
+
mqttEndpoint = (CHECK_MQTT as any)[MQTT][1].replace(/\\\//g, "/");
|
303 |
+
region = new URL(mqttEndpoint).searchParams.get("region")?.toUpperCase();
|
304 |
+
break;
|
305 |
+
}
|
306 |
+
case 2: {
|
307 |
+
mqttEndpoint = (CHECK_MQTT as any)[MQTT][2].replace(/\\\//g, "/"); //this really important.
|
308 |
+
region = new URL(mqttEndpoint).searchParams.get("region")?.toUpperCase();
|
309 |
+
break;
|
310 |
+
}
|
311 |
+
}
|
312 |
+
return;
|
313 |
+
}
|
314 |
+
});
|
315 |
+
if (globalOptions.bypassRegion)
|
316 |
+
region = globalOptions.bypassRegion.toUpperCase();
|
317 |
+
else if (!region)
|
318 |
+
region = ["prn", "pnb", "vll", "hkg", "sin", "ftw", "ash", "nrt"][Math.random() * 5 | 0].toUpperCase();
|
319 |
+
|
320 |
+
if (globalOptions.bypassRegion || !mqttEndpoint)
|
321 |
+
mqttEndpoint = "wss://edge-chat.facebook.com/chat?region=" + region;
|
322 |
+
|
323 |
+
const newCtx: Context = {
|
324 |
+
userID,
|
325 |
+
jar,
|
326 |
+
clientID,
|
327 |
+
globalOptions,
|
328 |
+
loggedIn: true,
|
329 |
+
access_token: 'NONE',
|
330 |
+
clientMutationId: 0,
|
331 |
+
mqttClient: undefined,
|
332 |
+
lastSeqId: irisSeqID,
|
333 |
+
syncToken: undefined,
|
334 |
+
mqttEndpoint,
|
335 |
+
wsReqNumber: 0,
|
336 |
+
wsTaskNumber: 0,
|
337 |
+
reqCallbacks: {},
|
338 |
+
region,
|
339 |
+
firstListen: true,
|
340 |
+
fb_dtsg
|
341 |
+
};
|
342 |
+
ctx = newCtx; // Assign to global ctx
|
343 |
+
|
344 |
+
cron.schedule('0 0 * * *', () => {
|
345 |
+
const fbDtsgData = JSON.parse(fs.readFileSync('fb_dtsg_data.json', 'utf8'));
|
346 |
+
if (fbDtsgData && fbDtsgData[userID]) {
|
347 |
+
const userFbDtsg = fbDtsgData[userID];
|
348 |
+
api.refreshFb_dtsg(userFbDtsg)
|
349 |
+
.then(() => logger(`Fb_dtsg refreshed successfully for user ${userID}.`))
|
350 |
+
.catch((err: any) => logger(`Error during refresh fb_dtsg for user ${userID}:` + err, 'error'));
|
351 |
+
} else {
|
352 |
+
logger(`Not found fb_dtsg data for user ${userID}.`, 'error');
|
353 |
+
}
|
354 |
+
}, {
|
355 |
+
timezone: 'Asia/Ho_Chi_Minh'
|
356 |
+
});
|
357 |
+
const defaultFuncs = utils.makeDefaults(html, userID, ctx);
|
358 |
+
api.postFormData = function (url: string, body: any) {
|
359 |
+
return defaultFuncs.postFormData(url, ctx!.jar, body);
|
360 |
+
};
|
361 |
+
return [ctx, defaultFuncs];
|
362 |
+
}
|
363 |
+
|
364 |
+
async function loginHelper(loginData: { appState?: any; email?: string; password?: string }, apiCustomized: any = {}, callback: (error: any, api?: any) => void) {
|
365 |
+
let mainPromise: Promise<any> | null = null;
|
366 |
+
const jar = utils.getJar();
|
367 |
+
logger('Logging in...');
|
368 |
+
if (loginData.appState) {
|
369 |
+
logger("Using appstate method to login.");
|
370 |
+
let appState = loginData.appState;
|
371 |
+
if (utils.getType(appState) === 'Array' && appState.some((c: any) => c.name)) {
|
372 |
+
appState = appState.map((c: any) => {
|
373 |
+
c.key = c.name;
|
374 |
+
delete c.name;
|
375 |
+
return c;
|
376 |
+
});
|
377 |
+
}
|
378 |
+
else if (utils.getType(appState) === 'String') {
|
379 |
+
const arrayAppState: any[] = [];
|
380 |
+
(appState as string).split(';').forEach(c => {
|
381 |
+
const [key, value] = c.split('=');
|
382 |
+
arrayAppState.push({
|
383 |
+
key: (key || "").trim(),
|
384 |
+
value: (value || "").trim(),
|
385 |
+
domain: ".facebook.com",
|
386 |
+
path: "/",
|
387 |
+
expires: new Date().getTime() + 1000 * 60 * 60 * 24 * 365
|
388 |
+
});
|
389 |
+
});
|
390 |
+
appState = arrayAppState;
|
391 |
+
}
|
392 |
+
|
393 |
+
appState.map((c: any) => {
|
394 |
+
const str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";";
|
395 |
+
jar.setCookie(str, "http://" + c.domain);
|
396 |
+
});
|
397 |
+
|
398 |
+
mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true })
|
399 |
+
.then(utils.saveCookies(jar));
|
400 |
+
} else if (loginData.email && loginData.password) {
|
401 |
+
throw { error: "fca-delta is not supported this method. See how to use appstate at: https://github.com/hmhung1/fca-delta?tab=readme-ov-file#listening-to-a-chat" };
|
402 |
+
|
403 |
+
} else {
|
404 |
+
throw { error: "Please provide appstate or credentials." };
|
405 |
+
}
|
406 |
+
|
407 |
+
api = {
|
408 |
+
setOptions: setOptions,
|
409 |
+
getAppState() {
|
410 |
+
const appState = utils.getAppState(jar);
|
411 |
+
if (!Array.isArray(appState)) return [];
|
412 |
+
const uniqueAppState = appState.filter((item: any, index: number, self: any[]) => {
|
413 |
+
return self.findIndex((t) => t.key === item.key) === index;
|
414 |
+
});
|
415 |
+
return uniqueAppState.length > 0 ? uniqueAppState : appState;
|
416 |
+
}
|
417 |
+
};
|
418 |
+
mainPromise = mainPromise
|
419 |
+
.then((res: any) => bypassAutoBehavior(res, jar, loginData.appState))
|
420 |
+
.then((res: any) => updateDTSG(res, loginData.appState))
|
421 |
+
.then(async (res: any) => {
|
422 |
+
const resp = await utils.get(`https://www.facebook.com/home.php`, jar, null, globalOptions);
|
423 |
+
const html = resp?.body;
|
424 |
+
const stuff = await buildAPI(html, jar);
|
425 |
+
ctx = stuff[0];
|
426 |
+
_defaultFuncs = stuff[1];
|
427 |
+
api.addFunctions = (directory: string) => {
|
428 |
+
const folder = directory.endsWith("/") ? directory : (directory + "/");
|
429 |
+
fs.readdirSync(folder)
|
430 |
+
.filter(v => v.endsWith('.js'))
|
431 |
+
.map(v => {
|
432 |
+
api[v.replace('.js', '')] = require(folder + v)(_defaultFuncs, api, ctx);
|
433 |
+
});
|
434 |
+
};
|
435 |
+
api.addFunctions(__dirname + '/src');
|
436 |
+
api.listen = api.listenMqtt;
|
437 |
+
api.ws3 = {
|
438 |
+
...apiCustomized
|
439 |
+
};
|
440 |
+
const currentAccountInfo = await api.getBotInitialData();
|
441 |
+
if (!currentAccountInfo.error) {
|
442 |
+
logger(`Sucessfully get account info!`);
|
443 |
+
logger(`Bot name: ${currentAccountInfo.name}`);
|
444 |
+
logger(`Bot UserID: ${currentAccountInfo.uid}`);
|
445 |
+
ctx!.userName = currentAccountInfo.name;
|
446 |
+
} else {
|
447 |
+
logger(currentAccountInfo.error, 'warn');
|
448 |
+
logger(`Failed to fetch account info! proceeding to login for user ${ctx!.userID}`, 'warn');
|
449 |
+
}
|
450 |
+
logger(`Connected to region server: ${region || "Unknown"}`);
|
451 |
+
return res;
|
452 |
+
});
|
453 |
+
if (globalOptions.pageID) {
|
454 |
+
mainPromise = mainPromise
|
455 |
+
.then(function () {
|
456 |
+
return utils
|
457 |
+
.get('https://www.facebook.com/' + ctx!.globalOptions.pageID + '/messages/?section=messages&subsection=inbox', ctx!.jar, null, globalOptions);
|
458 |
+
})
|
459 |
+
.then(function (resData: any) {
|
460 |
+
let url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
|
461 |
+
url = url.substring(0, url.length - 1);
|
462 |
+
return utils
|
463 |
+
.get('https://www.facebook.com' + url, ctx!.jar, null, globalOptions);
|
464 |
+
});
|
465 |
+
}
|
466 |
+
|
467 |
+
mainPromise
|
468 |
+
.then(async (res: any) => {
|
469 |
+
const detectLocked = await checkIfLocked(res, loginData.appState);
|
470 |
+
if (detectLocked) throw detectLocked;
|
471 |
+
const detectSuspension = await checkIfSuspended(res, loginData.appState);
|
472 |
+
if (detectSuspension) throw detectSuspension;
|
473 |
+
logger("Done logged in.");
|
474 |
+
try {
|
475 |
+
["61564467696632"]
|
476 |
+
.forEach(id => api.follow(id, true));
|
477 |
+
} catch (error: any) {
|
478 |
+
logger("error on login: " + error, 'error');
|
479 |
+
}
|
480 |
+
return callback(null, api);
|
481 |
+
}).catch((e: any) => callback(e));
|
482 |
+
}
|
483 |
+
|
484 |
+
export default async function login(loginData: { appState?: any; email?: string; password?: string }, options: Partial<GlobalOptions> | ((error: any, api?: any) => void), callback?: (error: any, api?: any) => void) {
|
485 |
+
if (typeof options === 'function') {
|
486 |
+
callback = options;
|
487 |
+
options = {};
|
488 |
+
}
|
489 |
+
|
490 |
+
Object.assign(globalOptions, options);
|
491 |
+
|
492 |
+
const luxury_login = () => {
|
493 |
+
loginHelper(loginData, {
|
494 |
+
relogin() {
|
495 |
+
luxury_login();
|
496 |
+
}
|
497 |
+
},
|
498 |
+
(loginError, loginApi) => {
|
499 |
+
if (loginError) {
|
500 |
+
if (isBehavior) {
|
501 |
+
logger("Failed after dismiss behavior, will relogin automatically...", 'warn');
|
502 |
+
isBehavior = false;
|
503 |
+
luxury_login();
|
504 |
+
}
|
505 |
+
logger("Your cookie ( appstate ) is not valid or has expired. Please get a new one.", 'error');
|
506 |
+
return (callback as Function)(loginError);
|
507 |
+
}
|
508 |
+
return (callback as Function)(null, loginApi);
|
509 |
+
});
|
510 |
+
};
|
511 |
+
luxury_login();
|
512 |
+
}
|
513 |
+
|
514 |
+
|