| 1 | """核对雪球编辑器、预览与服务端文章的文字、图片位置和原生结构。""" |
| 2 | import json |
| 3 | import re |
| 4 | from hashlib import sha256 |
| 5 | from pathlib import Path |
| 6 | from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit |
| 7 | |
| 8 | from patchright.async_api import async_playwright, expect |
| 9 | from conf import LOCAL_CHROME_PATH |
| 10 | from uploader.xueqiu_uploader.constants import XUEQIU_HOME_URL |
| 11 | from uploader.xueqiu_uploader.content import load_xueqiu_article |
| 12 | from uploader.xueqiu_uploader.session import load_xueqiu_identity, read_xueqiu_identity |
| 13 | |
| 14 | |
| 15 | async def check_xueqiu_article_content(body, document, image_sources=None): |
| 16 | """按文字和图片交错顺序核对,不用图片数量冒充段间位置正确。""" |
| 17 | await expect(body.locator("img")).to_have_count(len(document.images)) |
| 18 | if image_sources is not None: |
| 19 | # 服务端可能保留数量但交换图片;按首次上传取得的绝对 URL 核对每个原稿位置。 |
| 20 | actual_sources = await body.locator("img").evaluate_all( |
| 21 | "images => images.map(image => new URL(image.getAttribute('src'), 'https://mp.xueqiu.com/').href)") |
| 22 | if actual_sources != image_sources: |
| 23 | raise RuntimeError("雪球文章图片内容或顺序与本次上传不一致") |
| 24 | actual = await body.evaluate("""(body, html) => { |
| 25 | let sequence = ''; |
| 26 | function visit(node) { |
| 27 | if (node.nodeType === Node.TEXT_NODE) { sequence += node.nodeValue; return; } |
| 28 | if (node.nodeName === 'IMG') { sequence += '\\x00IMG\\x00'; return; } |
| 29 | node.childNodes.forEach(visit); |
| 30 | } |
| 31 | visit(body); |
| 32 | const source = document.createElement('template'); source.innerHTML = html; |
| 33 | return {sequence, headings: body.querySelectorAll('h4').length, |
| 34 | bold: body.querySelectorAll('b,strong').length, italic: body.querySelectorAll('i,em').length, |
| 35 | links: [...body.querySelectorAll('a')].map(a => ({text: a.textContent, href: a.href})), |
| 36 | expectedLinks: [...source.content.querySelectorAll('a')].map(a => ({text: a.textContent, |
| 37 | href: new URL(a.getAttribute('href'), document.baseURI).href}))}; |
| 38 | }""", document.content_html) |
| 39 | sequence = re.sub(r"[\s\u200b\ufeff]+", "", actual["sequence"]) |
| 40 | if sha256(sequence.encode()).hexdigest() != document.manifest["structure_sha256"]: |
| 41 | raise RuntimeError("雪球文章文字或段间图片位置与原稿不一致") |
| 42 | expected = {"headings": document.tags["h4"], "bold": document.tags["strong"], "italic": document.tags["em"]} |
| 43 | for key, count in expected.items(): |
| 44 | if actual[key] != count: |
| 45 | raise RuntimeError(f"雪球文章结构不一致: {key} 期望 {count},实际 {actual[key]}") |
| 46 | if actual["links"] != actual["expectedLinks"]: |
| 47 | raise RuntimeError("雪球文章链接文字或目标与原稿不一致") |
| 48 | |
| 49 | |
| 50 | async def query_xueqiu_article(page, identity, content_id, title=None, visibility=None): |
| 51 | """通过实测的已发布管理列表查询原 ID,只读核对,绝不重新发表。""" |
| 52 | await page.goto(XUEQIU_HOME_URL, wait_until="domcontentloaded", timeout=45000) |
| 53 | if (await read_xueqiu_identity(page))["uid"] != identity["uid"]: |
| 54 | raise RuntimeError("雪球查询主体与绑定账号不一致") |
| 55 | # 内容管理是首页实际侧栏入口;SPA 导航会附带平台所需的请求头,直接请求 JSON 并不等价。 |
| 56 | async with page.expect_response(lambda response: response.request.method == "GET" |
| 57 | and urlsplit(response.url).path == "/xq/query/v1/search/long", |
| 58 | timeout=30000) as listing: |
| 59 | await page.get_by_role("link", name="内容管理", exact=True).click() |
| 60 | response = await listing.value |
| 61 | payload = await response.json() |
| 62 | # 实测列表有 page/maxPage/list;后续页沿用该请求的认证头,不输出任何认证值。 |
| 63 | headers = await response.request.all_headers() |
| 64 | query_url = urlsplit(response.url) |
| 65 | params = parse_qs(query_url.query) |
| 66 | seen_pages = set() |
| 67 | while True: |
| 68 | if not response.ok or not isinstance(payload.get("list"), list): |
| 69 | raise RuntimeError(f"雪球原作品查询失败: HTTP {response.status},未返回已发布列表") |
| 70 | matches = [item for item in payload["list"] if str(item.get("id")) == str(content_id)] |
| 71 | if len(matches) > 1: |
| 72 | raise RuntimeError("雪球同一作品 ID 匹配多条记录") |
| 73 | if matches: |
| 74 | item = matches[0] |
| 75 | if str(item.get("user_id")) != identity["uid"] or (title is not None and item.get("title") != title): |
| 76 | raise RuntimeError("雪球原作品的主体或标题不一致") |
| 77 | if visibility is not None and item.get("is_private") is not (visibility == "私人"): |
| 78 | raise RuntimeError("雪球原作品的分享范围不一致") |
| 79 | # 首屏接口先于列表绘制返回;截图前等待原作品标题可见,避免把骨架屏当作后台证据。 |
| 80 | if payload.get("page") == 1: |
| 81 | await expect(page.get_by_text(item["title"], exact=True)).to_be_visible(timeout=30000) |
| 82 | return item |
| 83 | current, last = payload.get("page"), payload.get("maxPage") |
| 84 | if not isinstance(current, int) or not isinstance(last, int) or current >= last: |
| 85 | raise RuntimeError(f"已发布列表未找到原作品 {content_id},请核查后台,勿直接重发") |
| 86 | if current in seen_pages: |
| 87 | raise RuntimeError("雪球查询重复返回同一页,已停止查询;请核查后台,勿重新发表") |
| 88 | seen_pages.add(current) |
| 89 | params["page"] = [str(current + 1)] |
| 90 | url = urlunsplit(query_url._replace(query=urlencode(params, doseq=True))) |
| 91 | response = await page.context.request.get(url, headers=headers, timeout=30000) |
| 92 | payload = await response.json() |
| 93 | |
| 94 | |
| 95 | async def verify_xueqiu_result(account_file, result_file, headless=False): |
| 96 | """从结果文件恢复原作品 ID,在绑定账号下只读查询提交结果。""" |
| 97 | account_file = Path(account_file) |
| 98 | result_file = Path(result_file) |
| 99 | result = json.loads(result_file.read_text(encoding="utf-8")) |
| 100 | identity = load_xueqiu_identity(account_file) |
| 101 | content_id = result.get("content_id", "") |
| 102 | if not re.fullmatch(r"[1-9][0-9]*", str(content_id)): |
| 103 | raise ValueError("结果文件没有平台返回的作品 ID,请先在后台核查原作品,勿重新发表") |
| 104 | if result.get("identity", {}).get("uid") != identity["uid"]: |
| 105 | raise ValueError("结果文件与所选雪球账号不一致") |
| 106 | # 当前结果保存原稿路径;查询必须使用未修改的原稿重查正文,不能清除原有内容错误后直接报成功。 |
| 107 | document = None |
| 108 | if result.get("content_file"): |
| 109 | document = load_xueqiu_article(Path(result["content_file"])) |
| 110 | if document.manifest != result.get("manifest"): |
| 111 | raise ValueError("原稿与发表时的内容不一致,请恢复原稿后查询,勿重新发表") |
| 112 | elif result.get("error"): |
| 113 | raise ValueError("旧结果缺少原稿路径且保留核对错误,请先在后台核查原作品,勿重新发表") |
| 114 | async with async_playwright() as p: |
| 115 | browser = await p.chromium.launch(executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=headless) |
| 116 | try: |
| 117 | context = await browser.new_context(storage_state=str(account_file)) |
| 118 | page = await context.new_page() |
| 119 | record = await query_xueqiu_article(page, identity, content_id, result.get("title"), result.get("visibility")) |
| 120 | if document is not None: |
| 121 | # 核对后台实际保存的正文,不改写编辑器,不触发发表动作。 |
| 122 | check_page = await context.new_page() |
| 123 | await check_page.set_content(record.get("text") or "") |
| 124 | await check_xueqiu_article_content(check_page.locator("body"), document, result.get("images")) |
| 125 | await check_page.close() |
| 126 | screenshot = result_file.with_suffix(".verified.png") |
| 127 | await page.screenshot(path=str(screenshot), full_page=True) |
| 128 | result.update(success=True, status="published", management_verified=True, |
| 129 | url=f"https://xueqiu.com/{identity['uid']}/{content_id}", |
| 130 | verified_screenshot=str(screenshot), is_private=record["is_private"]) |
| 131 | result.pop("error", None) |
| 132 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 133 | return result |
| 134 | finally: |
| 135 | await browser.close() |
| 136 |