| import fs from 'fs'; |
| import path from 'path'; |
| import { info, error } from './logger.js'; |
|
|
| |
| |
| |
| |
| export function getHumanReadableTimestamp() { |
| const now = new Date(); |
| const year = now.getFullYear(); |
| const month = String(now.getMonth() + 1).padStart(2, '0'); |
| const day = String(now.getDate()).padStart(2, '0'); |
| const hours = String(now.getHours()).padStart(2, '0'); |
| const minutes = String(now.getMinutes()).padStart(2, '0'); |
| const seconds = String(now.getSeconds()).padStart(2, '0'); |
|
|
| return `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`; |
| } |
|
|
| |
| |
| |
| |
| export function ensureScreenshotDirectory(dir) { |
| if (!fs.existsSync(dir)) { |
| fs.mkdirSync(dir, { recursive: true }); |
| info(`创建截图目录: ${dir}`); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| export function checkCookieAvailability(cookieFile, cookiesFromEnv) { |
| |
| if (cookiesFromEnv) { |
| info('发现环境变量COOKIES,将使用环境变量中的cookies'); |
| try { |
| JSON.parse(cookiesFromEnv); |
| return true; |
| } catch (err) { |
| error('环境变量COOKIES格式无效:', err.message); |
| info('将尝试使用cookie文件...'); |
| } |
| } |
|
|
| |
| if (!fs.existsSync(cookieFile)) { |
| error(`Cookie文件不存在: ${cookieFile}`); |
| info('请先运行 npm run login 进行登录,或设置环境变量COOKIES'); |
| return false; |
| } |
| return true; |
| } |
|
|
| |
| |
| |
| |
| |
| export function checkCookieFile(cookieFile) { |
| if (!fs.existsSync(cookieFile)) { |
| error(`Cookie文件不存在: ${cookieFile}`); |
| info('请先运行 npm run login 进行登录'); |
| return false; |
| } |
| return true; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| export function loadCookies(cookieFile, cookiesFromEnv) { |
| try { |
| |
| if (cookiesFromEnv) { |
| info('从环境变量COOKIES加载cookies...'); |
| const cookies = JSON.parse(cookiesFromEnv); |
| info(`已从环境变量加载 ${cookies.length} 个cookies`); |
| return cookies; |
| } |
|
|
| |
| if (fs.existsSync(cookieFile)) { |
| info(`从文件加载cookies: ${cookieFile}`); |
| const cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf8')); |
| info(`已从文件加载 ${cookies.length} 个cookies`); |
| return cookies; |
| } |
| return []; |
| } catch (err) { |
| error('读取 Cookie 失败:', err); |
| throw err; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| export async function saveScreenshot(page, screenshotDir, prefix = 'screenshot') { |
| ensureScreenshotDirectory(screenshotDir); |
| const timestamp = getHumanReadableTimestamp(); |
| const screenshotPath = path.join(screenshotDir, `${prefix}.png`); |
| await page.screenshot({ path: screenshotPath }); |
| info(`截图已保存: ${screenshotPath}`); |
| return screenshotPath; |
| } |
|
|