返回 Social Auto Upload
session.py
根目录 / uploader / dayu_uploader / session.py
1 """大鱼号登录状态和发布主体核验,不把网络超时当作登录失效。"""
2 from __future__ import annotations
3
4 import json
5 import re
6 from pathlib import Path
7
8 from patchright.async_api import Page, async_playwright, expect
9
10 from conf import LOCAL_CHROME_PATH
11
12 DAYU_HOME_URL = "https://mp.dayu.com/dashboard/index"
13 DAYU_VIDEO_URL = "https://mp.dayu.com/dashboard/video/write"
14
15
16 async def read_dayu_identity(page: Page) -> dict:
17 """从后台页头及服务端注入的 wmid 读取当前主体,拒绝缺失或歧义。"""
18 # 页头账号区表达当前发布主体,限定 header-info 排除正文作者和作品列表里的同名文字。
19 name = page.locator(".header-info .name")
20 await expect(name).to_have_count(1)
21 await expect(name).to_be_visible()
22 scripts = "\n".join(await page.locator("script:not([src])").all_text_contents())
23 ids = set(re.findall(r'''["']?wmid["']?\s*:\s*["']([a-f0-9]{32})["']''', scripts))
24 if len(ids) != 1:
25 raise RuntimeError("无法唯一识别大鱼号主体 wmid;请检查登录状态或页面结构")
26 account_name = (await name.inner_text()).strip()
27 if not account_name:
28 raise RuntimeError("大鱼号页头账号名称为空")
29 return {"wmid": ids.pop(), "name": account_name}
30
31
32 def load_dayu_identity(account_file: str | Path) -> dict:
33 """读取登录时保存的主体绑定,不能用本地账号别名代替平台身份。"""
34 identity_file = Path(account_file).with_suffix(".identity.json")
35 identity = json.loads(identity_file.read_text(encoding="utf-8"))
36 if not re.fullmatch(r"[a-f0-9]{32}", identity.get("wmid", "")) or not identity.get("name"):
37 raise ValueError(f"大鱼号主体绑定不完整,请重新登录: {identity_file}")
38 return identity
39
40
41 async def login_dayu_account(account_file: str | Path, expected_name: str | None = None,
42 timeout: int = 600) -> dict:
43 """用户在可见 Chrome 中登录,核验主体后保存状态;验证码由用户完成。"""
44 account_file = Path(account_file).resolve()
45 async with async_playwright() as playwright:
46 browser = await playwright.chromium.launch(
47 executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=False,
48 )
49 try:
50 context = await browser.new_context()
51 page = await context.new_page()
52 await page.goto("https://mp.dayu.com/", wait_until="domcontentloaded", timeout=45000)
53 print("请在 Chrome 中完成大鱼号登录;账号密码及验证码直接在网页中输入。", flush=True)
54 await page.wait_for_url("https://mp.dayu.com/dashboard/**", timeout=timeout * 1000)
55 identity = await read_dayu_identity(page)
56 if expected_name is not None and identity["name"] != expected_name:
57 raise RuntimeError(f"登录主体不匹配,期望 {expected_name},实际 {identity['name']}")
58 identity_file = account_file.with_suffix(".identity.json")
59 if identity_file.exists() and load_dayu_identity(account_file)["wmid"] != identity["wmid"]:
60 raise RuntimeError("当前大鱼号与已绑定主体不同,拒绝覆盖原账号;请使用新的 --account")
61 account_file.parent.mkdir(parents=True, exist_ok=True)
62 await context.storage_state(path=str(account_file))
63 identity_file.write_text(json.dumps(identity, ensure_ascii=False, indent=2), encoding="utf-8")
64 return {"success": True, "account_file": str(account_file), "identity": identity}
65 finally:
66 await browser.close()
67
68
69 async def check_dayu_account(account_file: str | Path) -> bool:
70 """恢复登录状态并比较 wmid;仅明确回到登录 iframe 时返回失效。"""
71 account_file = Path(account_file)
72 if not account_file.is_file():
73 return False
74 expected = load_dayu_identity(account_file)
75 async with async_playwright() as playwright:
76 browser = await playwright.chromium.launch(
77 executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=True,
78 )
79 try:
80 context = await browser.new_context(storage_state=str(account_file))
81 page = await context.new_page()
82 await page.goto(DAYU_HOME_URL, wait_until="domcontentloaded", timeout=45000)
83 # 登录 iframe 的 CAS 域名和路径标识认证页;不能用普通 iframe 的存在推断登录失效。
84 if await page.locator('iframe[src*="uop.dayu.com/cas/"]').count():
85 return False
86 actual = await read_dayu_identity(page)
87 if actual["wmid"] != expected["wmid"]:
88 raise RuntimeError("大鱼号主体与账号文件绑定不一致")
89 return True
90 finally:
91 await browser.close()
92
92 lines PYTHON