dsh-qqbot-muu 0.1.15 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +168 -85
- package/client/qqbot-settings.js +13401 -12024
- package/config/modules.json +212 -0
- package/dist/channel-tools.js +21 -10
- package/dist/config.d.ts +14 -0
- package/dist/config.js +573 -449
- package/dist/features/contextless-store.js +247 -247
- package/dist/features/contextless-trim.js +455 -34
- package/dist/features/four-source.js +338 -336
- package/dist/features/group-join-request.js +289 -287
- package/dist/features/local-models.js +1494 -0
- package/dist/features/rotate-summarizer.js +438 -0
- package/dist/features/scenario-detect.js +321 -0
- package/dist/features/scheduler.js +8 -1
- package/dist/features/session-rotate.js +499 -0
- package/dist/features/session-title.js +199 -0
- package/dist/features/style-layer.js +501 -0
- package/dist/features/thinking-log.js +71 -69
- package/dist/gateway/bootstrap.js +1704 -1388
- package/dist/gateway/data-root.js +77 -3
- package/dist/gateway/middleware-setup.js +6 -3
- package/dist/index.js +4 -2
- package/dist/model/settings-reader.js +193 -102
- package/dist/session/session-manager.js +1730 -1587
- package/dist/shared/paths.js +128 -0
- package/dist/shared/settings-io.js +79 -0
- package/dist/transport/inbound.js +20 -1
- package/dist/transport/outbound.js +56 -4
- package/docs/RELEASE_CHECKLIST.md +24 -2
- package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
- package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
- package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
- package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
- package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
- package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
- package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
- package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
- package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
- package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
- package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
- package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
- package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
- package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
- package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
- package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
- package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
- package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
- package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
- package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
- package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
- package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
- package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
- package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
- package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
- package/package.json +119 -111
- package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
- package/scripts/_add_maintenance_cfg.py +20 -0
- package/scripts/_bench_keeplease.sh +10 -0
- package/scripts/_dbg_purge.py +15 -0
- package/scripts/_elev.sh +6 -0
- package/scripts/_fix_all_admin.cmd +16 -0
- package/scripts/_livecheck-image.mjs +33 -0
- package/scripts/_livecheck-llm.mjs +34 -0
- package/scripts/_livecheck-tts.mjs +37 -0
- package/scripts/_patch_curve.py +88 -0
- package/scripts/_patch_fan_thermal.py +24 -0
- package/scripts/_tag_tmp.py +13 -0
- package/scripts/adb-broker-client.mjs +87 -0
- package/scripts/adb-broker.mjs +205 -0
- package/scripts/ai-mode.cmd +6 -0
- package/scripts/ai-mode.py +387 -0
- package/scripts/ai-toolkit.py +607 -0
- package/scripts/apply-fan-gpu45.py +51 -0
- package/scripts/bench-fans.py +515 -0
- package/scripts/bench-load-direct.py +63 -0
- package/scripts/boot-tasks-hidden.vbs +20 -0
- package/scripts/boot-tasks.cmd +277 -0
- package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
- package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
- package/scripts/chat-archive/build-sft-v4.py +566 -0
- package/scripts/chat-archive/build-sft.py +390 -0
- package/scripts/chat-archive/eval-sft.py +155 -0
- package/scripts/chat-archive/extract-memory.py +143 -0
- package/scripts/chat-archive/inventory.py +182 -0
- package/scripts/chat-archive/merge-sft.py +114 -0
- package/scripts/chat-archive/qce-pull.py +217 -0
- package/scripts/chat-archive/qqheader.py +110 -0
- package/scripts/chat-archive/qqkey2.py +113 -0
- package/scripts/chat-archive/qqprobe.py +153 -0
- package/scripts/chat-archive/screen-collect.py +163 -0
- package/scripts/chat-archive/sqlcipher_probe.py +444 -0
- package/scripts/comfy_gen.py +209 -0
- package/scripts/compose-video.py +168 -0
- package/scripts/dl_models.py +45 -0
- package/scripts/draw-now.cmd +18 -0
- package/scripts/dsh-instance-guard.mjs +20 -2
- package/scripts/elev-extra.cmd +25 -0
- package/scripts/episode.py +529 -0
- package/scripts/fan-curve.py +218 -0
- package/scripts/fan-guard.cmd +8 -0
- package/scripts/fan-mode.py +380 -0
- package/scripts/fan_manual_safe.py +33 -0
- package/scripts/fan_restore_manual.py +46 -0
- package/scripts/fc_curves.py +359 -0
- package/scripts/fix-fan-and-timers.cmd +39 -0
- package/scripts/fix_admin_all.py +94 -0
- package/scripts/flows.mjs +224 -0
- package/scripts/gateway.cmd +126 -0
- package/scripts/gen-image.py +420 -0
- package/scripts/gen-video.py +186 -0
- package/scripts/git-askpass.cmd +2 -2
- package/scripts/gpu-mode.py +195 -0
- package/scripts/hw-profile.py +175 -0
- package/scripts/install-schedule.cmd +37 -0
- package/scripts/install-watch.cmd +29 -0
- package/scripts/matte-cutout.py +106 -0
- package/scripts/media-enhance.py +402 -0
- package/scripts/memory-audit.py +581 -0
- package/scripts/migrate-scope.mjs +140 -139
- package/scripts/model-registry.py +519 -0
- package/scripts/openid-audit.mjs +219 -0
- package/scripts/pull-gguf.py +127 -0
- package/scripts/purge-standby.py +151 -0
- package/scripts/qq-connect-login.py +133 -0
- package/scripts/qq-ip-sync-hidden.vbs +5 -0
- package/scripts/qq-ip-sync.py +300 -0
- package/scripts/qq-login-once.cmd +20 -0
- package/scripts/qq-login-qr.py +72 -0
- package/scripts/qq-whitelist-fix.cmd +27 -0
- package/scripts/qq-whitelist-login.cmd +26 -0
- package/scripts/qq-whitelist.cmd +12 -0
- package/scripts/qq-whitelist.py +1452 -0
- package/scripts/quality-compare.py +134 -0
- package/scripts/release-all.mjs +636 -430
- package/scripts/release-check.mjs +244 -226
- package/scripts/resume-coder.cmd +38 -0
- package/scripts/secure-room/index.html +334 -0
- package/scripts/secure-room/server.py +582 -0
- package/scripts/security-check.mjs +164 -0
- package/scripts/selftest-local-llm.mjs +20 -0
- package/scripts/selftest-local-models.mjs +754 -0
- package/scripts/selftest-rotate-style.mjs +308 -0
- package/scripts/shutdown-s5-optional.cmd +21 -0
- package/scripts/sleep-2325.cmd +75 -0
- package/scripts/start-comfyui.cmd +5 -0
- package/scripts/start-strata.cmd +17 -0
- package/scripts/start-strata.vbs +11 -0
- package/scripts/start-watch-hidden.vbs +3 -0
- package/scripts/stickers/auto-tag.mjs +161 -0
- package/scripts/storage.mjs +236 -0
- package/scripts/sync-plugin-copies.mjs +98 -23
- package/scripts/tests/test-qq-whitelist.py +192 -0
- package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
- package/scripts/train/gguf-quantize.py +92 -0
- package/scripts/train/gguf-to-hf.py +112 -0
- package/scripts/train/merge-lora.py +51 -0
- package/scripts/train/probe-mirrors.sh +12 -0
- package/scripts/train/probe-mirrors2.sh +20 -0
- package/scripts/train/setup-wsl.sh +23 -0
- package/scripts/train/setup-wsl2.sh +25 -0
- package/scripts/train/setup-wsl3.sh +22 -0
- package/scripts/train/setup-wsl4.sh +22 -0
- package/scripts/train/train-lora.py +319 -0
- package/scripts/vram-free.py +104 -0
- package/scripts/wechat-full-pull.mjs +1 -1
- package/settings-host.js +1047 -12
|
@@ -0,0 +1,1452 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
qq-whitelist.py — 自动更新 QQ 机器人(MuUAstra)的「服务器 IP 白名单」。
|
|
4
|
+
|
|
5
|
+
流程:q.qq.com 控制台 -> 机器人 -> 管理机器人 -> MuUAstra -> 开发设置
|
|
6
|
+
-> 服务器 IP 白名单:读出旧 IP -> 删掉非当前 IP -> 添加当前 IP -> 保存 -> 回读确认。
|
|
7
|
+
|
|
8
|
+
用法:
|
|
9
|
+
python qq-whitelist.py # 自动:先 headless,元素类失败再 headful 重试一次
|
|
10
|
+
python qq-whitelist.py --headless # 只跑无窗口(watcher 用)
|
|
11
|
+
python qq-whitelist.py --headful # 只跑有窗口
|
|
12
|
+
python qq-whitelist.py --login # 打开窗口让人工扫码登录一次(最多等 10 分钟)
|
|
13
|
+
python qq-whitelist.py --print-ip # 只打印当前 IPv4(不启动浏览器)
|
|
14
|
+
python qq-whitelist.py --dry-run # 只读白名单并打印计划,不点保存
|
|
15
|
+
python qq-whitelist.py --cookie-info # 只探测 profile 里的登录 cookie(不启动浏览器)
|
|
16
|
+
python qq-whitelist.py --probe # 导出页面结构 JSON,用来校准 TEXTS / 选择器
|
|
17
|
+
|
|
18
|
+
登录态(v2,2026-11-26 改):
|
|
19
|
+
logged_in 已登录(页面有「我的机器人/开发设置」等痕迹,或 profile 里有 skey/uin 等鉴权 cookie)
|
|
20
|
+
need_login 未登录,需要人工扫码一次(页面出现「QQ登录」登录卡)
|
|
21
|
+
unknown 判不清(页面没加载完 / 结构变了 / 被重定向),先跑 --probe
|
|
22
|
+
|
|
23
|
+
退出码:0 成功/已最新 10 需要人工登录 20 找不到元素 30 保存后回读失败 40 网络/页面打不开
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import argparse
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import shutil
|
|
32
|
+
import sqlite3
|
|
33
|
+
import subprocess
|
|
34
|
+
import sys
|
|
35
|
+
import tempfile
|
|
36
|
+
import time
|
|
37
|
+
import traceback
|
|
38
|
+
import urllib.request
|
|
39
|
+
from datetime import datetime
|
|
40
|
+
from pathlib import Path
|
|
41
|
+
|
|
42
|
+
# ---------------------------------------------------------------- 路径 / 常量
|
|
43
|
+
# 2026-12-01:不再写死作者本机路径 —— 默认按脚本位置推(scripts/ 的上一级就是仓库根),
|
|
44
|
+
# 需要时可临时用 QQBOT_REPO_ROOT 覆盖。
|
|
45
|
+
BASE = Path(os.environ.get("QQBOT_REPO_ROOT") or Path(__file__).resolve().parent.parent)
|
|
46
|
+
DATA_NET = BASE / "data" / "net"
|
|
47
|
+
LOG_DIR = BASE / "logs"
|
|
48
|
+
SHOT_DIR = LOG_DIR / "qq-whitelist-shots"
|
|
49
|
+
LAST_IP_FILE = DATA_NET / "last-ip.txt" # 最近一次探测到的 IP(boot-tasks 也会写)
|
|
50
|
+
APPLIED_IP_FILE = DATA_NET / "whitelist-applied.txt" # 最近一次「确认已在白名单」的 IP(只有本脚本写)
|
|
51
|
+
PROFILE_DIR = BASE / "data" / "edge-profile" # 专用配置目录,不碰日常 Edge
|
|
52
|
+
LOG_FILE = LOG_DIR / "qq-whitelist.log"
|
|
53
|
+
|
|
54
|
+
SITE = "https://q.qq.com/#/"
|
|
55
|
+
# 2026-11 改版:q.qq.com 落地页的「机器人」只是宣传页(只有一个「去创建或管理我的
|
|
56
|
+
# QQ 机器人」按钮,列表是空的),真正的后台在 /qqbot/dashboard/,机器人详情在
|
|
57
|
+
# /qqbot/dashboard/manage/<appid>,开发设置用 ?sec=dev-settings 直达。
|
|
58
|
+
MANAGER_URL = "https://q.qq.com/qqbot/dashboard/"
|
|
59
|
+
DEV_SEC = "?sec=dev-settings"
|
|
60
|
+
# 2026-12-01:q.qq.com 换了新门户(/#/apps 首页只剩宣传卡片,旧导航会点进宣传页 → no-heading)。
|
|
61
|
+
# 但登录后老后台 /qqbot/dashboard/manage/<appid> 仍然可用,直接开详情页最稳。
|
|
62
|
+
# AppID 可用环境变量覆盖(多机器人时不用改代码)。
|
|
63
|
+
# AppID 不再写死在源码里(那是本机账号信息,且换机器人就失效):
|
|
64
|
+
# ① 环境变量 QQBOT_APP_ID;② 本机未入库的 data/net/appid.txt;③ 留空并在使用时明确报错。
|
|
65
|
+
def _local_app_id() -> str:
|
|
66
|
+
try:
|
|
67
|
+
return (DATA_NET / "appid.txt").read_text(encoding="utf-8").strip()
|
|
68
|
+
except Exception:
|
|
69
|
+
return ""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
APP_ID = (os.environ.get("QQBOT_APP_ID") or _local_app_id()).strip()
|
|
73
|
+
MANAGE_URL = f"{MANAGER_URL}manage/{APP_ID}" if APP_ID else MANAGER_URL
|
|
74
|
+
BOT_NAME = "MuUAstra"
|
|
75
|
+
CAMPUS_HINT = "stu-xdwlan"
|
|
76
|
+
|
|
77
|
+
EXIT_OK = 0
|
|
78
|
+
EXIT_NEED_LOGIN = 10
|
|
79
|
+
EXIT_NO_ELEMENT = 20
|
|
80
|
+
EXIT_VERIFY_FAIL = 30
|
|
81
|
+
EXIT_NET_FAIL = 40
|
|
82
|
+
|
|
83
|
+
# ---------------------------------------------------------------- 文本候选
|
|
84
|
+
# 选择器坏了就改这里:每个 key 是一个候选文本数组,按顺序尝试(先精确、再包含)。
|
|
85
|
+
# 文档《qq机器人IP白名单自动更新.md》里写了「第 N 行加候选」的指引。
|
|
86
|
+
TEXTS = {
|
|
87
|
+
"nav_bot": ["机器人", "QQ机器人", "Bot"],
|
|
88
|
+
"manage_bot": ["管理机器人", "机器人管理", "我的机器人"],
|
|
89
|
+
"my_bot": [BOT_NAME, "MuU", "MuUAstra"],
|
|
90
|
+
"dev_settings": ["开发设置", "开发配置", "开发"],
|
|
91
|
+
"ip_whitelist": ["服务器 IP 白名单", "服务器IP白名单", "IP 白名单", "IP白名单"],
|
|
92
|
+
"add": ["添加", "新增", "添加 IP", "添加IP"],
|
|
93
|
+
"save": ["保存", "提交", "确定保存"],
|
|
94
|
+
"delete": ["删除", "移除"],
|
|
95
|
+
"dialog_confirm": ["确定", "确认", "保存", "添加"],
|
|
96
|
+
"login_markers": ["QQ登录", "邮箱登录", "扫码登录", "账号密码登录",
|
|
97
|
+
# 2026-12-01 改版:首页只剩一张二维码卡片,文案是「扫码」「二维码」这类,
|
|
98
|
+
# 以前一个都不命中 → 被判成已登录 → 后面找机器人列表 rc=20。
|
|
99
|
+
"扫码", "二维码", "请登录", "登录后", "QQ扫码", "手机QQ"],
|
|
100
|
+
"logged_markers": ["我的机器人", "管理机器人", "开发设置", "退出登录", "个人中心",
|
|
101
|
+
# 2026-11-27 实测:登录后落地页显示的是「账号信息 / 超级管理员 / 你好,<昵称>」
|
|
102
|
+
# + 左侧「首页 机器人 游戏社区服务」导航,上面那批文案一个都不出现,
|
|
103
|
+
# 导致已登录被判成 unknown。
|
|
104
|
+
"账号信息", "超级管理员", "帮助文档"],
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
# ---------------------------------------------------------------- 登录态常量
|
|
108
|
+
# 2026-11-26 复盘:原来只有 'logged' / 'login' / 'unknown' 三个字面量,日志里打印
|
|
109
|
+
# 「登录状态判断: login」看着像「已登录」,实际意思是「需要登录」——排查时误导人。
|
|
110
|
+
# 这里改名成自解释的字面量,并把判定拆成「纯逻辑函数 + 多信号」,方便单测。
|
|
111
|
+
LOGIN_LOGGED = "logged_in" # 已登录
|
|
112
|
+
LOGIN_NEED = "need_login" # 未登录,需要人工扫码一次
|
|
113
|
+
LOGIN_UNKNOWN = "unknown" # 判不清(页面没加载完 / 结构变了 / 被重定向)
|
|
114
|
+
|
|
115
|
+
# 真正代表「有登录态」的 cookie 名。
|
|
116
|
+
# 注意 qlogin_uid 在完全未登录时也会有(2026-11-26 实测),所以不能当登录依据。
|
|
117
|
+
# 2026-12-01:pt2gguin 也降级为「弱 cookie」—— 实测过期后它还在,但页面已经是二维码登录卡,
|
|
118
|
+
# 拿它当“已登录”会导致后面 rc=20(找不到机器人列表),必须重新扫码。
|
|
119
|
+
AUTH_COOKIE_NAMES = ("uin", "p_uin", "skey", "p_skey", "qm_keyst",
|
|
120
|
+
# 2026-12-01 新门户(q.qq.com/#/apps)改用 quin / qticket / b-token 鉴权,
|
|
121
|
+
# 不再写 skey/uin。缺了这三个会被误判 need_login(明明已登录)。
|
|
122
|
+
"quin", "qticket", "b-token")
|
|
123
|
+
WEAK_COOKIE_NAMES = ("pt2gguin", "qlogin_uid")
|
|
124
|
+
COOKIE_DB = PROFILE_DIR / "Default" / "Network" / "Cookies"
|
|
125
|
+
|
|
126
|
+
# 只允许这些 IPv4 前缀被当成「白名单条目」,避免把文档示例/内网地址误删
|
|
127
|
+
IGNORE_IP_PREFIXES = ("127.", "0.", "255.", "224.", "169.254.")
|
|
128
|
+
IPV4_RE = re.compile(r"\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b")
|
|
129
|
+
|
|
130
|
+
_shot_no = 0
|
|
131
|
+
_run_ts = ""
|
|
132
|
+
_cookie_cache = None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ---------------------------------------------------------------- 日志 / 截图
|
|
136
|
+
def _now() -> str:
|
|
137
|
+
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def log(step: str, msg: str, level: str = "INFO", shot: str | None = None) -> None:
|
|
141
|
+
line = f"{_now()} [{level}] [{step}] {msg}"
|
|
142
|
+
if shot:
|
|
143
|
+
line += f" | shot={shot}"
|
|
144
|
+
try:
|
|
145
|
+
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
|
146
|
+
with LOG_FILE.open("a", encoding="utf-8", newline="\n") as f:
|
|
147
|
+
f.write(line + "\n")
|
|
148
|
+
except OSError as e:
|
|
149
|
+
print(f"log write failed: {e}", file=sys.stderr)
|
|
150
|
+
try:
|
|
151
|
+
print(line)
|
|
152
|
+
except UnicodeEncodeError:
|
|
153
|
+
print(line.encode("utf-8", "replace").decode("utf-8", "replace"))
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def take_shot(page, tag: str) -> str:
|
|
157
|
+
global _shot_no
|
|
158
|
+
_shot_no += 1
|
|
159
|
+
SHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
160
|
+
name = f"{_run_ts}-{_shot_no:02d}-{tag}.png"
|
|
161
|
+
path = SHOT_DIR / name
|
|
162
|
+
try:
|
|
163
|
+
page.screenshot(path=str(path))
|
|
164
|
+
except Exception as e: # 截图失败不能影响主流程
|
|
165
|
+
log("shot", f"截图失败 {tag}: {e}", "WARN")
|
|
166
|
+
return ""
|
|
167
|
+
log("shot", f"截图 {name}", "DEBUG", shot=name)
|
|
168
|
+
return name
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# ---------------------------------------------------------------- 取 IP
|
|
172
|
+
def _decode(b: bytes) -> str:
|
|
173
|
+
# 控制台可能是 UTF-8(chcp 65001) 也可能是 GBK,先试 UTF-8 严格解码
|
|
174
|
+
for enc in ("utf-8", "gbk", "latin-1"):
|
|
175
|
+
try:
|
|
176
|
+
return b.decode(enc)
|
|
177
|
+
except UnicodeDecodeError:
|
|
178
|
+
continue
|
|
179
|
+
return b.decode("utf-8", "replace")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _run(cmd: list[str]) -> tuple[int, str]:
|
|
183
|
+
try:
|
|
184
|
+
p = subprocess.run(cmd, capture_output=True, timeout=25)
|
|
185
|
+
return p.returncode, _decode(p.stdout) + _decode(p.stderr)
|
|
186
|
+
except Exception as e:
|
|
187
|
+
return 1, f"{type(e).__name__}: {e}"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def parse_ipconfig(text: str) -> list[dict]:
|
|
191
|
+
"""把 ipconfig 文本拆成 [{name, ips:[...], default_gw:bool}]。"""
|
|
192
|
+
adapters: list[dict] = []
|
|
193
|
+
cur: dict | None = None
|
|
194
|
+
for raw in text.splitlines():
|
|
195
|
+
line = raw.rstrip()
|
|
196
|
+
if re.match(r"^\S.*(?:适配器|adapter)\s", line, re.I) and line.endswith(":"):
|
|
197
|
+
if cur:
|
|
198
|
+
adapters.append(cur)
|
|
199
|
+
cur = {"name": line.rstrip(":").strip(), "ips": [], "default_gw": False}
|
|
200
|
+
continue
|
|
201
|
+
if cur is None:
|
|
202
|
+
continue
|
|
203
|
+
m = re.search(r"IPv4\s*(?:地址|Address)[^::]*[::]\s*([0-9.]+)", line, re.I)
|
|
204
|
+
if m:
|
|
205
|
+
cur["ips"].append(m.group(1))
|
|
206
|
+
if re.search(r"默认网关|Default Gateway", line, re.I) and re.search(r"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+", line):
|
|
207
|
+
cur["default_gw"] = True
|
|
208
|
+
if cur:
|
|
209
|
+
adapters.append(cur)
|
|
210
|
+
return adapters
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _wifi_ssids() -> list[str]:
|
|
214
|
+
rc, out = _run(["netsh", "wlan", "show", "interfaces"])
|
|
215
|
+
if rc != 0:
|
|
216
|
+
return []
|
|
217
|
+
return [m.group(1).strip() for m in re.finditer(r"^\s*SSID\s*:\s*(.+)$", out, re.M)]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _default_route_aliases() -> list[str]:
|
|
221
|
+
rc, out = _run([
|
|
222
|
+
"powershell", "-NoProfile", "-Command",
|
|
223
|
+
"Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Sort-Object RouteMetric | "
|
|
224
|
+
"Select-Object -ExpandProperty InterfaceAlias",
|
|
225
|
+
])
|
|
226
|
+
if rc != 0:
|
|
227
|
+
return []
|
|
228
|
+
return [x.strip() for x in out.splitlines() if x.strip()]
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _usable(ip: str) -> bool:
|
|
232
|
+
if ip.startswith(IGNORE_IP_PREFIXES):
|
|
233
|
+
return False
|
|
234
|
+
# 100.64.0.0/10 是运营商级 NAT / Tailscale 网段,不是校园网出口地址
|
|
235
|
+
if ip.startswith("100."):
|
|
236
|
+
try:
|
|
237
|
+
if 64 <= int(ip.split(".")[1]) <= 127:
|
|
238
|
+
return False
|
|
239
|
+
except (IndexError, ValueError):
|
|
240
|
+
return False
|
|
241
|
+
return True
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# QQ 开放平台校验的是「服务器出口公网 IP」,不是局域网地址。
|
|
245
|
+
# 2026-11-27 修复:以前直接写 ipconfig 的 10.198.99.168,加进白名单等于没加(QQ 侧永远不放行)。
|
|
246
|
+
PUBLIC_IP_SOURCES = (
|
|
247
|
+
"https://ipinfo.io/ip", # 首选(用户指定)
|
|
248
|
+
"https://api.ipify.org",
|
|
249
|
+
"https://ifconfig.me/ip",
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _http_text(url: str, timeout: float = 8.0) -> str:
|
|
254
|
+
req = urllib.request.Request(url, headers={"User-Agent": "curl/8.5.0", "Accept": "text/plain"})
|
|
255
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
256
|
+
return r.read().decode("utf-8", "replace").strip()
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def get_public_ip(verbose: bool = False) -> str:
|
|
260
|
+
"""问外网自己是哪个 IP(多源回退)。全失败返回空串。"""
|
|
261
|
+
for url in PUBLIC_IP_SOURCES:
|
|
262
|
+
try:
|
|
263
|
+
text = _http_text(url)
|
|
264
|
+
except Exception as e:
|
|
265
|
+
if verbose:
|
|
266
|
+
log("ip", f"公网 IP 源失败 {url}: {type(e).__name__}", "WARN")
|
|
267
|
+
continue
|
|
268
|
+
m = IPV4_RE.search(text)
|
|
269
|
+
if m and _usable(m.group(0)):
|
|
270
|
+
if verbose:
|
|
271
|
+
log("ip", f"公网 IP <- {url}: {m.group(0)}")
|
|
272
|
+
return m.group(0)
|
|
273
|
+
if verbose:
|
|
274
|
+
log("ip", f"公网 IP 源返回异常内容 {url}: {text[:60]!r}", "WARN")
|
|
275
|
+
return ""
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def get_lan_ip(verbose: bool = False) -> str:
|
|
279
|
+
"""局域网兜底:校园网优先,其次默认路由网卡,最后任一可用 IPv4。"""
|
|
280
|
+
rc, out = _run(["ipconfig"])
|
|
281
|
+
if rc != 0:
|
|
282
|
+
raise RuntimeError(f"ipconfig 失败 rc={rc}")
|
|
283
|
+
adapters = parse_ipconfig(out)
|
|
284
|
+
ssids = _wifi_ssids()
|
|
285
|
+
routes = _default_route_aliases()
|
|
286
|
+
if verbose:
|
|
287
|
+
log("ip", f"适配器: {[(a['name'], a['ips'], a['default_gw']) for a in adapters]}")
|
|
288
|
+
log("ip", f"WiFi SSID: {ssids} | 默认路由网卡: {routes}")
|
|
289
|
+
|
|
290
|
+
# 规则 1:适配器名含 stu-xdwlan
|
|
291
|
+
for a in adapters:
|
|
292
|
+
if CAMPUS_HINT in a["name"].lower():
|
|
293
|
+
for ip in a["ips"]:
|
|
294
|
+
if _usable(ip):
|
|
295
|
+
if verbose:
|
|
296
|
+
log("ip", f"命中校园网适配器名: {a['name']} -> {ip}")
|
|
297
|
+
return ip
|
|
298
|
+
|
|
299
|
+
# 规则 2:连着校园网 SSID 时,走默认路由那张卡
|
|
300
|
+
if any(CAMPUS_HINT in s.lower() for s in ssids):
|
|
301
|
+
for alias in routes:
|
|
302
|
+
for a in adapters:
|
|
303
|
+
if a["name"].endswith(alias) or alias in a["name"]:
|
|
304
|
+
for ip in a["ips"]:
|
|
305
|
+
if _usable(ip):
|
|
306
|
+
if verbose:
|
|
307
|
+
log("ip", f"命中校园网 SSID({ssids}) + 默认路由 {alias} -> {ip}")
|
|
308
|
+
return ip
|
|
309
|
+
|
|
310
|
+
# 规则 3:默认路由网卡
|
|
311
|
+
for alias in routes:
|
|
312
|
+
for a in adapters:
|
|
313
|
+
if a["name"].endswith(alias) or alias in a["name"]:
|
|
314
|
+
for ip in a["ips"]:
|
|
315
|
+
if _usable(ip):
|
|
316
|
+
if verbose:
|
|
317
|
+
log("ip", f"退回默认路由网卡 {a['name']} -> {ip}")
|
|
318
|
+
return ip
|
|
319
|
+
|
|
320
|
+
# 规则 4:任一可用地址
|
|
321
|
+
for a in adapters:
|
|
322
|
+
for ip in a["ips"]:
|
|
323
|
+
if _usable(ip):
|
|
324
|
+
if verbose:
|
|
325
|
+
log("ip", f"退回首个可用地址 {a['name']} -> {ip}", "WARN")
|
|
326
|
+
return ip
|
|
327
|
+
|
|
328
|
+
raise RuntimeError("找不到可用的 IPv4 地址")
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def get_current_ip(verbose: bool = False) -> str:
|
|
332
|
+
"""当前「服务器出口 IP」:优先公网(ipinfo.io),拿不到才退回局域网探测。
|
|
333
|
+
|
|
334
|
+
QQ 白名单要的是公网出口 IP。局域网地址只在完全没网时兜底(会打 WARN,
|
|
335
|
+
因为这种 IP 填进 QQ 后台是无效的,脚本仍会写但日志里能看出来)。
|
|
336
|
+
"""
|
|
337
|
+
ip = get_public_ip(verbose)
|
|
338
|
+
if ip:
|
|
339
|
+
return ip
|
|
340
|
+
ip = get_lan_ip(verbose)
|
|
341
|
+
log("ip", f"公网 IP 全部来源失败,退回局域网地址 {ip}(很可能对 QQ 白名单无效)", "WARN")
|
|
342
|
+
return ip
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def read_last_ip() -> str:
|
|
346
|
+
try:
|
|
347
|
+
return LAST_IP_FILE.read_text(encoding="utf-8").strip()
|
|
348
|
+
except OSError:
|
|
349
|
+
return ""
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def write_last_ip(ip: str) -> None:
|
|
353
|
+
"""记录探测到的 IP;同时写 applied 标记(供 watcher 判断「已确认生效」)。"""
|
|
354
|
+
DATA_NET.mkdir(parents=True, exist_ok=True)
|
|
355
|
+
for path in (LAST_IP_FILE, APPLIED_IP_FILE):
|
|
356
|
+
tmp = path.with_suffix(".tmp")
|
|
357
|
+
tmp.write_text(ip + "\n", encoding="utf-8")
|
|
358
|
+
tmp.replace(path)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# ---------------------------------------------------------------- 纯逻辑(可单测)
|
|
362
|
+
def plan_update(current_ip: str, existing: list[str], prune: bool = True) -> dict:
|
|
363
|
+
"""幂等核心:当前 IP 已存在且没有历史残留 -> up-to-date。
|
|
364
|
+
|
|
365
|
+
prune=True(2026-11-27 起默认):只保留当前真实 IP,删掉其它历史 IP。
|
|
366
|
+
校园网出口 IP 会变,留着旧条目既没用又容易看错,用户要求「只保留最新真实 IP」。
|
|
367
|
+
想保留旧条目用 --keep-old。
|
|
368
|
+
"""
|
|
369
|
+
clean: list[str] = []
|
|
370
|
+
for ip in existing:
|
|
371
|
+
if ip not in clean and _usable(ip):
|
|
372
|
+
clean.append(ip)
|
|
373
|
+
others = [ip for ip in clean if ip != current_ip]
|
|
374
|
+
if current_ip in clean:
|
|
375
|
+
if prune and others:
|
|
376
|
+
# 当前 IP 已在名单里,但还留着历史 IP —— 用户要求只保留最新真实 IP
|
|
377
|
+
return {"action": "cleanup", "delete": others, "add": []}
|
|
378
|
+
return {"action": "up-to-date", "delete": [], "add": []}
|
|
379
|
+
return {
|
|
380
|
+
"action": "update",
|
|
381
|
+
"delete": others if prune else [],
|
|
382
|
+
"add": [current_ip],
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def apply_plan(existing: list[str], plan: dict) -> list[str]:
|
|
387
|
+
kept = [ip for ip in existing if ip not in plan["delete"]]
|
|
388
|
+
for ip in plan["add"]:
|
|
389
|
+
if ip not in kept:
|
|
390
|
+
kept.append(ip)
|
|
391
|
+
return kept
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
# ---------------------------------------------------------------- 页面辅助
|
|
395
|
+
def _visible(loc) -> bool:
|
|
396
|
+
try:
|
|
397
|
+
return loc.count() > 0 and loc.first.is_visible()
|
|
398
|
+
except Exception:
|
|
399
|
+
return False
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def find_text(page, texts: list[str], scope=None, timeout: int = 0):
|
|
403
|
+
"""按候选文本找可见元素:先精确匹配,再包含匹配。返回 Locator 或 None。"""
|
|
404
|
+
deadline = time.time() + timeout
|
|
405
|
+
while True:
|
|
406
|
+
root = scope or page
|
|
407
|
+
for t in texts:
|
|
408
|
+
for exact in (True, False):
|
|
409
|
+
try:
|
|
410
|
+
loc = root.get_by_text(t, exact=exact)
|
|
411
|
+
n = loc.count()
|
|
412
|
+
except Exception:
|
|
413
|
+
continue
|
|
414
|
+
for i in range(min(n, 8)):
|
|
415
|
+
cand = loc.nth(i)
|
|
416
|
+
try:
|
|
417
|
+
if cand.is_visible():
|
|
418
|
+
return cand
|
|
419
|
+
except Exception:
|
|
420
|
+
continue
|
|
421
|
+
if time.time() >= deadline:
|
|
422
|
+
return None
|
|
423
|
+
page.wait_for_timeout(500)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def click_text(page, texts: list[str], step: str, scope=None, timeout: int = 15000) -> bool:
|
|
427
|
+
loc = find_text(page, texts, scope=scope, timeout=timeout)
|
|
428
|
+
if not loc:
|
|
429
|
+
return False
|
|
430
|
+
try:
|
|
431
|
+
loc.scroll_into_view_if_needed(timeout=3000)
|
|
432
|
+
except Exception:
|
|
433
|
+
pass
|
|
434
|
+
try:
|
|
435
|
+
loc.click(timeout=8000)
|
|
436
|
+
except Exception:
|
|
437
|
+
try:
|
|
438
|
+
loc.click(timeout=5000, force=True)
|
|
439
|
+
except Exception as e:
|
|
440
|
+
log(step, f"点击失败: {e}", "WARN")
|
|
441
|
+
return False
|
|
442
|
+
page.wait_for_timeout(600)
|
|
443
|
+
return True
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
JS_WL_SNAPSHOT = r"""
|
|
447
|
+
() => {
|
|
448
|
+
const ipRe = /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g;
|
|
449
|
+
const heads = ['服务器 IP 白名单','服务器IP白名单','IP 白名单','IP白名单','服务器 IP'];
|
|
450
|
+
const nodes = Array.from(document.querySelectorAll('body *'));
|
|
451
|
+
let head = null;
|
|
452
|
+
for (const el of nodes) {
|
|
453
|
+
if (el.children.length > 3) continue;
|
|
454
|
+
const t = (el.innerText || '').trim();
|
|
455
|
+
if (!t || t.length > 40) continue;
|
|
456
|
+
if (heads.includes(t)) { head = el; break; }
|
|
457
|
+
}
|
|
458
|
+
if (!head) return { found: false, reason: 'no-heading' };
|
|
459
|
+
let box = head;
|
|
460
|
+
for (let i = 0; i < 9 && box.parentElement; i++) {
|
|
461
|
+
box = box.parentElement;
|
|
462
|
+
const t = box.innerText || '';
|
|
463
|
+
const ips = (t.match(ipRe) || []).filter(x => !x.startsWith('127.'));
|
|
464
|
+
if (ips.length > 0 && t.length < 6000) break;
|
|
465
|
+
if (/添加|新增|保存/.test(t) && t.length < 2500) break;
|
|
466
|
+
}
|
|
467
|
+
const txt = (box.innerText || '');
|
|
468
|
+
// 2026-11 改版后已有 IP 是渲染在 <input value> 里的(innerText 读不到),必须一起收
|
|
469
|
+
const vals = Array.from(box.querySelectorAll('input,textarea')).map(e => e.value || '').join(' ');
|
|
470
|
+
const all = txt + ' ' + vals;
|
|
471
|
+
let ips = Array.from(new Set((all.match(ipRe) || [])
|
|
472
|
+
.filter(x => !x.startsWith('127.') && !x.startsWith('0.') && !x.startsWith('169.254.'))));
|
|
473
|
+
// 卡片头(标题 + 「添加 IP」)和输入行常常是兄弟节点,box 里读不到就退化为全页扫描:
|
|
474
|
+
// 开发设置页除了白名单没有别的地方会放 IPv4,这样比按 DOM 层级猜稳。
|
|
475
|
+
if (!ips.length) {
|
|
476
|
+
const pageVals = Array.from(document.querySelectorAll('input,textarea')).map(e => e.value || '').join(' ');
|
|
477
|
+
ips = Array.from(new Set(((pageVals + ' ' + (document.body.innerText || '')).match(ipRe) || [])
|
|
478
|
+
.filter(x => !x.startsWith('127.') && !x.startsWith('0.') && !x.startsWith('169.254.'))));
|
|
479
|
+
}
|
|
480
|
+
return { found: true, ips, textLen: txt.length, preview: txt.slice(0, 800) };;
|
|
481
|
+
}
|
|
482
|
+
"""
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def wl_snapshot(page) -> dict:
|
|
486
|
+
try:
|
|
487
|
+
return page.evaluate(JS_WL_SNAPSHOT)
|
|
488
|
+
except Exception as e:
|
|
489
|
+
log("whitelist", f"读取失败: {e}", "WARN")
|
|
490
|
+
return {"found": False, "reason": str(e)}
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
JS_WL_BUTTON = r"""
|
|
494
|
+
(label) => {
|
|
495
|
+
const labels = label.split('|');
|
|
496
|
+
const heads = ['服务器 IP 白名单','服务器IP白名单','IP 白名单','IP白名单'];
|
|
497
|
+
let head = null;
|
|
498
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
499
|
+
if (el.children.length > 3) continue;
|
|
500
|
+
const t = (el.innerText || '').trim();
|
|
501
|
+
if (heads.includes(t)) { head = el; break; }
|
|
502
|
+
}
|
|
503
|
+
if (!head) return { ok: false, why: 'no-heading' };
|
|
504
|
+
let box = head;
|
|
505
|
+
for (let i = 0; i < 9 && box.parentElement; i++) {
|
|
506
|
+
box = box.parentElement;
|
|
507
|
+
if (/添加|新增|保存/.test(box.innerText || '')) break;
|
|
508
|
+
}
|
|
509
|
+
const cands = Array.from(box.querySelectorAll('button,[role=button],a,span,div'));
|
|
510
|
+
for (const b of cands) {
|
|
511
|
+
const t = (b.innerText || '').trim();
|
|
512
|
+
if (!labels.includes(t)) continue;
|
|
513
|
+
if (b.offsetParent === null) continue;
|
|
514
|
+
const r = b.getBoundingClientRect();
|
|
515
|
+
if (r.width < 4 || r.height < 4) continue;
|
|
516
|
+
return { ok: true, x: r.x + r.width / 2, y: r.y + r.height / 2, text: t };
|
|
517
|
+
}
|
|
518
|
+
return { ok: false, why: 'no-button' };
|
|
519
|
+
}
|
|
520
|
+
"""
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def wl_button_click(page, labels: list[str], step: str) -> bool:
|
|
524
|
+
res = page.evaluate(JS_WL_BUTTON, "|".join(labels))
|
|
525
|
+
if not res.get("ok"):
|
|
526
|
+
log(step, f"白名单区域里没找到按钮 {labels} ({res.get('why')})", "WARN")
|
|
527
|
+
return False
|
|
528
|
+
page.mouse.click(res["x"], res["y"])
|
|
529
|
+
page.wait_for_timeout(500)
|
|
530
|
+
log(step, f"点击按钮 {res.get('text')}", "DEBUG")
|
|
531
|
+
return True
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
JS_DELETE_BUTTON = r"""
|
|
535
|
+
(ip) => {
|
|
536
|
+
// 新版页面每行是「只读 input + 行尾一个图标按钮(垃圾桶,无文字)」,
|
|
537
|
+
// 所以既按文字找、也按 input.value 找,再从最近的容器里挑最小的那个按钮。
|
|
538
|
+
const holders = [];
|
|
539
|
+
for (const el of document.querySelectorAll('body *')) {
|
|
540
|
+
if (el.children.length === 0 && (el.textContent || '').trim() === ip) holders.push(el);
|
|
541
|
+
}
|
|
542
|
+
for (const el of document.querySelectorAll('input')) {
|
|
543
|
+
if ((el.value || '').trim() === ip) holders.push(el);
|
|
544
|
+
}
|
|
545
|
+
for (const el of holders) {
|
|
546
|
+
let a = el;
|
|
547
|
+
for (let i = 0; i < 9 && a; i++) {
|
|
548
|
+
const btns = Array.from(a.querySelectorAll('button,[role=button]'))
|
|
549
|
+
.filter(b => b.offsetParent !== null)
|
|
550
|
+
.map(b => ({ b, r: b.getBoundingClientRect() }))
|
|
551
|
+
.filter(o => o.r.width >= 8 && o.r.width <= 64 && o.r.height >= 8 && o.r.height <= 64);
|
|
552
|
+
if (btns.length) {
|
|
553
|
+
btns.sort((x, y) => (y.r.x - x.r.x)); // 垃圾桶在最右
|
|
554
|
+
const { r } = btns[0];
|
|
555
|
+
return { ok: true, x: r.x + r.width / 2, y: r.y + r.height / 2,
|
|
556
|
+
text: (btns[0].b.getAttribute('aria-label') || btns[0].b.title || 'icon-btn') };
|
|
557
|
+
}
|
|
558
|
+
a = a.parentElement;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return { ok: false };
|
|
562
|
+
}
|
|
563
|
+
"""
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def add_ip_dialog(page, ip: str) -> bool:
|
|
567
|
+
"""点「添加 IP」之后的弹窗:只有一个 IPv4 输入框 + 取消/添加。
|
|
568
|
+
|
|
569
|
+
2026-11 实测结构:placeholder=「请输入 IPv4」,底部按钮精确文字「添加」。
|
|
570
|
+
旧代码用 [class*=dialog] 泛匹配,页面里同时有 7 个这类节点,会点错。
|
|
571
|
+
"""
|
|
572
|
+
try:
|
|
573
|
+
inp = page.locator("input[placeholder*='IPv4'], input[placeholder*='IPv4 '], input[placeholder*='IP']").last
|
|
574
|
+
inp.wait_for(state="visible", timeout=8000)
|
|
575
|
+
inp.fill(ip, timeout=5000)
|
|
576
|
+
log("add", "弹窗已填 IPv4")
|
|
577
|
+
except Exception as e:
|
|
578
|
+
log("add", f"找不到 IPv4 输入框: {str(e)[:120]}", "WARN")
|
|
579
|
+
return False
|
|
580
|
+
for label in ("添加", "确定", "确认", "保存"):
|
|
581
|
+
try:
|
|
582
|
+
btn = page.get_by_role("button", name=label, exact=True)
|
|
583
|
+
n = btn.count()
|
|
584
|
+
for i in range(n - 1, -1, -1):
|
|
585
|
+
if btn.nth(i).is_visible():
|
|
586
|
+
btn.nth(i).click(timeout=5000)
|
|
587
|
+
log("add", f"弹窗已点「{label}」")
|
|
588
|
+
return True
|
|
589
|
+
except Exception:
|
|
590
|
+
continue
|
|
591
|
+
log("add", "弹窗里没找到确认按钮", "WARN")
|
|
592
|
+
return False
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def delete_ip_row(page, ip: str) -> bool:
|
|
596
|
+
log("delete", f"开始删除 {ip}", "DEBUG")
|
|
597
|
+
try:
|
|
598
|
+
res = page.evaluate(JS_DELETE_BUTTON, ip)
|
|
599
|
+
except Exception as e:
|
|
600
|
+
log("delete", f"{ip} 删除按钮定位异常: {e}", "WARN")
|
|
601
|
+
return False
|
|
602
|
+
if not res.get("ok"):
|
|
603
|
+
log("delete", f"{ip} 没找到行内删除按钮", "WARN")
|
|
604
|
+
return False
|
|
605
|
+
log("delete", f"{ip} 定位到行内按钮 {res.get('text')} @({res.get('x'):.0f},{res.get('y'):.0f})", "DEBUG")
|
|
606
|
+
# 用鼠标坐标点,不用 JS el.click():后者会在 evaluate 里同步触发原生 confirm(),
|
|
607
|
+
# 把同步 API 的事件循环一起卡死(2026-11-27 实测,两次都是这么挂的)。
|
|
608
|
+
page.mouse.click(res["x"], res["y"])
|
|
609
|
+
log("delete", "已点击行内删除按钮,等待确认弹窗", "DEBUG")
|
|
610
|
+
page.wait_for_timeout(600)
|
|
611
|
+
# 站点用的是自己写的 DOM 弹窗(标题「删除该 IP 白名单」,按钮「取消 / 确认删除」),
|
|
612
|
+
# 不是浏览器原生 confirm,也不是 ant-design 的 .ant-modal,所以按按钮文字点。
|
|
613
|
+
confirmed = False
|
|
614
|
+
for label in ("确认删除", "确定删除", "确认", "确定", "删除"):
|
|
615
|
+
try:
|
|
616
|
+
btn = page.get_by_role("button", name=label, exact=True)
|
|
617
|
+
n = btn.count()
|
|
618
|
+
for i in range(n - 1, -1, -1):
|
|
619
|
+
if btn.nth(i).is_visible():
|
|
620
|
+
btn.nth(i).click(timeout=4000)
|
|
621
|
+
log("delete", f"{ip} 确认弹窗已点「{label}」")
|
|
622
|
+
confirmed = True
|
|
623
|
+
break
|
|
624
|
+
except Exception as e:
|
|
625
|
+
log("delete", f"点「{label}」失败: {str(e)[:120]}", "DEBUG")
|
|
626
|
+
if confirmed:
|
|
627
|
+
break
|
|
628
|
+
if not confirmed:
|
|
629
|
+
log("delete", f"{ip} 没等到确认弹窗(可能直接删了)", "WARN")
|
|
630
|
+
page.wait_for_timeout(800)
|
|
631
|
+
log("delete", f"已删除旧 IP {ip}")
|
|
632
|
+
return True
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def detect_login_state(body: str, url: str = "", auth_cookies=None, cookie_ok=None):
|
|
636
|
+
"""纯逻辑:根据页面文本 + URL + 鉴权 cookie 名判定登录态。
|
|
637
|
+
|
|
638
|
+
返回 (state, detail)。state ∈ {logged_in, need_login, unknown}。
|
|
639
|
+
这块没有 I/O,单测直接喂字符串就行(见 tests/test-qq-whitelist.py)。
|
|
640
|
+
|
|
641
|
+
2026-12-01:QQ 开放平台改版后首页把「登录」做成一张二维码卡片,旧文案一个都不命中,
|
|
642
|
+
只剩 pt2gguin 这种弱 cookie,于是被判成 logged_in,白跑一趟最后 rc=20。
|
|
643
|
+
现在规则改成「**强 cookie 才算登录**;读不到 cookie 库时才回退看页面文字」。
|
|
644
|
+
"""
|
|
645
|
+
body = body or ""
|
|
646
|
+
url_l = (url or "").lower()
|
|
647
|
+
auth = [c for c in (auth_cookies or []) if c]
|
|
648
|
+
has_logged = any(m in body for m in TEXTS["logged_markers"])
|
|
649
|
+
has_login = any(m in body for m in TEXTS["login_markers"])
|
|
650
|
+
in_login_url = ("ptlogin" in url_l) or ("/login" in url_l)
|
|
651
|
+
|
|
652
|
+
if auth and has_login:
|
|
653
|
+
# cookie 还在但页面只显示登录卡:cookie 已失效(过期/被顶号),要重新扫码。
|
|
654
|
+
# 必须排在 has_logged 前面:登录页页脚也有「系统公告」这类 logged marker。
|
|
655
|
+
state, why = LOGIN_NEED, "有 cookie " + ",".join(auth) + " 但页面是登录卡 -> cookie 已失效"
|
|
656
|
+
elif auth and has_logged:
|
|
657
|
+
state, why = LOGIN_LOGGED, "页面有已登录痕迹 + cookie " + ",".join(auth)
|
|
658
|
+
elif auth:
|
|
659
|
+
state, why = LOGIN_LOGGED, "页面没有登录卡 + cookie " + ",".join(auth)
|
|
660
|
+
elif has_login or in_login_url:
|
|
661
|
+
state, why = LOGIN_NEED, "页面出现登录卡(扫码/二维码),需要人工扫码一次"
|
|
662
|
+
elif cookie_ok is False and has_logged:
|
|
663
|
+
# cookie 库被浏览器占用读不到,只能信页面
|
|
664
|
+
state, why = LOGIN_LOGGED, "页面有已登录痕迹(cookie 库读不到,按页面判定)"
|
|
665
|
+
elif has_logged:
|
|
666
|
+
# 页面像后台,但没有任何强鉴权 cookie(只有 pt2gguin 之类)→ 实际已掉登录
|
|
667
|
+
state, why = LOGIN_NEED, "页面像后台但只有弱 cookie(pt2gguin 不算登录),需要重新扫码"
|
|
668
|
+
else:
|
|
669
|
+
state, why = LOGIN_NEED, "既没有强鉴权 cookie 也没看到后台痕迹,按未登录处理"
|
|
670
|
+
|
|
671
|
+
return state, {
|
|
672
|
+
"state": state,
|
|
673
|
+
"why": why,
|
|
674
|
+
"summary": why,
|
|
675
|
+
"has_logged_marker": has_logged,
|
|
676
|
+
"has_login_marker": has_login,
|
|
677
|
+
"auth_cookies": auth,
|
|
678
|
+
"cookie_ok": cookie_ok,
|
|
679
|
+
"url": url,
|
|
680
|
+
"body_len": len(body),
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def _frame_text(page) -> str:
|
|
685
|
+
"""主文档 + 所有子 iframe 的可见文本(扫码框有时后在 iframe 里)。"""
|
|
686
|
+
parts = []
|
|
687
|
+
try:
|
|
688
|
+
parts.append(page.evaluate("document.body ? document.body.innerText : ''") or "")
|
|
689
|
+
except Exception:
|
|
690
|
+
pass
|
|
691
|
+
try:
|
|
692
|
+
frames = list(page.frames)
|
|
693
|
+
except Exception:
|
|
694
|
+
frames = []
|
|
695
|
+
for fr in frames:
|
|
696
|
+
try:
|
|
697
|
+
if fr is page.main_frame:
|
|
698
|
+
continue
|
|
699
|
+
parts.append(fr.evaluate("document.body ? document.body.innerText : ''") or "")
|
|
700
|
+
except Exception:
|
|
701
|
+
continue
|
|
702
|
+
return "\n".join(x for x in parts if x)
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def _cookie_rows(db_path: Path):
|
|
706
|
+
"""以只读方式读出 [(host_key, name), ...];打不开就抛异常。"""
|
|
707
|
+
uri = db_path.as_uri() + "?mode=ro"
|
|
708
|
+
con = sqlite3.connect(uri, uri=True)
|
|
709
|
+
try:
|
|
710
|
+
return con.execute("SELECT host_key, name FROM cookies").fetchall()
|
|
711
|
+
finally:
|
|
712
|
+
con.close()
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def probe_profile_cookies(profile_dir: Path | None = None, use_cache: bool = True) -> dict:
|
|
716
|
+
"""只读探测专用 profile 的 Cookies 数据库(不启动浏览器)。
|
|
717
|
+
|
|
718
|
+
cookie 值是 Chromium 加密过的,这里只取「名字 + 域」,判断有没有登录态。
|
|
719
|
+
返回 {ok, db, exists, size, mtime, total, qq_total, auth, error}
|
|
720
|
+
"""
|
|
721
|
+
global _cookie_cache
|
|
722
|
+
if use_cache and _cookie_cache is not None:
|
|
723
|
+
return _cookie_cache
|
|
724
|
+
|
|
725
|
+
db = (profile_dir or PROFILE_DIR) / "Default" / "Network" / "Cookies"
|
|
726
|
+
info = {"ok": False, "db": str(db), "exists": db.exists(), "size": 0,
|
|
727
|
+
"mtime": "", "total": 0, "qq_total": 0, "auth": [], "error": ""}
|
|
728
|
+
if not db.exists():
|
|
729
|
+
info["error"] = "Cookies 文件不存在(profile 还没被浏览器初始化过)"
|
|
730
|
+
_cookie_cache = info
|
|
731
|
+
return info
|
|
732
|
+
try:
|
|
733
|
+
st = db.stat()
|
|
734
|
+
info["size"] = st.st_size
|
|
735
|
+
info["mtime"] = datetime.fromtimestamp(st.st_mtime).strftime("%Y-%m-%d %H:%M:%S")
|
|
736
|
+
except OSError:
|
|
737
|
+
pass
|
|
738
|
+
|
|
739
|
+
rows = None
|
|
740
|
+
tmpdir = None
|
|
741
|
+
try:
|
|
742
|
+
tmpdir = tempfile.mkdtemp(prefix="qqwl-ck-")
|
|
743
|
+
copy = Path(tmpdir) / db.name
|
|
744
|
+
# Chromium 跑着的时候会锁库,shutil.copy2 可能抛 sharing violation,重试 3 次
|
|
745
|
+
last = None
|
|
746
|
+
for _ in range(3):
|
|
747
|
+
try:
|
|
748
|
+
shutil.copy2(str(db), str(copy))
|
|
749
|
+
last = None
|
|
750
|
+
break
|
|
751
|
+
except OSError as e:
|
|
752
|
+
last = e
|
|
753
|
+
time.sleep(0.15)
|
|
754
|
+
if last is not None:
|
|
755
|
+
raise last
|
|
756
|
+
# WAL 模式的库必须连 -wal/-shm 一起复制,否则读出来是空的/损坏的
|
|
757
|
+
for extra in ("-wal", "-shm", "-journal"):
|
|
758
|
+
src_x = db.parent / (db.name + extra)
|
|
759
|
+
if src_x.exists():
|
|
760
|
+
try:
|
|
761
|
+
shutil.copy2(str(src_x), str(Path(tmpdir) / (db.name + extra)))
|
|
762
|
+
except OSError:
|
|
763
|
+
pass
|
|
764
|
+
rows = _cookie_rows(copy)
|
|
765
|
+
except Exception as e:
|
|
766
|
+
info["error"] = f"{type(e).__name__}: {e}"
|
|
767
|
+
finally:
|
|
768
|
+
if tmpdir:
|
|
769
|
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
770
|
+
|
|
771
|
+
if rows is None:
|
|
772
|
+
# 复制这条路被锁挡住时,退回「直接以只读 URI 打开原库」
|
|
773
|
+
try:
|
|
774
|
+
rows = _cookie_rows(db)
|
|
775
|
+
info["error"] = ""
|
|
776
|
+
except Exception as e:
|
|
777
|
+
if not info["error"]:
|
|
778
|
+
info["error"] = f"{type(e).__name__}: {e}"
|
|
779
|
+
|
|
780
|
+
if rows is not None:
|
|
781
|
+
info["total"] = len(rows)
|
|
782
|
+
auth = []
|
|
783
|
+
for host, name in rows:
|
|
784
|
+
if "qq.com" in (host or ""):
|
|
785
|
+
info["qq_total"] += 1
|
|
786
|
+
if name in AUTH_COOKIE_NAMES and "qq.com" in (host or ""):
|
|
787
|
+
if name not in auth:
|
|
788
|
+
auth.append(name)
|
|
789
|
+
info["auth"] = auth
|
|
790
|
+
info["ok"] = True
|
|
791
|
+
_cookie_cache = info
|
|
792
|
+
return info
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def inspect_login(page):
|
|
796
|
+
"""页面 + profile cookie 一起判,返回 (state, detail)。"""
|
|
797
|
+
body = _frame_text(page)
|
|
798
|
+
try:
|
|
799
|
+
url = page.url
|
|
800
|
+
except Exception:
|
|
801
|
+
url = ""
|
|
802
|
+
ck = probe_profile_cookies()
|
|
803
|
+
state, detail = detect_login_state(body, url, ck.get("auth"), ck.get("ok"))
|
|
804
|
+
detail["cookie"] = {k: ck.get(k) for k in ("ok", "total", "qq_total", "auth", "size", "mtime", "error")}
|
|
805
|
+
return state, detail
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def read_login_state(page) -> str:
|
|
809
|
+
"""兼容旧调用:只要状态字符串。"""
|
|
810
|
+
state, _ = inspect_login(page)
|
|
811
|
+
return state
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
# ---------------------------------------------------------------- 浏览器流程
|
|
815
|
+
def kill_stale_edge() -> int:
|
|
816
|
+
"""杀掉还在占用 edge-profile 的残留 Edge。
|
|
817
|
+
|
|
818
|
+
2026-11-27 实测:脚本异常退出后,playwright 启动的 headless Edge 会变成孤儿进程
|
|
819
|
+
继续锁着 profile,下一次 launch 直接 failed(exitCode=21,Target page closed),
|
|
820
|
+
表现为「无论 headless 还是有窗口都起不来」。所以每次开跑前先清一遍。
|
|
821
|
+
只杀 --user-data-dir 指向本脚本 profile 的进程,不碰用户日常 Edge。
|
|
822
|
+
"""
|
|
823
|
+
ps = (
|
|
824
|
+
"Get-CimInstance Win32_Process -Filter \"Name='msedge.exe'\" | "
|
|
825
|
+
"Where-Object { $_.CommandLine -like '*qqbot\\data\\edge-profile*' } | "
|
|
826
|
+
"Select-Object -ExpandProperty ProcessId"
|
|
827
|
+
)
|
|
828
|
+
rc, out = _run(["powershell", "-NoProfile", "-Command", ps])
|
|
829
|
+
pids = [x.strip() for x in out.splitlines() if x.strip().isdigit()]
|
|
830
|
+
killed = 0
|
|
831
|
+
for pid in pids:
|
|
832
|
+
rc2, _ = _run(["taskkill", "/PID", pid, "/T", "/F"])
|
|
833
|
+
if rc2 == 0:
|
|
834
|
+
killed += 1
|
|
835
|
+
if pids:
|
|
836
|
+
log("edge", f"清理残留 Edge 进程 {len(pids)} 个(成功 {killed})", "WARN")
|
|
837
|
+
time.sleep(2)
|
|
838
|
+
return killed
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def _attach_dialogs(page) -> None:
|
|
842
|
+
"""给 page 挂原生弹窗处理。
|
|
843
|
+
|
|
844
|
+
2026-11-27 实测:点行内「删除该 IP」后页面会弹浏览器原生 confirm(),
|
|
845
|
+
不接这个事件渲染进程会被阻塞,之后所有 page.wait_for_timeout 都不返回(脚本假死)。
|
|
846
|
+
注意:机器人详情会开新标签页,所以每个 page(含新开的)都要挂,不能只挂首页。
|
|
847
|
+
"""
|
|
848
|
+
def _on_dialog(d):
|
|
849
|
+
try:
|
|
850
|
+
log("dialog", f"原生弹窗 {d.type}: {(d.message or '')[:120]} -> 接受", "DEBUG")
|
|
851
|
+
d.accept()
|
|
852
|
+
except Exception as e:
|
|
853
|
+
log("dialog", f"处理弹窗失败: {e}", "WARN")
|
|
854
|
+
|
|
855
|
+
try:
|
|
856
|
+
page.on("dialog", _on_dialog)
|
|
857
|
+
except Exception:
|
|
858
|
+
pass
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def _run_lock_path() -> Path:
|
|
862
|
+
return BASE / "data" / "whitelist-run.lock"
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def _acquire_run_lock() -> bool:
|
|
866
|
+
"""单实例锁。
|
|
867
|
+
|
|
868
|
+
2026-12-03 实测事故:人工扫码窗口开着的时候,又跑了一次 --headless,
|
|
869
|
+
_open_context → kill_stale_edge 把**正在扫码的那个浏览器**当成残留杀掉,
|
|
870
|
+
于是扫码白扫、cookie 被覆盖、页面又回到登录卡。
|
|
871
|
+
所以这里保证同一时间只有一个进程能碰 edge-profile。
|
|
872
|
+
"""
|
|
873
|
+
p = _run_lock_path()
|
|
874
|
+
try:
|
|
875
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
876
|
+
if p.exists():
|
|
877
|
+
try:
|
|
878
|
+
info = json.loads(p.read_text("utf-8"))
|
|
879
|
+
except Exception:
|
|
880
|
+
info = {}
|
|
881
|
+
pid = int(info.get("pid") or 0)
|
|
882
|
+
if pid and pid != os.getpid():
|
|
883
|
+
alive = False
|
|
884
|
+
try:
|
|
885
|
+
os.kill(pid, 0)
|
|
886
|
+
alive = True
|
|
887
|
+
except OSError:
|
|
888
|
+
alive = False
|
|
889
|
+
if alive:
|
|
890
|
+
log("lock", f"另一个白名单任务正在运行(PID {pid}),本次退出,不要同时开两个", "ERROR")
|
|
891
|
+
return False
|
|
892
|
+
p.write_text(json.dumps({"pid": os.getpid(), "at": time.time()}), "utf-8")
|
|
893
|
+
return True
|
|
894
|
+
except Exception:
|
|
895
|
+
return True
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _release_run_lock() -> None:
|
|
899
|
+
try:
|
|
900
|
+
p = _run_lock_path()
|
|
901
|
+
if p.exists():
|
|
902
|
+
info = json.loads(p.read_text("utf-8"))
|
|
903
|
+
if int(info.get("pid") or 0) == os.getpid():
|
|
904
|
+
p.unlink()
|
|
905
|
+
except Exception:
|
|
906
|
+
pass
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def _state_path() -> Path:
|
|
910
|
+
return BASE / "data" / "edge-profile-state.json"
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def _open_context(p, headless: bool, slow_mo: int = 0):
|
|
914
|
+
PROFILE_DIR.mkdir(parents=True, exist_ok=True)
|
|
915
|
+
if not _acquire_run_lock():
|
|
916
|
+
raise RuntimeError("已有一个白名单任务在跑(正在扫码就别再开第二个),本次不启动浏览器")
|
|
917
|
+
kill_stale_edge()
|
|
918
|
+
ctx = p.chromium.launch_persistent_context(
|
|
919
|
+
str(PROFILE_DIR),
|
|
920
|
+
channel="msedge",
|
|
921
|
+
headless=headless,
|
|
922
|
+
slow_mo=slow_mo,
|
|
923
|
+
viewport={"width": 1440, "height": 900},
|
|
924
|
+
locale="zh-CN",
|
|
925
|
+
timezone_id="Asia/Shanghai",
|
|
926
|
+
accept_downloads=False,
|
|
927
|
+
args=["--disable-blink-features=AutomationControlled", "--no-first-run"],
|
|
928
|
+
)
|
|
929
|
+
# profile 偶尔被别的进程覆盖(实测扫完码又被写成未登录),用独立快照兜底
|
|
930
|
+
try:
|
|
931
|
+
st = _state_path()
|
|
932
|
+
if st.exists():
|
|
933
|
+
snap = json.loads(st.read_text("utf-8"))
|
|
934
|
+
cookies = snap.get("cookies") or []
|
|
935
|
+
if cookies:
|
|
936
|
+
ctx.add_cookies(cookies)
|
|
937
|
+
log("login", f"已注入登录快照 cookie {len(cookies)} 条({st.name})")
|
|
938
|
+
except Exception as e:
|
|
939
|
+
log("login", f"注入登录快照失败(忽略): {e}", "WARN")
|
|
940
|
+
page = ctx.pages[0] if ctx.pages else ctx.new_page()
|
|
941
|
+
page.set_default_timeout(12000)
|
|
942
|
+
_attach_dialogs(page)
|
|
943
|
+
ctx.on("page", lambda pg: _attach_dialogs(pg)) # 新标签页也要挂
|
|
944
|
+
return ctx, page
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def _goto_site(page) -> bool:
|
|
948
|
+
for attempt in (1, 2):
|
|
949
|
+
try:
|
|
950
|
+
page.goto(SITE, wait_until="domcontentloaded", timeout=45000)
|
|
951
|
+
page.wait_for_timeout(3500)
|
|
952
|
+
return True
|
|
953
|
+
except Exception as e:
|
|
954
|
+
log("goto", f"打开 {SITE} 失败(第{attempt}次): {e}", "ERROR")
|
|
955
|
+
page.wait_for_timeout(2000)
|
|
956
|
+
return False
|
|
957
|
+
|
|
958
|
+
|
|
959
|
+
def _open_bot_manager(ctx, page):
|
|
960
|
+
"""走到「机器人详情 → 开发设置」页。
|
|
961
|
+
|
|
962
|
+
2026-11 平台改版后,老流程(点导航「机器人」→「管理机器人」→ 机器人名)会停在
|
|
963
|
+
宣传页,标题里就有「我的机器人」四个字,于是每一步都"点到了"却根本没进后台,
|
|
964
|
+
最后在白名单那一步报 no-heading。这里改成直达后台 + 直达机器人详情。
|
|
965
|
+
返回停在开发设置页的 page;失败返回 None。
|
|
966
|
+
"""
|
|
967
|
+
# 2026-12-01:新门户下先直达 /qqbot/dashboard/manage/<appid>?sec=dev-settings,
|
|
968
|
+
# 成功出现「开发设置/白名单」就直接用;不行再回退老的“点导航”流程。
|
|
969
|
+
if not APP_ID:
|
|
970
|
+
log("error", "没有 AppID:请设置环境变量 QQBOT_APP_ID,或把 AppID 写进 data/net/appid.txt(该目录不入库)")
|
|
971
|
+
return None
|
|
972
|
+
try:
|
|
973
|
+
page.goto(f"{MANAGE_URL}{DEV_SEC}", wait_until="domcontentloaded", timeout=45000)
|
|
974
|
+
page.wait_for_timeout(4500)
|
|
975
|
+
txt = _frame_text(page)
|
|
976
|
+
if "开发设置" in txt or any(k in txt for k in TEXTS["ip_whitelist"]):
|
|
977
|
+
take_shot(page, "02-manage-direct")
|
|
978
|
+
log("nav", f"直达机器人管理页: {page.url}")
|
|
979
|
+
return page
|
|
980
|
+
log("nav", "直达管理页没出现白名单/开发设置,回退点导航流程", "WARN")
|
|
981
|
+
except Exception as e:
|
|
982
|
+
log("nav", f"直达管理页失败: {e},回退点导航流程", "WARN")
|
|
983
|
+
|
|
984
|
+
try:
|
|
985
|
+
page.goto(MANAGER_URL, wait_until="domcontentloaded", timeout=45000)
|
|
986
|
+
page.wait_for_timeout(4000)
|
|
987
|
+
except Exception as e:
|
|
988
|
+
log("nav", f"打开机器人后台失败: {e}", "ERROR")
|
|
989
|
+
return None
|
|
990
|
+
take_shot(page, "02-dashboard")
|
|
991
|
+
if "我的机器人" not in _frame_text(page) and BOT_NAME not in _frame_text(page):
|
|
992
|
+
take_shot(page, "no-dashboard")
|
|
993
|
+
log("nav", "后台页没加载出机器人列表", "ERROR")
|
|
994
|
+
return None
|
|
995
|
+
|
|
996
|
+
if not click_text(page, [BOT_NAME], "bot", timeout=12000):
|
|
997
|
+
# 有一次重载的机会(首屏偶发只渲染骨架)
|
|
998
|
+
page.wait_for_timeout(3000)
|
|
999
|
+
take_shot(page, "bot-retry")
|
|
1000
|
+
if not click_text(page, [BOT_NAME], "bot", timeout=8000):
|
|
1001
|
+
take_shot(page, "no-bot")
|
|
1002
|
+
log("bot", f"后台里找不到机器人 {BOT_NAME}", "ERROR")
|
|
1003
|
+
return None
|
|
1004
|
+
page.wait_for_timeout(3000)
|
|
1005
|
+
if len(ctx.pages) > 1 and ctx.pages[-1] is not page:
|
|
1006
|
+
page = ctx.pages[-1]
|
|
1007
|
+
page.set_default_timeout(12000)
|
|
1008
|
+
_attach_dialogs(page)
|
|
1009
|
+
page.wait_for_timeout(2500)
|
|
1010
|
+
log("nav", "切换到机器人详情新标签页")
|
|
1011
|
+
take_shot(page, "03-bot-detail")
|
|
1012
|
+
log("nav", f"机器人详情页: {page.url}")
|
|
1013
|
+
|
|
1014
|
+
if not click_text(page, TEXTS["dev_settings"], "dev", timeout=12000):
|
|
1015
|
+
take_shot(page, "no-dev")
|
|
1016
|
+
log("dev", "找不到「开发设置」", "ERROR")
|
|
1017
|
+
return None
|
|
1018
|
+
page.wait_for_timeout(2500)
|
|
1019
|
+
take_shot(page, "04-dev")
|
|
1020
|
+
log("dev", f"开发设置页: {page.url}")
|
|
1021
|
+
return page
|
|
1022
|
+
|
|
1023
|
+
|
|
1024
|
+
def run_once(headless: bool, ip: str, dry_run: bool = False, prune: bool = True) -> int:
|
|
1025
|
+
from playwright.sync_api import sync_playwright # 延迟导入,--print-ip 不需要
|
|
1026
|
+
|
|
1027
|
+
# 先把 cookie 状态探一遍并缓存:Edge 一旦跑起来就会独占锁 Cookies 库
|
|
1028
|
+
# (实测 PermissionError: Errno 13),那时读不到。这份快照代表「启动前的登录态」,
|
|
1029
|
+
# 作为页面文本判定的辅助信号;页面判定才是主信号。
|
|
1030
|
+
pre = probe_profile_cookies()
|
|
1031
|
+
log("login", f"启动前 cookie 快照: ok={pre.get('ok')} total={pre.get('total')} "
|
|
1032
|
+
f"qq={pre.get('qq_total')} auth={pre.get('auth')} mtime={pre.get('mtime')} "
|
|
1033
|
+
f"err={pre.get('error')}")
|
|
1034
|
+
|
|
1035
|
+
with sync_playwright() as p:
|
|
1036
|
+
try:
|
|
1037
|
+
ctx, page = _open_context(p, headless=headless)
|
|
1038
|
+
except Exception as e:
|
|
1039
|
+
log("browser", f"启动 Edge 失败: {e}", "ERROR")
|
|
1040
|
+
return EXIT_NET_FAIL
|
|
1041
|
+
try:
|
|
1042
|
+
log("browser", f"Edge 已启动 headless={headless} profile={PROFILE_DIR}")
|
|
1043
|
+
if not _goto_site(page):
|
|
1044
|
+
take_shot(page, "net-fail")
|
|
1045
|
+
return EXIT_NET_FAIL
|
|
1046
|
+
|
|
1047
|
+
state, why = inspect_login(page)
|
|
1048
|
+
ck = why.get("cookie", {})
|
|
1049
|
+
log("login", f"登录状态: {state} —— {why.get('summary')}")
|
|
1050
|
+
log("login", f"profile cookie: db={ck.get('ok')} total={ck.get('total')} "
|
|
1051
|
+
f"qq={ck.get('qq_total')} auth={ck.get('auth')} size={ck.get('size')} "
|
|
1052
|
+
f"mtime={ck.get('mtime')} err={ck.get('error')}")
|
|
1053
|
+
if state != LOGIN_LOGGED:
|
|
1054
|
+
take_shot(page, "need-login")
|
|
1055
|
+
if state == LOGIN_NEED:
|
|
1056
|
+
log("login", "NEED_MANUAL_LOGIN 未登录:需要人工扫码一次 "
|
|
1057
|
+
"(python F:\\qqbot\\scripts\\qq-whitelist.py --login)", "ERROR")
|
|
1058
|
+
else:
|
|
1059
|
+
log("login", "LOGIN_UNKNOWN 判不清登录态:页面可能没加载完或结构变了,"
|
|
1060
|
+
"先跑 --probe 看结构", "ERROR")
|
|
1061
|
+
return EXIT_NEED_LOGIN
|
|
1062
|
+
|
|
1063
|
+
take_shot(page, "01-home")
|
|
1064
|
+
|
|
1065
|
+
# 直达后台(新版平台:导航「机器人」只是宣传页)
|
|
1066
|
+
page = _open_bot_manager(ctx, page)
|
|
1067
|
+
if page is None:
|
|
1068
|
+
return EXIT_NO_ELEMENT
|
|
1069
|
+
|
|
1070
|
+
snap = wl_snapshot(page)
|
|
1071
|
+
if not snap.get("found"):
|
|
1072
|
+
take_shot(page, "no-whitelist")
|
|
1073
|
+
log("whitelist", f"没定位到「服务器 IP 白名单」区域: {snap.get('reason')}", "ERROR")
|
|
1074
|
+
return EXIT_NO_ELEMENT
|
|
1075
|
+
existing = [x for x in snap.get("ips", []) if _usable(x)]
|
|
1076
|
+
log("whitelist", f"现有 IP: {existing}")
|
|
1077
|
+
take_shot(page, "06-whitelist")
|
|
1078
|
+
|
|
1079
|
+
plan = plan_update(ip, existing, prune)
|
|
1080
|
+
log("plan", f"当前 IP={ip} 计划={plan}")
|
|
1081
|
+
if plan["action"] == "up-to-date":
|
|
1082
|
+
log("result", f"up-to-date 当前 IP {ip} 已在白名单,无需改动")
|
|
1083
|
+
write_last_ip(ip)
|
|
1084
|
+
return EXIT_OK
|
|
1085
|
+
if dry_run:
|
|
1086
|
+
log("result", "dry-run 只打印计划,不修改")
|
|
1087
|
+
return EXIT_OK
|
|
1088
|
+
|
|
1089
|
+
# 删旧
|
|
1090
|
+
deleted_ok = 0
|
|
1091
|
+
for old in plan["delete"]:
|
|
1092
|
+
log("delete", f"尝试删除旧 IP {old}")
|
|
1093
|
+
if delete_ip_row(page, old):
|
|
1094
|
+
deleted_ok += 1
|
|
1095
|
+
log("delete", f"{old} 删除结果 ok={bool(deleted_ok)}")
|
|
1096
|
+
if deleted_ok:
|
|
1097
|
+
page.wait_for_timeout(600)
|
|
1098
|
+
take_shot(page, "07-deleted")
|
|
1099
|
+
# 这个页面是「改完即自动保存 + 右上角 toast 提示」,没有保存按钮。
|
|
1100
|
+
# 删完先回读一次,已经只剩当前 IP 就直接收工,别再走去点保存那条路
|
|
1101
|
+
# (实测那条路偶发卡在 renderer 上不返回)。
|
|
1102
|
+
try:
|
|
1103
|
+
now_ips = [x for x in wl_snapshot(page).get("ips", []) if _usable(x)]
|
|
1104
|
+
except Exception:
|
|
1105
|
+
now_ips = None
|
|
1106
|
+
if now_ips == [ip]:
|
|
1107
|
+
log("result", f"OK 白名单已只保留当前 IP {ip}(站点自动保存)")
|
|
1108
|
+
write_last_ip(ip)
|
|
1109
|
+
return EXIT_OK
|
|
1110
|
+
|
|
1111
|
+
# 添加当前 IP:新版是「添加 IP」→ 弹窗「添加 IP 白名单」(请输入 IPv4)→ 点「添加」
|
|
1112
|
+
if plan["add"]:
|
|
1113
|
+
if not wl_button_click(page, TEXTS["add"], "add"):
|
|
1114
|
+
if not click_text(page, TEXTS["add"], "add", timeout=5000):
|
|
1115
|
+
take_shot(page, "no-add")
|
|
1116
|
+
log("add", "找不到「添加」按钮", "ERROR")
|
|
1117
|
+
return EXIT_NO_ELEMENT
|
|
1118
|
+
if not add_ip_dialog(page, ip):
|
|
1119
|
+
take_shot(page, "add-fail")
|
|
1120
|
+
log("add", "填写/提交 IP 失败", "ERROR")
|
|
1121
|
+
return EXIT_NO_ELEMENT
|
|
1122
|
+
page.wait_for_timeout(1500)
|
|
1123
|
+
take_shot(page, "08-added")
|
|
1124
|
+
else:
|
|
1125
|
+
log("cleanup", f"只清理历史 IP {plan['delete']},当前 IP 已存在,不重复添加")
|
|
1126
|
+
|
|
1127
|
+
# 保存:这个页面是「改完即自动保存 + 右上角 toast(已添加 IP 白名单)」,
|
|
1128
|
+
# 没有保存按钮。2026-11-27:以前这里还去找「保存」按钮,Playwright 会卡在
|
|
1129
|
+
# renderer 上不返回(实测挂住 10 分钟),改成「直接回读,读到就收工」。
|
|
1130
|
+
final: list[str] = []
|
|
1131
|
+
t0 = time.time()
|
|
1132
|
+
while time.time() - t0 < 15:
|
|
1133
|
+
try:
|
|
1134
|
+
final = [x for x in wl_snapshot(page).get("ips", []) if _usable(x)]
|
|
1135
|
+
except Exception:
|
|
1136
|
+
final = []
|
|
1137
|
+
if ip in final:
|
|
1138
|
+
break
|
|
1139
|
+
time.sleep(1)
|
|
1140
|
+
take_shot(page, "09-saved")
|
|
1141
|
+
|
|
1142
|
+
# 回读确认
|
|
1143
|
+
log("verify", f"保存后白名单: {final}")
|
|
1144
|
+
leftovers = [x for x in final if x != ip]
|
|
1145
|
+
if ip in final:
|
|
1146
|
+
if leftovers:
|
|
1147
|
+
log("verify", f"当前 IP 已在白名单,但仍残留未删掉的旧 IP: {leftovers}", "WARN")
|
|
1148
|
+
log("result", f"OK 白名单已包含 {ip}")
|
|
1149
|
+
write_last_ip(ip)
|
|
1150
|
+
return EXIT_OK
|
|
1151
|
+
take_shot(page, "verify-fail")
|
|
1152
|
+
log("verify", f"回读失败:{ip} 不在 {final}", "ERROR")
|
|
1153
|
+
return EXIT_VERIFY_FAIL
|
|
1154
|
+
|
|
1155
|
+
except Exception as e:
|
|
1156
|
+
log("exception", f"{type(e).__name__}: {e}", "ERROR")
|
|
1157
|
+
log("exception", traceback.format_exc().replace("\n", " | ")[:1500], "ERROR")
|
|
1158
|
+
try:
|
|
1159
|
+
take_shot(page, "exception")
|
|
1160
|
+
except Exception:
|
|
1161
|
+
pass
|
|
1162
|
+
return EXIT_NO_ELEMENT
|
|
1163
|
+
finally:
|
|
1164
|
+
try:
|
|
1165
|
+
ctx.close()
|
|
1166
|
+
except Exception:
|
|
1167
|
+
pass
|
|
1168
|
+
|
|
1169
|
+
|
|
1170
|
+
# ---------------------------------------------------------------- 页面结构导出
|
|
1171
|
+
JS_DOM_DUMP = r"""
|
|
1172
|
+
() => {
|
|
1173
|
+
const vis = el => { try { const r = el.getBoundingClientRect();
|
|
1174
|
+
return (el.offsetParent !== null) && r.width > 2 && r.height > 2; } catch (e) { return false; } };
|
|
1175
|
+
const cut = (s, n) => (s || '').replace(/\s+/g, ' ').trim().slice(0, n || 80);
|
|
1176
|
+
const btns = [];
|
|
1177
|
+
document.querySelectorAll('button,[role=button],a,[class*=btn],[class*=Btn],[class*=button]').forEach(el => {
|
|
1178
|
+
if (!vis(el) || btns.length >= 80) return;
|
|
1179
|
+
btns.push({tag: el.tagName.toLowerCase(),
|
|
1180
|
+
text: cut(el.innerText || el.getAttribute('aria-label') || ''),
|
|
1181
|
+
cls: cut((el.className || '').toString(), 60)});
|
|
1182
|
+
});
|
|
1183
|
+
const inputs = [];
|
|
1184
|
+
document.querySelectorAll('input,textarea').forEach(el => {
|
|
1185
|
+
if (inputs.length >= 40) return;
|
|
1186
|
+
inputs.push({type: el.type || '', name: el.name || '', id: el.id || '',
|
|
1187
|
+
placeholder: el.placeholder || '', vis: vis(el),
|
|
1188
|
+
cls: cut((el.className || '').toString(), 60)});
|
|
1189
|
+
});
|
|
1190
|
+
const hints = [];
|
|
1191
|
+
document.querySelectorAll('h1,h2,h3,h4,h5,label,span,div,td,th,p').forEach(el => {
|
|
1192
|
+
if (hints.length >= 60 || el.children.length > 0 || !vis(el)) return;
|
|
1193
|
+
const t = cut(el.innerText || '', 40);
|
|
1194
|
+
if (t && /白名单|机器人|开发设置|添加|新增|保存|删除|移除|确定|IP/.test(t)) hints.push(t);
|
|
1195
|
+
});
|
|
1196
|
+
return {url: location.href, title: document.title, buttons: btns, inputs: inputs, hints: hints};
|
|
1197
|
+
}
|
|
1198
|
+
"""
|
|
1199
|
+
|
|
1200
|
+
|
|
1201
|
+
def _dump(page) -> dict:
|
|
1202
|
+
try:
|
|
1203
|
+
return page.evaluate(JS_DOM_DUMP)
|
|
1204
|
+
except Exception as e:
|
|
1205
|
+
return {"error": f"{type(e).__name__}: {e}"}
|
|
1206
|
+
|
|
1207
|
+
|
|
1208
|
+
def do_probe(headless: bool = False) -> int:
|
|
1209
|
+
"""把 q.qq.com 的页面结构导成 JSON,用来校准 TEXTS 里的候选文本。
|
|
1210
|
+
|
|
1211
|
+
只做「导航」,绝不点添加/保存/删除。
|
|
1212
|
+
"""
|
|
1213
|
+
from playwright.sync_api import sync_playwright
|
|
1214
|
+
|
|
1215
|
+
out = {"ts": _run_ts, "headless": headless, "steps": []}
|
|
1216
|
+
pre = probe_profile_cookies() # 浏览器一开就锁库,先拍快照
|
|
1217
|
+
log("probe", f"启动前 cookie 快照: ok={pre.get('ok')} total={pre.get('total')} "
|
|
1218
|
+
f"qq={pre.get('qq_total')} auth={pre.get('auth')} mtime={pre.get('mtime')} "
|
|
1219
|
+
f"err={pre.get('error')}")
|
|
1220
|
+
with sync_playwright() as p:
|
|
1221
|
+
try:
|
|
1222
|
+
ctx, page = _open_context(p, headless=headless, slow_mo=0 if headless else 120)
|
|
1223
|
+
except Exception as e:
|
|
1224
|
+
log("probe", f"启动 Edge 失败: {e}", "ERROR")
|
|
1225
|
+
return EXIT_NET_FAIL
|
|
1226
|
+
try:
|
|
1227
|
+
if not _goto_site(page):
|
|
1228
|
+
return EXIT_NET_FAIL
|
|
1229
|
+
state, detail = inspect_login(page)
|
|
1230
|
+
ck = detail.get("cookie", {})
|
|
1231
|
+
log("probe", f"登录状态={state} —— {detail.get('summary')}")
|
|
1232
|
+
log("probe", f"profile cookie: total={ck.get('total')} qq={ck.get('qq_total')} "
|
|
1233
|
+
f"auth={ck.get('auth')} mtime={ck.get('mtime')}")
|
|
1234
|
+
out["login"] = {"state": state, "detail": detail}
|
|
1235
|
+
out["steps"].append({"step": "home", "dump": _dump(page)})
|
|
1236
|
+
take_shot(page, "probe-home")
|
|
1237
|
+
|
|
1238
|
+
if state == LOGIN_LOGGED:
|
|
1239
|
+
for step, key in (("nav", "nav_bot"), ("manage", "manage_bot"),
|
|
1240
|
+
("bot", "my_bot"), ("dev", "dev_settings")):
|
|
1241
|
+
ok = click_text(page, TEXTS[key], step, timeout=10000)
|
|
1242
|
+
page.wait_for_timeout(2000)
|
|
1243
|
+
out["steps"].append({"step": step, "ok": ok, "dump": _dump(page)})
|
|
1244
|
+
take_shot(page, f"probe-{step}")
|
|
1245
|
+
if not ok:
|
|
1246
|
+
log("probe", f"第 {step} 步没点中(TEXTS[{key}]={TEXTS[key]}),结构见 JSON", "WARN")
|
|
1247
|
+
break
|
|
1248
|
+
snap = wl_snapshot(page)
|
|
1249
|
+
out["whitelist"] = snap
|
|
1250
|
+
log("probe", f"白名单快照: found={snap.get('found')} ips={snap.get('ips')} "
|
|
1251
|
+
f"preview={str(snap.get('preview'))[:200]}")
|
|
1252
|
+
else:
|
|
1253
|
+
log("probe", "未登录,只导出了落地页结构;登录后用 --probe --headful 再跑一次校准白名单选择器")
|
|
1254
|
+
|
|
1255
|
+
path = LOG_DIR / f"qq-whitelist-probe-{_run_ts}.json"
|
|
1256
|
+
path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
1257
|
+
log("probe", f"结构已导出: {path}")
|
|
1258
|
+
return EXIT_OK
|
|
1259
|
+
except Exception as e:
|
|
1260
|
+
log("probe", f"{type(e).__name__}: {e}", "ERROR")
|
|
1261
|
+
return EXIT_NO_ELEMENT
|
|
1262
|
+
finally:
|
|
1263
|
+
try:
|
|
1264
|
+
ctx.close()
|
|
1265
|
+
except Exception:
|
|
1266
|
+
pass
|
|
1267
|
+
|
|
1268
|
+
|
|
1269
|
+
def _bring_to_front(page) -> bool:
|
|
1270
|
+
"""把 Edge 窗口置前并还原(扫码得看得见)。失败不影响流程。"""
|
|
1271
|
+
try:
|
|
1272
|
+
page.bring_to_front()
|
|
1273
|
+
except Exception:
|
|
1274
|
+
pass
|
|
1275
|
+
try:
|
|
1276
|
+
import ctypes
|
|
1277
|
+
from ctypes import wintypes
|
|
1278
|
+
|
|
1279
|
+
user32 = ctypes.windll.user32
|
|
1280
|
+
hits = []
|
|
1281
|
+
|
|
1282
|
+
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
|
1283
|
+
def cb(hwnd, _lparam):
|
|
1284
|
+
try:
|
|
1285
|
+
if not user32.IsWindowVisible(hwnd):
|
|
1286
|
+
return True
|
|
1287
|
+
n = user32.GetWindowTextLengthW(hwnd)
|
|
1288
|
+
if n <= 0:
|
|
1289
|
+
return True
|
|
1290
|
+
buf = ctypes.create_unicode_buffer(n + 1)
|
|
1291
|
+
user32.GetWindowTextW(hwnd, buf, n + 1)
|
|
1292
|
+
t = buf.value or ""
|
|
1293
|
+
if ("QQ开放平台" in t) or ("q.qq.com" in t):
|
|
1294
|
+
hits.append(hwnd)
|
|
1295
|
+
except Exception:
|
|
1296
|
+
pass
|
|
1297
|
+
return True
|
|
1298
|
+
|
|
1299
|
+
user32.EnumWindows(cb, 0)
|
|
1300
|
+
for hwnd in hits:
|
|
1301
|
+
user32.ShowWindow(hwnd, 9) # SW_RESTORE
|
|
1302
|
+
user32.SetForegroundWindow(hwnd)
|
|
1303
|
+
return bool(hits)
|
|
1304
|
+
except Exception as e:
|
|
1305
|
+
log("login", f"窗口置前失败(不影响扫码): {e}", "WARN")
|
|
1306
|
+
return False
|
|
1307
|
+
|
|
1308
|
+
|
|
1309
|
+
def do_login(wait_sec: int) -> int:
|
|
1310
|
+
"""打开有窗口的 Edge,等人用手机 QQ 扫码登录。
|
|
1311
|
+
|
|
1312
|
+
- 窗口置前(SW_RESTORE + SetForegroundWindow)
|
|
1313
|
+
- 每 20s 截一张图到 logs\\qq-whitelist-shots\\
|
|
1314
|
+
- 约 110s 刷新一次页面,重开二维码(二维码有时效)
|
|
1315
|
+
成功后 cookie 就留在专用 profile 里,后面的跑法直接是 logged_in。
|
|
1316
|
+
"""
|
|
1317
|
+
from playwright.sync_api import sync_playwright
|
|
1318
|
+
|
|
1319
|
+
pre = probe_profile_cookies() # 浏览器一开就锁库,先拍快照
|
|
1320
|
+
log("login", f"启动前 cookie 快照: ok={pre.get('ok')} total={pre.get('total')} "
|
|
1321
|
+
f"qq={pre.get('qq_total')} auth={pre.get('auth')} err={pre.get('error')}")
|
|
1322
|
+
|
|
1323
|
+
with sync_playwright() as p:
|
|
1324
|
+
try:
|
|
1325
|
+
ctx, page = _open_context(p, headless=False)
|
|
1326
|
+
except Exception as e:
|
|
1327
|
+
log("login", f"启动 Edge 失败: {e}", "ERROR")
|
|
1328
|
+
return EXIT_NET_FAIL
|
|
1329
|
+
try:
|
|
1330
|
+
if not _goto_site(page):
|
|
1331
|
+
return EXIT_NET_FAIL
|
|
1332
|
+
page.wait_for_timeout(1500)
|
|
1333
|
+
front = _bring_to_front(page)
|
|
1334
|
+
log("login", "请用手机 QQ 扫码登录(机器人所属的那个 QQ 号),窗口已尽量置前"
|
|
1335
|
+
if front else "请用手机 QQ 扫码登录(机器人所属的那个 QQ 号)")
|
|
1336
|
+
log("login", f"最多等 {wait_sec}s;每 20s 截一张图;二维码过期会自动刷新重开")
|
|
1337
|
+
deadline = time.time() + wait_sec
|
|
1338
|
+
next_shot = time.time() + 20
|
|
1339
|
+
next_refresh = time.time() + 110
|
|
1340
|
+
shots = 0
|
|
1341
|
+
while time.time() < deadline:
|
|
1342
|
+
state, detail = inspect_login(page)
|
|
1343
|
+
if state == LOGIN_LOGGED:
|
|
1344
|
+
page.wait_for_timeout(2500)
|
|
1345
|
+
take_shot(page, "login-ok")
|
|
1346
|
+
try:
|
|
1347
|
+
ctx.storage_state(path=str(_state_path()))
|
|
1348
|
+
log("login", f"登录快照已保存: {_state_path()}")
|
|
1349
|
+
except Exception as e:
|
|
1350
|
+
log("login", f"保存登录快照失败(不影响本次登录): {e}", "WARN")
|
|
1351
|
+
log("login", f"LOGIN_OK 已登录({detail.get('summary')}),cookie 已保存到专用 profile")
|
|
1352
|
+
return EXIT_OK
|
|
1353
|
+
now = time.time()
|
|
1354
|
+
if now >= next_shot:
|
|
1355
|
+
shots += 1
|
|
1356
|
+
take_shot(page, f"login-wait-{shots:02d}")
|
|
1357
|
+
log("login", f"等待扫码… 判定={state},还剩 {int(deadline - now)}s(第 {shots} 张截图)")
|
|
1358
|
+
next_shot = now + 20
|
|
1359
|
+
if now >= next_refresh:
|
|
1360
|
+
log("login", "二维码可能过期,刷新页面重新生成(请扫最新那张)")
|
|
1361
|
+
try:
|
|
1362
|
+
page.reload(wait_until="domcontentloaded", timeout=30000)
|
|
1363
|
+
page.wait_for_timeout(2500)
|
|
1364
|
+
_bring_to_front(page)
|
|
1365
|
+
take_shot(page, "login-refresh")
|
|
1366
|
+
except Exception as e:
|
|
1367
|
+
log("login", f"刷新失败: {e}", "WARN")
|
|
1368
|
+
next_refresh = time.time() + 110
|
|
1369
|
+
page.wait_for_timeout(1500)
|
|
1370
|
+
take_shot(page, "login-timeout")
|
|
1371
|
+
log("login", "NEED_MANUAL_LOGIN 等待超时,仍未登录;"
|
|
1372
|
+
"随时可双击 F:\\qqbot\\scripts\\qq-whitelist-login.cmd 再来一次", "ERROR")
|
|
1373
|
+
return EXIT_NEED_LOGIN
|
|
1374
|
+
finally:
|
|
1375
|
+
try:
|
|
1376
|
+
ctx.close()
|
|
1377
|
+
except Exception:
|
|
1378
|
+
pass
|
|
1379
|
+
_release_run_lock()
|
|
1380
|
+
|
|
1381
|
+
|
|
1382
|
+
# ---------------------------------------------------------------- 入口
|
|
1383
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1384
|
+
global _run_ts
|
|
1385
|
+
ap = argparse.ArgumentParser(add_help=True)
|
|
1386
|
+
g = ap.add_mutually_exclusive_group()
|
|
1387
|
+
g.add_argument("--headless", action="store_true", help="只跑无窗口")
|
|
1388
|
+
g.add_argument("--headful", action="store_true", help="只跑有窗口")
|
|
1389
|
+
ap.add_argument("--login", action="store_true", help="人工登录模式(有窗口)")
|
|
1390
|
+
ap.add_argument("--login-wait", type=int, default=600, help="登录等待秒数,默认 600")
|
|
1391
|
+
ap.add_argument("--print-ip", action="store_true", help="只打印当前 IPv4")
|
|
1392
|
+
ap.add_argument("--dry-run", action="store_true", help="只读白名单不修改")
|
|
1393
|
+
ap.add_argument("--keep-old", action="store_true",
|
|
1394
|
+
help="保留白名单里的旧 IP(默认会删掉非当前 IP,只留最新真实 IP)")
|
|
1395
|
+
ap.add_argument("--ip", default="", help="手动指定要写进白名单的 IP(默认取本机出口 IP)")
|
|
1396
|
+
ap.add_argument("--probe", action="store_true", help="导出页面结构 JSON(校准选择器用)")
|
|
1397
|
+
ap.add_argument("--cookie-info", action="store_true", help="只探测 profile 里的登录 cookie")
|
|
1398
|
+
args = ap.parse_args(argv)
|
|
1399
|
+
|
|
1400
|
+
_run_ts = datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
1401
|
+
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
|
1402
|
+
SHOT_DIR.mkdir(parents=True, exist_ok=True)
|
|
1403
|
+
|
|
1404
|
+
if args.cookie_info:
|
|
1405
|
+
info = probe_profile_cookies(use_cache=False)
|
|
1406
|
+
print(json.dumps(info, ensure_ascii=False, indent=2))
|
|
1407
|
+
log("cookie", f"probe: ok={info['ok']} total={info['total']} qq={info['qq_total']} "
|
|
1408
|
+
f"auth={info['auth']} size={info['size']} mtime={info['mtime']} err={info['error']}")
|
|
1409
|
+
return EXIT_OK
|
|
1410
|
+
|
|
1411
|
+
if args.probe:
|
|
1412
|
+
return do_probe(headless=args.headless)
|
|
1413
|
+
|
|
1414
|
+
try:
|
|
1415
|
+
ip = args.ip.strip() if args.ip else get_current_ip(verbose=not args.print_ip)
|
|
1416
|
+
except Exception as e:
|
|
1417
|
+
log("ip", f"取 IP 失败: {e}", "ERROR")
|
|
1418
|
+
return EXIT_NET_FAIL
|
|
1419
|
+
|
|
1420
|
+
if args.print_ip:
|
|
1421
|
+
print(ip)
|
|
1422
|
+
return EXIT_OK
|
|
1423
|
+
|
|
1424
|
+
prev = read_last_ip()
|
|
1425
|
+
log("ip", f"当前 IP={ip} 上次记录={prev or '(无)'} 变化={'是' if prev and prev != ip else ('首次' if not prev else '否')}")
|
|
1426
|
+
|
|
1427
|
+
if args.login:
|
|
1428
|
+
rc_login = do_login(args.login_wait)
|
|
1429
|
+
if rc_login != EXIT_OK:
|
|
1430
|
+
return rc_login
|
|
1431
|
+
# 扫码成功:直接接着把白名单改完,省得再手工跑一遍
|
|
1432
|
+
log("login", "登录完成,继续更新 IP 白名单(有窗口模式)")
|
|
1433
|
+
args.headful = True
|
|
1434
|
+
|
|
1435
|
+
modes = [True] if args.headless else ([False] if args.headful else [True, False])
|
|
1436
|
+
rc = EXIT_NO_ELEMENT
|
|
1437
|
+
for idx, headless in enumerate(modes, 1):
|
|
1438
|
+
log("run", f"第 {idx}/{len(modes)} 次尝试 headless={headless}")
|
|
1439
|
+
rc = run_once(headless=headless, ip=ip, dry_run=args.dry_run,
|
|
1440
|
+
prune=not args.keep_old)
|
|
1441
|
+
log("run", f"第 {idx} 次结束 rc={rc}")
|
|
1442
|
+
if rc in (EXIT_OK, EXIT_NEED_LOGIN, EXIT_VERIFY_FAIL, EXIT_NET_FAIL):
|
|
1443
|
+
break
|
|
1444
|
+
if idx < len(modes):
|
|
1445
|
+
log("run", "10s 后重试")
|
|
1446
|
+
time.sleep(10)
|
|
1447
|
+
log("result", f"最终退出码 {rc}")
|
|
1448
|
+
return rc
|
|
1449
|
+
|
|
1450
|
+
|
|
1451
|
+
if __name__ == "__main__":
|
|
1452
|
+
sys.exit(main())
|