import { chromium } from "playwright"; import uniqueRandomArray from "unique-random-array"; import userAgents from "top-user-agents"; import setupRoute from "./setupRoute.js"; export async function login(email, password, proxy) { const browser = await chromium.launch({ headless: false, devtools: false, }); const options = { userAgent: uniqueRandomArray(userAgents)(), viewport: { width: parseInt(Math.random() * 100 + 1250), height: parseInt(Math.random() * 100 + 750), }, locale: "en-CA", timezoneId: "America/Toronto", serviceWorkers: "block", }; if (proxy) { console.log("Using proxy", proxy); options.proxy = proxy; } const context = await browser.newContext(options); const page = await context.newPage(); await setupRoute(context); let points = null; await context.route(/points$/, async (route, request) => { const response = await route.fetch(); points = await response.text(); await route.continue(); }); await page.goto("https://www.pcoptimum.ca/login"); await page.waitForURL("https://accounts.pcid.ca/login"); await page.fill('input[id="email"]', email); await page.fill('input[id="password"]', password); try { await new Promise(async (resolve, reject) => { await page.route(/\/login$/, async (route, request) => { console.log( `${request.method()} ${request.resourceType()} ${request.url()}` ); if (request.method() === "POST") { const response = await route.fetch(); const status = response.status(); console.log(status); if (status === 200) { await route.continue(); resolve(); } else if (status === 401) { reject(new Error("Invalid email or password")); } else if (status === 429) { reject( new Error( "Oops, something went wrong. Please try again later." ) ); } else { reject( new Error("Unknown error. Please try again later.") ); } } else { await route.continue(); } }); await page.click('button:has-text("Sign in")'); }); } catch (error) { await browser.close(); throw error; } try { await page.waitForURL("https://www.pcoptimum.ca/dashboard"); for (let i = 0; i < 30; i++) { await page.waitForTimeout(1000); if (points) break; } } catch (error) { console.error(error.stack); } let cookies = null; try { cookies = JSON.stringify(await context.cookies()); } catch (error) {} await browser.close(); return { points, cookies, options }; }