返回 Social Auto Upload
video.py
1 """知乎单视频上传:传输、元数据、定时选项和提交状态分开核对。"""
2 from __future__ import annotations
3
4 import asyncio
5 import json
6 import sys
7 import math
8 import re
9 from datetime import datetime
10 from pathlib import Path
11 from uuid import uuid4
12
13 import cv2
14 from patchright.async_api import Page, async_playwright, expect
15
16 from conf import LOCAL_CHROME_PATH
17 from uploader.zhihu_uploader.constants import (
18 ZHIHU_ORIGINALITY, ZHIHU_TIMEZONE, ZHIHU_VIDEO_DESCRIPTION_MAX, ZHIHU_VIDEO_EXTENSIONS,
19 ZHIHU_VIDEO_MAX_BYTES, ZHIHU_VIDEO_MIN_BYTES, ZHIHU_VIDEO_MAX_SECONDS, ZHIHU_VIDEO_TITLE_MAX,
20 ZHIHU_VIDEO_TITLE_MIN, ZHIHU_VIDEO_URL, ZHIHU_VIDEO_TOPICS_MAX,
21 )
22 from uploader.zhihu_uploader.schedule import fill_zhihu_video_schedule, validate_zhihu_schedule
23 from uploader.zhihu_uploader.session import load_zhihu_identity, read_zhihu_identity
24
25
26 class ZhihuVideo:
27 """上传并发布一个知乎视频,未知提交结果会保留在本地 JSON 中。"""
28
29 def __init__(self, title, file_path, account_file, description, category,
30 topics, video_mark, originality, schedule=None, show_options=False,
31 headless=True, debug=False, prepare_only=False, upload_timeout=1200):
32 self.title = title
33 self.file_path = Path(file_path).expanduser().resolve()
34 self.account_file = Path(account_file).resolve()
35 self.description = description
36 self.category = category
37 self.show_options = show_options
38 self.topics = topics
39 self.video_mark = video_mark
40 self.originality = originality
41 self.schedule = schedule
42 self.headless = headless
43 self.debug = debug
44 self.prepare_only = prepare_only
45 self.upload_timeout = upload_timeout
46
47 def validate_upload_args(self) -> None:
48 """依据页面提示检查视频、标题、简介和当前上传所需的分类参数。"""
49 if not self.file_path.is_file():
50 raise FileNotFoundError(f"知乎视频不存在: {self.file_path}")
51 if self.file_path.suffix.lower() not in ZHIHU_VIDEO_EXTENSIONS:
52 raise ValueError(f"知乎视频格式不受页面支持: {self.file_path.suffix}")
53 if self.file_path.stat().st_size <= ZHIHU_VIDEO_MIN_BYTES:
54 raise ValueError("知乎视频必须大于 100KB")
55 if self.file_path.stat().st_size > ZHIHU_VIDEO_MAX_BYTES:
56 raise ValueError("知乎视频文件不能超过 20 GB")
57 capture = cv2.VideoCapture(str(self.file_path))
58 try:
59 fps = capture.get(cv2.CAP_PROP_FPS)
60 frames = capture.get(cv2.CAP_PROP_FRAME_COUNT)
61 finally:
62 capture.release()
63 if not math.isfinite(fps) or not math.isfinite(frames) or fps <= 0 or frames <= 0:
64 raise ValueError("无法读取视频帧率或帧数,拒绝上传未知素材")
65 if frames / fps > ZHIHU_VIDEO_MAX_SECONDS:
66 raise ValueError("知乎视频时长不能超过 4 小时")
67 if not ZHIHU_VIDEO_TITLE_MIN <= len(self.title.strip()) <= ZHIHU_VIDEO_TITLE_MAX:
68 raise ValueError(f"知乎视频标题需为 {ZHIHU_VIDEO_TITLE_MIN}–{ZHIHU_VIDEO_TITLE_MAX} 字")
69 if len(self.description) > ZHIHU_VIDEO_DESCRIPTION_MAX:
70 raise ValueError(f"知乎视频简介不能超过 {ZHIHU_VIDEO_DESCRIPTION_MAX} 字")
71 if len(self.topics) > ZHIHU_VIDEO_TOPICS_MAX:
72 raise ValueError(f"知乎视频最多 {ZHIHU_VIDEO_TOPICS_MAX} 个话题")
73 if any(not topic.strip() for topic in self.topics):
74 raise ValueError("知乎视频话题不能为空")
75 if self.topics:
76 raise ValueError("知乎视频暂不支持自动选择话题,请使用简介描述内容")
77 if self.originality not in ZHIHU_ORIGINALITY:
78 raise ValueError("原创标记必须为 original 或 reprint")
79 self.schedule = validate_zhihu_schedule(self.schedule)
80 if not self.account_file.is_file():
81 raise FileNotFoundError("请先执行 sau zhihu login 保存账号")
82 self.identity = load_zhihu_identity(self.account_file)
83 if self.upload_timeout <= 0:
84 raise ValueError("上传期限必须大于 0 秒")
85
86 async def video_options(self, page: Page) -> dict:
87 """从本次素材实际渲染的菜单读取完整候选;不拿旧版二级领域代替新版表单。"""
88 # 所属领域标签限定业务行,visible 限定本次展开的列表,排除隐藏菜单。
89 field = page.locator(".VideoUploadForm-item").filter(has=page.get_by_text("所属领域", exact=True))
90 await expect(field).to_have_count(1)
91 control = field.get_by_role("combobox")
92 await control.click()
93 menu = page.locator(".VideoUploadForm-selectList:visible")
94 await expect(menu).to_have_count(1)
95 # 页面源码对每个领域只渲染一个 name;逐行读取完整菜单,不依赖未观察的子组件 class。
96 await expect(menu).to_contain_text(re.compile(r"\S"))
97 categories = [text.strip() for text in await menu.get_by_role("option").all_inner_texts()
98 if text.strip() and text.strip() != "选择领域"]
99 await control.click()
100 mark_field = page.locator(".VideoUploadForm-item").filter(has=page.get_by_text("视频标记", exact=True))
101 await mark_field.get_by_role("button", name="选择视频标记", exact=True).click()
102 modal = page.locator(".VideoUploadForm-videoTypeModal:visible")
103 await expect(modal).to_be_visible()
104 marks = [text.strip() for text in await modal.locator(".VideoUploadForm-videoTypeModalOption").all_inner_texts()
105 if text.strip() and text.strip() not in {"确认", "取消", "关闭"}]
106 # 只读完选项后取消弹层,不把第一个候选当成用户选择。
107 await modal.get_by_role("button", name="取消", exact=True).click()
108 await expect(modal).to_be_hidden()
109 if not categories or not marks or len(categories) != len(set(categories)) or len(marks) != len(set(marks)):
110 raise RuntimeError("知乎候选为空或重复,无法安全生成选择菜单")
111 return {"category": categories, "video_mark": marks}
112
113 async def select_option(self, label: str, value: str | None, choices: list[str]) -> str:
114 """终端显示实际候选并按编号选择;脚本调用只能使用本次菜单中存在的值。"""
115 if value is not None:
116 if value not in choices:
117 raise ValueError(f"{label}必须为: {'、'.join(choices)}")
118 return value
119 print(label + ":", file=sys.stderr)
120 for index, choice in enumerate(choices, 1):
121 print(f" {index}. {choice}", file=sys.stderr)
122 if not sys.stdin.isatty():
123 raise ValueError(f"非交互调用必须指定{label};可先使用 --show-options 获取完整候选")
124 answer = await asyncio.to_thread(input, f"选择{label}编号(1–{len(choices)}):")
125 if not answer.isdecimal() or not 1 <= int(answer) <= len(choices):
126 raise ValueError(f"{label}编号无效")
127 return choices[int(answer) - 1]
128
129 async def fill_video_options(self, page: Page) -> None:
130 """只选择已核对的实时菜单值,选择后读回表单。"""
131 field = page.locator(".VideoUploadForm-item").filter(has=page.get_by_text("所属领域", exact=True))
132 control = field.get_by_role("combobox")
133 await control.click()
134 await page.locator(".VideoUploadForm-selectList:visible").get_by_role("option", name=self.category, exact=True).click()
135 await expect(control).to_contain_text(self.category)
136 mark_field = page.locator(".VideoUploadForm-item").filter(has=page.get_by_text("视频标记", exact=True))
137 await mark_field.get_by_role("button", name="选择视频标记", exact=True).click()
138 modal = page.locator(".VideoUploadForm-videoTypeModal:visible")
139 await modal.get_by_role("button", name=self.video_mark, exact=True).click()
140 await modal.get_by_role("button", name="确认", exact=True).click()
141 await expect(modal).to_be_hidden()
142
143 async def fill_video_form(self, page: Page) -> None:
144 """等本次视频传输成功,再填写并读回页面要求的元数据。"""
145 form = page.locator(".VideoUploadForm-item").filter(
146 has=page.get_by_text("标题与介绍", exact=True),
147 )
148 await expect(form).to_be_visible(timeout=self.upload_timeout * 1000)
149 failure = page.get_by_text("视频上传失败", exact=True)
150 if await failure.count():
151 raise RuntimeError("知乎明确显示视频上传失败")
152 # 页面代码以“上传成功”作为 uploaded 状态;只等该状态,不把表单出现或进度完成当作处理完成。
153 await expect(page.get_by_text("上传成功", exact=True)).to_be_visible(timeout=self.upload_timeout * 1000)
154
155 title = form.locator("textarea")
156 await expect(title).to_have_count(1)
157 await title.fill(self.title)
158 await expect(title).to_have_value(self.title)
159 description = form.locator('[contenteditable="true"][role="textbox"]')
160 await expect(description).to_have_count(1)
161 await description.fill(self.description)
162 if self.description.strip():
163 await expect(description).to_contain_text(self.description[:80])
164
165 await self.fill_video_options(page)
166
167 # 原创/转载是页面的独立 checkbox;按参数状态设置,不依赖控件视觉顺序。
168 # 按“原创视频”业务行限定,避免与定时发布等其它 checkbox 混淆。
169 originality = page.locator(".VideoUploadForm-item").filter(
170 has=page.get_by_text("原创视频", exact=True),
171 ).get_by_role("checkbox")
172 await expect(originality).to_have_count(1)
173 wanted_original = self.originality == "original"
174 if await originality.is_checked() != wanted_original:
175 await originality.click()
176 if wanted_original:
177 await expect(originality).to_be_checked()
178 else:
179 await expect(originality).not_to_be_checked()
180
181 await fill_zhihu_video_schedule(page, self.schedule)
182
183 async def main(self) -> dict:
184 """只提交一次;页面没有确认本次作品 URL 时记录为 submission_unknown。"""
185 self.validate_upload_args()
186 results_dir = self.account_file.parent / "zhihu_results"
187 results_dir.mkdir(exist_ok=True)
188 result_file = results_dir / f"{datetime.now(ZHIHU_TIMEZONE):%Y%m%d-%H%M%S}-{uuid4().hex[:8]}.json"
189 result = {
190 "success": False, "status": "preparing", "type": "video", "title": self.title,
191 "video_file": str(self.file_path), "identity": self.identity, "topics": self.topics,
192 "category": self.category,
193 "video_mark": self.video_mark, "originality": self.originality,
194 "result_file": str(result_file),
195 }
196 if self.schedule:
197 result["schedule"] = self.schedule.isoformat()
198 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
199
200 async with async_playwright() as playwright:
201 browser = await playwright.chromium.launch(
202 executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=self.headless,
203 )
204 page = None
205 submitted = False
206 try:
207 context = await browser.new_context(
208 storage_state=str(self.account_file), timezone_id="Asia/Shanghai",
209 )
210 page = await context.new_page()
211 response = await page.goto(ZHIHU_VIDEO_URL, wait_until="domcontentloaded", timeout=45000)
212 if response is not None and response.status >= 400:
213 raise RuntimeError(f"知乎视频上传页访问失败,HTTP {response.status}")
214 if await read_zhihu_identity(page) != self.identity:
215 raise RuntimeError("知乎视频页头与本地账号绑定不一致")
216 # 该 input 的 class 和 accept 来自上传首页实际 DOM;不与封面/正文图片 input 混用。
217 video_input = page.locator("input.VideoUploadButton-fileInput[type=file]")
218 await expect(video_input).to_have_count(1)
219 await video_input.set_input_files(str(self.file_path))
220 result["status"] = "uploading"
221 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
222 # 表单在素材选择后才出现;候选来自该账号、该素材的实际页面。
223 await expect(page.get_by_text("上传成功", exact=True)).to_be_visible(timeout=self.upload_timeout * 1000)
224 choices = await self.video_options(page)
225 result["options"] = choices
226 if self.show_options:
227 result["status"] = "options_listed"
228 return result
229 self.category = await self.select_option("所属领域", self.category, choices["category"])
230 self.video_mark = await self.select_option("视频标记", self.video_mark, choices["video_mark"])
231 result.update(category=self.category, video_mark=self.video_mark)
232 await self.fill_video_form(page)
233 if await read_zhihu_identity(page) != self.identity:
234 raise RuntimeError("知乎视频填写期间当前账号发生变化")
235 result["status"] = "prepared"
236 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
237 if self.prepare_only:
238 return result
239
240 # 当前视频入口在原页显示成功弹层,“查看详情”另开 /pin/<id>。
241 # 不能等待原页跳转到旧版 /zvideo/,否则已发表也会被误判为未知。
242 publish = page.get_by_role("button", name="发布视频", exact=True)
243 await expect(publish).to_be_enabled()
244 submitted = True
245 result["status"] = "submission_unknown"
246 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
247 await publish.click()
248 await expect(page.get_by_text("发布成功", exact=True)).to_be_visible(timeout=60000)
249 result.update(success=True, status="published")
250 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
251 async with page.expect_popup() as detail_info:
252 await page.get_by_text("查看详情", exact=True).click()
253 detail = await detail_info.value
254 await detail.wait_for_url(re.compile(r"^https://www\.zhihu\.com/(?:pin|zvideo|video)/\d+"), timeout=60000)
255 result["url"] = detail.url
256 return result
257 except Exception as exc:
258 result["error"] = str(exc)
259 if result["status"] != "published":
260 result["status"] = "submission_unknown" if submitted else "failed_before_submit"
261 if submitted and page is not None and re.match(r"^https://www\.zhihu\.com/(?:pin|zvideo|video)/\d+", page.url):
262 result["url"] = page.url
263 if self.debug and page is not None:
264 screenshot = result_file.with_suffix(".png")
265 await page.screenshot(path=str(screenshot))
266 result["screenshot"] = str(screenshot)
267 if result["status"] == "published":
268 # 平台已经确认发表;保留详情读取错误供原作品查询,不返回可重试的发表失败。
269 return result
270 raise RuntimeError(f"知乎视频阶段={result['status']},结果文件={result_file}: {exc}") from exc
271 finally:
272 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
273 await browser.close()
274
274 lines PYTHON