| 1 | """只读确认原作品已提交发表;显式要求时再等待公开并核验内容。""" |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | import asyncio |
| 5 | import re |
| 6 | import time |
| 7 | from datetime import datetime |
| 8 | from hashlib import sha256 |
| 9 | from urllib.parse import parse_qs, urlencode, urlsplit |
| 10 | from uuid import uuid4 |
| 11 | |
| 12 | from patchright.async_api import Browser, BrowserContext, Locator, expect |
| 13 | from uploader.dayu_uploader.constants import DAYU_CONTENT_PUBLIC, DAYU_CONTENT_REVIEWING, DAYU_CONTENT_SCHEDULED, DAYU_TIMEZONE |
| 14 | from utils.log import dayu_logger |
| 15 | |
| 16 | |
| 17 | async def check_dayu_article_content(body: Locator, manifest: dict) -> None: |
| 18 | """编辑器和公开正文共用内容检查,图文顺序或支持的格式有变化即报错。""" |
| 19 | await expect(body.locator("img")).to_have_count(manifest["image_count"]) |
| 20 | text = re.sub(r"[\s\u200b\ufeff]+", "", await body.inner_text()) |
| 21 | if sha256(text.encode()).hexdigest() != manifest["text_sha256"]: |
| 22 | raise RuntimeError("文章正文与输入文件文字不一致") |
| 23 | sequence = await body.evaluate("""body => { |
| 24 | let value = ''; |
| 25 | function visit(node) { |
| 26 | if (node.nodeType === Node.TEXT_NODE) { value += node.nodeValue; return; } |
| 27 | if (node.nodeName === 'IMG') { value += '\\x00IMG\\x00'; return; } |
| 28 | if (node.nodeName === 'HR') { value += '\\x00HR\\x00'; return; } |
| 29 | node.childNodes.forEach(visit); |
| 30 | } |
| 31 | visit(body); return value; |
| 32 | }""") |
| 33 | sequence = re.sub(r"[\s\u200b\ufeff]+", "", sequence) |
| 34 | if sha256(sequence.encode()).hexdigest() != manifest["structure_sha256"]: |
| 35 | raise RuntimeError("文章的文字、图片或分隔线顺序与输入文件不一致") |
| 36 | for tag, count in manifest["formats"].items(): |
| 37 | await expect(body.locator(tag)).to_have_count(count) |
| 38 | if manifest.get("dayu_style"): |
| 39 | # 兼容排版使用服务器实测保留的 font/table 属性;检查实际计算颜色,避免属性存在却被覆盖。 |
| 40 | actual = await body.evaluate("""body => ({ |
| 41 | text_colors: [...body.querySelectorAll('font[color]')].map(font => ({ |
| 42 | text: font.textContent.replace(/[\\s\\u200b\\ufeff]+/g, ''), color: getComputedStyle(font).color, |
| 43 | })), |
| 44 | background_colors: [...body.querySelectorAll('table[bgcolor]')].map(table => getComputedStyle(table).backgroundColor), |
| 45 | })""") |
| 46 | if actual != manifest["dayu_style"]: |
| 47 | raise RuntimeError("大鱼号预览或公开正文未保留预期的主题文字颜色、背景色") |
| 48 | |
| 49 | |
| 50 | async def wait_dayu_publication(context: BrowserContext, content_id: str | None = None, |
| 51 | origin_id: str | None = None, title: str | None = None, |
| 52 | timeout: int = 60, public: bool = False, |
| 53 | schedule: str | None = None) -> dict: |
| 54 | """默认确认原作品已提交;只有显式公开核验才等待公开,始终不重发。""" |
| 55 | if not content_id and not origin_id: |
| 56 | raise ValueError("核验必须提供 content_id 或 origin_id(预览时保存的草稿 ID)") |
| 57 | deadline = time.monotonic() + timeout |
| 58 | record = None |
| 59 | last_status = None |
| 60 | while time.monotonic() < deadline: |
| 61 | page_number = 1 |
| 62 | total_pages = 1 |
| 63 | record = None |
| 64 | while page_number <= total_pages and time.monotonic() < deadline: |
| 65 | # 来自真实“全部”页的请求参数。不能依赖发表后跳转的 shortvideo 筛选。 |
| 66 | response = await context.request.get( |
| 67 | "https://mp.dayu.com/dashboard/getNewContentList", |
| 68 | params={"_rid": uuid4().hex, "currentView": "all", "source": "all", |
| 69 | "page": page_number, "currentTab": "all", "_": int(time.time() * 1000)}, |
| 70 | timeout=max(1, min(30000, int((deadline - time.monotonic()) * 1000))), |
| 71 | ) |
| 72 | if not response.ok: |
| 73 | raise RuntimeError(f"查询大鱼号作品失败: HTTP {response.status}") |
| 74 | payload = await response.json() |
| 75 | data_list = payload.get("dataList") |
| 76 | if not isinstance(data_list, dict) or not isinstance(data_list.get("data"), list): |
| 77 | raise RuntimeError("作品查询未返回 dataList.data;可能登录失效或平台接口变化") |
| 78 | total_pages = int(data_list["totalPage"]) |
| 79 | matches = [item for item in data_list["data"] |
| 80 | if (not content_id or str(item.get("content_id")) == content_id) |
| 81 | and (not origin_id or item.get("origin_id") == origin_id)] |
| 82 | if len(matches) > 1: |
| 83 | raise RuntimeError("同一作品 ID 匹配多条记录,拒绝判定成功") |
| 84 | if matches: |
| 85 | record = matches[0] |
| 86 | break |
| 87 | page_number += 1 |
| 88 | if record: |
| 89 | if title is not None and record.get("title") != title: |
| 90 | raise RuntimeError("作品 ID 对应的标题与本次提交不一致") |
| 91 | current_status = {"status": record.get("status"), "audit_status": record.get("audit_status")} |
| 92 | if current_status != last_status: |
| 93 | dayu_logger.info(f"大鱼号作品查询: content_id={record.get('content_id')},{current_status}") |
| 94 | last_status = current_status |
| 95 | # 审核中的原作品已提交成功;公开核验是调用者额外选择的检查范围。 |
| 96 | if schedule or record.get("status") == DAYU_CONTENT_SCHEDULED: |
| 97 | epoch = record.get("_app_extra", {}).get("time_for_release") |
| 98 | if isinstance(epoch, bool) or not isinstance(epoch, (int, float)) or epoch <= 0: |
| 99 | raise RuntimeError("原作品缺少已保存的定时安排,拒绝确认成功") |
| 100 | actual = datetime.fromtimestamp(epoch / 1000, DAYU_TIMEZONE) |
| 101 | if schedule and actual != datetime.fromisoformat(schedule): |
| 102 | raise RuntimeError(f"原作品定时时间不一致: 预期={schedule},实际={actual.isoformat()}") |
| 103 | accepted = (DAYU_CONTENT_PUBLIC,) if public else (DAYU_CONTENT_PUBLIC, DAYU_CONTENT_REVIEWING, DAYU_CONTENT_SCHEDULED) |
| 104 | if record.get("status") in accepted: |
| 105 | break |
| 106 | await asyncio.sleep(min(5, max(0, deadline - time.monotonic()))) |
| 107 | else: |
| 108 | target = "公开访问" if public else "提交发表确认" |
| 109 | raise TimeoutError(f"等待大鱼号{target}超时;最后状态={last_status},请核查原作品,勿重新上传") |
| 110 | |
| 111 | return record |
| 112 | |
| 113 | |
| 114 | async def verify_dayu_video(context: BrowserContext, browser: Browser, identity: dict, |
| 115 | content_id: str | None = None, origin_id: str | None = None, |
| 116 | title: str | None = None, timeout: int = 60, public: bool = False, |
| 117 | schedule: str | None = None) -> dict: |
| 118 | """确认原视频已提交;public=True 时额外验证匿名标题、作者及播放。""" |
| 119 | record = await wait_dayu_publication(context, content_id, origin_id, title, timeout, public, schedule) |
| 120 | result = {"success": True, "status": "published" if record["status"] == DAYU_CONTENT_PUBLIC else "submitted", "type": "video", |
| 121 | "content_id": str(record["content_id"]), "origin_id": record["origin_id"], |
| 122 | "title": record["title"], "identity": identity, "platform_status": record["status"]} |
| 123 | if schedule or record["status"] == DAYU_CONTENT_SCHEDULED: |
| 124 | result.update(schedule=datetime.fromtimestamp(record["_app_extra"]["time_for_release"] / 1000, DAYU_TIMEZONE).isoformat(), |
| 125 | schedule_verified=True) |
| 126 | if record["status"] != DAYU_CONTENT_PUBLIC: |
| 127 | result["status"] = "scheduled" |
| 128 | if not public: |
| 129 | return result |
| 130 | public_url = record.get("ucUrl", "") |
| 131 | parsed = urlsplit(public_url) |
| 132 | query = parse_qs(parsed.query) |
| 133 | if (parsed.scheme != "https" or parsed.hostname != "mparticle.uc.cn" |
| 134 | or parsed.path != "/video.html" |
| 135 | or query.get("wm_id") != [identity["wmid"]] |
| 136 | or query.get("wm_aid") != [record["origin_id"]]): |
| 137 | raise RuntimeError("作品公开地址的域名、主体或 origin_id 不匹配") |
| 138 | |
| 139 | # 新建不带 storage_state 的上下文,避免登录后的预览权限掩盖公开播放失败。 |
| 140 | public_context = await browser.new_context() |
| 141 | try: |
| 142 | public_page = await public_context.new_page() |
| 143 | await public_page.goto(public_url, wait_until="domcontentloaded", timeout=45000) |
| 144 | # 只使用组件含义前缀,排除构建生成的 class 哈希后缀与推荐卡片中的同名作者。 |
| 145 | await expect(public_page.locator('[class^="pc-videoContent-"]')).to_have_text(record["title"], timeout=30000) |
| 146 | await expect(public_page.locator('[class^="pc-userInfoContainer-"] > span')).to_have_text(identity["name"]) |
| 147 | video = public_page.locator("video") |
| 148 | await expect(video).to_have_count(1) |
| 149 | await video.evaluate("async v => { v.muted = true; await v.play(); }") |
| 150 | await public_page.wait_for_function( |
| 151 | """() => { const v = document.querySelector('video'); |
| 152 | return v && !v.error && v.readyState >= 2 && v.duration > 0 && v.currentTime > 0.1; }""", |
| 153 | timeout=30000, |
| 154 | ) |
| 155 | playback = await video.evaluate("v => ({duration: v.duration, current_time: v.currentTime, ready_state: v.readyState})") |
| 156 | finally: |
| 157 | await public_context.close() |
| 158 | result.update(status="published", audit_status=record.get("audit_status"), |
| 159 | audit_remark=record.get("_app_extra", {}).get("audit_remark", ""), |
| 160 | public_url=public_url, public_playback=playback) |
| 161 | return result |
| 162 | |
| 163 | |
| 164 | async def verify_dayu_article(context: BrowserContext, browser: Browser, identity: dict, |
| 165 | content_id: str | None = None, origin_id: str | None = None, |
| 166 | title: str | None = None, timeout: int = 60, |
| 167 | manifest: dict | None = None, public: bool = False, |
| 168 | schedule: str | None = None) -> dict: |
| 169 | """确认原文章已提交;public=True 时再匿名核对正文、图片位置及格式。""" |
| 170 | record = await wait_dayu_publication(context, content_id, origin_id, title, timeout, public, schedule) |
| 171 | result = {"success": True, "status": "published" if record["status"] == DAYU_CONTENT_PUBLIC else "submitted", "type": "article", |
| 172 | "content_id": str(record["content_id"]), "origin_id": record["origin_id"], |
| 173 | "title": record["title"], "identity": identity, "platform_status": record["status"]} |
| 174 | if schedule or record["status"] == DAYU_CONTENT_SCHEDULED: |
| 175 | result.update(schedule=datetime.fromtimestamp(record["_app_extra"]["time_for_release"] / 1000, DAYU_TIMEZONE).isoformat(), |
| 176 | schedule_verified=True) |
| 177 | if record["status"] != DAYU_CONTENT_PUBLIC: |
| 178 | result["status"] = "scheduled" |
| 179 | if not public: |
| 180 | return result |
| 181 | if not re.fullmatch(r"[a-f0-9]{32}", record.get("origin_id", "")): |
| 182 | raise RuntimeError("文章原稿 ID 不完整,无法打开公开文章") |
| 183 | # 实际后台点击已发布图文标题产生此地址;图文列表不提供视频使用的 ucUrl 字段。 |
| 184 | public_url = "https://mparticle.uc.cn/article.html?" + urlencode({ |
| 185 | "uc_param_str": "frdnsnpfvecpntnwprdssskt", "wm_aid": record["origin_id"], |
| 186 | }) |
| 187 | public_context = await browser.new_context() |
| 188 | try: |
| 189 | page = await public_context.new_page() |
| 190 | await page.goto(public_url, wait_until="domcontentloaded", timeout=45000) |
| 191 | # 公开正文组件前缀不包含构建哈希;限定文章容器,排除推荐区标题、作者及图片。 |
| 192 | article = page.locator('[class^="index-articleContainer-"]') |
| 193 | await expect(article.locator(":scope > h1")).to_have_text(record["title"], timeout=30000) |
| 194 | await expect(article.locator('[class^="article-userInfoName-"]')).to_have_text(identity["name"]) |
| 195 | body = article.locator('[class^="index-articleSummary-"]') |
| 196 | await expect(body).to_have_count(1) |
| 197 | await expect(body).not_to_be_empty() |
| 198 | images = body.locator("img") |
| 199 | if manifest: |
| 200 | await expect(images).to_have_count(manifest["image_count"]) |
| 201 | for index in range(await images.count()): |
| 202 | image = images.nth(index) |
| 203 | await image.scroll_into_view_if_needed() |
| 204 | await expect(image).to_have_attribute("src", re.compile(r"^https?://(?:image\.uc\.cn|mp\.dayu\.com)/")) |
| 205 | await expect(image).to_have_js_property("complete", True, timeout=30000) |
| 206 | if await image.evaluate("e => e.naturalWidth") <= 0: |
| 207 | raise RuntimeError(f"公开文章第 {index + 1} 张图片无法加载") |
| 208 | if manifest: |
| 209 | await check_dayu_article_content(body, manifest) |
| 210 | public_article = {"image_count": await images.count(), "content_checked": bool(manifest)} |
| 211 | finally: |
| 212 | await public_context.close() |
| 213 | result.update(status="published", audit_status=record.get("audit_status"), |
| 214 | audit_remark=record.get("_app_extra", {}).get("audit_remark", ""), |
| 215 | public_url=public_url, public_article=public_article) |
| 216 | return result |
| 217 |