| 1 | """大鱼号视频发布:核验主体、等待处理、填写表单、确认发表并记录提交结果。""" |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | import asyncio |
| 5 | import json |
| 6 | import math |
| 7 | import re |
| 8 | import time |
| 9 | from datetime import datetime |
| 10 | from pathlib import Path |
| 11 | from urllib.parse import urlsplit |
| 12 | from uuid import uuid4 |
| 13 | |
| 14 | import cv2 |
| 15 | from patchright.async_api import Page, async_playwright, expect |
| 16 | |
| 17 | from conf import LOCAL_CHROME_PATH |
| 18 | from uploader.base_video import BaseVideoUploader |
| 19 | from uploader.dayu_uploader.publication import submit_dayu_publication |
| 20 | from uploader.dayu_uploader.schedule import fill_dayu_schedule, validate_dayu_schedule |
| 21 | from uploader.dayu_uploader.session import DAYU_VIDEO_URL, load_dayu_identity, read_dayu_identity |
| 22 | from uploader.dayu_uploader.constants import DAYU_SOURCE_REPRINT, DAYU_SOURCE_TYPES, DAYU_VIDEO_CATEGORIES |
| 23 | from utils.log import dayu_logger |
| 24 | |
| 25 | |
| 26 | async def wait_dayu_processing(page: Page, filename: str, timeout: int = 600) -> None: |
| 27 | """处理失败优先于完成文案;100% 和“上传成功,处理中”都不能判为可发表。""" |
| 28 | deadline = time.monotonic() + timeout |
| 29 | # 视频容器是上传前后保留的业务区域;不把变化中的进度或结果文案写进锚点。 |
| 30 | region = page.locator(".article-write_video-container") |
| 31 | await expect(region).to_have_count(1) |
| 32 | previous = None |
| 33 | while time.monotonic() < deadline: |
| 34 | text = await region.inner_text(timeout=max(1, min(5000, int((deadline - time.monotonic()) * 1000)))) |
| 35 | if re.search(r"失败|不支持|小于|超出|(?<!不)超过|请重新上传|无法", text): |
| 36 | raise RuntimeError(f"大鱼号视频处理被拒绝: {text.strip()}") |
| 37 | if "视频上传成功,处理完成" in text: |
| 38 | await expect(region.locator(".article-write_video-container-result-desc p span")).to_have_text(filename) |
| 39 | return |
| 40 | if text != previous: |
| 41 | dayu_logger.info(f"大鱼号上传状态: {text.strip()}") |
| 42 | previous = text |
| 43 | await asyncio.sleep(min(.5, max(0, deadline - time.monotonic()))) |
| 44 | raise TimeoutError("等待大鱼号上传/处理超时;未提交发表,请检查当前素材状态") |
| 45 | |
| 46 | |
| 47 | class DayuVideo(BaseVideoUploader): |
| 48 | """以实际页面流程发表一个视频,持久化提交 ID 供断线后只读核验。""" |
| 49 | |
| 50 | SUPPORTED_VIDEO_EXTENSIONS = { |
| 51 | ".3gp", ".avi", ".flv", ".mp4", ".m3u8", ".mpg", ".asf", ".wmv", |
| 52 | ".mkv", ".mov", ".ts", ".webm", ".mts", |
| 53 | } |
| 54 | SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".gif", ".png", ".bmp", ".jpeg"} |
| 55 | |
| 56 | def __init__(self, title, file_path, tags, account_file, thumbnail_path, category, |
| 57 | source, desc="", headless=True, debug=False, prepare_only=False, |
| 58 | upload_timeout=600, source_url="", schedule=None): |
| 59 | self.title = title |
| 60 | self.file_path = file_path |
| 61 | self.tags = tags or [] |
| 62 | self.account_file = Path(account_file).resolve() |
| 63 | self.thumbnail_path = thumbnail_path |
| 64 | self.category = category |
| 65 | self.source = source |
| 66 | self.source_url = source_url |
| 67 | self.desc = desc |
| 68 | self.headless = headless |
| 69 | self.debug = debug |
| 70 | self.prepare_only = prepare_only |
| 71 | self.upload_timeout = upload_timeout |
| 72 | self.schedule = schedule |
| 73 | |
| 74 | def validate_upload_args(self) -> None: |
| 75 | """上传前拒绝无法解码、时长不足、超限素材及缺失必填信息。""" |
| 76 | self.schedule = validate_dayu_schedule(self.schedule) |
| 77 | self.file_path = self.validate_video_file(self.file_path) |
| 78 | self.thumbnail_path = self.validate_image_file(self.thumbnail_path) |
| 79 | if not self.account_file.is_file(): |
| 80 | raise FileNotFoundError("请先执行 sau dayu login 保存账号") |
| 81 | load_dayu_identity(self.account_file) |
| 82 | # 编辑器按汉字 1、ASCII 0.5 计数(页面上 demo 显示 2/60)。 |
| 83 | title_length = sum(.5 if ord(char) <= 255 else 1 for char in self.title.strip()) |
| 84 | if not 5 <= title_length <= 60: |
| 85 | raise ValueError("大鱼号标题长度需在 5–60 字之间(ASCII 按半字计数)") |
| 86 | if len(self.desc) > 200: |
| 87 | raise ValueError("大鱼号视频简介不能超过 200 字") |
| 88 | if self.category not in DAYU_VIDEO_CATEGORIES: |
| 89 | raise ValueError(f"视频分类必须为: {', '.join(DAYU_VIDEO_CATEGORIES)}") |
| 90 | if self.source not in DAYU_SOURCE_TYPES: |
| 91 | raise ValueError(f"必须明确提供信息来源: {', '.join(DAYU_SOURCE_TYPES)}") |
| 92 | if self.source == DAYU_SOURCE_REPRINT: |
| 93 | original = urlsplit(self.source_url) |
| 94 | if original.scheme not in ("http", "https") or not original.hostname: |
| 95 | raise ValueError("信息来源为转载时,必须使用 --source-url 提供 http/https 原文链接") |
| 96 | elif self.source_url: |
| 97 | raise ValueError("仅信息来源为转载时可以填写 --source-url 原文链接") |
| 98 | if any(not tag.strip() or len(tag) > 10 for tag in self.tags): |
| 99 | raise ValueError("视频标签不能为空且每个不能超过 10 字") |
| 100 | if self.upload_timeout <= 0: |
| 101 | raise ValueError("上传及发布核验期限必须大于 0 秒") |
| 102 | if self.thumbnail_path.stat().st_size > 5 * 1024 ** 2: |
| 103 | raise ValueError("大鱼号视频封面不能超过 5 MiB") |
| 104 | capture = cv2.VideoCapture(str(self.file_path)) |
| 105 | try: |
| 106 | fps = capture.get(cv2.CAP_PROP_FPS) |
| 107 | frames = capture.get(cv2.CAP_PROP_FRAME_COUNT) |
| 108 | width = capture.get(cv2.CAP_PROP_FRAME_WIDTH) |
| 109 | height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT) |
| 110 | finally: |
| 111 | capture.release() |
| 112 | if not all(math.isfinite(value) and value > 0 for value in (fps, frames, width, height)): |
| 113 | raise ValueError("无法读取视频尺寸、帧数或帧率,拒绝上传未知素材") |
| 114 | duration = frames / fps |
| 115 | if duration < 5: |
| 116 | raise ValueError(f"大鱼号视频至少需要 5 秒,当前约 {duration:.3f} 秒") |
| 117 | portrait = height > width |
| 118 | if self.file_path.stat().st_size > (5 if portrait else 10) * 1024 ** 3: |
| 119 | raise ValueError("视频超过大鱼号文件大小限制(横屏 10 GiB、竖屏 5 GiB)") |
| 120 | if portrait and duration > 1800: |
| 121 | raise ValueError("大鱼号竖屏视频时长不能超过 30 分钟") |
| 122 | |
| 123 | async def fill_video_form(self, page: Page) -> None: |
| 124 | """填写并读回标题、简介、分类、标签、封面与来源,不代选来源。""" |
| 125 | # 标题实际为 contenteditable;固定 placeholder 区分简介输入框和其他可编辑区域。 |
| 126 | title = page.locator('[contenteditable="true"][placeholder="视频标题最少5个字"]') |
| 127 | await title.fill(self.title) |
| 128 | await expect(title).to_have_text(self.title) |
| 129 | # 表单中简介使用 textarea;分类通过字段 label 限定,避免点击其他同构下拉框。 |
| 130 | description = page.locator(".w-form-field").filter(has=page.locator("textarea")).locator("textarea") |
| 131 | await description.fill(self.desc) |
| 132 | await expect(description).to_have_value(self.desc) |
| 133 | category = page.locator(".w-form-field").filter( |
| 134 | has=page.locator("label").filter(has_text="视频分类"), |
| 135 | ) |
| 136 | await category.locator(".widgets-selects_container").click() |
| 137 | await category.get_by_role("link", name=self.category, exact=True).click() |
| 138 | await expect(category.locator(".widgets-selects_container")).to_have_text(self.category) |
| 139 | if self.tags: |
| 140 | # 标签组件内会动态增加输入槽,先限定组件再按用户输入顺序选槽位。 |
| 141 | tags = page.locator(".article-write_video-tags") |
| 142 | await tags.click() |
| 143 | for index, tag in enumerate(self.tags): |
| 144 | # 标签槽按用户给定顺序排列;Enter 在末尾新增一个空槽,并非任意选第 N 个控件。 |
| 145 | inputs = tags.locator("input") |
| 146 | await expect(inputs).to_have_count(index + 1) |
| 147 | await inputs.nth(index).fill(tag) |
| 148 | await inputs.nth(index).press("Enter") |
| 149 | await title.click() |
| 150 | # 实测 Enter/失焦后会短暂少一个字并保留空槽,Vue 随后才恢复最终标签值。 |
| 151 | await expect(tags.locator("input")).to_have_count(len(self.tags)) |
| 152 | for index, tag in enumerate(self.tags): |
| 153 | await expect(tags.locator("input").nth(index)).to_have_value(tag) |
| 154 | # coverImg 是封面字段的语义 ID,限定其中 input 避免把封面传给主视频上传器。 |
| 155 | await page.locator("#coverImg input[type=file]").set_input_files(str(self.thumbnail_path)) |
| 156 | # 裁剪与素材选择共用弹窗组件,只定位本次可见实例,排除隐藏模板。 |
| 157 | dialog = page.locator(".article-material-image-dialog:visible") |
| 158 | await expect(dialog).to_have_count(1, timeout=30000) |
| 159 | await dialog.get_by_role("button", name="保存", exact=True).click() |
| 160 | await expect(page.locator(".article-material-image-dialog:visible")).to_have_count(0, timeout=30000) |
| 161 | cover = page.locator("#coverImg #form_main_cover_img") |
| 162 | await expect(cover).to_be_visible() |
| 163 | await expect(cover).to_have_attribute("src", re.compile(r"^https?://image\.uc\.cn/")) |
| 164 | # 来源 radio 的 value 与页面选项一致;用业务值区分选项,不依赖左右排列顺序。 |
| 165 | source = page.locator(f'input[type=radio][value="{self.source}"]') |
| 166 | await source.check() |
| 167 | await expect(source).to_be_checked() |
| 168 | # 原文链接按来源区域内的 label 定位,排除其他文本框;非转载时该条件字段应消失。 |
| 169 | original_link = page.locator(".source-remark-detail .article-write_box-form-filed").filter( |
| 170 | has=page.locator("label").filter(has_text="原文链接"), |
| 171 | ).locator('input[type="text"]') |
| 172 | if self.source == DAYU_SOURCE_REPRINT: |
| 173 | await original_link.fill(self.source_url) |
| 174 | await expect(original_link).to_have_value(self.source_url) |
| 175 | else: |
| 176 | await expect(original_link).to_have_count(0) |
| 177 | await fill_dayu_schedule(page, self.schedule) |
| 178 | |
| 179 | async def main(self) -> dict: |
| 180 | """提交只执行一次;平台最终发表响应确认本次作品 ID 后即成功。""" |
| 181 | self.validate_upload_args() |
| 182 | expected = load_dayu_identity(self.account_file) |
| 183 | results_dir = self.account_file.parent / "dayu_results" |
| 184 | results_dir.mkdir(exist_ok=True) |
| 185 | result_file = results_dir / f"{datetime.now():%Y%m%d-%H%M%S}-{uuid4().hex[:8]}.json" |
| 186 | result = {"success": False, "status": "preparing", "type": "video", "title": self.title, |
| 187 | "video_file": str(self.file_path), "identity": expected, |
| 188 | "result_file": str(result_file)} |
| 189 | if self.schedule: |
| 190 | result["schedule"] = self.schedule.isoformat() |
| 191 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 192 | async with async_playwright() as playwright: |
| 193 | browser = await playwright.chromium.launch( |
| 194 | executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=self.headless, |
| 195 | ) |
| 196 | page = None |
| 197 | try: |
| 198 | context = await browser.new_context(storage_state=str(self.account_file), timezone_id="Asia/Shanghai") |
| 199 | page = await context.new_page() |
| 200 | await page.goto(DAYU_VIDEO_URL, wait_until="domcontentloaded", timeout=45000) |
| 201 | identity = await read_dayu_identity(page) |
| 202 | if identity["wmid"] != expected["wmid"]: |
| 203 | raise RuntimeError("大鱼号主体不匹配,上传已中止") |
| 204 | result["identity"] = identity |
| 205 | # 主视频上传器有 name=file,封面 input 没有此属性,可据此区分两种上传入口。 |
| 206 | file_input = page.locator('input[type="file"][name="file"]') |
| 207 | await expect(file_input).to_have_count(1, timeout=30000) |
| 208 | await file_input.set_input_files(str(self.file_path)) |
| 209 | await wait_dayu_processing(page, self.file_path.name, self.upload_timeout) |
| 210 | await self.fill_video_form(page) |
| 211 | # 填表和异步封面处理之后,再次核对同一主体及视频处理结果。 |
| 212 | if (await read_dayu_identity(page))["wmid"] != identity["wmid"]: |
| 213 | raise RuntimeError("填表期间大鱼号主体发生变化,拒绝提交") |
| 214 | await wait_dayu_processing(page, self.file_path.name, self.upload_timeout) |
| 215 | if self.prepare_only: |
| 216 | await page.screenshot(path=str(result_file.with_suffix(".png")), full_page=True) |
| 217 | result.update(success=True, status="prepared") |
| 218 | return result |
| 219 | |
| 220 | await submit_dayu_publication(page, result, result_file) |
| 221 | await context.storage_state(path=str(self.account_file)) |
| 222 | action = "定时发布已安排" if self.schedule else "发表成功" |
| 223 | dayu_logger.success(f"大鱼号{action}: {result['content_id']}") |
| 224 | return result |
| 225 | except Exception as exc: |
| 226 | result["error"] = str(exc) |
| 227 | dayu_logger.error(f"大鱼号阶段={result['status']},结果文件={result_file}: {exc}") |
| 228 | if self.debug and page is not None: |
| 229 | await page.screenshot(path=str(result_file.with_suffix(".png"))) |
| 230 | raise |
| 231 | finally: |
| 232 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 233 | await browser.close() |
| 234 |