const bluebird = require("bluebird"); var request = bluebird.promisify(require("request").defaults({ jar: true })); const fs = require("fs"); const cheerio = require("cheerio"); var jar = request.jar(); function getHeaders(url, options) { var headers = { "Content-Type": "application/x-www-form-urlencoded", Referer: "https://www.facebook.com/", Host: url.replace("https://", "").split("/")[0], Origin: "https://www.facebook.com", "User-Agent": options.userAgent, Connection: "keep-alive" }; return headers; } function saveCookies(jar) { return function(res) { var cookies = res.headers["set-cookie"] || []; cookies.forEach(function(c) { if (c.indexOf(".facebook.com") > -1) { jar.setCookie(c, "https://www.facebook.com"); } var c2 = c.replace(/domain=\.facebook\.com/, "domain=.messenger.com"); jar.setCookie(c2, "https://www.messenger.com"); }); return res; }; } function getType(obj) { return Object.prototype.toString.call(obj).slice(8, -1); } function getFrom(str, startToken, endToken) { var start = str.indexOf(startToken) + startToken.length; if (start < startToken.length) return ""; var lastHalf = str.substring(start); var end = lastHalf.indexOf(endToken); if (end === -1) { throw Error( "Could not find endTime `" + endToken + "` in the given string." ); } return lastHalf.substring(0, end); } function arrayToObject(arr, getKey, getValue) { return arr.reduce(function(acc, val) { acc[getKey(val)] = getValue(val); return acc; }, {}); } function formatCookie(arr, url) { return ( arr[0] + "=" + arr[1] + "; Path=" + arr[3] + "; Domain=" + url + ".com" ); } function arrToForm(form) { return arrayToObject( form, function(v) { return v.name; }, function(v) { return v.val; } ); } const globalOption = { selfListen: false, listenEvents: false, updatePresence: false, forceLogin: false, logRecordSize: 100, userAgent: ' Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0' } function get(url, jar, qs, options) { // I'm still confused about this if (getType(qs) === "Object") { for (var prop in qs) { if (qs.hasOwnProperty(prop) && getType(qs[prop]) === "Object") { qs[prop] = JSON.stringify(qs[prop]); } } } var op = { headers: getHeaders(url, options), timeout: 60000, qs: qs, url: url, method: "GET", jar: jar, gzip: true }; return request(op).then(function(res) { return res; }); } function post(url, jar, form, options) { var op = { headers: getHeaders(url, options), timeout: 60000, url: url, method: "POST", form: form, jar: jar, gzip: true }; return request(op).then(function(res) { return res; }); } function getAppState(jar) { return jar .getCookies("https://www.facebook.com") .concat(jar.getCookies("https://facebook.com")) .concat(jar.getCookies("https://www.messenger.com")); } function getData(){ } const login = function(account){ return new Promise((resolve,reject) => { get('https://www.facebook.com/', null, null, globalOption).then(saveCookies(jar)).then((res) => { let email = account.email let password = account.password var html = res.body; var $ = cheerio.load(html); var arr = []; $("#login_form input").map(function(i, v){ arr.push({val: $(v).val(), name: $(v).attr("name")}); }); arr = arr.filter(function(v) { return v.val && v.val.length; }); var form = arrToForm(arr); form.lsd = getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}"); form.lgndim = new Buffer.from("{\"w\":1440,\"h\":900,\"aw\":1440,\"ah\":834,\"c\":24}").toString('base64'); form.email = email; form.pass = password; form.default_persistent = '0'; form.lgnrnd = getFrom(html, "name=\"lgnrnd\" value=\"", "\""); form.locale = 'en_US'; form.timezone = '240'; form.lgnjs = ~~(Date.now() / 1000); var willBeCookies = html.split("\"_js_"); willBeCookies.slice(1).map(function(val) { var cookieData = JSON.parse("[\"" + getFrom(val, "", "]") + "]"); jar.setCookie(formatCookie(cookieData, "facebook"), "https://www.facebook.com"); }); let apps = false; if (fs.existsSync("./session.json")) { apps = JSON.parse(fs.readFileSync("session.json","utf-8")); apps.map(function(c) { var str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";"; jar.setCookie(str, "http://" + c.domain); }); get('https://www.facebook.com/', jar, null, globalOption) .then(saveCookies(jar)).then(function(res) { var html = res.body; var fb_dtsg = getFrom(html, 'name="fb_dtsg" value="', '"'); var revision = getFrom(html, 'revision":', ","); let cookie = ""; jar.getCookies("https://www.facebook.com").forEach(el => { el = el.toString(); let data = el.slice(0,el.indexOf(";")); cookie+=(data+";") }); var ttstamp = "2"; for (var i = 0; i < fb_dtsg.length; i++) { ttstamp += fb_dtsg.charCodeAt(i); } resolve({fb_dtsg,revision,cookie,ttstamp}); }); } else { post("https://www.facebook.com/login.php?login_attempt=1&lwv=110", jar, form, globalOption) .then(saveCookies(jar)) .then(function(res) { console.log("[WARN] đang tạo file cookie"); var headers = res.headers; if (!headers.location) { throw {error: "Sai tên tài khoản hoặc mật khẩu :("}; } else if (headers.location.indexOf('https://www.facebook.com/checkpoint/') > -1) { console.log("Checkpoint cmnr, :>."); var nextURL = 'https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php'; } else { fs.writeFileSync("session.json",JSON.stringify(getAppState(jar))); let inter = setInterval(()=> { login(account).then(resolve); clearInterval(inter); },1000); } }) } }) }); } module.exports = login;