返回 Social Auto Upload
session.py
1 """微信公众号登录会话、账号绑定与动态 token 读取。
2
3 微信公众号后台的 token 属于会话级参数,每次登录都不同;发布前必须从当前会话
4 的后台首页 URL 重新读取,不能复用登录时保存的旧值。账号绑定只校验昵称,
5 避免把会变化的 token 当作账号身份。
6 """
7 from __future__ import annotations
8
9 import json
10 import re
11 from pathlib import Path
12 from urllib.parse import parse_qs, urlsplit
13
14 from patchright.async_api import Page, async_playwright, expect
15
16 from conf import LOCAL_CHROME_PATH
17 try:
18 from conf import BROWSER_LAUNCH_ARGS
19 except ImportError: # 兼容尚未配置该可选项的旧 conf.py
20 BROWSER_LAUNCH_ARGS = []
21 from uploader.wechat_uploader.constants import (
22 WECHAT_HOME_PATH, WECHAT_HOME_URL, WECHAT_LOGIN_HINTS,
23 )
24
25
26 def browser_launch_kwargs(headless: bool) -> dict:
27 """统一的浏览器启动参数;可选项来自 conf,默认不改变平台行为。"""
28 kwargs = {
29 "executable_path": LOCAL_CHROME_PATH or None,
30 "channel": "chrome",
31 "headless": headless,
32 }
33 if BROWSER_LAUNCH_ARGS:
34 kwargs["args"] = list(BROWSER_LAUNCH_ARGS)
35 return kwargs
36
37
38 # 后台首页右上角账号昵称;多个候选避免小程序/多账号后台的容器差异。
39 NICKNAME_SELECTORS = (
40 ".weui-desktop-account__nickname",
41 ".account_nickname",
42 "#account_nickname",
43 ".weui-desktop-dropdown__button .weui-desktop-account__nickname",
44 )
45
46
47 def wechat_is_login_url(url: str) -> bool:
48 """后台首页之外的登录/扫码路径均视为未登录。"""
49 target = urlsplit(url)
50 path = target.path.lower()
51 return any(hint in path for hint in WECHAT_LOGIN_HINTS) or path in {"/", ""}
52
53
54 def wechat_token_from_url(url: str) -> str | None:
55 """从当前后台 URL 读取会话 token;缺失或格式异常返回 None。"""
56 token = parse_qs(urlsplit(url).query).get("token", [""])[0]
57 return token if re.fullmatch(r"\d{5,15}", token or "") else None
58
59
60 async def read_wechat_identity(page: Page) -> dict:
61 """读取后台当前账号昵称,作为本地会话绑定信息。"""
62 for selector in NICKNAME_SELECTORS:
63 locator = page.locator(selector)
64 if await locator.count() < 1:
65 continue
66 try:
67 name = (await locator.first.inner_text(timeout=3000)).strip()
68 except Exception:
69 continue
70 if name:
71 return {"nickname": name}
72 # 部分后台把昵称放在 title 里,例如「公众号后台 - 昵称」。
73 title = (await page.title()).strip()
74 match = re.search(r"后台\s*[--—]\s*(.+)$", title)
75 if match and match.group(1).strip():
76 return {"nickname": match.group(1).strip()}
77 raise RuntimeError("微信公众号后台没有可读取的账号昵称,无法绑定当前会话")
78
79
80 def load_wechat_identity(account_file: str | Path) -> dict:
81 """读取登录时绑定的账号昵称。"""
82 path = Path(account_file).with_suffix(".identity.json")
83 identity = json.loads(path.read_text(encoding="utf-8"))
84 if not identity.get("nickname"):
85 raise ValueError(f"微信公众号账号绑定不完整,请重新登录: {path}")
86 return identity
87
88
89 async def login_wechat_account(account_file: str | Path, timeout: int = 600) -> dict:
90 """在可见 Chrome 扫码登录,核对账号昵称后保存本地 storage state。"""
91 if timeout <= 0:
92 raise ValueError("登录期限必须大于 0 秒")
93 account_file = Path(account_file).resolve()
94 async with async_playwright() as playwright:
95 browser = await playwright.chromium.launch(**browser_launch_kwargs(False))
96 try:
97 context = await browser.new_context(timezone_id="Asia/Shanghai")
98 page = await context.new_page()
99 await page.goto(WECHAT_HOME_URL, wait_until="domcontentloaded", timeout=45000)
100 print("请在打开的 Chrome 中用管理员微信扫码登录公众号后台;账号密码与二维码都在网页上。", flush=True)
101 # 登录完成后后台会带 token 跳到 /cgi-bin/home;只等昵称元素不足以证明会话可用。
102 await expect(page).to_have_url(
103 re.compile(rf"https://mp\.weixin\.qq\.com{re.escape(WECHAT_HOME_PATH)}.*token=\d+"),
104 timeout=timeout * 1000,
105 )
106 token = wechat_token_from_url(page.url)
107 if token is None:
108 raise RuntimeError("微信公众号后台 URL 缺少有效 token,请重新登录")
109 identity = await read_wechat_identity(page)
110 binding = account_file.with_suffix(".identity.json")
111 if binding.exists() and load_wechat_identity(account_file)["nickname"] != identity["nickname"]:
112 raise RuntimeError("当前公众号账号与已绑定账号不同,请使用新的 --account")
113 account_file.parent.mkdir(parents=True, exist_ok=True)
114 await context.storage_state(path=str(account_file))
115 binding.write_text(json.dumps(identity, ensure_ascii=False, indent=2), encoding="utf-8")
116 return {"success": True, "account_file": str(account_file),
117 "identity": identity, "token_obtained": True}
118 finally:
119 await browser.close()
120
121
122 async def check_wechat_account(account_file: str | Path, headless: bool = True) -> bool:
123 """仅明确回到登录页时返回失效;网络错误或昵称不一致直接报告。"""
124 account_file = Path(account_file)
125 if not account_file.is_file():
126 return False
127 expected = load_wechat_identity(account_file)
128 async with async_playwright() as playwright:
129 browser = await playwright.chromium.launch(**browser_launch_kwargs(headless))
130 try:
131 context = await browser.new_context(storage_state=str(account_file), timezone_id="Asia/Shanghai")
132 page = await context.new_page()
133 response = await page.goto(WECHAT_HOME_URL, wait_until="domcontentloaded", timeout=45000)
134 if response is not None and response.status >= 400:
135 raise RuntimeError(f"微信公众号后台访问失败,HTTP {response.status}")
136 await page.wait_for_load_state("domcontentloaded")
137 if wechat_is_login_url(page.url) or wechat_token_from_url(page.url) is None:
138 return False
139 actual = await read_wechat_identity(page)
140 if actual["nickname"] != expected["nickname"]:
141 raise RuntimeError("微信公众号当前账号与本地绑定不一致")
142 return True
143 finally:
144 await browser.close()
145
146
147 async def read_wechat_token(page: Page) -> str:
148 """打开后台首页并返回当前会话 token;失效则明确报错。"""
149 response = await page.goto(WECHAT_HOME_URL, wait_until="domcontentloaded", timeout=45000)
150 if response is not None and response.status >= 400:
151 raise RuntimeError(f"微信公众号后台访问失败,HTTP {response.status}")
152 if wechat_is_login_url(page.url):
153 raise RuntimeError("微信公众号登录态已失效,请重新执行 sau wechat login")
154 token = wechat_token_from_url(page.url)
155 if token is None:
156 raise RuntimeError("微信公众号后台 URL 缺少有效 token,请重新登录")
157 return token
158
158 lines PYTHON