| 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 async_playwright, expect |
| 10 | |
| 11 | from conf import LOCAL_CHROME_PATH |
| 12 | from uploader.zhihu_uploader.session import load_zhihu_identity, read_zhihu_identity |
| 13 | |
| 14 | |
| 15 | async def verify_zhihu_result(account_file, result_file, headless=False) -> dict: |
| 16 | """只读打开结果文件保存的作品 URL;缺 URL 时要求先查询创作中心原作品。""" |
| 17 | account_file = Path(account_file).resolve() |
| 18 | result_file = Path(result_file).resolve() |
| 19 | result = json.loads(result_file.read_text(encoding="utf-8")) |
| 20 | expected = load_zhihu_identity(account_file) |
| 21 | if result.get("identity") != expected: |
| 22 | raise ValueError("结果文件与当前知乎账号绑定不一致") |
| 23 | url = result.get("url") |
| 24 | if not url: |
| 25 | raise ValueError( |
| 26 | "结果文件没有知乎作品 URL;请在创作中心的内容管理中按标题和提交时间核对原作品,勿重新上传" |
| 27 | ) |
| 28 | parsed = urlsplit(url) |
| 29 | if parsed.scheme != "https" or parsed.hostname not in {"www.zhihu.com", "zhuanlan.zhihu.com"}: |
| 30 | raise ValueError("结果文件中的知乎作品 URL 不受支持") |
| 31 | if not re.search(r"/(?:p|pin|zvideo|video)/\d+/?$", parsed.path): |
| 32 | raise ValueError("结果文件 URL 未包含知乎文章或视频作品 ID") |
| 33 | |
| 34 | async with async_playwright() as playwright: |
| 35 | browser = await playwright.chromium.launch( |
| 36 | executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=headless, |
| 37 | ) |
| 38 | try: |
| 39 | context = await browser.new_context(storage_state=str(account_file), timezone_id="Asia/Shanghai") |
| 40 | page = await context.new_page() |
| 41 | response = await page.goto(url, wait_until="domcontentloaded", timeout=45000) |
| 42 | if response is not None and response.status >= 400: |
| 43 | raise RuntimeError(f"知乎原作品 URL 访问失败,HTTP {response.status}") |
| 44 | if await read_zhihu_identity(page) != expected: |
| 45 | raise RuntimeError("知乎核验页头与本地账号绑定不一致") |
| 46 | title = result.get("title") |
| 47 | if not title: |
| 48 | raise ValueError("结果文件缺少标题,无法核对原作品") |
| 49 | # 新版视频详情把标题与简介放在同一正文区,标题后还带分隔符。 |
| 50 | await expect(page.locator("main")).to_contain_text(title, timeout=30000) |
| 51 | result.update(success=True, status="published", verified=True) |
| 52 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 53 | return result |
| 54 | finally: |
| 55 | await browser.close() |
| 56 |