refactor(douyu): 统一腾讯角色绑定协议与状态判断

This commit is contained in:
yml
2026-11-18 10:59:20 +08:00
parent 9958e4ab7d
commit 8a58f2857d
14 changed files with 1681 additions and 215 deletions
+49 -24
View File
@@ -32,14 +32,24 @@ class DouyuActivityError(RuntimeError):
class DouyuActivityClient: class DouyuActivityClient:
"""封装斗鱼活动页、兑换、充值和送礼相关接口。""" """封装斗鱼活动页、兑换、充值和送礼相关接口。"""
TENCENT_BIND_INFO_API = (
"https://www.douyu.com/wgapi/ordnc/live/memberthird/tencent/bindInfo"
)
TENCENT_BIND_ROLE_PARAM_API = (
"https://www.douyu.com/wgapi/ordnc/live/memberthird/tencent/bindRoleParam"
)
TENCENT_ACT_BIND_API = (
"https://www.douyu.com/wgapi/ordnc/live/memberthird/tencent/actBind"
)
CSRF_API = "https://www.douyu.com/japi/carnival/nc/common/generateCsrf" CSRF_API = "https://www.douyu.com/japi/carnival/nc/common/generateCsrf"
ACF_CCN_API = "https://www.douyu.com/curl/csrfApi/getCsrfCookie?" ACF_CCN_API = "https://www.douyu.com/curl/csrfApi/getCsrfCookie?"
ACF_CCN_FALLBACK_API = "https://www.douyu.com/curl/csrfNlApi/getCsrfCookie" ACF_CCN_FALLBACK_API = "https://www.douyu.com/curl/csrfNlApi/getCsrfCookie"
SUBSCRIBE_API = "https://www.douyu.com/wgapi/livenc/asubscribe/userSubStatus" SUBSCRIBE_API = "https://www.douyu.com/wgapi/livenc/asubscribe/userSubStatus"
ROLE_PARAM_API = "https://www.douyu.com/japi/carnivalApi/v2/tencent/roleParam" ROLE_PARAM_API = TENCENT_BIND_ROLE_PARAM_API
BIND_INFO_API = "https://www.douyu.com/japi/carnivalApi/tencent/bindInfo" BIND_INFO_API = TENCENT_BIND_INFO_API
BIND_INFO_V2_API = "https://www.douyu.com/japi/carnivalApi/v2/tencent/bindInfo" BIND_INFO_V2_API = TENCENT_BIND_INFO_API
BIND_API = "https://www.douyu.com/japi/carnivalApi/tencent/bind" BIND_API = TENCENT_ACT_BIND_API
GOODS_API = "https://www.douyu.com/wgapi/ordnc/activity/peace/storehome" GOODS_API = "https://www.douyu.com/wgapi/ordnc/activity/peace/storehome"
CREATE_EXCHANGE_ORDER_API = ( CREATE_EXCHANGE_ORDER_API = (
"https://www.douyu.com/wgapi/ordnc/activity/peace/createExchangeOrder" "https://www.douyu.com/wgapi/ordnc/activity/peace/createExchangeOrder"
@@ -90,21 +100,15 @@ class DouyuActivityClient:
PEACE_ITEM_API = "https://www.douyu.com/japi/oms/web/peace/item" PEACE_ITEM_API = "https://www.douyu.com/japi/oms/web/peace/item"
PEACE_TIME_API = "https://www.douyu.com/japi/oms/web/peace/time" PEACE_TIME_API = "https://www.douyu.com/japi/oms/web/peace/time"
PAY_QR_API = "https://www.douyu.com/japi/oms/web/pay/getQrCode" PAY_QR_API = "https://www.douyu.com/japi/oms/web/pay/getQrCode"
ESPORTS_BIND_INFO_API = ( ESPORTS_BIND_INFO_API = TENCENT_BIND_INFO_API
"https://www.douyu.com/wgapi/ordnc/live/memberthird/tencent/bindInfo" ESPORTS_BIND_ROLE_PARAM_API = TENCENT_BIND_ROLE_PARAM_API
)
ESPORTS_BIND_ROLE_PARAM_API = (
"https://www.douyu.com/wgapi/ordnc/live/memberthird/tencent/bindRoleParam"
)
ESPORTS_CSRF_API = ( ESPORTS_CSRF_API = (
"https://www.douyu.com/wgapi/livenc/liveweb/csrfApi/getCsrfCookie" "https://www.douyu.com/wgapi/livenc/liveweb/csrfApi/getCsrfCookie"
) )
ESPORTS_AGREEMENT_API = ( ESPORTS_AGREEMENT_API = (
"https://www.douyu.com/wgapi/ordnc/activity/peacematch/agreement" "https://www.douyu.com/wgapi/ordnc/activity/peacematch/agreement"
) )
ESPORTS_ACT_BIND_API = ( ESPORTS_ACT_BIND_API = TENCENT_ACT_BIND_API
"https://www.douyu.com/wgapi/ordnc/live/memberthird/tencent/actBind"
)
ESPORTS_USER_INFO_API = ( ESPORTS_USER_INFO_API = (
"https://www.douyu.com/wgapi/ordnc/activity/peacematch/getUserInfo" "https://www.douyu.com/wgapi/ordnc/activity/peacematch/getUserInfo"
) )
@@ -383,10 +387,10 @@ class DouyuActivityClient:
return ctn return ctn
def get_bind_qr(self, act_alias: str) -> dict[str, Any]: def get_bind_qr(self, act_alias: str) -> dict[str, Any]:
"""生成腾讯游戏绑定二维码链接(v2 接口)。""" """按最新活动页链路生成腾讯游戏角色绑定二维码。"""
ctn = self.acf_ccn(refresh_subscribe=True) ctn = self.acf_ccn(refresh_subscribe=False)
payload = self._request_json( payload = self._request_json(
"post", "get",
self.ROLE_PARAM_API, self.ROLE_PARAM_API,
"获取绑定二维码", "获取绑定二维码",
params={"actAlias": act_alias}, params={"actAlias": act_alias},
@@ -394,10 +398,19 @@ class DouyuActivityClient:
"Referer": "https://www.douyu.com/", "Referer": "https://www.douyu.com/",
}, },
) )
url = (payload.get("data") or {}).get("url") or "" data = payload.get("data") or {}
url = data.get("url") or data.get("gameRoleBindUrl") or ""
if not url: if not url:
raise DouyuActivityError(payload.get("msg") or "获取绑定二维码失败") raise DouyuActivityError(payload.get("msg") or "获取绑定二维码失败")
return {"url": url, "ctn": ctn, "raw": payload} return {
"url": url,
"role_param_url": data.get("url") or "",
"game_role_bind_url": data.get("gameRoleBindUrl") or "",
"query_params": data.get("queryParams") or {},
"qq_app_scheme": data.get("qqAppScheme") or "",
"ctn": ctn,
"raw": payload,
}
@staticmethod @staticmethod
def _first_present(data: dict[str, Any], *keys: str): def _first_present(data: dict[str, Any], *keys: str):
@@ -499,11 +512,21 @@ class DouyuActivityClient:
"is_bound_account": str(bind_account) == "1", "is_bound_account": str(bind_account) == "1",
"is_bound_role": str(bind_role) == "1", "is_bound_role": str(bind_role) == "1",
"is_bound_act": str(bind_act) == "1", "is_bound_act": str(bind_act) == "1",
"is_granted": str(data.get("isGranted")) == "1",
"nickname": game_account.get("nick") or "", "nickname": game_account.get("nick") or "",
"account_bind_type": game_account.get("bindType") or 0,
"account_type": game_account.get("type") or "",
"account_avatar": game_account.get("faceuri") or "",
"role_name": game_role.get("roleName") or "", "role_name": game_role.get("roleName") or "",
"area_name": game_role.get("areaName") or "", "area_name": game_role.get("areaName") or "",
"plat_name": game_role.get("platName") or "", "plat_name": game_role.get("platName") or "",
"partition_name": game_role.get("partitionName") or "",
"tx_act": tx_act if isinstance(tx_act, dict) else {}, "tx_act": tx_act if isinstance(tx_act, dict) else {},
"tx_act_id": tx_act.get("txActId") or 0,
"game_id": tx_act.get("gameId") or "",
"game_name": tx_act.get("gameName") or "",
"activity_bind_type": tx_act.get("bindType") or 0,
"channel_type": tx_act.get("channelType") or 0,
"change_role_wait_time": change_role_wait_time, "change_role_wait_time": change_role_wait_time,
"can_change_role": can_change_role, "can_change_role": can_change_role,
"can_change_time": can_change_time, "can_change_time": can_change_time,
@@ -613,21 +636,23 @@ class DouyuActivityClient:
return {"agreement": agreement, "act_bind": bind} return {"agreement": agreement, "act_bind": bind}
def confirm_bind(self, act_alias: str) -> dict[str, Any]: def confirm_bind(self, act_alias: str) -> dict[str, Any]:
"""确认绑定当前扫码选择的游戏角色。""" """按最新 actBind 链路确认当前扫码选择的游戏角色。"""
token = self.csrf_token() ctn = self.acf_ccn(refresh_subscribe=False)
payload = self._request_json( payload = self._request_json(
"post", "post",
self.BIND_API, self.BIND_API,
"确认绑定", "确认绑定",
data={"actAlias": act_alias, "csrfToken": token}, files=self._multipart_fields({"actAlias": act_alias, "ctn": ctn}),
headers={ headers={
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Referer": (
"Referer": "https://www.douyu.com/", "https://www.douyu.com/pages/live-peace-handbook/web"
"?ditchname=pass0"
),
}, },
) )
if payload.get("error") not in (0, "0"): if payload.get("error") not in (0, "0"):
raise DouyuActivityError(payload.get("msg") or "确认绑定失败") raise DouyuActivityError(payload.get("msg") or "确认绑定失败")
return {"csrf_token": token, "raw": payload} return {"ctn": ctn, "raw": payload}
def create_elite_qr( def create_elite_qr(
self, *, ctn: str, act_alias: str, amount: int, room_id: str self, *, ctn: str, act_alias: str, amount: int, room_id: str
+39
View File
@@ -0,0 +1,39 @@
# 微博 CK 油猴导入
脚本:`web/userscripts/weibo-cookie-login.user.js`
## 作用
在微博网页内粘贴 CK,覆盖当前浏览器中的微博登录 Cookie,然后打开微博首页并验证 UID。脚本只处理 `weibo.com` 主域,不会把 Cookie 发到其他业务域名。
## 安装
1. 安装 Tampermonkey Beta 或脚本猫。
2. 在 Tampermonkey 管理面板中导入 `weibo-cookie-login.user.js`。
3. 打开 `https://weibo.com/`,右下角会出现钥匙按钮;也可以从 Tampermonkey 菜单选择“导入微博 CK”。
`HttpOnly` Cookie 需要 Tampermonkey Beta。稳定版 Tampermonkey 无法写入 `HttpOnly` 标记时,脚本会重试为普通 Cookie;登录态本身仍可使用,但安全性低于 Beta 版。脚本猫会通过浏览器 Cookie API 直接写入 `httpOnly` 属性。
脚本同时兼容 Tampermonkey 的 `(error)` 和脚本猫的 `(result, error)` Cookie 回调格式。脚本猫首次读写 Cookie 域时可能弹出单独的 Cookie 权限确认。
## 使用
1. 粘贴完整的 `Cookie:` 请求头值,例如包含 `SCF`、`SUB`、`SUBP`、`ALF`、`XSRF-TOKEN`、`WBPSESS`。
2. 点击“导入并登录”。
3. 脚本写入 Cookie 后跳到 `https://weibo.com/`,通过 `/ajax/statuses/config?type=uid` 显示登录成功的 UID。
脚本不会保存 CK 到 `GM_setValue`、`localStorage` 或远端接口。`GM_setValue` 只记录一次性的导入时间标记,用于跳转后做登录验证。
## Cookie 域映射
| Cookie | 域 |
| --- | --- |
| `SUB`、`SUBP`、`SCF`、`ALF` 及其他普通 Cookie | `.weibo.com` |
| `WBPSESS`、`XSRF-TOKEN` | `weibo.com` 主机级 |
| `X-CSRF-TOKEN`、`ALC` | `passport.weibo.com` 主机级 |
## 限制
- 只覆盖微博网页主站登录态,不广播到 `.weibo.cn` 或 `.sina.com.cn`,避免覆盖其他域的 SSO 值。
- CK 已过期、被微博风控或账号被强制退出时,脚本无法恢复登录,需要重新登录并导出 CK。
- “清除登录态”会删除脚本识别的微博网页 Cookie,不会删除微博账号或云端会话。
+13
View File
@@ -35,6 +35,19 @@
`DouyuActivityClient` 的只读查询方法。商品映射弹窗使用实时活动商品接口, `DouyuActivityClient` 的只读查询方法。商品映射弹窗使用实时活动商品接口,
不再依赖本地是否执行过 `refresh_goods`。 不再依赖本地是否执行过 `refresh_goods`。
腾讯游戏绑定状态只有一个业务入口:
`web/backend/services/account_binding.py`。原始接口字段由
`core/douyu/activity_client.py` 统一解析,执行器、账号刷新、外部单协作和
账号概览只能消费 `binding_snapshot()` 及其派生函数,不得各自判断
`bindRole` / `bindAct`。
2026-11-17 最新抓包确认:
- 扫码选中角色后是 `bindRole=1, bindAct=0`,业务状态为待确认;
- 调用 `actBind` 后是 `bindAct=1`,此时才是最终绑定完成;
- 绑定响应只有角色名、区服、平台、昵称和头像,没有游戏 UID / 角色 ID;
- 未最终绑定时即使接口返回换绑倒计时,也不能当成真实冷却。
选号前会调用 `web/backend/services/douyu_account_state.py` 实时刷新账号: 选号前会调用 `web/backend/services/douyu_account_state.py` 实时刷新账号:
- 不依赖 `status`、`ck_check_status`、`elite_opened`、`points` 等缓存结论; - 不依赖 `status`、`ck_check_status`、`elite_opened`、`points` 等缓存结论;
+15 -10
View File
@@ -1291,22 +1291,27 @@ class TestDeriveFromBindInfo:
== BIND_BOUND == BIND_BOUND
) )
def test_role_flag_is_the_only_signal(self): def test_bind_act_is_the_final_confirmation_signal(self):
"""**只看 is_bound_role** —— 这一列问的是「角色绑没绑」。 """最新抓包:bindRole 只是选中角色,actBind 后 bindAct 才是最终绑定。"""
曾经用 is_bound_act 做兜底("避免漏掉已绑但没回角色名的"),
那是把"活动维度"当成"角色维度"。实测那些判为 bound 的账号
**100% 都有角色名**,证明 is_bound_role 本身就够用。
"""
from web.backend.services.account_binding import ( from web.backend.services.account_binding import (
BIND_BOUND, BIND_BOUND,
BIND_PENDING,
derive_from_bind_info, derive_from_bind_info,
) )
assert (
derive_from_bind_info(
{"is_bound_role": True, "is_bound_act": False, "role_name": "x"}
)
== BIND_PENDING
)
assert derive_from_bind_info({"is_bound_role": True}) == BIND_BOUND assert derive_from_bind_info({"is_bound_role": True}) == BIND_BOUND
# 只有 act 没有 role → **推不出角色结论**,保持 unknown(别拿活动当角色) # 新接口的最终绑定以 bindAct 为准。
assert derive_from_bind_info({"is_bound_act": True}) is None assert (
assert derive_from_bind_info({"is_bound_act": "1"}) is None derive_from_bind_info({"is_bound_role": False, "is_bound_act": True})
== BIND_BOUND
)
assert derive_from_bind_info({"is_bound_act": "1"}) == BIND_BOUND
def test_unbound_when_role_flag_explicitly_false(self): def test_unbound_when_role_flag_explicitly_false(self):
from web.backend.services.account_binding import ( from web.backend.services.account_binding import (
+227
View File
@@ -0,0 +1,227 @@
"""斗鱼腾讯角色绑定的统一状态与最新 HAR 协议测试。"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from core.douyu import DouyuActivityClient
from web.backend.services.account_binding import (
BIND_BOUND,
BIND_PENDING,
BIND_UNBOUND,
binding_snapshot,
derive_from_bind_info,
is_role_change_cooling,
role_change_available_at,
)
ACT_ALIAS = "20260120QYOOB"
def _payload(
*,
bind_account: int,
bind_role: int,
bind_act: int,
role_name: str = "",
area_name: str = "",
plat_name: str = "",
wait_time: int = 0,
can_change_time: int = 0,
) -> dict[str, Any]:
return {
"error": 0,
"msg": "请求正常",
"data": {
"bindAccount": bind_account,
"bindRole": bind_role,
"bindAct": bind_act,
"needBindRole": 1,
"needBindAct": 1,
"txAct": {
"txActId": 16046,
"gameId": "cjm",
"gameName": "和平精英",
"bindType": 1,
"channelType": 3,
},
"gameAccount": (
{"bindType": 2, "type": "wx", "faceuri": "", "nick": "微信用户"}
if bind_account
else None
),
"gameRole": (
{
"roleName": role_name,
"areaName": area_name,
"platName": plat_name,
"partitionName": "",
}
if role_name
else None
),
"isGranted": 0,
"canChangeRole": 0,
"changeRoleWaitTime": wait_time,
"canChangeTime": can_change_time,
},
}
def _parse(payload: dict[str, Any]) -> dict[str, Any]:
return DouyuActivityClient("")._parse_bind_info(
payload,
act_alias=ACT_ALIAS,
api_version="v2",
)
def test_unbound_wait_time_is_not_a_real_cooldown():
parsed = _parse(
_payload(
bind_account=0,
bind_role=0,
bind_act=0,
wait_time=2_592_000,
)
)
snapshot = binding_snapshot(parsed)
assert derive_from_bind_info(parsed) == BIND_UNBOUND
assert snapshot["bind_confirmed"] is False
assert snapshot["is_change_cooling"] is False
assert is_role_change_cooling(parsed) is False
assert role_change_available_at(parsed) is None
def test_scanned_role_is_pending_until_act_bind():
parsed = _parse(
_payload(
bind_account=1,
bind_role=1,
bind_act=0,
role_name="巫师基尔斯84",
area_name="微信",
plat_name="苹果(iOS)",
wait_time=2_592_000,
)
)
snapshot = binding_snapshot(parsed)
assert derive_from_bind_info(parsed) == BIND_PENDING
assert snapshot["bind_phase"] == "role_ready"
assert snapshot["bind_ready_for_confirm"] is True
assert snapshot["bind_confirmed"] is False
assert snapshot["is_change_cooling"] is False
assert snapshot["role_name"] == "巫师基尔斯84"
assert snapshot["game_channel"] == "微信 / 苹果(iOS)"
def test_act_bind_is_the_single_final_bound_signal():
can_change_time = 1_795_449_600
parsed = _parse(
_payload(
bind_account=1,
bind_role=1,
bind_act=1,
role_name="狗鼻子弗尼亚bd",
area_name="微信",
plat_name="安卓(android)",
wait_time=539_342,
can_change_time=can_change_time,
)
)
snapshot = binding_snapshot(parsed)
available_at = role_change_available_at(
parsed,
checked_at=datetime(2026, 11, 17, tzinfo=UTC),
)
assert derive_from_bind_info(parsed) == BIND_BOUND
assert snapshot["bind_phase"] == "confirmed"
assert snapshot["bind_confirmed"] is True
assert snapshot["is_change_cooling"] is True
assert snapshot["can_change_role"] is False
assert available_at == datetime.fromtimestamp(can_change_time, tz=UTC)
def test_binding_response_has_role_identity_but_no_game_uid():
parsed = _parse(
_payload(
bind_account=1,
bind_role=1,
bind_act=1,
role_name="狗鼻子弗尼亚bd",
area_name="微信",
plat_name="安卓(android)",
wait_time=539_342,
can_change_time=1_795_449_600,
)
)
assert parsed["role_name"] == "狗鼻子弗尼亚bd"
assert parsed["area_name"] == "微信"
assert parsed["plat_name"] == "安卓(android)"
assert parsed["game_id"] == "cjm"
assert parsed["game_name"] == "和平精英"
assert not {"role_id", "game_uid", "openid", "open_id", "uin"} & parsed.keys()
def test_latest_elite_binding_endpoints_are_used_once():
assert DouyuActivityClient.ROLE_PARAM_API == (
"https://www.douyu.com/wgapi/ordnc/live/memberthird/tencent/bindRoleParam"
)
assert DouyuActivityClient.BIND_INFO_API == (
"https://www.douyu.com/wgapi/ordnc/live/memberthird/tencent/bindInfo"
)
assert DouyuActivityClient.BIND_API == (
"https://www.douyu.com/wgapi/ordnc/live/memberthird/tencent/actBind"
)
def test_qr_and_confirm_requests_follow_latest_har(monkeypatch):
calls: list[dict[str, Any]] = []
client = DouyuActivityClient("acf_ccn=ctn")
monkeypatch.setattr(
client,
"acf_ccn",
lambda *, refresh_subscribe=True: "ctn",
)
def request_json(method: str, url: str, source: str, **kwargs: Any):
calls.append(
{
"method": method,
"url": url,
"source": source,
**kwargs,
}
)
if url.endswith("/bindRoleParam"):
return {
"error": 0,
"data": {
"url": "https://livelink.example/role",
"gameRoleBindUrl": "https://livelink.example/bind",
},
}
return {"error": 0, "msg": "请求正常", "data": {}}
monkeypatch.setattr(client, "_request_json", request_json)
qr = client.get_bind_qr(ACT_ALIAS)
confirmed = client.confirm_bind(ACT_ALIAS)
assert qr["url"] == "https://livelink.example/role"
assert qr["game_role_bind_url"] == "https://livelink.example/bind"
assert confirmed["ctn"] == "ctn"
assert calls[0]["method"] == "get"
assert calls[0]["url"].endswith("/bindRoleParam")
assert calls[0]["params"] == {"actAlias": ACT_ALIAS}
assert calls[1]["method"] == "post"
assert calls[1]["url"].endswith("/actBind")
assert calls[1]["files"] == {
"actAlias": (None, ACT_ALIAS),
"ctn": (None, "ctn"),
}
+3
View File
@@ -32,6 +32,9 @@ class FakeClient:
def bind_info(self, **_): def bind_info(self, **_):
return { return {
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": True,
"role_name": "角色A", "role_name": "角色A",
"area_name": "微信", "area_name": "微信",
"plat_name": "苹果(iOS)", "plat_name": "苹果(iOS)",
+173 -59
View File
@@ -32,7 +32,7 @@
from __future__ import annotations from __future__ import annotations
from datetime import UTC, datetime from datetime import UTC, datetime, timedelta
from typing import Any from typing import Any
from ..models import Account from ..models import Account
@@ -190,85 +190,199 @@ def bind_payload(account: Account) -> dict[str, str]:
def derive_from_bind_info(info: dict | None) -> str | None: def derive_from_bind_info(info: dict | None) -> str | None:
"""从斗鱼 `bind_info` 的返回推导绑定状态;**推导不出来时返回 None**。 """从斗鱼腾讯绑定信息推导唯一业务状态。
返回 None 表示「这次查询没能得出可靠结论」—— 调用方应当**保持原值或写 最新抓包证明 `bindRole` 与 `bindAct` 不是同一阶段:
unknown**,绝不要把它当成 `unbound`。"没查到"和"没绑定"必须分开。
判定依据(字段含义见 `core/douyu/activity_client.py:_parse_bind_info`): - 扫码选中角色后:`bindRole=1, bindAct=0`,此时应为 `pending`;
- 调用 `actBind` 后:`bindAct=1`,此时才是 `bound`;
- 两个标志都是 0:明确未绑定。
- `is_bound_role` 为真 → **bound**(已经绑了角色) 兼容旧接口:如果响应里完全没有 `is_bound_act`,才回退到
- `is_bound_role` 为假 → **unbound**(接口明确说了没绑) `is_bound_role` 判断。新接口始终会带上 `is_bound_act`。
- 缺失(接口没给 / 解析失败)→ **None**(推不出来,别猜)
⚠️ **只看 `is_bound_role`,不掺 `is_bound_act`。**
这一列问的是「**角色**绑没绑」,而**「活动是否开通/参与」和「是否绑定角色」
是两件独立的事**(用户明确指出的领域事实)。生产实测也印证了:
电竞 opened=False 且 bind=bound → 187 个账号
也就是说这 187 个账号**绑了角色、但手册压根没开通**。
曾经用 `is_bound_act` 做兜底("避免漏掉已绑但没回角色名的"),
那是把"活动维度"当成了"角色维度" —— 一旦有账号 `is_bound_act=True`
而角色未绑,就会报出"角色已绑定"的**错结论**。实测没触发过,
但语义是错的,所以去掉。(当时那些判为 bound 的账号 100% 都有角色名,
证明 `is_bound_role` 本身就够用。)
⚠️ 这里刻意**不产出 pending**:`pending` 描述的是"正在绑定/待确认"这种
**进行中的动作**(例如刚生成过绑定二维码),那是一次查询的**副作用**,
不是查询能观测到的状态。硬用查询结果去推 pending 就是编造。
""" """
if not isinstance(info, dict): if not isinstance(info, dict):
return None return None
bound_act = _explicit_flag(info.get("is_bound_act"))
def flag(key: str) -> bool | None: bound_role = _explicit_flag(info.get("is_bound_role"))
value = info.get(key) role_name = _binding_role_name(info)
if value is None: if bound_act is True:
return None return BIND_BOUND
if isinstance(value, bool): if bound_act is False:
return value if bound_role is True or bool(role_name):
text = str(value).strip().lower() return BIND_PENDING
if text in {"1", "true", "yes", "y"}: return BIND_UNBOUND
return True # 旧接口没有 is_bound_act,保留原行为。
if text in {"0", "false", "no", "n", ""}:
return False
return None
bound_role = flag("is_bound_role")
if bound_role is True: if bound_role is True:
return BIND_BOUND return BIND_BOUND
if bound_role is False: if bound_role is False:
return BIND_UNBOUND return BIND_UNBOUND
# 接口没给结论:保持 unknown,别把"没查到"写成"没绑定"
return None return None
def is_role_change_cooling(info: dict | None) -> bool: def is_confirmed_binding(info: dict | None) -> bool:
"""是否处于真实换绑冷却:已有绑定角色且当前不可换绑。""" """是否已经完成最终绑定。
新接口以 `bindAct=1` 为准;旧接口缺少该字段时才回退到 `bindRole`。
"""
if not isinstance(info, dict): if not isinstance(info, dict):
return False return False
role_name = str(info.get("role_name") or info.get("role") or "").strip() bound_act = _explicit_flag(info.get("is_bound_act"))
if not role_name or not _truthy_flag(info.get("is_bound_act")): if bound_act is not None:
return False return bound_act
if str(info.get("api_version") or "") == "esports": return _explicit_flag(info.get("is_bound_role")) is True
can_change_time = _to_int(info.get("can_change_time"))
if can_change_time is not None:
return can_change_time > int(datetime.now(UTC).timestamp()) def is_bound_act(info: dict | None) -> bool:
"""接口原始 `bindAct` 标志,仅供绑定状态机和候选筛选使用。"""
return isinstance(info, dict) and _explicit_flag(info.get("is_bound_act")) is True
def can_change_role(info: dict | None, *, now: datetime | None = None) -> bool:
"""是否允许换绑。未绑定状态永远不受接口倒计时影响。"""
if not is_confirmed_binding(info):
return True
assert isinstance(info, dict)
moment = now or datetime.now(UTC)
can_change_time = _to_int(info.get("can_change_time"))
if can_change_time is not None and can_change_time > 0:
return can_change_time <= int(moment.timestamp())
wait_time = _to_int(info.get("change_role_wait_time")) wait_time = _to_int(info.get("change_role_wait_time"))
if wait_time is not None and wait_time > 0: if wait_time is not None and wait_time > 0:
return False
raw_can_change = _explicit_flag(info.get("can_change_role"))
if raw_can_change is not None:
return raw_can_change
return True
def is_role_change_cooling(
info: dict | None,
*,
now: datetime | None = None,
) -> bool:
"""是否处于真实换绑冷却:最终绑定已完成且当前不可换绑。"""
return is_confirmed_binding(info) and not can_change_role(info, now=now)
def role_change_available_at(
info: dict | None,
*,
checked_at: datetime | None = None,
) -> datetime | None:
"""统一的换绑可用时间;未确认绑定或没有冷却时返回 None。"""
if not is_role_change_cooling(info, now=checked_at):
return None
assert isinstance(info, dict)
moment = checked_at or datetime.now(UTC)
can_change_time = _to_int(info.get("can_change_time"))
if can_change_time is not None and can_change_time > 0:
return datetime.fromtimestamp(can_change_time, tz=UTC)
wait_time = _to_int(info.get("change_role_wait_time"))
if wait_time is not None and wait_time > 0:
return moment + timedelta(seconds=wait_time)
return None
def is_pending_binding_role(
info: dict | None,
*,
baseline_role_name: str = "",
baseline_is_bound_act: bool = False,
) -> bool:
"""是否出现了可确认的扫码角色。"""
if not isinstance(info, dict):
return False
snapshot = binding_snapshot(info)
role_name = snapshot["role_name"]
if not role_name:
return False
if snapshot["is_bound_act"]:
return bool(baseline_role_name) and role_name != baseline_role_name
if snapshot["need_bind_act"] or snapshot["need_bind_role"]:
if not baseline_role_name:
return True
return role_name != baseline_role_name or baseline_is_bound_act
if not baseline_role_name:
return True return True
if info.get("can_change_role") is not None: if role_name != baseline_role_name:
return not _truthy_flag(info.get("can_change_role")) return True
return False return baseline_is_bound_act
def binding_channel(info: dict | None) -> str:
"""统一游戏渠道展示:区服 / 平台。"""
if not isinstance(info, dict):
return ""
return " / ".join(
part
for part in (
str(info.get("area_name") or "").strip(),
str(info.get("plat_name") or "").strip(),
)
if part
)
def binding_snapshot(info: dict | None) -> dict[str, Any]:
"""斗鱼腾讯绑定的唯一业务快照,供执行器、账号刷新和概览复用。"""
data = info if isinstance(info, dict) else {}
role_name = _binding_role_name(data)
bound_status = derive_from_bind_info(data)
phase = {
BIND_BOUND: "confirmed",
BIND_PENDING: "role_ready",
BIND_UNBOUND: "unbound",
}.get(bound_status or "", "unknown")
bound_act = _explicit_flag(data.get("is_bound_act")) is True
return {
"role_name": role_name,
"area_name": str(data.get("area_name") or "").strip(),
"plat_name": str(data.get("plat_name") or "").strip(),
"partition_name": str(data.get("partition_name") or "").strip(),
"game_channel": binding_channel(data),
"nickname": str(data.get("nickname") or "").strip(),
"account_type": str(data.get("account_type") or "").strip(),
"account_avatar": str(data.get("account_avatar") or "").strip(),
"is_bound_account": _truthy_flag(data.get("is_bound_account")),
"is_bound_role": _truthy_flag(data.get("is_bound_role")),
"is_bound_act": bound_act,
"need_bind_act": _truthy_flag(data.get("need_bind_act")),
"need_bind_role": _truthy_flag(data.get("need_bind_role")),
"change_role_wait_time": _to_int(data.get("change_role_wait_time")),
"can_change_time": _to_int(data.get("can_change_time")),
"can_change_role": can_change_role(data),
"is_change_cooling": is_role_change_cooling(data),
"bind_status": bound_status,
"bind_phase": phase,
"bind_confirmed": bound_status == BIND_BOUND,
"bind_ready_for_confirm": bound_status == BIND_PENDING and bool(role_name),
"game_id": str(data.get("game_id") or "").strip(),
"game_name": str(data.get("game_name") or "").strip(),
"tx_act_id": _to_int(data.get("tx_act_id")) or 0,
"bind_info": data,
}
def _binding_role_name(info: dict) -> str:
return str(info.get("role_name") or info.get("role") or "").strip()
def _explicit_flag(value: Any) -> bool | None:
if value is None or value == "":
return None
if isinstance(value, bool):
return value
text = str(value).strip().lower()
if text in {"1", "true", "yes", "y"}:
return True
if text in {"0", "false", "no", "n", ""}:
return False
return None
def _truthy_flag(value: Any) -> bool: def _truthy_flag(value: Any) -> bool:
if value is True: return _explicit_flag(value) is True
return True
if value is False or value is None:
return False
return str(value).strip().lower() in {"1", "true", "yes", "y"}
def _to_int(value: Any) -> int | None: def _to_int(value: Any) -> int | None:
+10 -19
View File
@@ -9,7 +9,7 @@ from __future__ import annotations
from collections.abc import Callable from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime
from typing import Any from typing import Any
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -19,8 +19,9 @@ from core.douyu import DouyuActivityClient
from ..models import Account from ..models import Account
from .account_binding import ( from .account_binding import (
SCOPE_ELITE, SCOPE_ELITE,
derive_from_bind_info, binding_snapshot,
is_role_change_cooling, is_role_change_cooling,
role_change_available_at,
set_bind_status, set_bind_status,
) )
from .account_lifecycle import on_ck_verdict from .account_lifecycle import on_ck_verdict
@@ -235,30 +236,20 @@ def _apply_bind_state(
*, *,
checked_at: datetime, checked_at: datetime,
) -> datetime | None: ) -> datetime | None:
derived = derive_from_bind_info(bind_info) snapshot = binding_snapshot(bind_info)
derived = snapshot["bind_status"]
if derived is not None: if derived is not None:
set_bind_status(account, SCOPE_ELITE, derived) set_bind_status(account, SCOPE_ELITE, derived)
role_name = str(bind_info.get("role_name") or bind_info.get("role") or "").strip() role_name = snapshot["role_name"]
if role_name: if role_name:
account.game_name = role_name[:128] account.game_name = role_name[:128]
area_name = str(bind_info.get("area_name") or "").strip() channel = snapshot["game_channel"]
plat_name = str(bind_info.get("plat_name") or "").strip()
channel = " · ".join(item for item in (area_name, plat_name) if item)
if channel: if channel:
account.game_channel = channel[:128] account.game_channel = channel.replace(" / ", " · ")[:128]
wait_seconds = _to_int(bind_info.get("change_role_wait_time")) account.change_role_wait_time = snapshot["change_role_wait_time"]
can_change_time = _to_int(bind_info.get("can_change_time")) available_at = role_change_available_at(bind_info, checked_at=checked_at)
account.change_role_wait_time = wait_seconds
if not is_role_change_cooling(bind_info):
available_at = None
elif can_change_time is not None and can_change_time > 0:
available_at = datetime.fromtimestamp(can_change_time, tz=UTC)
elif wait_seconds is not None and wait_seconds > 0:
available_at = checked_at + timedelta(seconds=wait_seconds)
else:
available_at = account.role_change_available_at
account.role_change_available_at = available_at account.role_change_available_at = available_at
return available_at return available_at
@@ -15,6 +15,7 @@ from typing import Any
from core.douyu import DouyuActivityClient from core.douyu import DouyuActivityClient
from core.douyu.cookie_utils import cookie_value from core.douyu.cookie_utils import cookie_value
from .account_binding import binding_snapshot
from .douyu_goods_service import serialize_goods from .douyu_goods_service import serialize_goods
ERROR_MAX_LENGTH = 240 ERROR_MAX_LENGTH = 240
@@ -275,6 +276,7 @@ def query_account_overview(
return { return {
"elite": elite, "elite": elite,
"bind": bind, "bind": bind,
"bind_snapshot": binding_snapshot(bind),
"gold": gold, "gold": gold,
"goods": goods, "goods": goods,
"serialized_goods": [serialize_goods(item) for item in goods], "serialized_goods": [serialize_goods(item) for item in goods],
+8 -5
View File
@@ -297,6 +297,7 @@ def _probe_with_client(
) )
elite = overview["elite"] elite = overview["elite"]
bind = overview["bind"] bind = overview["bind"]
bind_snapshot = overview["bind_snapshot"]
gold = overview["gold"] gold = overview["gold"]
goods = overview["serialized_goods"] goods = overview["serialized_goods"]
error_labels = { error_labels = {
@@ -315,13 +316,13 @@ def _probe_with_client(
expire_time = _to_int(elite.get("expire_time")) expire_time = _to_int(elite.get("expire_time"))
user_info = elite.get("user_info") or {} user_info = elite.get("user_info") or {}
profile = DouyuActivityClient.profile_from_cookie(str(account.cookie or "")) profile = DouyuActivityClient.profile_from_cookie(str(account.cookie or ""))
bind_role = _text(bind.get("role_name"), max_length=128) bind_role = _text(bind_snapshot["role_name"], max_length=128)
area_name = _text(bind.get("area_name"), max_length=64) area_name = _text(bind_snapshot["area_name"], max_length=64)
plat_name = _text(bind.get("plat_name"), max_length=64) plat_name = _text(bind_snapshot["plat_name"], max_length=64)
bind_channel = " · ".join(item for item in (area_name, plat_name) if item) bind_channel = " · ".join(item for item in (area_name, plat_name) if item)
bind_account = _text(bind.get("nickname"), max_length=128) bind_account = _text(bind_snapshot["nickname"], max_length=128)
ck_status = CK_VALID if (elite or bind) else CK_INVALID ck_status = CK_VALID if (elite or bind) else CK_INVALID
ok = bool(bind_role) and not (elite == {} and bind == {}) ok = bool(bind_snapshot["bind_confirmed"]) and not (elite == {} and bind == {})
return { return {
"found": True, "found": True,
@@ -340,6 +341,8 @@ def _probe_with_client(
"manual_score": manual_score, "manual_score": manual_score,
"expire_time": expire_time, "expire_time": expire_time,
"manual_opened": bool(manual_type is not None and manual_type >= 1), "manual_opened": bool(manual_type is not None and manual_type >= 1),
"bind_status": bind_snapshot["bind_status"],
"bind_phase": bind_snapshot["bind_phase"],
"bind_game_account": bind_account, "bind_game_account": bind_account,
"bind_game_role": bind_role, "bind_game_role": bind_role,
"bind_game_channel": bind_channel, "bind_game_channel": bind_channel,
+24 -88
View File
@@ -17,7 +17,11 @@ from .account_binding import (
BIND_UNBOUND, BIND_UNBOUND,
SCOPE_ELITE, SCOPE_ELITE,
SCOPE_ESPORTS, SCOPE_ESPORTS,
binding_snapshot,
is_bound_act,
is_pending_binding_role,
is_role_change_cooling, is_role_change_cooling,
role_change_available_at,
set_bind_status, set_bind_status,
) )
from .business_events import record_bind from .business_events import record_bind
@@ -106,45 +110,9 @@ class BindMixin:
aliases.append(alias) aliases.append(alias)
return aliases return aliases
@staticmethod
def _role_channel(bind_info: dict) -> str:
return " / ".join(
part
for part in [bind_info.get("area_name"), bind_info.get("plat_name")]
if part
)
@staticmethod
def _is_truthy_flag(value) -> bool:
if value is True:
return True
if value is False or value is None:
return False
text = str(value).strip().lower()
return text in {"1", "true", "yes", "y"}
@classmethod @classmethod
def _is_bound_act(cls, bind_info: dict | None) -> bool: def _is_bound_act(cls, bind_info: dict | None) -> bool:
if not bind_info: return is_bound_act(bind_info)
return False
return cls._is_truthy_flag(bind_info.get("is_bound_act"))
@classmethod
def _can_change_role(cls, bind_info: dict | None) -> bool:
"""综合 can_change_role 与换绑倒计时判断是否允许换绑。"""
if not bind_info:
return True
if str(bind_info.get("api_version") or "") == "esports":
can_change_time = cls._to_int(bind_info.get("can_change_time"))
if can_change_time is not None:
return can_change_time <= int(datetime.now(UTC).timestamp())
wait_time = cls._to_int(bind_info.get("change_role_wait_time"))
if wait_time is not None and wait_time > 0:
return False
if bind_info.get("can_change_role") is not None:
return cls._is_truthy_flag(bind_info.get("can_change_role"))
# 已绑定但接口没给倒计时/开关时,默认允许(避免误杀首次绑定)
return True
@classmethod @classmethod
def _is_change_cooling(cls, bind_info: dict | None) -> bool: def _is_change_cooling(cls, bind_info: dict | None) -> bool:
@@ -168,47 +136,14 @@ class BindMixin:
4. need_bind_act / need_bind_role 且角色相对 baseline 有变化,算 pending 4. need_bind_act / need_bind_role 且角色相对 baseline 有变化,算 pending
5. 无 baseline 且未绑定但有角色,视为待确认残留 5. 无 baseline 且未绑定但有角色,视为待确认残留
""" """
if not bind_info: return is_pending_binding_role(
return False bind_info,
role_name = str(bind_info.get("role_name") or "").strip() baseline_role_name=baseline_role_name,
if not role_name: baseline_is_bound_act=baseline_is_bound_act,
return False )
is_bound_act = cls._is_bound_act(bind_info)
need_bind_act = cls._is_truthy_flag(bind_info.get("need_bind_act"))
need_bind_role = cls._is_truthy_flag(bind_info.get("need_bind_role"))
role_changed = bool(baseline_role_name) and role_name != baseline_role_name
if is_bound_act:
# 已绑定:仅当相对 baseline 角色发生变化时才视为新扫码结果
return role_changed
if need_bind_act or need_bind_role:
if not baseline_role_name:
return True
return role_changed or baseline_is_bound_act
if not baseline_role_name:
return True
if role_changed:
return True
# 同一角色从已绑定变为未绑定
return baseline_is_bound_act
def _bind_snapshot(self, bind_info: dict | None) -> dict: def _bind_snapshot(self, bind_info: dict | None) -> dict:
info = bind_info or {} return binding_snapshot(bind_info)
role_name = str(info.get("role_name") or "")
return {
"role_name": role_name,
"area_name": info.get("area_name") or "",
"plat_name": info.get("plat_name") or "",
"nickname": info.get("nickname") or "",
"is_bound_act": self._is_bound_act(info),
"is_bound_role": self._is_truthy_flag(info.get("is_bound_role")),
"is_bound_account": self._is_truthy_flag(info.get("is_bound_account")),
"need_bind_act": self._is_truthy_flag(info.get("need_bind_act")),
"need_bind_role": self._is_truthy_flag(info.get("need_bind_role")),
"change_role_wait_time": self._to_int(info.get("change_role_wait_time")),
"can_change_time": self._to_int(info.get("can_change_time")),
"can_change_role": self._can_change_role(info),
"bind_info": info,
}
def _format_bind_summary( def _format_bind_summary(
self, bind_info: dict | None, *, pending: bool | None = None self, bind_info: dict | None, *, pending: bool | None = None
@@ -241,12 +176,14 @@ class BindMixin:
(`query_game_name` 等)就该这样:它们**没有资格**改变绑定状态。 (`query_game_name` 等)就该这样:它们**没有资格**改变绑定状态。
传值时只能是 `account_binding` 的四个枚举。 传值时只能是 `account_binding` 的四个枚举。
""" """
role_name = str(bind_info.get("role_name") or "") snapshot = binding_snapshot(bind_info)
role_name = snapshot["role_name"]
account.game_name = role_name or account.game_name account.game_name = role_name or account.game_name
account.game_channel = self._role_channel(bind_info) or account.game_channel account.game_channel = (
account.change_role_wait_time = self._to_int( snapshot["game_channel"].replace(" / ", " · ") or account.game_channel
bind_info.get("change_role_wait_time")
) )
account.change_role_wait_time = snapshot["change_role_wait_time"]
account.role_change_available_at = role_change_available_at(bind_info)
if state is not None: if state is not None:
set_bind_status(account, SCOPE_ELITE, state) set_bind_status(account, SCOPE_ELITE, state)
account.updated_at = datetime.now(UTC) account.updated_at = datetime.now(UTC)
@@ -255,15 +192,15 @@ class BindMixin:
self, account: Account, bind_info: dict, state: str | None = None self, account: Account, bind_info: dict, state: str | None = None
) -> None: ) -> None:
"""将电竞手册角色状态写入专属字段,避免覆盖精英宝典数据。""" """将电竞手册角色状态写入专属字段,避免覆盖精英宝典数据。"""
role_name = str(bind_info.get("role_name") or "") snapshot = binding_snapshot(bind_info)
role_name = snapshot["role_name"]
account.esports_game_name = role_name or account.esports_game_name account.esports_game_name = role_name or account.esports_game_name
account.esports_game_channel = ( account.esports_game_channel = (
self._role_channel(bind_info) or account.esports_game_channel snapshot["game_channel"].replace(" / ", " · ")
or account.esports_game_channel
) )
account.esports_change_role_wait_time = self._to_int( account.esports_change_role_wait_time = snapshot["change_role_wait_time"]
bind_info.get("change_role_wait_time") account.esports_can_change_time = snapshot["can_change_time"]
)
account.esports_can_change_time = self._to_int(bind_info.get("can_change_time"))
if state is not None: if state is not None:
set_bind_status(account, SCOPE_ESPORTS, state) set_bind_status(account, SCOPE_ESPORTS, state)
account.updated_at = datetime.now(UTC) account.updated_at = datetime.now(UTC)
@@ -278,12 +215,11 @@ class BindMixin:
activity_snapshot = self._bind_snapshot(activity_info) activity_snapshot = self._bind_snapshot(activity_info)
esports_bound = activity_snapshot["is_bound_act"] esports_bound = activity_snapshot["is_bound_act"]
has_selected_role = bool(activity_snapshot["role_name"]) has_selected_role = bool(activity_snapshot["role_name"])
tx_act = activity_info.get("tx_act") or {}
return { return {
**activity_snapshot, **activity_snapshot,
"is_bound_role": has_selected_role, "is_bound_role": has_selected_role,
"act_alias": act_alias, "act_alias": act_alias,
"game_id": tx_act.get("gameId") or "", "game_id": activity_snapshot["game_id"],
"esports_bound": esports_bound, "esports_bound": esports_bound,
"has_selected_role": has_selected_role, "has_selected_role": has_selected_role,
"bind_ready_for_confirm": has_selected_role and not esports_bound, "bind_ready_for_confirm": has_selected_role and not esports_bound,
+16 -10
View File
@@ -33,7 +33,7 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient from core.douyu import DouyuActivityClient
from ..models import Account, DouyuTask from ..models import Account, DouyuTask
from .account_binding import derive_from_bind_info, set_bind_status from .account_binding import binding_snapshot, set_bind_status
from .business_events import record_official_exchange from .business_events import record_official_exchange
from .douyu_activity_query import ( from .douyu_activity_query import (
query_activity_goods, query_activity_goods,
@@ -367,8 +367,8 @@ class OverviewMixin:
# #
# 这三个值以前**从来没人查过** —— 只是 S6 迁移时从旧的垃圾场列 # 这三个值以前**从来没人查过** —— 只是 S6 迁移时从旧的垃圾场列
# `bind_status` 能推的推、推不出的留 `unknown`,于是界面上 97% 显示"未知"。 # `bind_status` 能推的推、推不出的留 `unknown`,于是界面上 97% 显示"未知"。
# 实测校准:开发库 4 个账号里 3 个其实**已绑定**(`is_bound_role=True` 且有角色名), # 实测校准:最终绑定以 `bindAct=1` 为准;只识别到 `bindRole=1`
# 全被 unknown 盖住了。 # 但尚未 actBind 的账号必须保持 pending。
# 和平小店总开关:关着时**完全跳过**它的所有请求。 # 和平小店总开关:关着时**完全跳过**它的所有请求。
# 小店目前是关闭状态,不跳过的话每个账号都会产生一条 # 小店目前是关闭状态,不跳过的话每个账号都会产生一条
# "Livelink登录态校验失败"(实测 200 个里失败 195 次,100%), # "Livelink登录态校验失败"(实测 200 个里失败 195 次,100%),
@@ -394,17 +394,23 @@ class OverviewMixin:
continue continue
try: try:
info = self._fetch_bind_info(client, scope, alias) info = self._fetch_bind_info(client, scope, alias)
derived = derive_from_bind_info(info) snapshot = binding_snapshot(info)
derived = snapshot["bind_status"]
# 把**明细**也带上:运营要看的是"绑的哪个角色、哪个区服、 # 把**明细**也带上:运营要看的是"绑的哪个角色、哪个区服、
# 什么时候能换绑",不是一个"已绑定"就完事。 # 什么时候能换绑",不是一个"已绑定"就完事。
overview["bind"][scope] = { overview["bind"][scope] = {
"derived": derived, "derived": derived,
"role_name": str(info.get("role_name") or info.get("role") or ""), "phase": snapshot["bind_phase"],
"area_name": str(info.get("area_name") or ""), "role_name": snapshot["role_name"],
"plat_name": str(info.get("plat_name") or ""), "area_name": snapshot["area_name"],
"nickname": str(info.get("nickname") or ""), "plat_name": snapshot["plat_name"],
"change_role_wait_time": _ts(info.get("change_role_wait_time")), "nickname": snapshot["nickname"],
"can_change_time": _ts(info.get("can_change_time")), "game_id": snapshot["game_id"],
"game_name": snapshot["game_name"],
"is_change_cooling": snapshot["is_change_cooling"],
"can_change_role": snapshot["can_change_role"],
"change_role_wait_time": _ts(snapshot["change_role_wait_time"]),
"can_change_time": _ts(snapshot["can_change_time"]),
} }
if derived is not None: if derived is not None:
# 唯一写入者;推不出来(None)时**不动原值** —— 宁可留 unknown, # 唯一写入者;推不出来(None)时**不动原值** —— 宁可留 unknown,
+144
View File
@@ -0,0 +1,144 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const {
parseCookieText,
cookieExpiration,
planCookieWrite,
writeCookies,
} = require('./weibo-cookie-login.user.js');
test('解析 Cookie 请求头、Set-Cookie 属性与重复字段', () => {
const entries = parseCookieText(`
Cookie: SCF=fake-scf; SUB=fake-sub==; SUBP=fake-subp
Path=/
Domain=.weibo.com
WBPSESS=fake-session; HttpOnly; Secure; SameSite=None
SUB=fake-sub-last
`);
const values = new Map(entries);
assert.equal(values.get('SCF'), 'fake-scf');
assert.equal(values.get('SUB'), 'fake-sub-last');
assert.equal(values.get('SUBP'), 'fake-subp');
assert.equal(values.get('WBPSESS'), 'fake-session');
assert.equal(values.has('Path'), false);
assert.equal(values.has('Domain'), false);
assert.equal(values.has('HttpOnly'), false);
});
test('拒绝空输入、无登录字段和非法 Cookie 名称', () => {
assert.throws(() => parseCookieText(''), /请先粘贴/);
assert.throws(() => parseCookieText('foo=bar'), /未找到微博登录 Cookie/);
assert.throws(() => parseCookieText('SUB=x; bad name=x'), /名称格式错误/);
});
test('按微博真实域属性规划 Cookie', () => {
const now = 1_800_000_000;
const sub = planCookieWrite('SUB', 'fake-sub', now);
const session = planCookieWrite('WBPSESS', 'fake-session', now);
const passportToken = planCookieWrite('X-CSRF-TOKEN', 'fake-token', now);
assert.equal(sub.domain, '.weibo.com');
assert.equal(sub.url, 'https://weibo.com/');
assert.equal(sub.httpOnly, true);
assert.equal(sub.sameSite, 'no_restriction');
assert.equal('domain' in session, false);
assert.equal(session.httpOnly, true);
assert.equal(session.expirationDate, now + 86400);
assert.equal(passportToken.url, 'https://passport.weibo.com/');
assert.equal('domain' in passportToken, false);
assert.equal(passportToken.httpOnly, false);
});
test('Cookie 有效期按微博用途区分', () => {
const now = 1_800_000_000;
assert.equal(cookieExpiration('WBPSESS', now), now + 86400);
assert.equal(cookieExpiration('ALF', now), now + 30 * 86400);
assert.equal(cookieExpiration('SUB', now), now + 365 * 86400);
assert.equal(cookieExpiration('XSRF-TOKEN', now), now + 365 * 86400);
});
test('优先使用 GM_cookie 写入完整 Cookie 属性', async () => {
const calls = [];
globalThis.GM_cookie = {
set(details, callback) {
calls.push(details);
callback();
},
};
try {
const result = await writeCookies([
['SUB', 'fake-sub'],
['WBPSESS', 'fake-session'],
]);
assert.deepEqual(result.written, ['SUB', 'WBPSESS']);
assert.deepEqual(result.failures, []);
assert.deepEqual(result.modes, ['GM_cookie']);
assert.equal(calls.length, 2);
assert.equal(calls[0].domain, '.weibo.com');
assert.equal(calls[0].httpOnly, true);
assert.equal('domain' in calls[1], false);
assert.equal(calls[1].httpOnly, true);
} finally {
delete globalThis.GM_cookie;
}
});
test('稳定版拒绝 HttpOnly 时自动降级重试', async () => {
const calls = [];
globalThis.GM_cookie = {
set(details, callback) {
calls.push(details);
callback(details.httpOnly ? 'HttpOnly is not supported' : undefined);
},
};
try {
const result = await writeCookies([['SUB', 'fake-sub']]);
assert.deepEqual(result.written, ['SUB']);
assert.deepEqual(result.failures, []);
assert.equal(calls.length, 2);
assert.equal(calls[0].httpOnly, true);
assert.equal(calls[1].httpOnly, false);
} finally {
delete globalThis.GM_cookie;
}
});
test('兼容脚本猫 GM_cookie 的 (result, error) 回调', async () => {
globalThis.GM_cookie = {
set(details, callback) {
callback(undefined, details.httpOnly ? 'HttpOnly rejected' : undefined);
},
};
try {
const result = await writeCookies([['SUB', 'fake-sub']]);
assert.deepEqual(result.written, ['SUB']);
assert.deepEqual(result.failures, []);
assert.deepEqual(result.modes, ['GM_cookie']);
} finally {
delete globalThis.GM_cookie;
}
});
test('脚本猫 GM_cookie 返回真实错误时不会误判成功', async () => {
globalThis.GM_cookie = {
set(details, callback) {
callback(undefined, new Error('permission denied'));
},
};
try {
await assert.rejects(
writeCookies([['SUB', 'fake-sub']]),
/GM_cookie 与页面 Cookie 均写入失败/,
);
} finally {
delete globalThis.GM_cookie;
}
});
+958
View File
@@ -0,0 +1,958 @@
// ==UserScript==
// @name 微博 CK 登录助手
// @namespace live-hub-py/weibo-cookie-login
// @version 1.0.1
// @description 在微博网页内导入 CK,覆盖微博域登录 Cookie,并验证当前 UID。
// @author live-hub-py
// @license MIT
// @match https://weibo.com/*
// @match https://www.weibo.com/*
// @match https://passport.weibo.com/*
// @grant GM_cookie
// @grant GM_registerMenuCommand
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @noframes
// @run-at document-end
// ==/UserScript==
(() => {
'use strict';
const VERIFY_KEY = 'weiboCkLoginVerifyAt';
const VERIFY_WINDOW_MS = 2 * 60 * 1000;
const MAIN_COOKIE_URL = 'https://weibo.com/';
const PASSPORT_COOKIE_URL = 'https://passport.weibo.com/';
const AUTH_COOKIE_NAMES = new Set([
'SUB',
'SUBP',
'SCF',
'ALF',
'WBPSESS',
'XSRF-TOKEN',
'X-CSRF-TOKEN',
'ALC',
'SSOLoginState',
'SRF',
'SUHB',
]);
const LOGIN_MARKER_NAMES = ['SUB', 'SUBP', 'SCF', 'WBPSESS'];
const HOST_ONLY_MAIN_COOKIES = new Set(['WBPSESS', 'XSRF-TOKEN']);
const HOST_ONLY_PASSPORT_COOKIES = new Set(['ALC', 'X-CSRF-TOKEN']);
const HTTP_ONLY_COOKIES = new Set([
'SUB',
'SUBP',
'SCF',
'ALF',
'WBPSESS',
'ALC',
'SSOLoginState',
'SRF',
'SUHB',
]);
const SET_COOKIE_ATTRIBUTES = new Set([
'domain',
'path',
'expires',
'max-age',
'secure',
'httponly',
'samesite',
'priority',
'partitioned',
]);
const COOKIE_NAME_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
function parseCookieText(raw) {
let text = String(raw || '').trim();
if (!text) throw new Error('请先粘贴微博 Cookie');
text = text.replace(/^cookie:\s*/i, '').replace(/\r/g, '\n');
const pairs = new Map();
for (const fragment of text.split(/[;\n]+/)) {
const part = fragment.trim();
if (!part) continue;
const separator = part.indexOf('=');
if (separator < 0) {
if (SET_COOKIE_ATTRIBUTES.has(part.toLowerCase())) continue;
throw new Error(`Cookie 片段格式错误:${part.slice(0, 32)}`);
}
const name = part.slice(0, separator).trim();
const value = part.slice(separator + 1).trim();
if (SET_COOKIE_ATTRIBUTES.has(name.toLowerCase())) continue;
if (!COOKIE_NAME_RE.test(name)) {
throw new Error(`Cookie 名称格式错误:${name.slice(0, 32)}`);
}
if (AUTH_COOKIE_NAMES.has(name) && !value) {
throw new Error(`Cookie ${name} 的值为空`);
}
pairs.set(name, value);
}
if (!pairs.size) throw new Error('没有识别到 Cookie');
if (!LOGIN_MARKER_NAMES.some((name) => pairs.has(name))) {
throw new Error('未找到微博登录 Cookie(SUB/SUBP/SCF/WBPSESS)');
}
return [...pairs.entries()];
}
function cookieExpiration(name, nowSeconds = Math.floor(Date.now() / 1000)) {
const days = name === 'WBPSESS' ? 1 : name === 'ALF' ? 30 : 365;
return nowSeconds + days * 86400;
}
function planCookieWrite(name, value, nowSeconds = Math.floor(Date.now() / 1000)) {
const details = {
url: MAIN_COOKIE_URL,
name,
value,
path: '/',
secure: true,
sameSite: 'no_restriction',
httpOnly: HTTP_ONLY_COOKIES.has(name),
expirationDate: cookieExpiration(name, nowSeconds),
};
if (HOST_ONLY_PASSPORT_COOKIES.has(name)) {
details.url = PASSPORT_COOKIE_URL;
} else if (!HOST_ONLY_MAIN_COOKIES.has(name)) {
details.domain = '.weibo.com';
}
return details;
}
function planCookieWrites(entries, nowSeconds = Math.floor(Date.now() / 1000)) {
return entries.map(([name, value]) => planCookieWrite(name, value, nowSeconds));
}
function gmCookieAvailable() {
return (
typeof GM_cookie !== 'undefined' &&
GM_cookie &&
typeof GM_cookie.set === 'function'
);
}
function gmCookieSet(details) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Cookie 写入超时')), 5000);
try {
GM_cookie.set(details, function (result, callbackError) {
clearTimeout(timer);
// Tampermonkey 回调为 (error),脚本猫为 (result, error)。
const error = arguments.length >= 2 ? callbackError : result;
if (error) {
reject(new Error(String(error.message || error)));
} else {
resolve();
}
});
} catch (error) {
clearTimeout(timer);
reject(error);
}
});
}
function gmCookieList(details) {
return new Promise((resolve, reject) => {
if (
typeof GM_cookie === 'undefined' ||
!GM_cookie ||
typeof GM_cookie.list !== 'function'
) {
reject(new Error('当前油猴版本不支持 GM_cookie.list'));
return;
}
const timer = setTimeout(() => reject(new Error('Cookie 读取超时')), 5000);
try {
GM_cookie.list(details, (cookies, error) => {
clearTimeout(timer);
if (error) {
reject(new Error(String(error.message || error)));
} else {
resolve(Array.isArray(cookies) ? cookies : []);
}
});
} catch (error) {
clearTimeout(timer);
reject(error);
}
});
}
function gmCookieDelete(details) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Cookie 删除超时')), 5000);
try {
GM_cookie.delete(details, function (result, callbackError) {
clearTimeout(timer);
// Tampermonkey 回调为 (error),脚本猫为 (result, error)。
const error = arguments.length >= 2 ? callbackError : result;
if (error) {
reject(new Error(String(error.message || error)));
} else {
resolve();
}
});
} catch (error) {
clearTimeout(timer);
reject(error);
}
});
}
function uniqueAttempts(details) {
const attempts = [details];
if (details.httpOnly) attempts.push({ ...details, httpOnly: false });
attempts.push({ ...details, httpOnly: false, sameSite: undefined });
const seen = new Set();
return attempts.filter((attempt) => {
const clean = Object.fromEntries(
Object.entries(attempt).filter(([, value]) => value !== undefined),
);
const key = JSON.stringify(clean);
if (seen.has(key)) return false;
seen.add(key);
Object.keys(attempt).forEach((name) => {
if (attempt[name] === undefined) delete attempt[name];
});
return true;
});
}
function setWithTampermonkey(details) {
return (async () => {
let lastError = null;
for (const attempt of uniqueAttempts({ ...details })) {
try {
await gmCookieSet(attempt);
return;
} catch (error) {
lastError = error;
}
}
throw lastError || new Error('GM_cookie 写入失败');
})();
}
function visibleCookieValue(name) {
for (const fragment of document.cookie.split(';')) {
const part = fragment.trim();
const separator = part.indexOf('=');
if (separator < 0) continue;
if (part.slice(0, separator).trim() === name) {
return part.slice(separator + 1);
}
}
return null;
}
function fallbackCookieDomain(details) {
if (details.domain) return details.domain;
const hostname = location.hostname.toLowerCase();
const targetHost = new URL(details.url).hostname;
if (hostname === targetHost) return '';
if (targetHost === 'weibo.com' || targetHost.endsWith('.weibo.com')) {
return '.weibo.com';
}
return '';
}
function setWithDocumentCookie(details) {
const domain = fallbackCookieDomain(details);
const attributes = [
`${details.name}=${details.value}`,
'Path=/',
'Secure',
'SameSite=None',
`Expires=${new Date(details.expirationDate * 1000).toUTCString()}`,
];
if (domain) attributes.push(`Domain=${domain}`);
document.cookie = attributes.join('; ');
if (visibleCookieValue(details.name) === null) {
throw new Error('浏览器拒绝了 Cookie 写入');
}
}
async function writeOneCookie(details) {
let gmError = null;
if (gmCookieAvailable()) {
try {
await setWithTampermonkey(details);
return 'GM_cookie';
} catch (error) {
gmError = error;
}
}
try {
setWithDocumentCookie(details);
return 'document.cookie';
} catch (error) {
if (gmError) {
throw new Error(`GM_cookie 与页面 Cookie 均写入失败:${error.message}`);
}
throw error;
}
}
async function writeCookies(entries) {
const plans = planCookieWrites(entries);
const written = [];
const failures = [];
const modes = new Set();
for (const details of plans) {
try {
const mode = await writeOneCookie(details);
written.push(details.name);
modes.add(mode);
} catch (error) {
failures.push({ name: details.name, message: error.message });
}
}
if (!written.length) {
throw new Error(failures[0]?.message || '没有 Cookie 写入成功');
}
return { written, failures, modes: [...modes] };
}
async function clearWeiboCookies() {
if (!window.confirm('清除微博网页登录 Cookie?这不会删除微博账号。')) return false;
let removed = 0;
if (gmCookieAvailable()) {
for (const url of [MAIN_COOKIE_URL, PASSPORT_COOKIE_URL]) {
let cookies = [];
try {
cookies = await gmCookieList({ url });
} catch (error) {
continue;
}
for (const cookie of cookies) {
if (!AUTH_COOKIE_NAMES.has(cookie.name)) continue;
const hostname = String(cookie.domain || '').replace(/^\./, '');
if (!hostname) continue;
const cookieUrl = new URL(cookie.path || '/', `https://${hostname}/`).href;
try {
await gmCookieDelete({ url: cookieUrl, name: cookie.name });
removed += 1;
} catch (error) {
// 单个 Cookie 删除失败时继续清理其余项。
}
}
}
}
if (!removed) {
const expires = 'Thu, 01 Jan 1970 00:00:00 GMT';
for (const name of AUTH_COOKIE_NAMES) {
document.cookie = `${name}=; Path=/; Secure; SameSite=None; Expires=${expires}`;
document.cookie = `${name}=; Path=/; Domain=.weibo.com; Secure; SameSite=None; Expires=${expires}`;
}
}
clearVerifyMarker();
return true;
}
function setVerifyMarker() {
if (typeof GM_setValue === 'function') {
GM_setValue(VERIFY_KEY, Date.now());
}
}
function readVerifyMarker() {
if (typeof GM_getValue !== 'function') return 0;
return Number(GM_getValue(VERIFY_KEY, 0)) || 0;
}
function clearVerifyMarker() {
if (typeof GM_deleteValue === 'function') {
GM_deleteValue(VERIFY_KEY);
}
}
async function readCurrentUid() {
const response = await fetch(
'https://weibo.com/ajax/statuses/config?type=uid',
{
credentials: 'include',
cache: 'no-store',
headers: { Accept: 'application/json' },
},
);
if (!response.ok) throw new Error(`微博返回 HTTP ${response.status}`);
const payload = await response.json();
const uid = String(payload?.data || '').trim();
if (payload?.ok === 1 && /^\d+$/.test(uid)) return uid;
throw new Error('微博未返回登录 UID');
}
function navigateToWeiboHome() {
const home = new URL(MAIN_COOKIE_URL);
if (
location.origin === home.origin &&
location.pathname === '/' &&
!location.search
) {
location.reload();
return;
}
location.assign(home.href);
}
const ICONS = {
key: `
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M2.59 17.41A2 2 0 0 0 2 18.83V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.17a2 2 0 0 0 1.42-.59l.81-.81a6.5 6.5 0 1 0-4-4z"/>
<circle cx="16.5" cy="7.5" r=".5" fill="currentColor"/>
</svg>`,
close: `
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M18 6 6 18"/><path d="m6 6 12 12"/>
</svg>`,
login: `
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>
<path d="m10 17 5-5-5-5"/><path d="M15 12H3"/>
</svg>`,
trash: `
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M3 6h18"/><path d="M8 6V4h8v2"/>
<path d="m19 6-1 14H6L5 6"/><path d="M10 11v5"/><path d="M14 11v5"/>
</svg>`,
check: `
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="9"/><path d="m8 12 2.5 2.5L16 9"/>
</svg>`,
alert: `
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="9"/><path d="M12 8v5"/><path d="M12 16h.01"/>
</svg>`,
spinner: `
<svg class="spin" viewBox="0 0 24 24" aria-hidden="true">
<path d="M21 12a9 9 0 1 1-6.22-8.56"/>
</svg>`,
};
function init() {
const host = document.createElement('div');
host.id = 'weibo-ck-login-host';
host.style.cssText =
'all: initial; position: fixed; inset: 0; z-index: 2147483647; pointer-events: none;';
(document.documentElement || document.body).appendChild(host);
const shadow = host.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
:host {
color-scheme: light dark;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
letter-spacing: 0;
}
*, *::before, *::after { box-sizing: border-box; }
[hidden] { display: none !important; }
button, textarea { font: inherit; }
button { letter-spacing: 0; }
svg {
width: 18px;
height: 18px;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
flex: 0 0 auto;
}
.launcher {
pointer-events: auto;
position: fixed;
right: 24px;
bottom: 24px;
width: 48px;
height: 48px;
border: 1px solid #cbd5e1;
border-radius: 50%;
background: #ffffff;
color: #0a67d1;
box-shadow: 0 10px 28px rgba(15, 23, 42, .20);
display: grid;
place-items: center;
cursor: pointer;
}
.launcher:hover { background: #eef5ff; border-color: #8bb8ed; }
.launcher:focus-visible, .icon-button:focus-visible, .button:focus-visible {
outline: 3px solid rgba(10, 103, 209, .28);
outline-offset: 2px;
}
.launcher svg { width: 22px; height: 22px; }
.overlay {
pointer-events: auto;
position: fixed;
inset: 0;
display: grid;
place-items: center;
padding: 16px;
background: rgba(15, 23, 42, .48);
backdrop-filter: blur(3px);
}
.dialog {
width: min(560px, calc(100vw - 32px));
max-height: calc(100vh - 32px);
overflow: auto;
border: 1px solid #d8dee9;
border-radius: 8px;
background: #ffffff;
color: #172033;
box-shadow: 0 24px 70px rgba(15, 23, 42, .30);
}
.header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
padding: 20px 20px 16px;
border-bottom: 1px solid #e6ebf2;
}
.title-wrap { display: flex; align-items: center; gap: 11px; min-width: 0; }
.title-icon {
width: 34px;
height: 34px;
border-radius: 8px;
display: grid;
place-items: center;
color: #0a67d1;
background: #eaf3ff;
}
h2 {
margin: 0;
font-size: 17px;
line-height: 1.35;
font-weight: 650;
color: #172033;
}
.subtitle {
margin: 3px 0 0;
color: #64748b;
font-size: 12px;
line-height: 1.45;
}
.icon-button {
width: 34px;
height: 34px;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
color: #64748b;
display: grid;
place-items: center;
cursor: pointer;
flex: 0 0 auto;
}
.icon-button:hover { background: #f1f5f9; color: #172033; }
.body { padding: 18px 20px 20px; }
label {
display: block;
margin-bottom: 8px;
font-size: 13px;
font-weight: 600;
color: #334155;
}
textarea {
display: block;
width: 100%;
min-height: 178px;
resize: vertical;
border: 1px solid #cbd5e1;
border-radius: 6px;
padding: 11px 12px;
background: #fbfdff;
color: #172033;
caret-color: #0a67d1;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 12px;
line-height: 1.55;
overflow-wrap: anywhere;
}
textarea::placeholder { color: #94a3b8; }
textarea:focus {
outline: none;
border-color: #79aee8;
box-shadow: 0 0 0 3px rgba(10, 103, 209, .12);
background: #ffffff;
}
.status {
min-height: 24px;
margin-top: 10px;
display: flex;
align-items: flex-start;
gap: 7px;
color: #64748b;
font-size: 12px;
line-height: 1.5;
}
.status[data-type="success"] { color: #16794b; }
.status[data-type="error"] { color: #b42318; }
.status[data-type="working"] { color: #0a67d1; }
.status svg { width: 16px; height: 16px; margin-top: 1px; }
.privacy {
margin: 9px 0 0;
color: #7b8799;
font-size: 11px;
line-height: 1.5;
}
.actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 18px;
}
.action-group { display: flex; align-items: center; gap: 9px; }
.button {
min-height: 38px;
border: 1px solid transparent;
border-radius: 6px;
padding: 0 14px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 7px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
white-space: nowrap;
}
.button:disabled { cursor: not-allowed; opacity: .55; }
.button.primary { background: #0a67d1; color: #ffffff; }
.button.primary:hover:not(:disabled) { background: #0859b4; }
.button.secondary {
border-color: #cbd5e1;
background: #ffffff;
color: #334155;
}
.button.secondary:hover:not(:disabled) { background: #f8fafc; border-color: #94a3b8; }
.button.danger {
border-color: transparent;
background: transparent;
color: #b42318;
padding-left: 9px;
padding-right: 9px;
}
.button.danger:hover:not(:disabled) { background: #fff1f0; }
.spin { animation: spin .8s linear infinite; }
.toast {
pointer-events: auto;
position: fixed;
top: 22px;
left: 50%;
transform: translateX(-50%);
width: max-content;
max-width: min(520px, calc(100vw - 32px));
border: 1px solid #cbd5e1;
border-radius: 8px;
padding: 11px 14px;
background: #ffffff;
color: #172033;
box-shadow: 0 12px 35px rgba(15, 23, 42, .22);
display: flex;
align-items: flex-start;
gap: 8px;
font-size: 13px;
line-height: 1.45;
}
.toast[data-type="success"] { border-color: #a7d8bf; color: #12633d; }
.toast[data-type="error"] { border-color: #f0b8b3; color: #9f261b; }
.toast svg { margin-top: 1px; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-color-scheme: dark) {
.launcher, .dialog, .toast { background: #172033; color: #e8eef7; }
.launcher { border-color: #475569; color: #78b4ff; }
.launcher:hover { background: #22304a; border-color: #6d9fe0; }
.dialog { border-color: #3c4b63; }
.header { border-bottom-color: #2d3a50; }
.title-icon { background: #203a5d; color: #78b4ff; }
h2, label { color: #e8eef7; }
.subtitle, .status, .privacy { color: #a8b5c8; }
.icon-button { color: #a8b5c8; }
.icon-button:hover { background: #22304a; color: #ffffff; }
textarea { background: #111b2c; border-color: #475569; color: #e8eef7; }
textarea:focus { background: #0f1928; border-color: #6d9fe0; }
.button.secondary { background: #172033; border-color: #475569; color: #d8e2f0; }
.button.secondary:hover:not(:disabled) { background: #22304a; }
.button.danger:hover:not(:disabled) { background: #3a2025; }
.toast { border-color: #475569; }
}
@media (max-width: 520px) {
.launcher { right: 16px; bottom: 16px; }
.overlay { padding: 10px; }
.dialog { width: calc(100vw - 20px); max-height: calc(100vh - 20px); }
.header { padding: 17px 16px 14px; }
.body { padding: 16px; }
.actions { align-items: stretch; flex-direction: column-reverse; }
.action-group { display: grid; grid-template-columns: 1fr 1fr; }
.button.danger { grid-column: 1 / -1; }
}
@media (prefers-reduced-motion: reduce) {
.spin { animation-duration: 1.8s; }
}
</style>
<button class="launcher" type="button" title="导入微博 CK" aria-label="导入微博 CK"></button>
<div class="overlay" hidden>
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="weibo-ck-title">
<header class="header">
<div class="title-wrap">
<div class="title-icon" aria-hidden="true">${ICONS.key}</div>
<div>
<h2 id="weibo-ck-title">导入微博 CK</h2>
<p class="subtitle">写入当前浏览器的微博登录态</p>
</div>
</div>
<button class="icon-button close" type="button" title="关闭" aria-label="关闭"></button>
</header>
<div class="body">
<label for="weibo-cookie-input">Cookie</label>
<textarea id="weibo-cookie-input" spellcheck="false" autocomplete="off"
placeholder="SCF=...; SUB=...; SUBP=...; ALF=...; WBPSESS=..."></textarea>
<div class="status" role="status" aria-live="polite"></div>
<p class="privacy">Cookie 只用于当前浏览器的微博域,不会保存到脚本存储或发送到其他站点。</p>
<div class="actions">
<button class="button danger clear" type="button"></button>
<div class="action-group">
<button class="button secondary close" type="button">取消</button>
<button class="button primary import" type="button"></button>
</div>
</div>
</div>
</section>
</div>
<div class="toast" role="status" aria-live="polite" hidden></div>
`;
const overlay = shadow.querySelector('.overlay');
const dialog = shadow.querySelector('.dialog');
const launcher = shadow.querySelector('.launcher');
const textarea = shadow.querySelector('textarea');
const status = shadow.querySelector('.status');
const importButton = shadow.querySelector('.import');
const clearButton = shadow.querySelector('.clear');
const toast = shadow.querySelector('.toast');
const closeButtons = shadow.querySelectorAll('.close');
let busy = false;
let statusTimer = null;
let toastTimer = null;
launcher.innerHTML = ICONS.key;
clearButton.innerHTML = `${ICONS.trash}<span>清除登录态</span>`;
importButton.innerHTML = `${ICONS.login}<span>导入并登录</span>`;
closeButtons.forEach((button) => {
button.innerHTML = button.classList.contains('icon-button')
? ICONS.close
: '取消';
});
function setStatus(message = '', type = 'info', icon = '') {
clearTimeout(statusTimer);
status.dataset.type = type;
status.replaceChildren();
if (!message) return;
const iconName = icon || (type === 'error' ? 'alert' : type === 'success' ? 'check' : '');
if (iconName && ICONS[iconName]) {
const iconWrap = document.createElement('span');
iconWrap.innerHTML = ICONS[iconName];
status.appendChild(iconWrap.firstElementChild);
}
const text = document.createElement('span');
text.textContent = message;
status.appendChild(text);
}
function showToast(message, type = 'info', duration = 7000) {
clearTimeout(toastTimer);
toast.dataset.type = type;
toast.replaceChildren();
const iconWrap = document.createElement('span');
iconWrap.innerHTML = type === 'error' ? ICONS.alert : ICONS.check;
toast.appendChild(iconWrap.firstElementChild);
const text = document.createElement('span');
text.textContent = message;
toast.appendChild(text);
toast.hidden = false;
toastTimer = setTimeout(() => {
toast.hidden = true;
}, duration);
}
function openPanel() {
if (!overlay.hidden) {
textarea.focus();
return;
}
overlay.hidden = false;
setStatus('');
requestAnimationFrame(() => textarea.focus());
}
function closePanel(force = false) {
if (busy && !force) return;
overlay.hidden = true;
textarea.value = '';
setStatus('');
}
function setBusy(nextBusy) {
busy = nextBusy;
importButton.disabled = nextBusy;
clearButton.disabled = nextBusy;
textarea.disabled = nextBusy;
closeButtons.forEach((button) => {
button.disabled = nextBusy;
});
}
function validateInput(showEmpty = false) {
const raw = textarea.value;
if (!raw.trim()) {
importButton.disabled = busy;
if (showEmpty) setStatus('请先粘贴微博 Cookie', 'error');
else setStatus('');
return null;
}
try {
const entries = parseCookieText(raw);
importButton.disabled = busy;
setStatus(`已识别 ${entries.length} 个 Cookie`, 'info');
return entries;
} catch (error) {
importButton.disabled = true;
if (showEmpty) setStatus(error.message, 'error');
else setStatus('');
return null;
}
}
async function importAndLogin() {
if (busy) return;
let entries = null;
try {
entries = parseCookieText(textarea.value);
} catch (error) {
setStatus(error.message, 'error');
return;
}
setBusy(true);
setStatus(`正在写入 ${entries.length} 个 Cookie...`, 'working', 'spinner');
try {
const result = await writeCookies(entries);
textarea.value = '';
const mode = result.modes.includes('GM_cookie') ? 'GM_cookie' : '页面 Cookie';
if (result.failures.length) {
const names = result.failures.slice(0, 4).map((item) => item.name).join('、');
setStatus(
`已写入 ${result.written.length} 个,${result.failures.length} 个失败:${names}`,
'error',
);
} else {
setStatus(`已通过 ${mode} 写入 ${result.written.length} 个 Cookie`, 'success');
}
setVerifyMarker();
statusTimer = setTimeout(navigateToWeiboHome, 550);
} catch (error) {
setStatus(error.message, 'error');
} finally {
setBusy(false);
}
}
async function clearLogin() {
if (busy) return;
setBusy(true);
setStatus('正在清除微博登录 Cookie...', 'working', 'spinner');
try {
const removed = await clearWeiboCookies();
if (removed) {
setStatus('已清除微博网页登录态', 'success');
statusTimer = setTimeout(() => location.reload(), 500);
}
} catch (error) {
setStatus(`清除失败:${error.message}`, 'error');
} finally {
setBusy(false);
}
}
let inputTimer = null;
textarea.addEventListener('input', () => {
clearTimeout(inputTimer);
inputTimer = setTimeout(() => validateInput(false), 180);
});
textarea.addEventListener('keydown', (event) => {
event.stopPropagation();
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
event.preventDefault();
importAndLogin();
}
if (event.key === 'Escape') closePanel();
});
overlay.addEventListener('click', (event) => {
if (event.target === overlay) closePanel();
});
dialog.addEventListener('click', (event) => event.stopPropagation());
launcher.addEventListener('click', openPanel);
importButton.addEventListener('click', importAndLogin);
clearButton.addEventListener('click', clearLogin);
closeButtons.forEach((button) => button.addEventListener('click', () => closePanel()));
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && !overlay.hidden) closePanel();
});
if (typeof GM_registerMenuCommand === 'function') {
GM_registerMenuCommand('导入微博 CK', openPanel);
GM_registerMenuCommand('清除微博网页登录态', clearLogin);
}
async function verifyPendingLogin() {
if (location.hostname !== 'weibo.com') return;
const marker = readVerifyMarker();
if (!marker) return;
clearVerifyMarker();
if (Date.now() - marker > VERIFY_WINDOW_MS) return;
await new Promise((resolve) => setTimeout(resolve, 450));
try {
const uid = await readCurrentUid();
showToast(`微博登录成功,UID ${uid}`, 'success', 10000);
} catch (error) {
showToast(`Cookie 未生效或已过期:${error.message}`, 'error', 12000);
}
}
verifyPendingLogin();
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
parseCookieText,
cookieExpiration,
planCookieWrite,
planCookieWrites,
writeCookies,
};
} else if (typeof document !== 'undefined') {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init, { once: true });
} else {
init();
}
}
})();