| | import time |
| | import sys |
| | from playwright.sync_api import TimeoutError, Error as PlaywrightError |
| |
|
| |
|
| | class CookieValidator: |
| | """Cookie验证器,负责定期验证Cookie的有效性。""" |
| |
|
| | def __init__(self, page, context, logger): |
| | """ |
| | 初始化Cookie验证器 |
| | |
| | Args: |
| | page: 主页面实例 |
| | context: 浏览器上下文 |
| | logger: 日志记录器 |
| | """ |
| | self.page = page |
| | self.context = context |
| | self.logger = logger |
| |
|
| | |
| | def validate_cookies_in_main_thread(self): |
| | """ |
| | 在主线程中执行Cookie验证(由主线程调用) |
| | |
| | Returns: |
| | bool: Cookie是否有效 |
| | """ |
| | validation_page = None |
| | try: |
| | |
| | self.logger.info("开始Cookie验证...") |
| | validation_page = self.context.new_page() |
| |
|
| | |
| | validation_url = "https://aistudio.google.com/apps" |
| | validation_page.goto(validation_url, wait_until='domcontentloaded', timeout=30000) |
| |
|
| | |
| | validation_page.wait_for_timeout(2000) |
| |
|
| | |
| | final_url = validation_page.url |
| |
|
| | |
| | if "accounts.google.com/v3/signin/identifier" in final_url: |
| | self.logger.error("Cookie验证失败: 被重定向到登录页面") |
| | return False |
| |
|
| | if "accounts.google.com/v3/signin/accountchooser" in final_url: |
| | self.logger.error("Cookie验证失败: 被重定向到账户选择页面") |
| | return False |
| |
|
| | |
| | self.logger.info("Cookie验证成功") |
| | return True |
| |
|
| | except TimeoutError: |
| | self.logger.error("Cookie验证失败: 页面加载超时") |
| | return False |
| |
|
| | except PlaywrightError as e: |
| | self.logger.error(f"Cookie验证失败: {e}") |
| | return False |
| |
|
| | except Exception as e: |
| | self.logger.error(f"Cookie验证失败: {e}") |
| | return False |
| |
|
| | finally: |
| | |
| | if validation_page: |
| | try: |
| | validation_page.close() |
| | except Exception: |
| | pass |
| |
|
| | def shutdown_instance_on_cookie_failure(self): |
| | """ |
| | 因Cookie失效而关闭实例 |
| | """ |
| | self.logger.error("Cookie失效,关闭实例") |
| | time.sleep(1) |
| | sys.exit(1) |