Spaces:
Sleeping
Sleeping
File size: 33,983 Bytes
efd8f02 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 |
import re
import time
import random
import threading
from enum import Enum
from typing import Optional, Callable
from dataclasses import dataclass, field
from datetime import datetime
from urllib.parse import urlparse, parse_qs
import logging
from DrissionPage import Chromium, ChromiumOptions
from email_manager import EmailManager
logger = logging.getLogger(__name__)
class AccountStatus(Enum):
PENDING = "pending"
CREATING_EMAIL = "creating_email"
OPENING_PAGE = "opening_page"
ENTERING_EMAIL = "entering_email"
WAITING_CODE = "waiting_code"
ENTERING_CODE = "entering_code"
VERIFYING = "verifying"
ENTERING_NAME = "entering_name"
AGREEING = "agreeing"
WAITING_REDIRECT = "waiting_redirect"
COMPLETING = "completing"
EXTRACTING_DATA = "extracting_data"
SUCCESS = "success"
FAILED = "failed"
UPDATING = "updating"
@dataclass
class AccountInfo:
email: str = ""
jwt: str = ""
status: AccountStatus = AccountStatus.PENDING
error_message: str = ""
verification_code: str = ""
c_oses: str = ""
c_ses: str = ""
csesidx: str = ""
config_id: str = ""
created_at: str = ""
updated_at: str = ""
email_config: dict = field(default_factory=dict)
def to_dict(self) -> dict:
return {
"email": self.email,
"status": self.status.value,
"error_message": self.error_message,
"verification_code": self.verification_code,
"c_oses": self.c_oses,
"c_ses": self.c_ses,
"csesidx": self.csesidx,
"config_id": self.config_id,
"created_at": self.created_at,
"updated_at": self.updated_at,
"is_complete": self.is_complete()
}
def to_export_dict(self) -> dict:
"""导出格式,包含时间戳"""
return {
"available": True,
"csesidx": self.csesidx,
"host_c_oses": self.c_oses,
"secure_c_ses": self.c_ses,
"team_id": self.config_id,
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
"created_at": self.created_at or datetime.now().isoformat(),
"updated_at": self.updated_at or self.created_at or datetime.now().isoformat()
}
def is_complete(self) -> bool:
return all([
self.c_oses,
self.c_ses,
self.csesidx,
self.config_id
])
class BrowserWorker(threading.Thread):
"""浏览器工作线程"""
def __init__(
self,
worker_id: int,
account: AccountInfo,
config,
mode: str = "register",
on_update: Optional[Callable] = None,
on_complete: Optional[Callable] = None
):
super().__init__(daemon=True)
self.worker_id = worker_id
self.account = account
self.config = config
self.mode = mode
self.on_update = on_update
self.on_complete = on_complete
self.is_running = True
self.browser: Optional[Chromium] = None
self.page = None
def update_status(self, status: AccountStatus, error: str = ""):
"""更新状态"""
self.account.status = status
self.account.error_message = error
self.account.updated_at = datetime.now().isoformat()
if self.on_update:
self.on_update(self.account.email, self.account)
def create_browser(self) -> bool:
"""创建浏览器实例"""
try:
self.close_browser()
options = ChromiumOptions().auto_port()
# 设置浏览器路径
browser_path = self.config.get_browser_path()
if browser_path:
options.set_browser_path(browser_path)
logger.info(f"[{self.worker_id}] 使用浏览器: {browser_path}")
ua = self.config.get_user_agent()
options.set_user_agent(ua)
if self.config.get_headless():
options.set_argument('--headless=new')
options.set_argument('--incognito')
options.set_argument('--disable-blink-features=AutomationControlled')
options.set_argument('--no-sandbox')
options.set_argument('--disable-dev-shm-usage')
options.set_argument('--disable-gpu')
options.set_argument('--lang=zh-CN')
options.set_argument('--disable-web-security')
options.set_argument('--disable-features=VizDisplayCompositor')
fingerprint = self.config.get_browser_fingerprint()
if fingerprint:
if fingerprint.get('window_size'):
w, h = fingerprint['window_size'].split('x')
options.set_argument(f'--window-size={w},{h}')
if fingerprint.get('timezone'):
options.set_argument(f'--timezone={fingerprint["timezone"]}')
if fingerprint.get('locale'):
options.set_argument(f'--lang={fingerprint["locale"]}')
options.set_argument('--disable-reading-from-canvas')
options.set_pref('credentials_enable_service', False)
options.set_pref('profile.password_manager_enabled', False)
self.browser = Chromium(options)
self.page = self.browser.latest_tab
self._inject_fingerprint_script()
return True
except Exception as e:
logger.error(f"创建浏览器失败: {e}")
return False
def _inject_fingerprint_script(self):
"""注入指纹混淆脚本"""
script = '''
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] });
Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh', 'en'] });
window.chrome = { runtime: {} };
'''
try:
self.page.run_js(script)
except:
pass
def close_browser(self):
"""关闭浏览器"""
if self.browser:
try:
self.browser.quit()
except:
pass
finally:
self.browser = None
self.page = None
def get_screenshot(self) -> Optional[str]:
"""获取当前页面截图 (Base64)"""
if self.page:
try:
return self.page.get_screenshot(as_base64=True, full_page=False)
except Exception as e:
logger.error(f"截图失败: {e}")
return None
return None
def safe_input(self, selector: str, text: str, max_retries: int = 3) -> bool:
"""安全输入文本"""
for attempt in range(max_retries):
try:
ele = self.page.ele(selector, timeout=10)
if not ele:
continue
ele.clear()
time.sleep(0.3)
clean_text = ''.join(c for c in text if ord(c) < 128)
ele.input(clean_text)
time.sleep(0.5)
input_value = ele.attr('value') or ele.value
if input_value and clean_text in input_value:
return True
else:
ele.clear()
time.sleep(0.5)
except Exception as e:
logger.error(f"输入失败: {e}")
time.sleep(1)
return False
def wait_and_input(self, selector: str, text: str, timeout: float = 10, description: str = "") -> bool:
"""等待元素并输入"""
try:
ele = self.page.ele(selector, timeout=timeout)
if ele:
ele.clear()
ele.input(text)
logger.info(f"输入成功: {description}")
return True
else:
logger.warning(f"未找到输入框: {description}")
return False
except Exception as e:
logger.error(f"输入失败 {description}: {e}")
return False
def wait_and_click(self, selector: str, timeout: float = 10) -> bool:
"""等待并点击元素"""
try:
ele = self.page.ele(selector, timeout=timeout)
if ele:
ele.click()
return True
return False
except Exception as e:
logger.error(f"点击失败: {e}")
return False
def wait_for_url_pattern(self, pattern: str, timeout: float = 60) -> bool:
"""等待URL匹配模式"""
start_time = time.time()
while time.time() - start_time < timeout:
if not self.is_running:
return False
try:
current_url = self.page.url
if re.search(pattern, current_url):
return True
except:
pass
time.sleep(1)
return False
def wait_for_element(self, selector: str, timeout: float = 30) -> bool:
"""等待元素出现"""
start_time = time.time()
while time.time() - start_time < timeout:
if not self.is_running:
return False
try:
ele = self.page.ele(selector, timeout=1)
if ele:
return True
except:
pass
time.sleep(0.5)
return False
def extract_data(self) -> bool:
"""提取数据"""
try:
cookies = self.page.cookies()
for cookie in cookies:
name = cookie.get('name', '')
if name == '__Host-C_OSES':
self.account.c_oses = cookie.get('value', '')
elif name == '__Secure-C_SES':
self.account.c_ses = cookie.get('value', '')
current_url = self.page.url
parsed = urlparse(current_url)
query_params = parse_qs(parsed.query)
self.account.csesidx = query_params.get('csesidx', [''])[0]
path_match = re.search(r'/cid/([a-f0-9-]+)', parsed.path)
if path_match:
self.account.config_id = path_match.group(1)
# 设置更新时间
self.account.updated_at = datetime.now().isoformat()
return self.account.is_complete()
except Exception as e:
logger.error(f"提取数据失败: {e}")
return False
def handle_welcome_dialog(self) -> bool:
"""处理欢迎对话框"""
try:
time.sleep(2)
try:
app_ele = self.page.ele('tag:ucs-standalone-app', timeout=5)
if app_ele:
sr1 = app_ele.shadow_root
if sr1:
dialog_ele = sr1.ele('tag:ucs-welcome-dialog', timeout=3)
if dialog_ele:
sr2 = dialog_ele.shadow_root
if sr2:
btn_ele = sr2.ele('tag:md-text-button', timeout=3)
if btn_ele:
sr3 = btn_ele.shadow_root
if sr3:
inner_btn = sr3.ele('tag:button', timeout=3)
if inner_btn:
inner_btn.click()
return True
except:
pass
try:
js_code = '''
function clickWelcomeButton() {
const app = document.querySelector('ucs-standalone-app');
if (app && app.shadowRoot) {
const dialog = app.shadowRoot.querySelector('ucs-welcome-dialog');
if (dialog && dialog.shadowRoot) {
const btn = dialog.shadowRoot.querySelector('md-text-button');
if (btn) {
if (btn.shadowRoot) {
const innerBtn = btn.shadowRoot.querySelector('button');
if (innerBtn) { innerBtn.click(); return true; }
}
btn.click();
return true;
}
}
}
return false;
}
return clickWelcomeButton();
'''
result = self.page.run_js(js_code)
return bool(result)
except:
pass
return False
except:
return False
def click_verify_button(self) -> bool:
"""点击验证按钮"""
verify_selectors = [
'xpath://button[@jsname="XooR8e"]',
'xpath://button[@aria-label="验证"]',
'xpath://button[contains(@class, "YUhpIc-LgbsSe") and @type="submit"]',
'xpath://button[.//span[contains(text(), "验证")]]',
'css:button[jsname="XooR8e"]',
'css:button[aria-label="验证"]',
]
for selector in verify_selectors:
try:
ele = self.page.ele(selector, timeout=3)
if ele:
time.sleep(0.5)
ele.click()
logger.info(f"成功点击验证按钮: {selector}")
return True
except:
continue
try:
js_code = '''
const buttons = document.querySelectorAll('button');
for (const btn of buttons) {
if (btn.getAttribute('jsname') === 'XooR8e' ||
btn.getAttribute('aria-label') === '验证' ||
btn.innerText.includes('验证')) {
btn.click();
return true;
}
}
return false;
'''
result = self.page.run_js(js_code)
if result:
logger.info("通过 JavaScript 成功点击验证按钮")
return True
except:
pass
return False
def click_resend_button(self) -> bool:
"""点击重新发送按钮"""
resend_selectors = [
'button[aria-label="Resend Code"]',
'button[aria-label="重新发送"]',
'xpath://button[contains(., "Resend")]',
'xpath://button[contains(., "重新发送验证码")]',
]
for sel in resend_selectors:
if self.wait_and_click(sel, timeout=5):
logger.info(f"[{self.worker_id}] 已点击重新发送按钮")
return True
return False
def get_verification_code_with_retry(self, email_manager) -> Optional[str]:
"""带重试机制的获取验证码"""
max_loops = 1
for i in range(max_loops):
logger.info(f"[{self.worker_id}] 第 {i+1} 次尝试获取验证码流程")
# 1. 第一次检测 (15次)
logger.info(f"[{self.worker_id}] 正在检测邮件 (10次尝试)...")
code = email_manager.check_verification_code(self.account.email, max_retries=10)
if code:
return code
# 2. 如果没收到,检测是否有重发按钮
logger.info(f"[{self.worker_id}] 未收到邮件,检查重发按钮...")
if self.click_resend_button():
logger.info(f"[{self.worker_id}] 点击了重发按钮,等待邮件发送...")
time.sleep(10) # 等待邮件发送
continue # 重新开始循环,会再次检测邮件
# 3. 如果没有重发按钮,继续等待15次
logger.info(f"[{self.worker_id}] 未找到重发按钮,继续等待邮件 (10次尝试)...")
code = email_manager.check_verification_code(self.account.email, max_retries=10)
if code:
return code
# 4. 再次检测重发按钮
logger.info(f"[{self.worker_id}] 仍未收到邮件,再次检查重发按钮...")
if self.click_resend_button():
logger.info(f"[{self.worker_id}] 点击了重发按钮,等待邮件发送...")
time.sleep(10)
continue
else:
logger.warning(f"[{self.worker_id}] 无法找到重发按钮且未收到邮件,本轮失败")
return None
return None
def register_account(self) -> bool:
"""注册账号"""
try:
self.update_status(AccountStatus.OPENING_PAGE)
logger.info(f"[{self.worker_id}] 正在打开页面...")
self.page.get('https://business.gemini.google')
email_input_selectors = [
'xpath://input[@id="email-input"]',
'xpath://input[@name="loginHint"]',
'#email-input',
]
email_input_found = False
for selector in email_input_selectors:
if self.wait_for_element(selector, timeout=30):
email_input_found = True
break
if not email_input_found:
raise Exception("等待邮箱输入框超时")
time.sleep(1)
self.update_status(AccountStatus.ENTERING_EMAIL)
logger.info(f"[{self.worker_id}] 正在输入邮箱: {self.account.email}")
input_success = False
for selector in email_input_selectors:
if self.safe_input(selector, self.account.email):
input_success = True
break
if not input_success:
raise Exception("无法输入邮箱")
time.sleep(1)
continue_selectors = [
'xpath://button[@id="log-in-button"]',
'xpath://button[contains(@aria-label, "使用邮箱继续")]',
'#log-in-button',
]
clicked = False
for selector in continue_selectors:
if self.wait_and_click(selector, timeout=5):
clicked = True
break
if not clicked:
raise Exception("无法点击继续按钮")
time.sleep(2)
self.update_status(AccountStatus.WAITING_CODE)
logger.info(f"[{self.worker_id}] 正在等待验证码...")
email_manager = EmailManager(
self.account.email_config.get('worker_domain', ''),
self.account.email_config.get('email_domain', ''),
self.account.email_config.get('admin_password', '')
)
verification_code = self.get_verification_code_with_retry(email_manager)
if not verification_code:
raise Exception("未收到验证码 (已重试)")
self.account.verification_code = verification_code
logger.info(f"[{self.worker_id}] 获取到验证码: {verification_code}")
self.update_status(AccountStatus.ENTERING_CODE)
code_input_selectors = [
'xpath://input[@name="pinInput"]',
'xpath://input[contains(@aria-label, "验证码")]',
'input[name="pinInput"]',
]
logger.info(f"[{self.worker_id}] 正在输入验证码: {self.account.email}")
input_success = False
for selector in code_input_selectors:
if self.wait_and_input(selector, verification_code, timeout=10, description="验证码输入框"):
input_success = True
break
if not input_success:
raise Exception("无法输入验证码")
time.sleep(1)
self.update_status(AccountStatus.VERIFYING)
if not self.click_verify_button():
raise Exception("无法点击验证按钮")
time.sleep(3)
# 检查验证码错误并重试
if self.page.ele('text:请输入验证码。', timeout=2):
logger.warning(f"[{self.worker_id}] 验证码失效,尝试重新发送...")
resend_selectors = [
'button[aria-label="重新发送验证码"]',
'xpath://button[contains(., "重新发送验证码")]'
]
resend_clicked = False
for sel in resend_selectors:
if self.wait_and_click(sel, timeout=5):
resend_clicked = True
break
if resend_clicked:
logger.info(f"[{self.worker_id}] 已点击重新发送,等待新验证码...")
time.sleep(10) # 等待邮件发送
verification_code = email_manager.check_verification_code(self.account.email)
if not verification_code:
raise Exception("重发后未收到验证码")
self.account.verification_code = verification_code
logger.info(f"[{self.worker_id}] 获取到新验证码: {verification_code}")
input_success = False
for selector in code_input_selectors:
if self.wait_and_input(selector, verification_code, timeout=10, description="验证码输入框"):
input_success = True
break
if input_success:
time.sleep(1)
if not self.click_verify_button():
raise Exception("无法点击验证按钮(重试)")
time.sleep(3)
else:
raise Exception("无法重新输入验证码")
else:
logger.warning(f"[{self.worker_id}] 未找到重新发送按钮")
self.update_status(AccountStatus.ENTERING_NAME)
fullname = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=5))
name_selectors = [
'xpath://input[@formcontrolname="fullName"]',
'xpath://input[@placeholder="全名"]',
'input[formcontrolname="fullName"]',
]
name_input_found = False
for selector in name_selectors:
if self.wait_for_element(selector, timeout=15):
name_input_found = True
break
if not name_input_found:
raise Exception("等待姓名输入框超时")
input_success = False
for selector in name_selectors:
if self.safe_input(selector, fullname):
input_success = True
break
if not input_success:
raise Exception("无法输入姓名")
time.sleep(1)
self.update_status(AccountStatus.AGREEING)
agree_selectors = [
'xpath://button[contains(@class, "agree-button")]',
'xpath://button[contains(., "同意并开始使用")]',
'xpath://button[contains(., "同意")]',
'button.agree-button',
]
clicked = False
for selector in agree_selectors:
if self.wait_and_click(selector, timeout=5):
clicked = True
break
if not clicked:
raise Exception("无法点击同意按钮")
self.update_status(AccountStatus.WAITING_REDIRECT)
target_pattern = r'business\.gemini\.google/home/cid/[a-f0-9-]+\?csesidx=\d+'
if not self.wait_for_url_pattern(target_pattern, timeout=90):
current_url = self.page.url
if '/admin/create' in current_url:
time.sleep(15)
if not self.wait_for_url_pattern(target_pattern, timeout=120):
raise Exception("页面跳转超时")
else:
raise Exception("页面跳转超时")
time.sleep(3)
self.update_status(AccountStatus.COMPLETING)
self.handle_welcome_dialog()
time.sleep(2)
self.update_status(AccountStatus.EXTRACTING_DATA)
if self.extract_data():
# 设置创建时间
if not self.account.created_at:
self.account.created_at = datetime.now().isoformat()
self.update_status(AccountStatus.SUCCESS)
logger.info(f"[{self.worker_id}] 注册成功!")
return True
else:
raise Exception("未能获取完整数据")
except Exception as e:
error_msg = str(e)
logger.error(f"[{self.worker_id}] 注册失败: {error_msg}")
self.update_status(AccountStatus.FAILED, error_msg)
return False
def refresh_account(self) -> bool:
"""刷新账号Cookie"""
try:
self.update_status(AccountStatus.UPDATING)
logger.info(f"[{self.worker_id}] 正在刷新账号: {self.account.email}")
self.page.get('https://business.gemini.google')
email_input_selectors = [
'xpath://input[@id="email-input"]',
'xpath://input[@name="loginHint"]',
'#email-input',
]
logger.info(f"[{self.worker_id}] 正在等待邮箱输入框: {self.account.email}")
email_input_found = False
for selector in email_input_selectors:
if self.wait_for_element(selector, timeout=30):
email_input_found = True
break
if not email_input_found:
raise Exception("等待邮箱输入框超时")
time.sleep(1)
input_success = False
for selector in email_input_selectors:
if self.safe_input(selector, self.account.email):
input_success = True
break
if not input_success:
raise Exception("无法输入邮箱")
time.sleep(1)
logger.info(f"[{self.worker_id}] 正在点击继续按钮: {self.account.email}")
continue_selectors = [
'xpath://button[@id="log-in-button"]',
'xpath://button[contains(@aria-label, "使用邮箱继续")]',
'#log-in-button',
]
clicked = False
for selector in continue_selectors:
if self.wait_and_click(selector, timeout=5):
clicked = True
break
if not clicked:
raise Exception("无法点击继续按钮")
time.sleep(2)
email_manager = EmailManager(
self.account.email_config.get('worker_domain', ''),
self.account.email_config.get('email_domain', ''),
self.account.email_config.get('admin_password', '')
)
logger.info(f"[{self.worker_id}] 正在获取邮箱验证码: {self.account.email}")
verification_code = self.get_verification_code_with_retry(email_manager)
if not verification_code:
raise Exception("未收到验证码 (已重试)")
self.account.verification_code = verification_code
code_input_selectors = [
'xpath://input[@name="pinInput"]',
'xpath://input[contains(@aria-label, "验证码")]',
'input[name="pinInput"]',
]
logger.info(f"[{self.worker_id}] 正在输入验证码: {self.account.email}")
input_success = False
for selector in code_input_selectors:
if self.wait_and_input(selector, verification_code, timeout=10, description="验证码输入框"):
input_success = True
break
if not input_success:
raise Exception("无法输入验证码")
time.sleep(1)
if not self.click_verify_button():
raise Exception("无法点击验证按钮")
time.sleep(3)
# 检查验证码错误并重试
if self.page.ele('text:请输入验证码。', timeout=2):
logger.warning(f"[{self.worker_id}] 验证码失效,尝试重新发送...")
resend_selectors = [
'button[aria-label="重新发送验证码"]',
'xpath://button[contains(., "重新发送验证码")]'
]
resend_clicked = False
for sel in resend_selectors:
if self.wait_and_click(sel, timeout=5):
resend_clicked = True
break
if resend_clicked:
logger.info(f"[{self.worker_id}] 已点击重新发送,等待新验证码...")
time.sleep(10) # 等待邮件发送
verification_code = email_manager.check_verification_code(self.account.email)
if not verification_code:
raise Exception("重发后未收到验证码")
self.account.verification_code = verification_code
logger.info(f"[{self.worker_id}] 获取到新验证码: {verification_code}")
input_success = False
for selector in code_input_selectors:
if self.wait_and_input(selector, verification_code, timeout=10, description="验证码输入框"):
input_success = True
break
if input_success:
time.sleep(1)
if not self.click_verify_button():
raise Exception("无法点击验证按钮(重试)")
time.sleep(3)
else:
raise Exception("无法重新输入验证码")
else:
logger.warning(f"[{self.worker_id}] 未找到重新发送按钮")
logger.info(f"[{self.worker_id}] 正在等待跳转: {self.account.email}")
target_pattern = r'business\.gemini\.google/home/cid/[a-f0-9-]+\?csesidx=\d+'
if not self.wait_for_url_pattern(target_pattern, timeout=120):
raise Exception("页面跳转超时")
time.sleep(3)
self.handle_welcome_dialog()
time.sleep(2)
if self.extract_data():
self.account.updated_at = datetime.now().isoformat()
self.update_status(AccountStatus.SUCCESS)
logger.info(f"[{self.worker_id}] 刷新成功!")
return True
else:
raise Exception("未能获取完整数据")
except Exception as e:
error_msg = str(e)
logger.error(f"[{self.worker_id}] 刷新失败: {error_msg}")
self.update_status(AccountStatus.FAILED, error_msg)
return False
def run(self):
"""运行工作线程"""
success = False
try:
if not self.create_browser():
self.update_status(AccountStatus.FAILED, "创建浏览器失败")
return
if self.mode == "register":
success = self.register_account()
else:
success = self.refresh_account()
except Exception as e:
self.update_status(AccountStatus.FAILED, str(e))
finally:
self.close_browser()
if self.on_complete:
self.on_complete(self.worker_id, self.account.email, success)
def stop(self):
"""停止工作线程"""
self.is_running = False
self.close_browser()
|