| 1 | """雪球长文:结构化原稿、原位置插图、封面、预览与单次发表。""" |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | import json |
| 5 | import re |
| 6 | import sys |
| 7 | from datetime import datetime |
| 8 | from pathlib import Path |
| 9 | from uuid import uuid4 |
| 10 | |
| 11 | from patchright.async_api import Page, async_playwright, expect |
| 12 | |
| 13 | from conf import LOCAL_CHROME_PATH |
| 14 | from uploader.xueqiu_uploader.constants import ( |
| 15 | XUEQIU_ARTICLE_URL, XUEQIU_DECLARATIONS, XUEQIU_IMAGE_SUFFIXES, XUEQIU_VISIBILITY, |
| 16 | ) |
| 17 | from uploader.xueqiu_uploader.session import load_xueqiu_identity, read_xueqiu_identity |
| 18 | from uploader.xueqiu_uploader.content import load_xueqiu_article |
| 19 | from uploader.xueqiu_uploader.verification import check_xueqiu_article_content, query_xueqiu_article |
| 20 | |
| 21 | |
| 22 | class XueqiuArticle: |
| 23 | """通过原生粘贴与图片上传保留文章结构,以服务端确认作为发表结果。""" |
| 24 | |
| 25 | def __init__(self, title, content_file, account_file, visibility="公开", |
| 26 | declaration="不添加创作声明", prepare_only=False, headless=False, debug=False, |
| 27 | cover=None): |
| 28 | self.title = title.strip() |
| 29 | self.content_file = Path(content_file).expanduser().resolve() |
| 30 | self.account_file = Path(account_file).resolve() |
| 31 | self.visibility = visibility |
| 32 | self.declaration = declaration |
| 33 | self.prepare_only = prepare_only |
| 34 | self.headless = headless |
| 35 | self.debug = debug |
| 36 | self.cover = Path(cover).expanduser().resolve() if cover else None |
| 37 | |
| 38 | def validate_upload_args(self): |
| 39 | """所有本地参数在创建远端草稿前校验,不猜测尚未观察到的长度上限。""" |
| 40 | if not self.title or "\n" in self.title or "\r" in self.title: |
| 41 | raise ValueError("雪球标题必须为非空单行文字") |
| 42 | self.document = load_xueqiu_article(self.content_file) |
| 43 | if self.visibility not in XUEQIU_VISIBILITY: |
| 44 | raise ValueError(f"分享范围必须为: {', '.join(XUEQIU_VISIBILITY)}") |
| 45 | if self.declaration not in XUEQIU_DECLARATIONS: |
| 46 | raise ValueError(f"创作声明必须为: {', '.join(XUEQIU_DECLARATIONS)}") |
| 47 | for image in self.document.images + ([self.cover] if self.cover else []): |
| 48 | if image.suffix.lower() not in XUEQIU_IMAGE_SUFFIXES: |
| 49 | raise ValueError(f"雪球图片支持: {', '.join(XUEQIU_IMAGE_SUFFIXES)}") |
| 50 | if not image.is_file(): |
| 51 | raise FileNotFoundError(f"图片不存在: {image}") |
| 52 | if image.stat().st_size == 0: |
| 53 | raise ValueError(f"图片不能为空: {image}") |
| 54 | if not self.account_file.is_file(): |
| 55 | raise FileNotFoundError("请先执行 sau xueqiu login 保存账号") |
| 56 | self.identity = load_xueqiu_identity(self.account_file) |
| 57 | |
| 58 | async def fill_article_body(self, page, body): |
| 59 | """在原稿图片位置放置唯一标记,原生上传后再核对完整图文交错顺序。""" |
| 60 | parts = [] |
| 61 | insertions = [] |
| 62 | for part in self.document.parts: |
| 63 | if isinstance(part, Path): |
| 64 | marker = f"SAU_IMAGE_{uuid4().hex}" |
| 65 | parts.append(marker) |
| 66 | insertions.append((marker, part)) |
| 67 | else: |
| 68 | parts.append(part) |
| 69 | await page.context.grant_permissions(["clipboard-read", "clipboard-write"], origin="https://mp.xueqiu.com") |
| 70 | await page.evaluate("""async html => navigator.clipboard.write([ |
| 71 | new ClipboardItem({'text/html': new Blob([html], {type: 'text/html'})}) |
| 72 | ])""", "".join(parts)) |
| 73 | await body.click() |
| 74 | await body.press("Meta+V" if sys.platform == "darwin" else "Control+V") |
| 75 | # 标题字段用于失焦;等待本次末尾文字实际进入模型,再开始选择图片标记。 |
| 76 | await page.get_by_placeholder("请输入标题", exact=True).click() |
| 77 | for marker, _ in insertions: |
| 78 | await expect(body).to_contain_text(marker) |
| 79 | self.uploaded_images = [] |
| 80 | for index, (marker, image) in enumerate(insertions): |
| 81 | # 在正文实际文本节点选择唯一标记;使用原生选区而非改写 ProseMirror innerHTML。 |
| 82 | # 实测该选区经 Shift 刷新后会被工具栏上传替换,后续段落保持原位。 |
| 83 | await body.evaluate("""(body, marker) => { |
| 84 | body.focus(); const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT); |
| 85 | let node; |
| 86 | while (node = walker.nextNode()) { |
| 87 | const offset = node.textContent.indexOf(marker); |
| 88 | if (offset < 0) continue; |
| 89 | const range = document.createRange(); range.setStart(node, offset); |
| 90 | range.setEnd(node, offset + marker.length); |
| 91 | const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); |
| 92 | return; |
| 93 | } |
| 94 | throw Error('找不到本次原稿图片位置标记'); |
| 95 | }""", marker) |
| 96 | await body.press("Shift") |
| 97 | # data-tip 是实测上传动作语义;限定 snb_toolbar 排除独立封面 input。 |
| 98 | async with page.expect_file_chooser() as chooser: |
| 99 | await page.locator('#snb_toolbar [data-tip="上传图片"]').click() |
| 100 | file_chooser = await chooser.value |
| 101 | # input 保留旧文件;只清空原生值而不派发空 change,允许相同文件在不同原稿位置出现。 |
| 102 | await file_chooser.element.evaluate("input => { input.value = ''; }") |
| 103 | await file_chooser.set_files(str(image)) |
| 104 | await expect(body).not_to_contain_text(marker) |
| 105 | await expect(body.locator("img")).to_have_count(index + 1, timeout=60000) |
| 106 | # 图片按原稿顺序逐个替换,已断言数量;data/blob 预览不代表服务端完成。 |
| 107 | inserted = body.locator("img").nth(index) |
| 108 | await expect(inserted).to_have_attribute("src", re.compile(r"^(?:https:)?//xqimg\.imedao\.com/"), timeout=60000) |
| 109 | await expect(inserted).to_have_js_property("complete", True, timeout=60000) |
| 110 | if await inserted.evaluate("e => e.naturalWidth") <= 0: |
| 111 | raise RuntimeError(f"正文图片无法加载: {image.name}") |
| 112 | self.uploaded_images.append(await inserted.evaluate("e => e.src")) |
| 113 | await page.get_by_placeholder("请输入标题", exact=True).click() |
| 114 | await check_xueqiu_article_content(body, self.document) |
| 115 | |
| 116 | async def fill_article_form(self, page: Page): |
| 117 | """按真实字段填写、读回选项和正文,再独立检查预览与自动保存。""" |
| 118 | # 标题占位符表达字段职责;正文 placeholder 在输入后消失,使用 editor 直属可编辑节点, |
| 119 | # 排除上传图片内部 contenteditable=false 的工具容器,填表前后使用同一定位器。 |
| 120 | title = page.get_by_placeholder("请输入标题", exact=True) |
| 121 | body = page.locator('#editor > [contenteditable="true"]') |
| 122 | await expect(title).to_have_count(1) |
| 123 | await expect(body).to_have_count(1) |
| 124 | # 新任务只写空编辑器;页面若恢复已有草稿,不覆盖用户原文。 |
| 125 | if (await title.input_value()).strip() or (await body.inner_text()).strip() or await body.locator("img").count(): |
| 126 | raise RuntimeError("雪球编辑器已有内容,拒绝覆盖;请先处理现有草稿") |
| 127 | await title.fill(self.title) |
| 128 | await expect(title).to_have_value(self.title) |
| 129 | await self.fill_article_body(page, body) |
| 130 | self.cover_url = None |
| 131 | if self.cover: |
| 132 | # 封面字段行以 label 限域,input 的 type 表达上传用途,不与工具栏正文上传器混用。 |
| 133 | cover_row = page.locator('div[class*="index_sectionFlex_"]').filter( |
| 134 | has=page.get_by_text("封面图片:", exact=True), |
| 135 | ) |
| 136 | await cover_row.locator('input[type="file"]').set_input_files(str(self.cover)) |
| 137 | # 实测封面必须经过独立裁剪弹窗;保留默认裁剪框,不猜测尺寸或操作隐藏状态。 |
| 138 | crop = page.locator('div[class*="modal_modal-content_"]').filter( |
| 139 | has=page.get_by_text("选择封面图片", exact=True), |
| 140 | ) |
| 141 | await expect(crop).to_be_visible() |
| 142 | await expect(crop.locator('img[alt="Crop"]')).to_have_js_property("complete", True) |
| 143 | if await crop.locator('img[alt="Crop"]').evaluate("e => e.naturalWidth") <= 0: |
| 144 | raise RuntimeError("封面裁剪预览无法加载") |
| 145 | await crop.get_by_role("button", name="确认裁剪", exact=True).click() |
| 146 | await expect(crop).to_have_count(0, timeout=60000) |
| 147 | # 实测成功封面以背景图展示,原上传按钮被 hidden;不能检查占位 img 的固定地址。 |
| 148 | cover_preview = cover_row.locator('div[class*="index_input-cover-pic-btn_"]') |
| 149 | await expect(cover_preview).to_have_attribute("style", re.compile(r".*xqimg\.imedao\.com/.*"), timeout=60000) |
| 150 | self.cover_url = await cover_preview.evaluate( |
| 151 | "e => new URL(getComputedStyle(e).backgroundImage.slice(5, -2), location.href).href") |
| 152 | for label, value in (("分享范围:", self.visibility), ("创作声明:", self.declaration)): |
| 153 | # class 仅保留字段行和组件职责前缀;以本行 label 限域,排除另一组同构下拉菜单。 |
| 154 | row = page.locator('div[class*="index_sectionFlex_"]').filter( |
| 155 | has=page.get_by_text(label, exact=True), |
| 156 | ) |
| 157 | selected = row.locator('div[class*="index_selectWrap_"]') |
| 158 | await selected.click() |
| 159 | # optionContainer 是展开选项容器;visible 排除当前未展开的另一菜单。 |
| 160 | option = row.locator('div[class*="index_optionContainer_"]:visible').get_by_text(value, exact=True) |
| 161 | await expect(option).to_have_count(1) |
| 162 | await option.click() |
| 163 | await expect(selected).to_contain_text(value) |
| 164 | # publish_state 是独立自动保存状态区域,不以正文里的同名文字判断保存完成。 |
| 165 | await expect(page.locator('div[class*="publish_state_"]')).to_contain_text("已经保存至草稿", timeout=60000) |
| 166 | await page.get_by_role("button", name="预览", exact=True).click() |
| 167 | # 预览容器的业务前缀在实测 DOM 中稳定;h1 与 content-text 分别承载预览标题、正文。 |
| 168 | preview = page.locator('div[class*="index_preview-content_"]') |
| 169 | await expect(preview).to_be_visible() |
| 170 | await expect(preview.locator("h1")).to_have_text(self.title) |
| 171 | # 预览由异步服务端结果填入,先等本次文字,不能只等空预览外壳可见。 |
| 172 | preview_body = preview.locator('div[class*="index_content-text_"] > div') |
| 173 | await expect(preview_body).to_contain_text(next(text.strip() for text in self.document.text if text.strip()), timeout=30000) |
| 174 | await check_xueqiu_article_content(preview_body, self.document) |
| 175 | # 预览 content-text 直属封面 img 与直属 div 内的正文图片并存;只在后者核对插图。 |
| 176 | preview_images = preview.locator('div[class*="index_content-text_"] > div img') |
| 177 | await expect(preview_images).to_have_count(len(self.uploaded_images)) |
| 178 | for index, source in enumerate(self.uploaded_images): |
| 179 | # 平台预览会给 // 地址补 https;比较解析后的 src,并按正文顺序排除错图或重排。 |
| 180 | await expect(preview_images.nth(index)).to_have_js_property("src", source) |
| 181 | await expect(preview_images.nth(index)).to_have_js_property("complete", True) |
| 182 | if await preview_images.nth(index).evaluate("e => e.naturalWidth") <= 0: |
| 183 | raise RuntimeError(f"预览中第 {index + 1} 张正文图片无法加载") |
| 184 | if self.cover_url: |
| 185 | # 实测 index_first-pic 是预览直属封面,独立于正文 div,核对本次裁剪结果。 |
| 186 | cover_image = preview.locator('div[class*="index_content-text_"] > img[class*="index_first-pic_"]') |
| 187 | await expect(cover_image).to_have_js_property("src", self.cover_url) |
| 188 | await expect(cover_image).to_have_js_property("complete", True) |
| 189 | if await cover_image.evaluate("e => e.naturalWidth") <= 0: |
| 190 | raise RuntimeError("预览中的封面无法加载") |
| 191 | if (await read_xueqiu_identity(page))["uid"] != self.identity["uid"]: |
| 192 | raise RuntimeError("雪球填写期间账号发生变化,已中止") |
| 193 | |
| 194 | async def main(self) -> dict: |
| 195 | """准备模式保留草稿和预览;提交模式只点击一次,结果未知时禁止自动重发。""" |
| 196 | self.validate_upload_args() |
| 197 | results_dir = self.account_file.parent / "xueqiu_results" |
| 198 | results_dir.mkdir(exist_ok=True) |
| 199 | result_file = results_dir / f"{datetime.now():%Y%m%d-%H%M%S}-{uuid4().hex[:8]}.json" |
| 200 | result = {"success": False, "status": "preparing", "title": self.title, |
| 201 | "content_file": str(self.content_file), |
| 202 | "identity": self.identity, "visibility": self.visibility, "declaration": self.declaration, |
| 203 | "result_file": str(result_file), "remote_draft_possible": False} |
| 204 | async with async_playwright() as playwright: |
| 205 | browser = await playwright.chromium.launch( |
| 206 | executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=self.headless, |
| 207 | ) |
| 208 | page = None |
| 209 | try: |
| 210 | context = await browser.new_context(storage_state=str(self.account_file)) |
| 211 | page = await context.new_page() |
| 212 | response = await page.goto(XUEQIU_ARTICLE_URL, wait_until="domcontentloaded", timeout=45000) |
| 213 | if response is not None and response.status >= 400: |
| 214 | raise RuntimeError(f"雪球编辑器访问失败,HTTP {response.status}") |
| 215 | if (await read_xueqiu_identity(page))["uid"] != self.identity["uid"]: |
| 216 | raise RuntimeError("雪球主体与绑定账号不一致") |
| 217 | result["remote_draft_possible"] = True |
| 218 | await self.fill_article_form(page) |
| 219 | result.update(images=self.uploaded_images, cover=self.cover_url, |
| 220 | source_format=self.document.source_format, normalizations=self.document.normalizations, |
| 221 | manifest=self.document.manifest) |
| 222 | await page.screenshot(path=str(result_file.with_suffix(".png")), full_page=True) |
| 223 | result["screenshot"] = str(result_file.with_suffix(".png")) |
| 224 | if self.prepare_only: |
| 225 | result.update(success=True, status="prepared", url=page.url) |
| 226 | return result |
| 227 | # index_preview_ 是预览遮罩,直接子级 index_close_ 是实测关闭控件;不删除遮罩或强制点击。 |
| 228 | await page.locator('div[class*="index_preview_"] > div[class*="index_close_"]').click() |
| 229 | # 关闭后组件仍保留在 DOM,由父层隐藏;不能要求节点被删除。 |
| 230 | await expect(page.locator('div[class*="index_preview-content_"]')).to_be_hidden() |
| 231 | publish = page.get_by_role("button", name="发布", exact=True) |
| 232 | # 页面用 class 表达禁用态,不能仅依赖 HTML disabled;保留语义前缀排除哈希变化。 |
| 233 | await expect(publish).not_to_have_class(re.compile(r".*publish_disabled_.*"), timeout=30000) |
| 234 | result.update(status="submission_unknown", editor_url=page.url) |
| 235 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 236 | # 实测最终发表 POST /xq/statuses/update.json 返回作品 ID、user_id、title、text、is_private。 |
| 237 | # 页面随后回首页,因此不能用“跳转作者详情”这一错误假设判断成功。 |
| 238 | async with page.expect_response(lambda response: response.request.method == "POST" |
| 239 | and response.url == "https://mp.xueqiu.com/xq/statuses/update.json", |
| 240 | timeout=60000) as submitted: |
| 241 | await publish.click() |
| 242 | response = await submitted.value |
| 243 | payload = await response.json() |
| 244 | content_id = payload.get("id") |
| 245 | if not response.ok or not isinstance(content_id, int) or isinstance(content_id, bool) or content_id <= 0: |
| 246 | raise RuntimeError(f"雪球未确认受理: HTTP {response.status},{payload.get('error_description', payload.get('error_code', '缺少作品 ID'))}") |
| 247 | # 先持久化已返回的 ID,即使后续内容核对异常也只能查询原作品,禁止重发。 |
| 248 | result["content_id"] = str(content_id) |
| 249 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 250 | if str(payload.get("user_id")) != self.identity["uid"] or payload.get("title") != self.title: |
| 251 | raise RuntimeError("雪球受理作品的主体或标题不符,请核查原作品") |
| 252 | if payload.get("is_private") is not (self.visibility == "私人"): |
| 253 | raise RuntimeError("雪球受理作品的分享范围不符,请核查原作品") |
| 254 | # 用平台返回的已发表正文创建独立页面核对,不改写编辑器模型,也不追加真实发表动作。 |
| 255 | check_page = await context.new_page() |
| 256 | await check_page.set_content(payload.get("text") or "") |
| 257 | await check_xueqiu_article_content(check_page.locator("body"), self.document, self.uploaded_images) |
| 258 | result.update(success=True, status="published", |
| 259 | url=f"https://xueqiu.com/{self.identity['uid']}/{content_id}") |
| 260 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 261 | # 发表响应已确认受理;再查已发布原 ID,核验不能误触发第二次提交。 |
| 262 | record = await query_xueqiu_article(page, self.identity, content_id, self.title, self.visibility) |
| 263 | await check_page.set_content(record.get("text") or "") |
| 264 | await check_xueqiu_article_content(check_page.locator("body"), self.document, self.uploaded_images) |
| 265 | await check_page.close() |
| 266 | result["management_verified"] = True |
| 267 | await page.screenshot(path=str(result_file.with_suffix(".published.png")), full_page=True) |
| 268 | result["published_screenshot"] = str(result_file.with_suffix(".published.png")) |
| 269 | await context.storage_state(path=str(self.account_file)) |
| 270 | return result |
| 271 | except Exception as exc: |
| 272 | result["error"] = str(exc) |
| 273 | if result["status"] == "preparing": |
| 274 | result["status"] = "failed" |
| 275 | if self.debug and page is not None: |
| 276 | await page.screenshot(path=str(result_file.with_suffix(".error.png")), full_page=True) |
| 277 | raise |
| 278 | finally: |
| 279 | result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") |
| 280 | print(f"雪球操作结果: {result_file}", flush=True) |
| 281 | await browser.close() |
| 282 |