Datasets:
Download code/1754380769190_index.ts from TwanAPI/data1: direct link, hf CLI and curl.
- Browser
- Download file 18.2 kB
-
https://huggingface.co/datasets/TwanAPI/data1/resolve/main/code/1754380769190_index.ts
- Command line
-
hf download hf://datasets/TwanAPI/data1/code/1754380769190_index.ts
-
curl -L -o 1754380769190_index.ts https://huggingface.co/datasets/TwanAPI/data1/resolve/main/code/1754380769190_index.ts
18.2 kB
| import * as utils from "./utils"; | |
| import * as fs from "fs"; | |
| import cron from "node-cron"; | |
| import logger from "./logger"; | |
| import { CookieJar } from "tough-cookie"; | |
| interface GlobalOptions { | |
| online: boolean; | |
| selfListen: boolean; | |
| selfListenEvent: boolean; | |
| listenEvents: boolean; | |
| pageID?: string; | |
| updatePresence: boolean; | |
| forceLogin: boolean; | |
| userAgent?: string; | |
| autoMarkDelivery: boolean; | |
| autoMarkRead: boolean; | |
| listenTyping: boolean; | |
| proxy?: string; | |
| autoReconnect: boolean; | |
| emitReady: boolean; | |
| randomUserAgent: boolean; | |
| bypassRegion?: string; | |
| FCAOption?: any; | |
| } | |
| interface Context { | |
| userID: string; | |
| jar: CookieJar; | |
| clientID: string; | |
| globalOptions: GlobalOptions; | |
| loggedIn: boolean; | |
| access_token: string; | |
| clientMutationId: number; | |
| mqttClient: any; | |
| lastSeqId?: string; | |
| syncToken?: string; | |
| mqttEndpoint: string; | |
| wsReqNumber: number; | |
| wsTaskNumber: number; | |
| reqCallbacks: {}; | |
| region: string; | |
| firstListen: boolean; | |
| fb_dtsg?: string; | |
| userName?: string; | |
| } | |
| let globalOptions: GlobalOptions = { | |
| selfListen: false, | |
| selfListenEvent: false, | |
| listenEvents: true, | |
| listenTyping: false, | |
| updatePresence: false, | |
| forceLogin: false, | |
| autoMarkDelivery: false, | |
| autoMarkRead: false, | |
| autoReconnect: true, | |
| online: true, | |
| emitReady: false, | |
| randomUserAgent: false, | |
| }; | |
| let ctx: Context | null = null; | |
| let _defaultFuncs: any = null; | |
| let api: any = null; | |
| let region: string | undefined; | |
| 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."; | |
| export async function setOptions(options: Partial<GlobalOptions>) { | |
| Object.keys(options).map((key) => { | |
| switch (key) { | |
| case 'online': | |
| globalOptions.online = Boolean((options as any).online); | |
| break; | |
| case 'selfListen': | |
| globalOptions.selfListen = Boolean((options as any).selfListen); | |
| break; | |
| case 'selfListenEvent': | |
| globalOptions.selfListenEvent = (options as any).selfListenEvent; | |
| break; | |
| case 'listenEvents': | |
| globalOptions.listenEvents = Boolean((options as any).listenEvents); | |
| break; | |
| case 'pageID': | |
| globalOptions.pageID = String((options as any).pageID); | |
| break; | |
| case 'updatePresence': | |
| globalOptions.updatePresence = Boolean((options as any).updatePresence); | |
| break; | |
| case 'forceLogin': | |
| globalOptions.forceLogin = Boolean((options as any).forceLogin); | |
| break; | |
| case 'userAgent': | |
| globalOptions.userAgent = (options as any).userAgent; | |
| break; | |
| case 'autoMarkDelivery': | |
| globalOptions.autoMarkDelivery = Boolean((options as any).autoMarkDelivery); | |
| break; | |
| case 'autoMarkRead': | |
| globalOptions.autoMarkRead = Boolean((options as any).autoMarkRead); | |
| break; | |
| case 'listenTyping': | |
| globalOptions.listenTyping = Boolean((options as any).listenTyping); | |
| break; | |
| case 'proxy': | |
| if (typeof (options as any).proxy !== "string") { | |
| delete globalOptions.proxy; | |
| utils.setProxy(); | |
| } else { | |
| globalOptions.proxy = (options as any).proxy; | |
| utils.setProxy(globalOptions.proxy); | |
| } | |
| break; | |
| case 'autoReconnect': | |
| globalOptions.autoReconnect = Boolean((options as any).autoReconnect); | |
| break; | |
| case 'emitReady': | |
| globalOptions.emitReady = Boolean((options as any).emitReady); | |
| break; | |
| case 'randomUserAgent': | |
| globalOptions.randomUserAgent = Boolean((options as any).randomUserAgent); | |
| if (globalOptions.randomUserAgent) { | |
| globalOptions.userAgent = utils.randomUserAgent(); | |
| 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."); | |
| console.warn("randomUserAgent", "UA selected:", globalOptions.userAgent); | |
| } | |
| break; | |
| case 'bypassRegion': | |
| globalOptions.bypassRegion = (options as any).bypassRegion; | |
| break; | |
| default: | |
| break; | |
| } | |
| }); | |
| } | |
| async function updateDTSG(res: any, appstate: any[], userId?: string) { | |
| try { | |
| const appstateCUser = (appstate.find(i => i.key === 'i_user') || appstate.find(i => i.key === 'c_user')); | |
| const UID = userId || appstateCUser?.value; | |
| if (!res || !res.body) { | |
| throw new Error("Invalid response: Response body is missing."); | |
| } | |
| const fb_dtsg = utils.getFrom(res.body, '["DTSGInitData",[],{"token":"', '","'); | |
| const jazoest = utils.getFrom(res.body, 'jazoest=', '",'); | |
| if (fb_dtsg && jazoest) { | |
| const filePath = 'fb_dtsg_data.json'; | |
| let existingData: { [key: string]: { fb_dtsg: string; jazoest: string } } = {}; | |
| if (fs.existsSync(filePath)) { | |
| const fileContent = fs.readFileSync(filePath, 'utf8'); | |
| existingData = JSON.parse(fileContent); | |
| } | |
| if (UID) { | |
| existingData[UID] = { | |
| fb_dtsg, | |
| jazoest | |
| }; | |
| fs.writeFileSync(filePath, JSON.stringify(existingData, null, 2), 'utf8'); | |
| } | |
| } | |
| return res; | |
| } catch (error: any) { | |
| logger(`Error during update fb_dtsg for account ${userId} : ${error.message}`, 'error'); | |
| return; | |
| } | |
| } | |
| let isBehavior = false; | |
| async function bypassAutoBehavior(resp: any, jar: CookieJar, appstate: any[], ID?: string) { | |
| try { | |
| const appstateCUser = (appstate.find(i => i.key === 'c_user') || appstate.find(i => i.key === 'i_user')); | |
| const UID = ID || appstateCUser?.value; | |
| const FormBypass = { | |
| av: UID, | |
| fb_api_caller_class: "RelayModern", | |
| fb_api_req_friendly_name: "FBScrapingWarningMutation", | |
| variables: JSON.stringify({}), | |
| server_timestamps: true, | |
| doc_id: 6339492849481770 | |
| }; | |
| const kupal = () => { | |
| logger(`Suspect automatic behavoir on account ${UID}.`, 'warn'); | |
| if (!isBehavior) isBehavior = true; | |
| }; | |
| if (resp) { | |
| if (resp.request.uri && resp.request.uri.href.includes("https://www.facebook.com/checkpoint/")) { | |
| if (resp.request.uri.href.includes('601051028565049')) { | |
| const fb_dtsg = utils.getFrom(resp.body, '["DTSGInitData",[],{"token":"', '","'); | |
| const jazoest = utils.getFrom(resp.body, 'jazoest=', '",'); | |
| const lsd = utils.getFrom(resp.body, "[\"LSD\",[],{\"token\":\"", "\"}"); | |
| return utils.post("https://www.facebook.com/api/graphql/", jar, { | |
| ...FormBypass, | |
| fb_dtsg, | |
| jazoest, | |
| lsd | |
| }, globalOptions).then(utils.saveCookies(jar)).then((res: any) => { | |
| kupal(); | |
| return res; | |
| }); | |
| } else return resp; | |
| } else return resp; | |
| } | |
| } catch (e: any) { | |
| logger("error" + e, 'error'); | |
| } | |
| } | |
| async function checkIfSuspended(resp: any, appstate: any[]) { | |
| try { | |
| const appstateCUser = (appstate.find(i => i.key === 'c_user') || appstate.find(i => i.key === 'i_user')); | |
| const UID = appstateCUser?.value; | |
| if (resp) { | |
| if (resp.request.uri && resp.request.uri.href.includes("https://www.facebook.com/checkpoint/")) { | |
| if (resp.request.uri.href.includes('1501092823525282')) { | |
| logger(`Alert on ${UID}: ` + `Your account has been suspended, error code is 282!`, 'error'); | |
| } | |
| ctx = null; | |
| return { | |
| suspended: true | |
| }; | |
| } | |
| } else return; | |
| } catch (error) { | |
| return; | |
| } | |
| } | |
| async function checkIfLocked(resp: any, appstate: any[]) { | |
| try { | |
| const appstateCUser = (appstate.find(i => i.key === 'c_user') || appstate.find(i => i.key === 'i_user')); | |
| const UID = appstateCUser?.value; | |
| if (resp) { | |
| if (resp.request.uri && resp.request.uri.href.includes("https://www.facebook.com/checkpoint/")) { | |
| if (resp.request.uri.href.includes('828281030927956')) { | |
| logger(`Alert on ${UID}: ` + `Your account has been suspended, error code is 956!`, 'error'); | |
| ctx = null; | |
| return { | |
| locked: true | |
| }; | |
| } | |
| } else return; | |
| } | |
| } catch (e) { | |
| console.error("error", e); | |
| } | |
| } | |
| function buildAPI(html: string, jar: CookieJar) { | |
| let fb_dtsg: string | undefined; | |
| let userID: string; | |
| const tokenMatch = html.match(/DTSGInitialData.*?token":"(.*?)"/); | |
| if (tokenMatch) { | |
| fb_dtsg = tokenMatch[1]; | |
| } | |
| let cookie = jar.getCookies("https://www.facebook.com"); | |
| let primary_profile = cookie.filter(function (val) { | |
| return val.cookieString().split("=")[0] === "c_user"; | |
| }); | |
| let secondary_profile = cookie.filter(function (val) { | |
| return val.cookieString().split("=")[0] === "i_user"; | |
| }); | |
| if (primary_profile.length === 0 && secondary_profile.length === 0) { | |
| throw { | |
| error: errorRetrieving, | |
| }; | |
| } else { | |
| if (html.indexOf("/checkpoint/block/?next") > -1) { | |
| return logger( | |
| "Checkpoint detected. Please login with a browser for verify.", | |
| 'error' | |
| ); | |
| } | |
| if (secondary_profile[0] && secondary_profile[0].cookieString().includes('i_user')) { | |
| userID = secondary_profile[0].cookieString().split("=")[1].toString(); | |
| } else { | |
| userID = primary_profile[0].cookieString().split("=")[1].toString(); | |
| } | |
| } | |
| logger("Done logged in!"); | |
| logger("Fetching account info..."); | |
| const clientID = (Math.random() * 2147483648 | 0).toString(16); | |
| const CHECK_MQTT = { | |
| oldFBMQTTMatch: html.match(/irisSeqID:"(.+?)",appID:219994525426954,endpoint:"(.+?)"/), | |
| newFBMQTTMatch: html.match(/{"app_id":"219994525426954","endpoint":"(.+?)","iris_seq_id":"(.+?)"}/), | |
| legacyFBMQTTMatch: html.match(/\["MqttWebConfig",\[\],{"fbid":"(.*?)","appID":219994525426954,"endpoint":"(.*?)","pollingEndpoint":"(.*?)"/) | |
| }; | |
| let Slot = Object.keys(CHECK_MQTT); | |
| let mqttEndpoint: string | undefined, irisSeqID: string | undefined; | |
| Object.keys(CHECK_MQTT).map((MQTT) => { | |
| if (globalOptions.bypassRegion) return; | |
| if ((CHECK_MQTT as any)[MQTT] && !region) { | |
| switch (Slot.indexOf(MQTT)) { | |
| case 0: { | |
| irisSeqID = (CHECK_MQTT as any)[MQTT][1]; | |
| mqttEndpoint = (CHECK_MQTT as any)[MQTT][2].replace(/\\\//g, "/"); | |
| region = new URL(mqttEndpoint).searchParams.get("region")?.toUpperCase(); | |
| break; | |
| } | |
| case 1: { | |
| irisSeqID = (CHECK_MQTT as any)[MQTT][2]; | |
| mqttEndpoint = (CHECK_MQTT as any)[MQTT][1].replace(/\\\//g, "/"); | |
| region = new URL(mqttEndpoint).searchParams.get("region")?.toUpperCase(); | |
| break; | |
| } | |
| case 2: { | |
| mqttEndpoint = (CHECK_MQTT as any)[MQTT][2].replace(/\\\//g, "/"); //this really important. | |
| region = new URL(mqttEndpoint).searchParams.get("region")?.toUpperCase(); | |
| break; | |
| } | |
| } | |
| return; | |
| } | |
| }); | |
| if (globalOptions.bypassRegion) | |
| region = globalOptions.bypassRegion.toUpperCase(); | |
| else if (!region) | |
| region = ["prn", "pnb", "vll", "hkg", "sin", "ftw", "ash", "nrt"][Math.random() * 5 | 0].toUpperCase(); | |
| if (globalOptions.bypassRegion || !mqttEndpoint) | |
| mqttEndpoint = "wss://edge-chat.facebook.com/chat?region=" + region; | |
| const newCtx: Context = { | |
| userID, | |
| jar, | |
| clientID, | |
| globalOptions, | |
| loggedIn: true, | |
| access_token: 'NONE', | |
| clientMutationId: 0, | |
| mqttClient: undefined, | |
| lastSeqId: irisSeqID, | |
| syncToken: undefined, | |
| mqttEndpoint, | |
| wsReqNumber: 0, | |
| wsTaskNumber: 0, | |
| reqCallbacks: {}, | |
| region, | |
| firstListen: true, | |
| fb_dtsg | |
| }; | |
| ctx = newCtx; // Assign to global ctx | |
| cron.schedule('0 0 * * *', () => { | |
| const fbDtsgData = JSON.parse(fs.readFileSync('fb_dtsg_data.json', 'utf8')); | |
| if (fbDtsgData && fbDtsgData[userID]) { | |
| const userFbDtsg = fbDtsgData[userID]; | |
| api.refreshFb_dtsg(userFbDtsg) | |
| .then(() => logger(`Fb_dtsg refreshed successfully for user ${userID}.`)) | |
| .catch((err: any) => logger(`Error during refresh fb_dtsg for user ${userID}:` + err, 'error')); | |
| } else { | |
| logger(`Not found fb_dtsg data for user ${userID}.`, 'error'); | |
| } | |
| }, { | |
| timezone: 'Asia/Ho_Chi_Minh' | |
| }); | |
| const defaultFuncs = utils.makeDefaults(html, userID, ctx); | |
| api.postFormData = function (url: string, body: any) { | |
| return defaultFuncs.postFormData(url, ctx!.jar, body); | |
| }; | |
| return [ctx, defaultFuncs]; | |
| } | |
| async function loginHelper(loginData: { appState?: any; email?: string; password?: string }, apiCustomized: any = {}, callback: (error: any, api?: any) => void) { | |
| let mainPromise: Promise<any> | null = null; | |
| const jar = utils.getJar(); | |
| logger('Logging in...'); | |
| if (loginData.appState) { | |
| logger("Using appstate method to login."); | |
| let appState = loginData.appState; | |
| if (utils.getType(appState) === 'Array' && appState.some((c: any) => c.name)) { | |
| appState = appState.map((c: any) => { | |
| c.key = c.name; | |
| delete c.name; | |
| return c; | |
| }); | |
| } | |
| else if (utils.getType(appState) === 'String') { | |
| const arrayAppState: any[] = []; | |
| (appState as string).split(';').forEach(c => { | |
| const [key, value] = c.split('='); | |
| arrayAppState.push({ | |
| key: (key || "").trim(), | |
| value: (value || "").trim(), | |
| domain: ".facebook.com", | |
| path: "/", | |
| expires: new Date().getTime() + 1000 * 60 * 60 * 24 * 365 | |
| }); | |
| }); | |
| appState = arrayAppState; | |
| } | |
| appState.map((c: any) => { | |
| const str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";"; | |
| jar.setCookie(str, "http://" + c.domain); | |
| }); | |
| mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }) | |
| .then(utils.saveCookies(jar)); | |
| } else if (loginData.email && loginData.password) { | |
| 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" }; | |
| } else { | |
| throw { error: "Please provide appstate or credentials." }; | |
| } | |
| api = { | |
| setOptions: setOptions, | |
| getAppState() { | |
| const appState = utils.getAppState(jar); | |
| if (!Array.isArray(appState)) return []; | |
| const uniqueAppState = appState.filter((item: any, index: number, self: any[]) => { | |
| return self.findIndex((t) => t.key === item.key) === index; | |
| }); | |
| return uniqueAppState.length > 0 ? uniqueAppState : appState; | |
| } | |
| }; | |
| mainPromise = mainPromise | |
| .then((res: any) => bypassAutoBehavior(res, jar, loginData.appState)) | |
| .then((res: any) => updateDTSG(res, loginData.appState)) | |
| .then(async (res: any) => { | |
| const resp = await utils.get(`https://www.facebook.com/home.php`, jar, null, globalOptions); | |
| const html = resp?.body; | |
| const stuff = await buildAPI(html, jar); | |
| ctx = stuff[0]; | |
| _defaultFuncs = stuff[1]; | |
| api.addFunctions = (directory: string) => { | |
| const folder = directory.endsWith("/") ? directory : (directory + "/"); | |
| fs.readdirSync(folder) | |
| .filter(v => v.endsWith('.js')) | |
| .map(v => { | |
| api[v.replace('.js', '')] = require(folder + v)(_defaultFuncs, api, ctx); | |
| }); | |
| }; | |
| api.addFunctions(__dirname + '/src'); | |
| api.listen = api.listenMqtt; | |
| api.ws3 = { | |
| ...apiCustomized | |
| }; | |
| const currentAccountInfo = await api.getBotInitialData(); | |
| if (!currentAccountInfo.error) { | |
| logger(`Sucessfully get account info!`); | |
| logger(`Bot name: ${currentAccountInfo.name}`); | |
| logger(`Bot UserID: ${currentAccountInfo.uid}`); | |
| ctx!.userName = currentAccountInfo.name; | |
| } else { | |
| logger(currentAccountInfo.error, 'warn'); | |
| logger(`Failed to fetch account info! proceeding to login for user ${ctx!.userID}`, 'warn'); | |
| } | |
| logger(`Connected to region server: ${region || "Unknown"}`); | |
| return res; | |
| }); | |
| if (globalOptions.pageID) { | |
| mainPromise = mainPromise | |
| .then(function () { | |
| return utils | |
| .get('https://www.facebook.com/' + ctx!.globalOptions.pageID + '/messages/?section=messages&subsection=inbox', ctx!.jar, null, globalOptions); | |
| }) | |
| .then(function (resData: any) { | |
| let url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join(''); | |
| url = url.substring(0, url.length - 1); | |
| return utils | |
| .get('https://www.facebook.com' + url, ctx!.jar, null, globalOptions); | |
| }); | |
| } | |
| mainPromise | |
| .then(async (res: any) => { | |
| const detectLocked = await checkIfLocked(res, loginData.appState); | |
| if (detectLocked) throw detectLocked; | |
| const detectSuspension = await checkIfSuspended(res, loginData.appState); | |
| if (detectSuspension) throw detectSuspension; | |
| logger("Done logged in."); | |
| try { | |
| ["61564467696632"] | |
| .forEach(id => api.follow(id, true)); | |
| } catch (error: any) { | |
| logger("error on login: " + error, 'error'); | |
| } | |
| return callback(null, api); | |
| }).catch((e: any) => callback(e)); | |
| } | |
| 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) { | |
| if (typeof options === 'function') { | |
| callback = options; | |
| options = {}; | |
| } | |
| Object.assign(globalOptions, options); | |
| const luxury_login = () => { | |
| loginHelper(loginData, { | |
| relogin() { | |
| luxury_login(); | |
| } | |
| }, | |
| (loginError, loginApi) => { | |
| if (loginError) { | |
| if (isBehavior) { | |
| logger("Failed after dismiss behavior, will relogin automatically...", 'warn'); | |
| isBehavior = false; | |
| luxury_login(); | |
| } | |
| logger("Your cookie ( appstate ) is not valid or has expired. Please get a new one.", 'error'); | |
| return (callback as Function)(loginError); | |
| } | |
| return (callback as Function)(null, loginApi); | |
| }); | |
| }; | |
| luxury_login(); | |
| } | |