返回 Social Auto Upload
article.py
根目录 / uploader / dayu_uploader / article.py
1 """大鱼号图文:正文文件、富文本粘贴、本地图片上传及发表确认。"""
2 from __future__ import annotations
3
4 import json
5 import math
6 import re
7 import sys
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 from patchright.async_api import Locator, Page, async_playwright, expect
15
16 from conf import LOCAL_CHROME_PATH
17 from uploader.dayu_uploader.article_content import load_dayu_article
18 from uploader.dayu_uploader.article_style import render_dayu_compatible_html
19 from uploader.dayu_uploader.constants import DAYU_SOURCE_REPRINT, DAYU_SOURCE_TYPES
20 from uploader.dayu_uploader.publication import submit_dayu_publication
21 from uploader.dayu_uploader.schedule import fill_dayu_schedule, validate_dayu_schedule
22 from uploader.dayu_uploader.session import load_dayu_identity, read_dayu_identity
23 from uploader.dayu_uploader.verification import check_dayu_article_content
24 from utils.log import dayu_logger
25
26 DAYU_ARTICLE_URL = "https://mp.dayu.com/dashboard/article/write"
27 DAYU_ARTICLE_COVER_MODES = {1: "单封面", 3: "三封面"}
28 # 实测页面还有 UEditor 辅助 iframe;限定正文编辑区与 iframeholder 才唯一指向文章正文。
29 ARTICLE_BODY = ".article-write_box-editor .edui-editor-iframeholder iframe"
30
31
32 async def wait_dayu_article_body_stable(body: Locator) -> None:
33 """粘贴后的异步清理会替换容器节点;稳定后才缓存插图选区或核对最终正文。"""
34 deadline = time.monotonic() + 15
35 previous = None
36 stable = 0
37 while time.monotonic() < deadline:
38 current = await body.inner_html()
39 stable = stable + 1 if current == previous else 0
40 previous = current
41 if stable >= 3:
42 return
43 await body.page.wait_for_timeout(1000)
44 raise RuntimeError("大鱼号正文持续变化,未确认最终编辑结果")
45
46
47 class DayuArticle:
48 """正文以 UTF-8 文件传入;图片顺序由 HTML 中 img 的位置决定。"""
49
50 def __init__(self, title, content_file, account_file, source, source_url="", author=None,
51 cover_indices=None, headless=True, debug=False, prepare_only=False,
52 upload_timeout=600, theme=None, schedule=None):
53 self.title = title
54 self.content_file = Path(content_file).expanduser().resolve()
55 self.account_file = Path(account_file).resolve()
56 self.source = source
57 self.source_url = source_url
58 self.author = author
59 self.cover_indices = cover_indices or []
60 self.headless = headless
61 self.debug = debug
62 self.prepare_only = prepare_only
63 self.upload_timeout = upload_timeout
64 self.theme = theme
65 self.schedule = schedule
66
67 def validate_upload_args(self):
68 """在接触远端素材之前,检查正文格式、封面序号及来源的条件必填项。"""
69 self.schedule = validate_dayu_schedule(self.schedule)
70 self.document = load_dayu_article(self.content_file, self.theme)
71 title_length = math.ceil(sum(.5 if ord(char) <= 255 else 1 for char in self.title.strip()))
72 if not 5 <= title_length <= 50:
73 raise ValueError("大鱼号图文标题需要 5–50 字(英文字符按半字计数并向上取整)")
74 if not self.account_file.is_file():
75 raise FileNotFoundError("请先执行 sau dayu login 保存账号")
76 load_dayu_identity(self.account_file)
77 if self.source not in DAYU_SOURCE_TYPES:
78 raise ValueError(f"信息来源必须为: {', '.join(DAYU_SOURCE_TYPES)}")
79 if self.source == DAYU_SOURCE_REPRINT:
80 original = urlsplit(self.source_url)
81 if original.scheme not in ("http", "https") or not original.hostname:
82 raise ValueError("转载时必须使用 --source-url 提供 http/https 原文链接")
83 elif self.source_url:
84 raise ValueError("仅信息来源为转载时可以填写 --source-url")
85 if self.author is not None:
86 author_length = math.ceil(sum(.5 if ord(char) <= 255 else 1 for char in self.author.strip()))
87 if not 1 <= author_length <= 10:
88 raise ValueError("作者名称需要 1–10 字(英文字符按半字计数并向上取整)")
89 if self.cover_indices:
90 if len(self.cover_indices) not in DAYU_ARTICLE_COVER_MODES:
91 raise ValueError("--cover-indices 需要提供 1 个或 3 个正文图片序号,对应单封面或三封面")
92 if any(index < 1 or index > len(self.document.images) for index in self.cover_indices):
93 raise ValueError("封面序号超出正文图片范围,图片从 1 开始计数")
94 if len(set(self.cover_indices)) != len(self.cover_indices):
95 raise ValueError("三封面请提供不同的正文图片序号")
96 if self.upload_timeout <= 0:
97 raise ValueError("上传期限必须大于 0 秒")
98
99 async def fill_article_body(self, page: Page):
100 """经原生粘贴导入格式,再在各图片位置使用平台上传器插图,保留编辑器元数据。"""
101 document = self.document
102 insertions = []
103 parts = []
104 for part in document.parts:
105 if isinstance(part, Path) or part == "<hr>":
106 marker = f"SAU_ITEM_{uuid4().hex}"
107 parts.append(marker)
108 insertions.append((marker, part if isinstance(part, Path) else None))
109 else:
110 parts.append(part)
111 # 平台把 section 改成 span、把 figure 放进 p,导致图片回调无法定位图片说明。
112 # 这两种元素在主题中是布局容器;仅改为 div,保留主题内联样式和正文顺序。
113 html = re.sub(r"<(\/?)(?:section|figure)(?=[\s>])", r"<\1div", "".join(parts), flags=re.I)
114 await page.context.grant_permissions(["clipboard-read", "clipboard-write"], origin="https://mp.dayu.com")
115 await page.evaluate("""async html => navigator.clipboard.write([
116 new ClipboardItem({'text/html': new Blob([html], {type: 'text/html'})})
117 ])""", html)
118 # 正文位于独立 iframe,其可编辑 body 才是粘贴目标,不能在主文档查 contenteditable。
119 body = page.frame_locator(ARTICLE_BODY).locator("body[contenteditable=true]")
120 await expect(body).to_have_count(1, timeout=30000)
121 await body.click()
122 shortcut = "Meta" if sys.platform == "darwin" else "Control"
123 await body.press(f"{shortcut}+A")
124 await body.press(f"{shortcut}+V")
125 await expect(body).to_contain_text(next(text.strip()[:30] for text in document.text if text.strip()))
126 # 主题包含多层容器,粘贴后平台异步重建节点;过早选中标记会使插图位置失效。
127 await page.locator("#title").click()
128 await wait_dayu_article_body_stable(body)
129 image_number = 0
130 for marker, image_path in insertions:
131 await expect(body).to_contain_text(marker)
132 # 选中唯一图片标记;按键和 mouseup 刷新 UEditor 的选区缓存,工具栏才能替换正确位置。
133 await body.evaluate("""(body, marker) => {
134 body.focus(); const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
135 let node;
136 while (node = walker.nextNode()) {
137 const offset = node.textContent.indexOf(marker);
138 if (offset < 0) continue;
139 const range = document.createRange(); range.setStart(node, offset);
140 range.setEnd(node, offset + marker.length);
141 const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);
142 return;
143 }
144 throw Error('正文中未找到本次图片位置标记');
145 }""", marker)
146 await body.press("Shift")
147 await body.dispatch_event("mouseup")
148 if image_path is None:
149 # 原生粘贴会过滤 hr,使用页面本身的分隔线命令保留其发布语义。
150 # 工具栏 datatitle 表达具体动作,不依赖图标样式和按钮序号。
151 await page.locator('.edui-toolbar [datatitle="分隔线"]').click()
152 await expect(body).not_to_contain_text(marker)
153 continue
154 # 用动作语义 datatitle 找插图工具;正文与封面共用弹窗,仅选择当前可见实例。
155 await page.locator('.edui-toolbar [datatitle="插入图片"]').click()
156 dialog = page.locator(".article-material-image-dialog:visible")
157 # 本地上传 input 在打开弹窗后才生成;限定当前弹窗排除封面等隐藏上传器。
158 upload = dialog.locator('input[type="file"]')
159 await expect(upload).to_have_count(1)
160 await upload.set_input_files(str(image_path))
161 # chosen 是本次已选素材状态,结合文件名及远端 src 确认本次上传对象。
162 chosen = dialog.locator(".article-material-localImage_list_item_chosen")
163 await expect(chosen).to_have_count(1, timeout=self.upload_timeout * 1000)
164 await expect(chosen.locator("p")).to_have_text(image_path.name)
165 await expect(chosen.locator("img")).to_have_attribute("src", re.compile(r"^https://mp\.dayu\.com/dayu/image\?"))
166 await dialog.get_by_role("button", name="确认", exact=True).click()
167 await expect(dialog).to_have_count(0)
168 await expect(body).not_to_contain_text(marker)
169 image_number += 1
170 await expect(body.locator("img")).to_have_count(image_number)
171 # 插图逐张按正文顺序完成,已有图片数量已断言;序号对应本次插入的正文位置。
172 await expect(body.locator("img").nth(image_number - 1)).to_have_attribute("data-infoed", "1")
173 # data-infoed 后仍会异步补写图片说明并清理正文;这次清理会删除过早插入的 hr。
174 # 先失焦并确认本次插图稳定,再处理后续分隔线/图片,不能仅等图片元数据出现。
175 await page.locator("#title").click()
176 await wait_dayu_article_body_stable(body)
177 dayu_logger.info(f"大鱼号正文图片 {image_number}/{len(document.images)} 已插入: {image_path.name}")
178 # 页面会异步规范化正文;必须在失焦并连续三次读回一致后核对,避免瞬时 DOM 误报成功。
179 # 标题 ID 是正文外的实际表单字段,切换焦点不会提交或改变文章正文。
180 await page.locator("#title").click()
181 await wait_dayu_article_body_stable(body)
182 # 独立核对文字和语义格式;不因粘贴成功就假设正文完整、样式保留。
183 await check_dayu_article_content(body, document.manifest)
184 self.publication_html = None
185 self.style_result = {"mode": "native"}
186 if re.search(r'\sstyle="[^\"]+"', document.content_html):
187 # 编辑器和保存接口均会过滤 CSS;从原稿转换表现属性,图片沿用本次原生上传的元数据。
188 images = await body.locator("img").evaluate_all("images => images.map(image => image.outerHTML)")
189 compatible = await render_dayu_compatible_html(page, document.content_html, images)
190 self.publication_html = compatible["html"]
191 document.manifest["dayu_style"] = compatible["expectations"]
192 self.style_result = {"mode": compatible["mode"], "limitations": compatible["limitations"],
193 "preview_checked": False}
194 for index in range(len(document.images)):
195 await expect(body.locator("img").nth(index)).to_have_js_property("complete", True)
196 if await body.locator("img").nth(index).evaluate("e => e.naturalWidth") <= 0:
197 raise RuntimeError(f"正文第 {index + 1} 张图片无法加载")
198
199 async def fill_article_form(self, page: Page):
200 """正文、标题、作者及来源填写后逐项读回;作者缺省时沿用页面值。"""
201 await self.fill_article_body(page)
202 # title、author 是表单字段的语义 ID,避免把正文中的标题和作者文字当成输入控件。
203 await page.locator("#title").fill(self.title)
204 await expect(page.locator("#title")).to_have_value(self.title)
205 if self.author is not None:
206 await page.locator("#author input").fill(self.author)
207 await expect(page.locator("#author input")).to_have_value(self.author)
208 # 限定来源组件并按 radio 的业务 value 选择,避免其他单选组或选项顺序变化干扰。
209 source = page.locator(f'.article-write-source-remark input[value="{self.source}"]')
210 # 当前页 CSS 把透明 radio input 拉宽到 240px,指针中心会落到相邻选项;原生键盘选择不受影响。
211 await source.focus()
212 await source.press("Space")
213 await expect(source).to_be_checked()
214 # 条件原文链接没有独立语义 ID,使用字段 label 与同容器 input 的局部关系定位。
215 original = page.locator(".article-write_box-form-filed").filter(
216 has=page.locator("label").filter(has_text="原文链接"),
217 ).locator('input[type="text"]')
218 if self.source == DAYU_SOURCE_REPRINT:
219 await original.fill(self.source_url)
220 await expect(original).to_have_value(self.source_url)
221 else:
222 await expect(original).to_have_count(0)
223 if self.cover_indices:
224 mode = DAYU_ARTICLE_COVER_MODES[len(self.cover_indices)]
225 # 封面模式限定横版封面组件并匹配选项文本,避免与竖版封面和来源单选组混淆。
226 option = page.locator(".article-write-article-cover_normal-option").filter(has_text=mode)
227 await option.locator(".w-radio").click()
228 await expect(option.locator(".w-radio")).to_have_class(re.compile(r"w-radio_checked"))
229 slots = page.locator(".article-write-article-cover_normal-item")
230 await expect(slots).to_have_count(len(self.cover_indices))
231 for slot_number, image_index in enumerate(self.cover_indices):
232 # 槽位顺序对应用户给定的封面顺序;弹窗图片顺序对应正文图片顺序。
233 await slots.nth(slot_number).locator(".article-write-article-cover-cover-item").click()
234 dialog = page.locator(".article-material-image-dialog:visible")
235 choices = dialog.locator(".article-material-image_image-choose img")
236 await expect(choices).to_have_count(len(self.document.images))
237 await choices.nth(image_index - 1).click()
238 await expect(dialog.locator(".article-material-image_image-choose .chosen")).to_have_count(1)
239 await dialog.get_by_role("button", name="下一步", exact=True).click()
240 await expect(dialog.get_by_role("button", name="保存", exact=True)).to_be_visible()
241 await dialog.get_by_role("button", name="保存", exact=True).click()
242 await expect(dialog).to_have_count(0, timeout=30000)
243 preview = slots.nth(slot_number).locator("img")
244 await expect(preview).to_have_count(1)
245 await expect(preview).to_have_attribute("src", re.compile(r"^https?://image\.uc\.cn/"))
246 await fill_dayu_schedule(page, self.schedule)
247
248 async def main(self) -> dict:
249 """核对编辑器内容并提交发表,平台确认本次作品 ID 后即成功。"""
250 self.validate_upload_args()
251 expected = load_dayu_identity(self.account_file)
252 results_dir = self.account_file.parent / "dayu_results"
253 results_dir.mkdir(exist_ok=True)
254 result_file = results_dir / f"{datetime.now():%Y%m%d-%H%M%S}-{uuid4().hex[:8]}.json"
255 result = {"success": False, "status": "preparing", "type": "article", "title": self.title,
256 "content_file": str(self.content_file), "identity": expected,
257 "manifest": self.document.manifest, "result_file": str(result_file)}
258 if self.schedule:
259 result["schedule"] = self.schedule.isoformat()
260 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
261 async with async_playwright() as playwright:
262 browser = await playwright.chromium.launch(
263 executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=self.headless,
264 )
265 page = None
266 try:
267 context = await browser.new_context(storage_state=str(self.account_file), timezone_id="Asia/Shanghai")
268 page = await context.new_page()
269 await page.goto(DAYU_ARTICLE_URL, wait_until="domcontentloaded", timeout=45000)
270 identity = await read_dayu_identity(page)
271 if identity["wmid"] != expected["wmid"]:
272 raise RuntimeError("大鱼号主体不匹配,图文上传已中止")
273 result["identity"] = identity
274 await self.fill_article_form(page)
275 result.update(source_format=self.document.source_format, theme=self.document.theme,
276 style_check=self.style_result)
277 if (await read_dayu_identity(page))["wmid"] != identity["wmid"]:
278 raise RuntimeError("填表期间大鱼号主体发生变化,拒绝发表")
279 if self.prepare_only:
280 await page.screenshot(path=str(result_file.with_suffix(".png")), full_page=True)
281 result.update(success=True, status="prepared")
282 return result
283 await submit_dayu_publication(page, result, result_file, article_html=self.publication_html)
284 await context.storage_state(path=str(self.account_file))
285 action = "定时发布已安排" if self.schedule else "发表成功"
286 dayu_logger.success(f"大鱼号图文{action}: {result['content_id']}")
287 return result
288 except Exception as exc:
289 result["error"] = str(exc)
290 dayu_logger.error(f"大鱼号图文阶段={result['status']},结果文件={result_file}: {exc}")
291 if self.debug and page is not None:
292 await page.screenshot(path=str(result_file.with_suffix(".png")))
293 raise
294 finally:
295 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
296 await browser.close()
297
297 lines PYTHON