| import { chromium } from 'playwright'; |
| import fs from 'fs'; |
| import config from './config.js'; |
| import { fileURLToPath } from 'url'; |
| import path from 'path'; |
| import { loadCookies } from './utils/common-utils.js'; |
| import { info, error } from './utils/logger.js'; |
| async function login() { |
| info('启动浏览器...'); |
| const browser = await chromium.launch(config.browserOptions); |
| const context = await browser.newContext(); |
|
|
| const cookies = loadCookies(config.cookieFile, config.cookiesFromEnv); |
| await context.addCookies(cookies); |
|
|
| const page = await context.newPage(); |
|
|
| try { |
| info(`导航到登录页面:${config.webideUrl}...`); |
| |
| await page.goto(config.webideUrl); |
|
|
| |
| await page.waitForTimeout(config.waitTimes.pageLoad); |
|
|
| info('当前页面URL:', page.url()); |
| info('页面标题:', await page.title()); |
|
|
| |
| const isLoggedIn = await page.locator(config.selectors.editor).count() > 0; |
|
|
| if (isLoggedIn) { |
| info('检测到已经登录状态,保存cookie...'); |
| } else { |
| info('需要登录,请在浏览器中手动完成登录过程...'); |
| info('登录完成后,请按 Enter 键继续...'); |
|
|
| |
| await waitForUserInput(); |
|
|
| |
| info('等待登录完成...'); |
| try { |
| await page.goto(config.webideUrl); |
| await page.waitForSelector(config.selectors.editor, { |
| timeout: 60000 |
| }); |
|
|
| } catch (err) { |
| info('未检测到编辑器界面,但继续保存cookie...'); |
| } |
| } |
|
|
| |
| const cookies = await context.cookies(); |
| fs.writeFileSync(config.cookieFile, JSON.stringify(cookies, null, 2)); |
| info(`Cookies已保存到 ${config.cookieFile}`); |
| info(`保存了 ${cookies.length} 个cookies`); |
|
|
| |
| info('保存的cookie名称:'); |
| cookies.forEach(cookie => { |
| info(` - ${cookie.name} (域名: ${cookie.domain})`); |
| }); |
|
|
| } catch (err) { |
| error('登录过程中发生错误:', err); |
| } finally { |
| await browser.close(); |
| } |
| } |
|
|
| |
| async function waitForUserInput() { |
| const { default: readline } = await import('readline'); |
| return new Promise((resolve) => { |
| const rl = readline.createInterface({ |
| input: process.stdin, |
| output: process.stdout |
| }); |
|
|
| rl.question('', () => { |
| rl.close(); |
| resolve(); |
| }); |
| }); |
| } |
|
|
| |
| const __filename = fileURLToPath(import.meta.url); |
| const scriptPath = path.resolve(process.argv[1]); |
|
|
| if (path.resolve(__filename) === scriptPath) { |
| login().catch(error); |
| } |
|
|
|
|