| 1 | """微信公众号图文发布:标题、摘要、正文、封面与多步发表确认。 |
| 2 | |
| 3 | 微信公众号正文编辑器(UEditor / ProseMirror)会过滤外部样式,且发表前需要连过 |
| 4 | 创作来源声明、发表方式、群发确认和管理员扫码验证。扫码验证只能由账号管理员 |
| 5 | 本人完成,本模块在检测到验证二维码后暂停并明确提示,不代劳、不绕过。 |
| 6 | """ |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import json |
| 10 | import re |
| 11 | from datetime import datetime |
| 12 | from pathlib import Path |
| 13 | from uuid import uuid4 |
| 14 | |
| 15 | from patchright.async_api import Page, async_playwright, expect |
| 16 | |
| 17 | from utils.article_render import load_article |
| 18 | from uploader.wechat_uploader.constants import ( |
| 19 | WECHAT_ARTICLE_PATH, WECHAT_ARTICLE_TITLE_MAX, WECHAT_AUTHOR_MAX, |
| 20 | WECHAT_DIGEST_MAX, WECHAT_IMAGE_SUFFIXES, WECHAT_TIMEZONE, WECHAT_ORIGINALITY, |
| 21 | ) |
| 22 | from uploader.wechat_uploader.session import ( |
| 23 | browser_launch_kwargs, load_wechat_identity, read_wechat_identity, read_wechat_token, |
| 24 | ) |
| 25 | |
| 26 | |
| 27 | TITLE_EDITOR = '.title-editor__input .ProseMirror, #title-editor .ProseMirror, .title-editor__input' |
| 28 | BODY_EDITOR = '#ueditor_0 .ProseMirror, .ProseMirror[contenteditable="true"]' |
| 29 | DIGEST_INPUT = '#js_description' |
| 30 | |
| 31 | |
| 32 | def build_article_url(token: str) -> str: |
| 33 | """用当前会话 token 构造新建图文地址。""" |
| 34 | return (f"https://mp.weixin.qq.com{WECHAT_ARTICLE_PATH}" |
| 35 | f"?t=media/appmsg_edit_v2&action=edit&isNew=1&type=77" |
| 36 | f"&createType=0&token={token}&lang=zh_CN") |
| 37 | |
| 38 | |
| 39 | class WechatArticle: |
| 40 | """按原稿填写图文并核对;发表只触发一次,扫码验证交给管理员。""" |
| 41 | |
| 42 | def __init__(self, title, content_file, account_file, digest=None, author=None, |
| 43 | cover=None, originality="none", broadcast=True, prepare_only=False, |
| 44 | headless=False, debug=False, qr_timeout=600): |
| 45 | self.title = title |
| 46 | self.content_file = Path(content_file).expanduser().resolve() |
| 47 | self.account_file = Path(account_file).resolve() |
| 48 | self.digest = digest |
| 49 | self.author = author |
| 50 | self.cover = Path(cover).expanduser().resolve() if cover else None |
| 51 | self.originality = originality |
| 52 | self.broadcast = broadcast |
| 53 | self.prepare_only = prepare_only |
| 54 | self.headless = headless |
| 55 | self.debug = debug |
| 56 | self.qr_timeout = qr_timeout |
| 57 | |
| 58 | def validate_upload_args(self) -> None: |
| 59 | """启动浏览器前检查标题、正文、封面、账号与选项。""" |
| 60 | if not self.title.strip() or len(self.title) > WECHAT_ARTICLE_TITLE_MAX: |
| 61 | raise ValueError(f"微信公众号文章标题需为 1–{WECHAT_ARTICLE_TITLE_MAX} 字") |
| 62 | if self.digest is not None and len(self.digest) > WECHAT_DIGEST_MAX: |
| 63 | raise ValueError(f"微信公众号摘要最多 {WECHAT_DIGEST_MAX} 字") |
| 64 | if self.author is not None and len(self.author) > WECHAT_AUTHOR_MAX: |
| 65 | raise ValueError(f"微信公众号作者最多 {WECHAT_AUTHOR_MAX} 字") |
| 66 | if self.originality not in WECHAT_ORIGINALITY: |
| 67 | raise ValueError(f"创作来源声明必须为: {', '.join(WECHAT_ORIGINALITY)}") |
| 68 | if self.qr_timeout <= 0: |
| 69 | raise ValueError("扫码验证期限必须大于 0 秒") |
| 70 | self.document = load_article(self.content_file) |
| 71 | if not "".join(self.document.text).strip(): |
| 72 | raise ValueError("微信公众号文章正文不能为空") |
| 73 | if not self.account_file.is_file(): |
| 74 | raise FileNotFoundError("请先执行 sau wechat login 保存账号") |
| 75 | self.identity = load_wechat_identity(self.account_file) |
| 76 | if self.cover is not None: |
| 77 | if not self.cover.is_file(): |
| 78 | raise FileNotFoundError(f"封面图片不存在: {self.cover}") |
| 79 | if self.cover.suffix.lower() not in WECHAT_IMAGE_SUFFIXES: |
| 80 | raise ValueError(f"封面图片格式不支持: {self.cover.suffix}") |
| 81 | for image in self.document.images: |
| 82 | if not image.is_file(): |
| 83 | raise FileNotFoundError(f"正文图片不存在: {image}") |
| 84 | if image.suffix.lower() not in WECHAT_IMAGE_SUFFIXES: |
| 85 | raise ValueError(f"正文图片格式不支持: {image.suffix}") |
| 86 | |
| 87 | async def fill_article_form(self, page: Page) -> None: |
| 88 | """填写标题、摘要与正文;图片按原稿位置逐个上传。""" |
| 89 | title = page.locator(TITLE_EDITOR).first |
| 90 | await expect(title).to_be_visible(timeout=30000) |
| 91 | await title.click() |
| 92 | await title.press("ControlOrMeta+A") |
| 93 | await title.fill(self.title) |
| 94 | await expect(page.locator('#title, input[name="title"]').first).to_have_value( |
| 95 | self.title, timeout=15000) |
| 96 | |
| 97 | if self.digest: |
| 98 | digest = page.locator(DIGEST_INPUT) |
| 99 | await expect(digest).to_have_count(1) |
| 100 | await digest.fill(self.digest) |
| 101 | await expect(digest).to_have_value(self.digest) |
| 102 | if self.author: |
| 103 | author = page.locator('#author') |
| 104 | if await author.count(): |
| 105 | await author.fill(self.author) |
| 106 | |
| 107 | body = page.locator(BODY_EDITOR).first |
| 108 | await expect(body).to_be_visible(timeout=30000) |
| 109 | await body.click() |
| 110 | await body.press("ControlOrMeta+A") |
| 111 | # clipboard HTML 粘贴让编辑器自行建模,保留标题、加粗、链接与图片位置。 |
| 112 | parts, insertions = [], [] |
| 113 | for part in self.document.parts: |
| 114 | if isinstance(part, Path): |
| 115 | marker = f"SAU_WX_IMAGE_{uuid4().hex}" |
| 116 | parts.append(marker) |
| 117 | insertions.append((marker, part)) |
| 118 | else: |
| 119 | parts.append(part) |
| 120 | await page.context.grant_permissions( |
| 121 | ["clipboard-read", "clipboard-write"], origin="https://mp.weixin.qq.com") |
| 122 | await page.evaluate("""async html => navigator.clipboard.write([ |
| 123 | new ClipboardItem({'text/html': new Blob([html], {type: 'text/html'})}) |
| 124 | ])""", "".join(parts)) |
| 125 | await body.press("ControlOrMeta+V") |
| 126 | |
| 127 | self.uploaded_images = [] |
| 128 | for index, (marker, image) in enumerate(insertions, 1): |
| 129 | await expect(body).to_contain_text(marker, timeout=15000) |
| 130 | await body.evaluate("""(body, marker) => { |
| 131 | body.focus(); const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT); |
| 132 | let node; |
| 133 | while (node = walker.nextNode()) { |
| 134 | const offset = node.textContent.indexOf(marker); |
| 135 | if (offset < 0) continue; |
| 136 | const range = document.createRange(); |
| 137 | range.setStart(node, offset); |
| 138 | range.setEnd(node, offset + marker.length); |
| 139 | const selection = getSelection(); |
| 140 | selection.removeAllRanges(); |
| 141 | selection.addRange(range); |
| 142 | return; |
| 143 | } |
| 144 | throw Error('找不到原稿图片位置标记'); |
| 145 | }""", marker) |
| 146 | if image.suffix.lower() == ".png": |
| 147 | import base64 |
| 148 | await page.evaluate("""async encoded => { |
| 149 | const bytes = Uint8Array.from(atob(encoded), c => c.charCodeAt(0)); |
| 150 | await navigator.clipboard.write([ |
| 151 | new ClipboardItem({'image/png': new Blob([bytes], {type: 'image/png'})}) |
| 152 | ]); |
| 153 | }""", base64.b64encode(image.read_bytes()).decode("ascii")) |
| 154 | await body.press("ControlOrMeta+A") |
| 155 | # 撤销全选对正文的影响:重新把光标放回标记处再粘贴。 |
| 156 | await body.evaluate("""(body, marker) => { |
| 157 | const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT); |
| 158 | let node; |
| 159 | while (node = walker.nextNode()) { |
| 160 | const offset = node.textContent.indexOf(marker); |
| 161 | if (offset < 0) continue; |
| 162 | const range = document.createRange(); |
| 163 | range.setStart(node, offset); |
| 164 | range.setEnd(node, offset + marker.length); |
| 165 | const selection = getSelection(); |
| 166 | selection.removeAllRanges(); |
| 167 | selection.addRange(range); |
| 168 | return; |
| 169 | } |
| 170 | }""", marker) |
| 171 | await body.press("Backspace") |
| 172 | await body.press("ControlOrMeta+V") |
| 173 | else: |
| 174 | image_input = page.locator('input[type="file"][accept*="image"]').last |
| 175 | await image_input.set_input_files(str(image)) |
| 176 | await expect(body).not_to_contain_text(marker, timeout=30000) |
| 177 | self.uploaded_images.append(str(image)) |
| 178 | |
| 179 | await self.verify_form(page, title, body) |
| 180 | |
| 181 | async def verify_form(self, page: Page, title, body) -> None: |
| 182 | """提交前核对标题、摘要和正文首段,防止粘贴丢失或串位。""" |
| 183 | actual_title = await page.locator('#title, input[name="title"]').first.input_value() |
| 184 | if actual_title.strip() != self.title: |
| 185 | raise RuntimeError("微信公众号标题与本地稿不一致,停止提交") |
| 186 | body_text = (await body.inner_text()).strip() |
| 187 | first_text = next((text.strip() for text in self.document.text if text.strip()), "") |
| 188 | if not first_text or first_text[:12] not in body_text: |
| 189 | raise RuntimeError("微信公众号正文首段未正确写入,停止提交") |
| 190 | if self.digest: |
| 191 | actual_digest = await page.locator(DIGEST_INPUT).input_value() |
| 192 | if actual_digest.strip() != self.digest.strip(): |
| 193 | raise RuntimeError("微信公众号摘要与本地稿不一致,停止提交") |
| 194 | if await read_wechat_identity(page) != self.identity: |
| 195 | raise RuntimeError("微信公众号填写期间账号发生变化,已中止") |
| 196 | |
| 197 | async def upload_cover(self, page: Page) -> None: |
| 198 | """通过图片库上传独立封面;封面为可选项,失败时明确报错。""" |
| 199 | if self.cover is None: |
| 200 | return |
| 201 | # 封面 "+" 框用真实鼠标点击才会弹出选图菜单;DOM click 实测无效。 |
| 202 | cover_box = page.locator('.appmsg_cover, .cover, [class*="cover_area"]').first |
| 203 | await cover_box.click(position={"x": 20, "y": 20}) |
| 204 | await page.get_by_text("从图片库选择", exact=True).click() |
| 205 | file_input = page.locator('.js_upload_btn_container input[type="file"]').first |
| 206 | await expect(file_input).to_have_count(1, timeout=15000) |
| 207 | await file_input.set_input_files(str(self.cover)) |
| 208 | await page.get_by_text(self.cover.name, exact=False).first.wait_for(state="visible", timeout=30000) |
| 209 | await page.get_by_role("button", name="确定", exact=True).last.click() |
| 210 | # 封面裁剪确认弹窗;不同账号可能不出现,仅在出现时点击。 |
| 211 | try: |
| 212 | confirm = page.get_by_role("button", name="确认", exact=True) |
| 213 | if await confirm.count() and await confirm.last.is_visible(): |
| 214 | await confirm.last.click() |
| 215 | except Exception: |
| 216 | pass |
| 217 | |
| 218 | async def main(self) -> dict: |
| 219 | """填写并可发表;扫码验证由管理员完成,程序在二维码处暂停等待。""" |
| 220 | self.validate_upload_args() |
| 221 | results_dir = self.account_file.parent / "wechat_results" |
| 222 | results_dir.mkdir(exist_ok=True) |
| 223 | result_file = results_dir / f"{datetime.now(WECHAT_TIMEZONE):%Y%m%d-%H%M%S}-{uuid4().hex[:8]}.json" |
| 224 | result = { |
| 225 | "success": False, "status": "preparing", "type": "article", |
| 226 | "title": self.title, "content_file": str(self.content_file), |
| 227 | "digest": self.digest, "author": self.author, |
| 228 | "cover": str(self.cover) if self.cover else None, |
| 229 | "originality": self.originality, "broadcast": self.broadcast, |
| 230 | "identity": self.identity, "result_file": str(result_file), |
| 231 | } |
| 232 | |
| 233 | async with async_playwright() as playwright: |
| 234 | browser = await playwright.chromium.launch(**browser_launch_kwargs(self.headless)) |
| 235 | page = None |
| 236 | submitted = False |
| 237 | try: |
| 238 | context = await browser.new_context( |
| 239 | storage_state=str(self.account_file), timezone_id="Asia/Shanghai") |
| 240 | page = await context.new_page() |
| 241 | token = await read_wechat_token(page) |
| 242 | result["token_prefix"] = token[:4] + "***" |
| 243 | article_url = build_article_url(token) |
| 244 | response = await page.goto(article_url, wait_until="domcontentloaded", timeout=45000) |
| 245 | if response is not None and response.status >= 400: |
| 246 | raise RuntimeError(f"微信公众号图文编辑器访问失败,HTTP {response.status}") |
| 247 | if await read_wechat_identity(page) != self.identity: |
| 248 | raise RuntimeError("微信公众号编辑器账号与本地绑定不一致") |
| 249 | |
| 250 | await self.fill_article_form(page) |
| 251 | await self.upload_cover(page) |
| 252 | result.update(images=self.uploaded_images, manifest=self.document.manifest, |
| 253 | editor_url=page.url) |
| 254 | result["status"] = "prepared" |
| 255 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 256 | screenshot = result_file.with_suffix(".png") |
| 257 | await page.screenshot(path=str(screenshot), full_page=True) |
| 258 | result["screenshot"] = str(screenshot) |
| 259 | if self.prepare_only: |
| 260 | return result |
| 261 | |
| 262 | # 发表后依次处理创作来源声明、发表方式与群发确认;每步只点一次。 |
| 263 | publish = page.get_by_role("button", name="发表", exact=True).last |
| 264 | await expect(publish).to_be_enabled(timeout=30000) |
| 265 | result["status"] = "submission_unknown" |
| 266 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 267 | await publish.click() |
| 268 | |
| 269 | # 创作来源声明:按用户选择处理,不擅自替作者声明原创。 |
| 270 | try: |
| 271 | declare = page.get_by_role("button", name=re.compile("声明|原创|不声明|无需声明")) |
| 272 | if await declare.count() and await declare.first.is_visible(timeout=5000): |
| 273 | if self.originality == "original": |
| 274 | await page.get_by_role("button", name=re.compile("声明原创")).first.click() |
| 275 | else: |
| 276 | await page.get_by_role("button", name=re.compile("无需声明|不声明")).first.click() |
| 277 | except Exception: |
| 278 | pass |
| 279 | |
| 280 | # 发表方式弹窗:群发通知开关按 --broadcast 决定。 |
| 281 | try: |
| 282 | if await page.get_by_text("发表方式", exact=False).count(): |
| 283 | if self.broadcast: |
| 284 | toggle = page.locator('.weui-desktop-switch, [role="switch"]').first |
| 285 | if await toggle.count() and "on" not in (await toggle.get_attribute("class") or ""): |
| 286 | await toggle.click() |
| 287 | await page.get_by_role("button", name="发表", exact=True).last.click() |
| 288 | # 已开启群发通知的二次确认。 |
| 289 | continue_btn = page.get_by_role("button", name=re.compile("继续发表")) |
| 290 | if await continue_btn.count() and await continue_btn.last.is_visible(timeout=5000): |
| 291 | await continue_btn.last.click() |
| 292 | except Exception: |
| 293 | pass |
| 294 | |
| 295 | submitted = True |
| 296 | # 管理员扫码验证:检测到二维码后暂停等待,超时则如实报告未知。 |
| 297 | try: |
| 298 | qr_hint = page.get_by_text(re.compile("扫码.*验证|管理员.*验证")) |
| 299 | if await qr_hint.count() and await qr_hint.first.is_visible(timeout=5000): |
| 300 | result["status"] = "awaiting_admin_qr" |
| 301 | result["message"] = "请用管理员微信扫码完成验证" |
| 302 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 303 | print("请用管理员微信扫描页面二维码完成验证;程序正在等待...", flush=True) |
| 304 | await expect(page).to_have_url( |
| 305 | re.compile(r"mp\.weixin\.qq\.com.*(home|appmsg)"), |
| 306 | timeout=self.qr_timeout * 1000) |
| 307 | except Exception: |
| 308 | pass |
| 309 | |
| 310 | await page.wait_for_timeout(3000) |
| 311 | result["status"] = "submitted" |
| 312 | result["message"] = ("已提交发表;如触发扫码验证请确认已完成," |
| 313 | "并到「已发表」核实发布结果") |
| 314 | result["success"] = True |
| 315 | await page.screenshot(path=str(result_file.with_suffix(".submitted.png")), full_page=True) |
| 316 | return result |
| 317 | except Exception as exc: |
| 318 | result["error"] = str(exc) |
| 319 | if submitted: |
| 320 | result["status"] = "submission_unknown" |
| 321 | elif result["status"] == "preparing": |
| 322 | result["status"] = "failed_before_submit" |
| 323 | if self.debug and page is not None: |
| 324 | screenshot = result_file.with_suffix(".error.png") |
| 325 | await page.screenshot(path=str(screenshot), full_page=True) |
| 326 | result["screenshot"] = str(screenshot) |
| 327 | raise RuntimeError(f"微信公众号阶段={result['status']},结果文件={result_file}: {exc}") from exc |
| 328 | finally: |
| 329 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 330 | await browser.close() |
| 331 |