login.mjs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. let points = null;
  19. await page.route(/points$/, async (route, request) => {
  20. const response = await route.fetch();
  21. points = await response.text();
  22. await route.continue();
  23. });
  24. await page.route(/(\.png$)|(\.jpg$)/i, (route) => route.abort());
  25. await page.goto("https://www.pcoptimum.ca/");
  26. const link = await page.$('a > span:has-text("sign in")');
  27. link.click();
  28. await page.waitForURL("https://accounts.pcid.ca/login");
  29. await page.fill('input[id="email"]', email);
  30. await page.fill('input[id="password"]', password);
  31. try {
  32. await new Promise(async (resolve, reject) => {
  33. await page.route(/\/login$/, async (route, request) => {
  34. console.log(
  35. `${request.method()} ${request.resourceType()} ${request.url()}`
  36. );
  37. if (request.method() === "POST") {
  38. const response = await route.fetch();
  39. const status = response.status();
  40. console.log(status);
  41. if (status === 200) {
  42. await route.continue();
  43. resolve();
  44. } else if (status === 401) {
  45. reject(new Error("Invalid email or password"));
  46. } else if (status === 429) {
  47. reject(
  48. new Error(
  49. "Oops, something went wrong. Please try again later."
  50. )
  51. );
  52. } else {
  53. reject(
  54. new Error("Unknown error. Please try again later.")
  55. );
  56. }
  57. } else {
  58. await route.continue();
  59. }
  60. });
  61. await page.click('button:has-text("Sign in")');
  62. });
  63. } catch (error) {
  64. await browser.close();
  65. throw error;
  66. }
  67. try {
  68. await page.waitForURL("https://www.pcoptimum.ca/dashboard");
  69. await page.waitForTimeout(5000);
  70. } catch (error) {
  71. console.error(error.stack);
  72. }
  73. await browser.close();
  74. return points;
  75. }