283 lines
11 KiB
Python
283 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""微盟(Weimob)登录模块(xq0047 插件内自包含)。
|
||
|
||
自 workflows/XQ0001-0100/XQ0047 微盟数据导出/wm_login.py 迁移,插件化改造点:
|
||
- 账号密码由插件界面配置经 fields 注入(不再读共享 .env);
|
||
- print → config.log(转发 ctx.log);
|
||
- 浏览器使用独立固定用户目录(%LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0047)。
|
||
|
||
登录说明:
|
||
- 微盟登录页默认打开是「验证码登录」,脚本自动切换到「密码登录」tab;
|
||
- 点击登录后若弹出腾讯验证码(滑块/点选),自动化无法绕过:脚本暂停并提示人工在浏览器窗口
|
||
手动完成,完成后自动继续并保存登录态;已有有效登录态则直接复用,不重新登录;
|
||
- 登录态与影刀版共用:%LOCALAPPDATA%\\37duAutomation\\.sessions\\weimob_cookies.json
|
||
(Cookies)与 weimob_tokens.json(localStorage 票据)。
|
||
"""
|
||
import json
|
||
import os
|
||
import time
|
||
|
||
import requests
|
||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||
|
||
from .. import config
|
||
|
||
|
||
# ================== Cookies / 票据持久化 ==================
|
||
def _ensure_dir(path):
|
||
if path:
|
||
os.makedirs(path, exist_ok=True)
|
||
|
||
|
||
def save_session(page):
|
||
"""登录成功后保存 Cookies 与 localStorage 票据。"""
|
||
cookies = page.cookies(all_domains=True)
|
||
_ensure_dir(config.SESSIONS_DIR)
|
||
if cookies:
|
||
with open(config.COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||
config.log(f"已保存 {len(cookies)} 个 Cookies 到 {config.COOKIE_FILE}")
|
||
try:
|
||
raw = page.run_js('''
|
||
const data = {};
|
||
for (let i = 0; i < localStorage.length; i++) {
|
||
const k = localStorage.key(i);
|
||
const v = localStorage.getItem(k);
|
||
if (v && v.length < 100000) data[k] = v;
|
||
}
|
||
return JSON.stringify(data);
|
||
''')
|
||
ls = json.loads(raw) if raw else {}
|
||
if ls:
|
||
with open(config.TOKEN_FILE, 'w', encoding='utf-8') as f:
|
||
json.dump({"localStorage": ls, "saved_at": time.strftime("%Y-%m-%d %H:%M:%S")},
|
||
f, ensure_ascii=False, indent=2)
|
||
config.log(f"已保存 localStorage 票据 {len(ls)} 项到 {config.TOKEN_FILE}")
|
||
except Exception as e:
|
||
config.log(f"保存 localStorage 票据失败(不影响 Cookies):{e}", "WARN")
|
||
|
||
|
||
def load_cookies():
|
||
if not os.path.exists(config.COOKIE_FILE):
|
||
return None
|
||
try:
|
||
with open(config.COOKIE_FILE, encoding='utf-8') as f:
|
||
cookies = json.load(f)
|
||
except Exception as e:
|
||
config.log(f"读取 Cookies 文件失败:{e}", "WARN")
|
||
return None
|
||
return cookies or None
|
||
|
||
|
||
# ================== 会话构建与校验(无需打开浏览器) ==================
|
||
def _build_validate_body():
|
||
"""构造 download/list 校验请求体(仅商家标识可变)。"""
|
||
bos_id = config.BOS_ID
|
||
return {
|
||
"bosId": bos_id,
|
||
"pageSize": 1,
|
||
"basicInfo": {
|
||
"merchantId": config.MERCHANT_ID,
|
||
"bosId": int(bos_id),
|
||
"vid": config.VID,
|
||
"vidType": 2,
|
||
"vidTypes": [2],
|
||
"productId": config.PRODUCT_ID,
|
||
"productVersionId": config.PRODUCT_VERSION_ID,
|
||
"productInstanceId": config.PRODUCT_INSTANCE_ID,
|
||
"tcode": config.TCODE,
|
||
},
|
||
"i18n": {"language": "zh-CN", "timezone": 8},
|
||
"extendInfo": {"refer": config.REFER_EXTEND, "source": 80},
|
||
}
|
||
|
||
|
||
def build_session():
|
||
"""用保存的 cookies 构建 requests.Session(仅注入微盟相关域)。
|
||
|
||
微盟 api3 接口除 cookie 外,还必须携带如下请求头才能通过鉴权(否则 errcode=1041 fail auth):
|
||
Authorization: Bearer <saasAuthData cookie 值>
|
||
Apiclient: saas-pc
|
||
weimob-bosId: <bosId>
|
||
"""
|
||
cookies = load_cookies()
|
||
if not cookies:
|
||
return None
|
||
token = next((c["value"] for c in cookies
|
||
if c.get("name") == "saasAuthData" and c.get("value")), "")
|
||
session = requests.Session()
|
||
session.headers.update({
|
||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||
"Content-Type": "application/json",
|
||
"Accept": "application/json, text/plain, */*",
|
||
"Origin": "https://master.weimob.com",
|
||
"Referer": "https://master.weimob.com/",
|
||
"Authorization": f"Bearer {token}",
|
||
"Apiclient": "saas-pc",
|
||
"weimob-bosId": config.BOS_ID,
|
||
})
|
||
for c in cookies:
|
||
domain = c.get("domain") or ""
|
||
if any(k in domain for k in ("weimob.com", "weimobwmc.com")):
|
||
session.cookies.set(c["name"], c["value"], domain=domain, path=c.get("path", "/"))
|
||
return session
|
||
|
||
|
||
def is_session_valid():
|
||
"""API 轻量校验微盟登录态:download/list 返回 {"errcode":"0"} 视为有效。"""
|
||
session = build_session()
|
||
if session is None:
|
||
return False
|
||
try:
|
||
resp = session.post(config.DOWNLOAD_LIST_URL, json=_build_validate_body(), timeout=15)
|
||
except Exception as e:
|
||
config.log(f"API 校验微盟登录态异常:{e}")
|
||
return False
|
||
if resp.status_code != 200:
|
||
config.log(f"API 校验微盟登录态状态码异常:{resp.status_code}")
|
||
return False
|
||
try:
|
||
data = resp.json()
|
||
if data.get("errcode") == "0":
|
||
return True
|
||
config.log(f"API 校验返回非成功码:{str(data)[:200]}(若为账号配置问题请检查 bosId)", "WARN")
|
||
return False
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
# ================== 登录主流程 ==================
|
||
def _wait_login(page):
|
||
"""登录等待:处理协议弹窗 + 提示人工完成腾讯验证码,直到登录成功或超时。"""
|
||
deadline = time.time() + config.LOGIN_WAIT
|
||
captcha_hinted = False
|
||
while time.time() < deadline:
|
||
if config.SUCCESS_KEYWORD in page.url:
|
||
return True
|
||
# 协议确认弹窗(首次登录出现「同意」按钮),自动点同意
|
||
try:
|
||
agree = page.ele('xpath://button[contains(.,"意")]', timeout=1)
|
||
if agree:
|
||
config.log("检测到协议确认弹窗,点击「同意」")
|
||
agree.click()
|
||
time.sleep(1)
|
||
continue
|
||
except Exception:
|
||
pass
|
||
# 腾讯验证码提示(跨域 iframe,脚本无法自动操作,交给人工)
|
||
if not captcha_hinted:
|
||
try:
|
||
cap = page.ele('css:iframe[src*="captcha"],iframe[src*="gtimg"]', timeout=1)
|
||
if cap:
|
||
config.log("检测到腾讯验证码,请在浏览器窗口手动完成验证……完成前脚本会持续等待")
|
||
captcha_hinted = True
|
||
except Exception:
|
||
pass
|
||
time.sleep(2)
|
||
return False
|
||
|
||
|
||
def _do_login(username, password):
|
||
"""打开浏览器完成微盟登录(人工兜底验证码),成功保存登录态。"""
|
||
co = ChromiumOptions()
|
||
if config.HEADLESS:
|
||
co.headless()
|
||
co.set_argument('--start-maximized')
|
||
co.set_pref('credentials_enable_service', False)
|
||
co.set_pref('profile.password_manager_enabled', False)
|
||
# 独立固定用户目录(%LOCALAPPDATA% 下):登录态跨次保留,不占用用户日常 Chrome 配置
|
||
co.set_user_data_path(config.get_browser_profile_dir())
|
||
page = ChromiumPage(co)
|
||
try:
|
||
page.get(config.LOGIN_URL)
|
||
time.sleep(2)
|
||
|
||
if config.SUCCESS_KEYWORD in page.url:
|
||
config.log("已是登录状态,直接保存登录态")
|
||
save_session(page)
|
||
return True
|
||
|
||
# 默认打开是「验证码登录」,切换到「密码登录」tab
|
||
if not page.ele('css:input[placeholder="请输入密码"]', timeout=5):
|
||
tab = page.ele('xpath://span[contains(@class,"tabItem") and text()="密码登录"]', timeout=5)
|
||
if tab:
|
||
tab.click()
|
||
time.sleep(1)
|
||
else:
|
||
config.log("找不到「密码登录」切换入口", "ERROR")
|
||
return False
|
||
|
||
account = page.ele('css:input[placeholder="请输入手机号码"]', timeout=config.TIMEOUT)
|
||
if not account:
|
||
config.log("找不到手机号输入框", "ERROR")
|
||
return False
|
||
account.clear()
|
||
account.input(username)
|
||
time.sleep(0.5)
|
||
|
||
pwd = page.ele('css:input[placeholder="请输入密码"]', timeout=config.TIMEOUT)
|
||
if not pwd:
|
||
config.log("找不到密码输入框", "ERROR")
|
||
return False
|
||
pwd.clear()
|
||
pwd.input(password)
|
||
time.sleep(0.5)
|
||
|
||
# 勾选「登录即表示同意」协议复选框(未勾选时点击一次)
|
||
try:
|
||
checkbox = page.ele('css:input[type="checkbox"].ant-checkbox-input', timeout=3)
|
||
if checkbox:
|
||
if getattr(checkbox, 'checked', False):
|
||
config.log("协议复选框已勾选")
|
||
else:
|
||
checkbox.click()
|
||
time.sleep(0.5)
|
||
config.log("已勾选「登录即表示同意」协议复选框")
|
||
except Exception as e:
|
||
config.log(f"勾选协议复选框异常(继续尝试登录):{e}", "WARN")
|
||
|
||
# 登录按钮文本在子 span 内,需用 contains(.,...) 才能匹配
|
||
login_btn = page.ele('xpath://button[contains(.,"登")]', timeout=5)
|
||
if not login_btn:
|
||
config.log("找不到登录按钮", "ERROR")
|
||
return False
|
||
login_btn.click()
|
||
|
||
if _wait_login(page):
|
||
config.log("登录成功")
|
||
save_session(page)
|
||
return True
|
||
config.log(f"登录失败(等待超时 {config.LOGIN_WAIT}s 未进入后台)", "ERROR")
|
||
return False
|
||
finally:
|
||
try:
|
||
page.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def ensure_login(username, password, force=False):
|
||
"""确保存在有效的微盟登录态并缓存 Cookies/票据。
|
||
|
||
返回 dict:{success, cookie_path, message, relogin}
|
||
"""
|
||
username = (username or '').strip()
|
||
password = (password or '').strip()
|
||
if not (username and password):
|
||
return {"success": False, "cookie_path": config.COOKIE_FILE,
|
||
"message": "微盟登录账号/密码缺失:请在插件界面填写并保存配置后重试", "relogin": False}
|
||
|
||
# 优先复用已保存的登录态(通过 API 校验有效性,无需打开浏览器)
|
||
if not force and is_session_valid():
|
||
config.log("已通过缓存的 Cookies 复用微盟登录态")
|
||
return {"success": True, "cookie_path": config.COOKIE_FILE,
|
||
"message": "复用缓存登录态", "relogin": False}
|
||
|
||
config.log("登录态失效或不存在,打开浏览器登录(腾讯验证码需人工完成)…")
|
||
ok = _do_login(username, password)
|
||
if ok:
|
||
return {"success": True, "cookie_path": config.COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||
return {"success": False, "cookie_path": config.COOKIE_FILE,
|
||
"message": "登录失败(可能验证码未完成或账号密码有误)", "relogin": True}
|