| 1 | """知乎登录会话保存与当前页身份核对。""" |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | import json |
| 5 | from pathlib import Path |
| 6 | from urllib.parse import urlsplit |
| 7 | |
| 8 | from patchright.async_api import Page, async_playwright, expect |
| 9 | |
| 10 | from conf import LOCAL_CHROME_PATH |
| 11 | from uploader.zhihu_uploader.constants import ZHIHU_CREATOR_URL |
| 12 | |
| 13 | |
| 14 | PROFILE_IMAGE = "button.AppHeader-profileEntry img[alt^='点击打开'][alt$='的主页']" |
| 15 | |
| 16 | |
| 17 | async def read_zhihu_identity(page: Page) -> dict: |
| 18 | """从知乎页头已登录头像读取展示名与头像地址,作为本地会话绑定信息。""" |
| 19 | # AppHeader-profileEntry 是创作中心与视频页实际共用的当前用户入口。 |
| 20 | profile = page.locator(PROFILE_IMAGE) |
| 21 | await expect(profile).to_have_count(1, timeout=30000) |
| 22 | await expect(profile).to_be_visible() |
| 23 | label = (await profile.get_attribute("alt") or "").strip() |
| 24 | name = label.removeprefix("点击打开").removesuffix("的主页").strip() |
| 25 | avatar = profile.get_attribute("src") |
| 26 | avatar_url = (await avatar or "").strip() |
| 27 | if not name or not avatar_url: |
| 28 | raise RuntimeError("知乎页头没有可读取的当前账号信息") |
| 29 | avatar_path = urlsplit(avatar_url).path |
| 30 | if not avatar_path: |
| 31 | raise RuntimeError("知乎页头头像缺少稳定路径,无法绑定当前会话") |
| 32 | return {"name": name, "avatar_path": avatar_path} |
| 33 | |
| 34 | |
| 35 | def load_zhihu_identity(account_file: str | Path) -> dict: |
| 36 | """读取登录时记录的知乎页头信息,避免误用另一个本地账号文件。""" |
| 37 | identity_file = Path(account_file).with_suffix(".identity.json") |
| 38 | identity = json.loads(identity_file.read_text(encoding="utf-8")) |
| 39 | if not identity.get("name") or not identity.get("avatar_path"): |
| 40 | raise ValueError(f"知乎账号绑定不完整,请重新登录: {identity_file}") |
| 41 | return identity |
| 42 | |
| 43 | |
| 44 | async def login_zhihu_account(account_file: str | Path, timeout: int = 600) -> dict: |
| 45 | """在可见 Chrome 完成登录,核对页头账号后保存本地 storage state。""" |
| 46 | if timeout <= 0: |
| 47 | raise ValueError("登录期限必须大于 0 秒") |
| 48 | account_file = Path(account_file).resolve() |
| 49 | async with async_playwright() as playwright: |
| 50 | browser = await playwright.chromium.launch( |
| 51 | executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=False, |
| 52 | ) |
| 53 | try: |
| 54 | context = await browser.new_context(timezone_id="Asia/Shanghai") |
| 55 | page = await context.new_page() |
| 56 | await page.goto(ZHIHU_CREATOR_URL, wait_until="domcontentloaded", timeout=45000) |
| 57 | print("请在打开的 Chrome 中完成知乎登录;账号密码和验证码直接在网页输入。", flush=True) |
| 58 | await page.locator(PROFILE_IMAGE).wait_for(state="visible", timeout=timeout * 1000) |
| 59 | identity = await read_zhihu_identity(page) |
| 60 | identity_file = account_file.with_suffix(".identity.json") |
| 61 | if identity_file.exists() and load_zhihu_identity(account_file) != identity: |
| 62 | raise RuntimeError("当前知乎页头与已绑定会话不同,请使用新的 --account") |
| 63 | account_file.parent.mkdir(parents=True, exist_ok=True) |
| 64 | await context.storage_state(path=str(account_file)) |
| 65 | identity_file.write_text(json.dumps(identity, ensure_ascii=False, indent=2), encoding="utf-8") |
| 66 | return {"success": True, "account_file": str(account_file), "identity": identity} |
| 67 | finally: |
| 68 | await browser.close() |
| 69 | |
| 70 | |
| 71 | async def check_zhihu_account(account_file: str | Path, headless: bool = True) -> bool: |
| 72 | """仅明确回到登录路径时返回失效;网络错误或身份不一致直接报告。""" |
| 73 | account_file = Path(account_file) |
| 74 | if not account_file.is_file(): |
| 75 | return False |
| 76 | expected = load_zhihu_identity(account_file) |
| 77 | async with async_playwright() as playwright: |
| 78 | browser = await playwright.chromium.launch( |
| 79 | executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=headless, |
| 80 | ) |
| 81 | try: |
| 82 | context = await browser.new_context(storage_state=str(account_file), timezone_id="Asia/Shanghai") |
| 83 | page = await context.new_page() |
| 84 | response = await page.goto(ZHIHU_CREATOR_URL, wait_until="domcontentloaded", timeout=45000) |
| 85 | if response is not None and response.status >= 400: |
| 86 | raise RuntimeError(f"知乎创作中心访问失败,HTTP {response.status}") |
| 87 | target = urlsplit(page.url) |
| 88 | if target.path.startswith(("/signin", "/account/unlogin")): |
| 89 | return False |
| 90 | actual = await read_zhihu_identity(page) |
| 91 | if actual != expected: |
| 92 | raise RuntimeError("知乎当前页头与本地账号绑定不一致") |
| 93 | return True |
| 94 | finally: |
| 95 | await browser.close() |
| 96 |