| 1 | """雪球登录及账号绑定;网络故障与明确退出登录分别处理。""" |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | import json |
| 5 | import re |
| 6 | from pathlib import Path |
| 7 | from urllib.parse import urlsplit |
| 8 | |
| 9 | from patchright.async_api import Page, async_playwright, expect |
| 10 | |
| 11 | from conf import LOCAL_CHROME_PATH |
| 12 | from uploader.xueqiu_uploader.constants import XUEQIU_HOME_URL |
| 13 | |
| 14 | |
| 15 | async def read_xueqiu_identity(page: Page) -> dict: |
| 16 | """页头 data-id 是当前用户 ID;昵称用于展示,不代替身份比较。""" |
| 17 | # header-user 是已登录页头固定账号区,data-id 在首页及长文编辑器均可读取。 |
| 18 | user = page.locator("nav .header-user[data-id]") |
| 19 | await expect(user).to_have_count(1, timeout=30000) |
| 20 | await expect(user).to_be_visible() |
| 21 | uid = await user.get_attribute("data-id") |
| 22 | # 用户区内 span 承载昵称,排除侧栏和正文中可能出现的相同名字。 |
| 23 | name = (await user.locator("span").inner_text()).strip() |
| 24 | if not re.fullmatch(r"[1-9][0-9]*", uid or "") or not name: |
| 25 | raise RuntimeError("雪球页头身份缺失,无法核验发布账号") |
| 26 | return {"uid": uid, "name": name} |
| 27 | |
| 28 | |
| 29 | def load_xueqiu_identity(account_file: str | Path) -> dict: |
| 30 | """恢复登录时绑定的真实用户 ID,拒绝使用未绑定账号。""" |
| 31 | path = Path(account_file).with_suffix(".identity.json") |
| 32 | identity = json.loads(path.read_text(encoding="utf-8")) |
| 33 | if not re.fullmatch(r"[1-9][0-9]*", identity.get("uid", "")) or not identity.get("name"): |
| 34 | raise ValueError(f"雪球账号绑定不完整,请重新登录: {path}") |
| 35 | return identity |
| 36 | |
| 37 | |
| 38 | async def login_xueqiu_account(account_file: str | Path, expected_name=None, timeout=600) -> dict: |
| 39 | """在独立可见 Chrome 登录;账号密码、协议与验证码均由用户在网页完成。""" |
| 40 | if timeout <= 0: |
| 41 | raise ValueError("登录期限必须大于 0 秒") |
| 42 | account_file = Path(account_file).resolve() |
| 43 | async with async_playwright() as playwright: |
| 44 | browser = await playwright.chromium.launch( |
| 45 | executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=False, |
| 46 | ) |
| 47 | try: |
| 48 | context = await browser.new_context() |
| 49 | page = await context.new_page() |
| 50 | await page.goto(XUEQIU_HOME_URL, wait_until="domcontentloaded", timeout=45000) |
| 51 | print("请在 Chrome 中完成雪球登录,然后进入创作者中心;登录态将保存到本地账号文件。", flush=True) |
| 52 | # 只等待已观察的创作者页头,登录表单消失或 Cookie 出现均不足以证明登录完成。 |
| 53 | await page.locator("nav .header-user[data-id]").wait_for(state="visible", timeout=timeout * 1000) |
| 54 | identity = await read_xueqiu_identity(page) |
| 55 | if expected_name is not None and identity["name"] != expected_name: |
| 56 | raise RuntimeError("雪球昵称与 --expected-name 不匹配") |
| 57 | binding = account_file.with_suffix(".identity.json") |
| 58 | if binding.exists() and load_xueqiu_identity(account_file)["uid"] != identity["uid"]: |
| 59 | raise RuntimeError("当前雪球账号与已绑定账号不同,请使用新的 --account") |
| 60 | account_file.parent.mkdir(parents=True, exist_ok=True) |
| 61 | await context.storage_state(path=str(account_file)) |
| 62 | binding.write_text(json.dumps(identity, ensure_ascii=False, indent=2), encoding="utf-8") |
| 63 | return {"success": True, "account_file": str(account_file), "identity": identity} |
| 64 | finally: |
| 65 | await browser.close() |
| 66 | |
| 67 | |
| 68 | async def check_xueqiu_account(account_file: str | Path, headless=False) -> bool: |
| 69 | """仅明确进入登录页时返回失效;403、网络超时和身份歧义直接报错。""" |
| 70 | account_file = Path(account_file) |
| 71 | if not account_file.is_file(): |
| 72 | return False |
| 73 | expected = load_xueqiu_identity(account_file) |
| 74 | async with async_playwright() as playwright: |
| 75 | browser = await playwright.chromium.launch( |
| 76 | executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=headless, |
| 77 | ) |
| 78 | try: |
| 79 | context = await browser.new_context(storage_state=str(account_file)) |
| 80 | page = await context.new_page() |
| 81 | response = await page.goto(XUEQIU_HOME_URL, wait_until="domcontentloaded", timeout=45000) |
| 82 | if response is not None and response.status >= 400: |
| 83 | raise RuntimeError(f"雪球访问失败,HTTP {response.status},不能据此判断登录失效") |
| 84 | target = urlsplit(page.url) |
| 85 | if target.hostname in {"xueqiu.com", "www.xueqiu.com"} and target.path == "/account/login": |
| 86 | return False |
| 87 | actual = await read_xueqiu_identity(page) |
| 88 | if actual["uid"] != expected["uid"]: |
| 89 | raise RuntimeError("雪球会话主体与本地绑定不一致") |
| 90 | return True |
| 91 | finally: |
| 92 | await browser.close() |
| 93 |