{"size": 2117, "ext": "js", "max_stars_repo_path": "src/loginFacebook.js", "max_stars_repo_name": "solominh/puppeteer-facebook", "max_stars_repo_stars_event_min_datetime": "2021-08-29T09:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T09:57:36.000Z", "max_issues_repo_path": "src/loginFacebook.js", "max_issues_repo_name": "solominh/puppeteer-facebook", "max_issues_repo_issues_event_min_datetime": "2021-02-26T10:06:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T10:06:41.000Z", "max_forks_repo_path": "src/loginFacebook.js", "max_forks_repo_name": "solominh/puppeteer-facebook", "max_forks_repo_forks_event_min_datetime": "2021-08-29T09:57:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T09:57:39.000Z"}
{"max_stars_count": 1, "max_issues_count": 5, "max_forks_count": 1, "avg_line_length": 25.2023809524, "max_line_length": 72, "alphanum_fraction": 0.6424185168}
require('dotenv').config()
const fs = require('fs-extra')
const path = require('path')
var crypto = require('crypto')

const loginFacebook = async page => {
  const loggedCheck = async page => {
    try {
      await page.waitForSelector('#ssrb_root_start', { timeout: 10000 })
      return true
    } catch (err) {
      return false
    }
  }

  const fetchCookies = async email => {
    let filePath = path.join(__dirname, 'facebookCache.json')
    let facebookCache = {}
    try {
      facebookCache = await fs.readJSON(filePath)
    } catch (error) {}

    const key = crypto
      .createHash('md5')
      .update(email)
      .digest('hex')
    let cookies = facebookCache[key]
    return cookies
  }

  const saveCookies = async (email, cookies) => {
    let filePath = path.join(__dirname, 'facebookCache.json')
    let facebookCache = {}
    try {
      facebookCache = await fs.readJSON(filePath)
    } catch (error) {}
    const key = crypto
      .createHash('md5')
      .update(email)
      .digest('hex')

    facebookCache[key] = cookies
    try {
      await fs.outputFile(filePath, JSON.stringify(facebookCache))
    } catch (error) {

    }
  }

  const { EMAIL, PASS } = process.env
  let isLogged = false
  const cookies = await fetchCookies(EMAIL)

  if (cookies) {
    console.log('Try to use cookies from cache..')
    await page.setCookie(...cookies)
    await page.goto('https://facebook.com')
    isLogged = await loggedCheck(page)
  }

  if (!isLogged) {
    console.log(`Cookies from cache didn't work, try to login..`)
    await page.goto('https://facebook.com')
    await page.type('#email', EMAIL)
    await page.type('#pass', PASS)
    await page.click('[data-testid="royal_login_button"]')
    await page.waitForNavigation()
    isLogged = await loggedCheck(page)
  }

  if (!isLogged) {
    throw new Error('Incorrect username or password!')
  }

  // Get cookies and refresh them in store cache
  console.log(`Saving new cookies to cache..`)
  const newCookies = await page.cookies()
  await saveCookies(EMAIL, newCookies)
}

module.exports = {
  loginFacebook: loginFacebook,
}
