login.mjs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { chromium } from "playwright";
  2. import uniqueRandomArray from "unique-random-array";
  3. import userAgents from "top-user-agents";
  4. export async function login(email, password) {
  5. const browser = await chromium.launch({
  6. headless: true,
  7. devtools: false,
  8. });
  9. const page = await browser.newPage({
  10. userAgent: uniqueRandomArray(userAgents)(),
  11. viewport: {
  12. width: parseInt(Math.random() * 100 + 1250),
  13. height: parseInt(Math.random() * 100 + 750),
  14. },
  15. locale: "en-CA",
  16. timezoneId: "America/Toronto",
  17. });
  18. await page.route(/(\.png$)|(\.jpg$)/i, (route) => route.abort());
  19. await page.goto("https://www.pcoptimum.ca/");
  20. const link = await page.$('a > span:has-text("sign in")');
  21. link.click();
  22. await page.waitForURL("https://accounts.pcid.ca/login");
  23. await page.fill('input[id="email"]', email);
  24. await page.fill('input[id="password"]', password);
  25. try {
  26. await new Promise(async (resolve, reject) => {
  27. await page.route(/\/login$/, async (route, request) => {
  28. console.log(
  29. `${request.method()} ${request.resourceType()} ${request.url()}`
  30. );
  31. if (request.method() === "POST") {
  32. const response = await route.fetch();
  33. const status = response.status();
  34. console.log(status);
  35. if (status === 200) {
  36. await route.continue();
  37. resolve();
  38. } else if (status === 401) {
  39. reject(new Error("Invalid email or password"));
  40. } else if (status === 429) {
  41. reject(
  42. new Error(
  43. "Oops, something went wrong. Please try again later."
  44. )
  45. );
  46. } else {
  47. reject(new Error("Unknown error. Please try again later."));
  48. }
  49. } else {
  50. await route.continue();
  51. }
  52. });
  53. await page.click('button:has-text("Sign in")');
  54. });
  55. } catch (error) {
  56. await browser.close();
  57. throw error;
  58. }
  59. let points = null;
  60. await page.route(/points$/, async (route, request) => {
  61. const response = await route.fetch();
  62. points = await response.text();
  63. await route.continue();
  64. });
  65. try {
  66. await page.waitForURL("https://www.pcoptimum.ca/dashboard");
  67. } catch (error) {
  68. console.error(error.stack);
  69. }
  70. await browser.close();
  71. return points;
  72. }