diff --git a/README.md b/README.md index d7b6493..a293630 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 直播账号运营后台 -斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.29)。 +斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.31)。 ## 能做什么 diff --git a/core/weibo/client.py b/core/weibo/client.py index 5176ffe..4c7a0dc 100644 --- a/core/weibo/client.py +++ b/core/weibo/client.py @@ -12,6 +12,7 @@ from __future__ import annotations import json +import math import secrets import time from dataclasses import dataclass @@ -37,7 +38,9 @@ WEIBO_DESKTOP_UA = ( "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/156.0.0.0 Safari/537.36" ) -WEIBO_AUTH_ERROR_CODES = {100002, 100004, 400000, 400002} +# 实测确认:100002 是参数/校验错误(msg=参数错误,如 GoodsID required),不是登录失效; +# 真实未登录是 400002(msg=未登陆)。因此 100002 不能进入鉴权失效集合。 +WEIBO_AUTH_ERROR_CODES = {100004, 400000, 400002} class WeiboError(RuntimeError): @@ -232,6 +235,49 @@ def normalize_weibo_image_url(value: Any) -> str: return text +def _as_int(value: Any) -> int | None: + """把微博返回的数字字段解析成 int;缺失或无法解析时返回 None。 + + 兑换预检不能用 ``int(x or 0)``:缺失字段被当成 0 会掩盖接口异常, + 导致“0 价格/0 余额”这类假数据通过校验。 + """ + + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, float): + # 小数不能被截断成整数,否则 100.9 会绕过 expected_price 校验。 + if math.isfinite(value) and value.is_integer(): + return int(value) + return None + if not isinstance(value, str): + return None + text = value.strip() + if not text: + return None + try: + return int(text) + except ValueError: + return None + + +def _is_truthy_clickable(value: Any) -> bool: + """判断 ``payment_button.clickable`` 是否表示“可点击”。 + + 微博这个字段在不同端/版本上可能是 ``True``、``1`` 或字符串 + ``"1"``/``"true"``;用 ``is True`` 会把后者误判成不可兑换。 + """ + + if isinstance(value, bool): + return value + if isinstance(value, int): + return value == 1 + if isinstance(value, str): + return value.strip().lower() in {"1", "true"} + return False + + def _parse_cookie_pairs(cookie: str) -> dict[str, str]: pairs: dict[str, str] = {} for item in cookie.split(";"): @@ -332,6 +378,7 @@ class WeiboClient: params: dict[str, Any] | None = None, data: dict[str, Any] | None = None, json: dict[str, Any] | None = None, + timeout: float | None = None, ) -> dict[str, Any]: response: requests.Response | None = None try: @@ -342,7 +389,7 @@ class WeiboClient: params=params, data=data, json=json, - timeout=self.timeout, + timeout=self.timeout if timeout is None else timeout, ) response.raise_for_status() payload = response.json() @@ -424,6 +471,7 @@ class WeiboClient: data: dict[str, Any] | None = None, headers: dict[str, str] | None = None, base: str = WEIBO_API_BASE, + timeout: float | None = None, ) -> dict[str, Any]: payload = self._request_json( method, @@ -431,6 +479,7 @@ class WeiboClient: params=params, data=data, headers=headers, + timeout=timeout, ) code = payload.get("code") if code in WEIBO_AUTH_ERROR_CODES: @@ -494,13 +543,16 @@ class WeiboClient: activity=resolved_activity, ) - def list_mall(self, activity: str = "") -> dict[str, Any]: + def list_mall( + self, activity: str = "", *, timeout: float | None = None + ) -> dict[str, Any]: """查询微豆商城商品列表。""" payload = self._weibo_api( "GET", "/mall/list", params={"F": activity, "_t": int(time.time() * 1000)}, + timeout=timeout, ) data = payload.get("data") or {} if not isinstance(data, dict): @@ -520,6 +572,127 @@ class WeiboClient: normalized_goods.append(normalized) return {**data, "list": normalized_goods} + def _xsrf_headers(self) -> dict[str, str]: + """兑换接口需要带上 Cookie 里的 XSRF-TOKEN 作为 ``x-xsrf-token``。 + + 不用 ``cookies.get("XSRF-TOKEN")``:Jar 同时存在 ``.weibo.com`` 与 + ``vipclub.e.weibo.com`` 同名 Cookie 时会抛 ``CookieConflictError``。 + 这里只取与目标域匹配、且 domain 最具体(最长)的那个。 + 缺失时不硬性拒绝,兼容历史 CK 里没有该 Cookie 的情况。 + """ + + host = (urlsplit(WEIBO_API_BASE).hostname or "").lower() + best_token = "" + best_domain_len = -1 + for cookie in self.session.cookies: + if cookie.name != "XSRF-TOKEN": + continue + token = (cookie.value or "").strip() + if not token: + continue + domain = (cookie.domain or "").strip().lstrip(".").lower() + if not domain: + continue + if not (host == domain or host.endswith("." + domain)): + continue + if len(domain) > best_domain_len: + best_domain_len = len(domain) + best_token = token + if best_token: + return {"x-xsrf-token": best_token} + return {} + + def _fetch_goods_detail(self, goods_id: int, activity: str) -> dict[str, Any]: + """兑换前读取商品详情,用于价格、余额、库存和按钮状态预检。""" + + payload = self._weibo_api( + "GET", + "/mall/detail", + params={ + "F": activity, + "goods_id": goods_id, + "_t": int(time.time() * 1000), + }, + headers={"_failtoast": "true"}, + ) + data = payload.get("data") or {} + return data if isinstance(data, dict) else {} + + def _submit_exchange(self, goods_id: int, activity: str) -> dict[str, Any]: + """提交一次兑换请求(POST + form)。 + + 真实接口是 ``POST /aj/game/exchangegoods``,Query 与 Body 都带 + ``F``、``goods_id``、``_t``,并需要 ``x-xsrf-token``、``Origin``、 + ``Referer`` 和 ``_failtoast``。用 GET 会得到 ``400404`` 迷路页。 + 失败分类顺序敏感:连接超时可以安全认为未提交,其余网络错误结果未知。 + """ + + timestamp = int(time.time() * 1000) + params = {"F": activity, "goods_id": goods_id, "_t": timestamp} + headers = { + "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", + "Origin": "https://vipclub.e.weibo.com", + "Referer": f"https://vipclub.e.weibo.com/game/mall?F={activity}", + "_failtoast": "true", + **self._xsrf_headers(), + } + try: + response = self.session.post( + f"{WEIBO_API_BASE}/game/exchangegoods", + params=params, + data=params, + headers=headers, + timeout=self.timeout, + ) + except requests.exceptions.ConnectTimeout as exc: + raise WeiboExchangeError("连接微博超时,兑换未提交,可稍后重试") from exc + except requests.RequestException as exc: + raise WeiboExchangeUncertainError( + "兑换请求已发出,但网络中断导致结果未知;请先查兑换记录,不要立即重试" + ) from exc + + if response.status_code >= 500: + raise WeiboExchangeUncertainError( + f"微博兑换接口返回 HTTP {response.status_code},兑换结果未知;" + "请先查兑换记录,不要立即重试" + ) + if response.status_code >= 400: + raise WeiboExchangeError( + f"兑换未提交:微博兑换接口返回 HTTP {response.status_code}" + ) + + try: + payload = response.json() + except (requests.exceptions.JSONDecodeError, ValueError) as exc: + text = unescape(str(getattr(response, "text", "") or "")) + if "retcode=6102" in text or "/sso/login.php" in text: + raise WeiboAuthError( + "微博支付/活动域登录态已失效(retcode=6102)," + "请重新登录微博后重新导入 CK" + ) from exc + raise WeiboExchangeUncertainError( + "兑换请求已发出,但微博返回非 JSON,兑换结果未知;" + "请先查兑换记录,不要立即重试" + ) from exc + if not isinstance(payload, dict): + raise WeiboExchangeUncertainError( + "兑换请求已发出,但微博返回结构异常,兑换结果未知;" + "请先查兑换记录,不要立即重试" + ) + code = payload.get("code") + # code 必须是 int(bool 是 int 子类,需单独排除)。缺失/类型异常说明微博 + # 返回结构不可信,无法判定是否已扣微豆,只能按"结果未知"处理。 + if isinstance(code, bool) or not isinstance(code, int): + raise WeiboExchangeUncertainError( + "兑换请求已发出,但微博返回结构异常,兑换结果未知;" + "请先查兑换记录,不要立即重试" + ) + if code in WEIBO_AUTH_ERROR_CODES: + raise WeiboAuthError(str(payload.get("msg") or "微博 CK 已失效")) + if code != 100000: + raise WeiboExchangeError(str(payload.get("msg") or f"兑换失败 code={code}")) + return payload + def exchange_goods( self, goods_id: int, @@ -527,91 +700,93 @@ class WeiboClient: expected_price: int, activity: str = "", ) -> WeiboExchangeResult: - """手动兑换商品:预检后只提交一次,成功后尽力复核。""" + """手动兑换商品:详情预检后只提交一次,成功后尽力复核。""" - before = self.list_mall(activity) - goods_list = before.get("list") or [] - goods = next( - ( - item - for item in goods_list - if isinstance(item, dict) and int(item.get("id") or 0) == goods_id - ), - None, - ) - if goods is None: - raise WeiboExchangeError("商品不存在或已下架") - price = int(goods.get("price") or 0) - balance_before = int(before.get("weidou_balance") or 0) - remain_before = ( - int(goods["remain_count"]) - if goods.get("remain_count") is not None - else None - ) + try: + detail = self._fetch_goods_detail(goods_id, activity) + except WeiboAuthError: + raise + except WeiboError as exc: + raise WeiboExchangeError( + f"兑换前无法确认商品状态,已取消本次兑换: {exc}" + ) from exc + + raw_goods_info = detail.get("goods_info") + goods_info = raw_goods_info if isinstance(raw_goods_info, dict) else {} + raw_button = detail.get("payment_button") + payment_button = raw_button if isinstance(raw_button, dict) else {} + + price = _as_int(goods_info.get("price")) + balance_before = _as_int(detail.get("weidou_balance")) + remain_before = _as_int(goods_info.get("remain_count")) + if price is None or balance_before is None or remain_before is None: + raise WeiboExchangeError("微博未返回商品价格/微豆余额/库存,已取消兑换") + if not payment_button: + raise WeiboExchangeError( + "微博未返回兑换按钮状态,已取消兑换(接口结构可能变化)" + ) + if str(payment_button.get("type")).strip() != "exchange": + raise WeiboExchangeError( + "微博未返回可用的兑换按钮类型,已取消兑换(接口结构可能变化)" + ) + if not _is_truthy_clickable(payment_button.get("clickable")): + button_text = str(payment_button.get("text") or "").strip() + if button_text and button_text != "立即兑换": + raise WeiboExchangeError(button_text) + raise WeiboExchangeError( + "微博当前不允许兑换该商品(可能已达单人/单日上限或库存不足)" + ) if expected_price > 0 and price != expected_price: raise WeiboExchangeError( f"商品价格已变化:页面 {expected_price},当前 {price}" ) - if goods.get("is_sold_out") or remain_before == 0: + if remain_before == 0: raise WeiboExchangeError("商品库存不足") if balance_before < price: raise WeiboExchangeError( f"微豆余额不足:当前 {balance_before},需要 {price}" ) - try: - payload = self._weibo_api( - "GET", - "/game/exchangegoods", - params={ - "F": activity, - "goods_id": goods_id, - "_t": int(time.time() * 1000), - }, - headers={ - "User-Agent": WEIBO_DESKTOP_UA, - "Referer": f"https://vipclub.e.weibo.com/game/mall?F={activity}", - }, - ) - except WeiboTransportError as exc: - raise WeiboExchangeUncertainError( - "兑换请求已发出,但网络中断导致结果未知;请先查兑换记录,不要立即重试" - ) from exc - if payload.get("code") != 100000: - raise WeiboExchangeError( - str(payload.get("msg") or f"兑换失败 code={payload.get('code')}") - ) + self._submit_exchange(goods_id, activity) balance_after: int | None = None remain_after: int | None = None verified = False verify_error = "" try: - after = self.list_mall(activity) - balance_after = int(after.get("weidou_balance") or 0) - refreshed = next( - ( - item - for item in (after.get("list") or []) - if isinstance(item, dict) and int(item.get("id") or 0) == goods_id - ), - None, - ) - if refreshed and refreshed.get("remain_count") is not None: - remain_after = int(refreshed["remain_count"]) - verified = balance_after != balance_before or ( - remain_after is not None - and remain_before is not None - and remain_after != remain_before - ) + # 余额入账可能有延迟:最多复核 3 次,仅在余额未变化时重试。 + for attempt in range(3): + after = self.list_mall(activity, timeout=min(self.timeout, 8.0)) + after_balance = _as_int(after.get("weidou_balance")) + refreshed = next( + ( + item + for item in (after.get("list") or []) + if isinstance(item, dict) + and _as_int(item.get("id")) == goods_id + ), + None, + ) + remain_after = ( + _as_int(refreshed.get("remain_count")) + if isinstance(refreshed, dict) + else None + ) + if after_balance is not None and after_balance != balance_before: + balance_after = after_balance + break + if attempt < 2: + time.sleep(0.4) + verified = balance_after is not None and balance_after != balance_before if not verified: - verify_error = "兑换成功,但余额和库存暂未变化,请查兑换记录复核" + # 库存变化只作附带信息,不能单独证明兑换成功。 + verify_error = "兑换已提交,但微豆余额暂未变化,请查兑换记录复核" except (WeiboError, ValueError, TypeError) as exc: verify_error = f"兑换已提交,但复核失败: {exc}" return WeiboExchangeResult( goods_id=goods_id, - goods_name=str(goods.get("goods_name") or ""), + goods_name=str(goods_info.get("goods_name") or ""), price=price, balance_before=balance_before, balance_after=balance_after, diff --git a/docs/微博/微博微豆-CK接口与兑换链路确认-2026-11-07.md b/docs/微博/微博微豆-CK接口与兑换链路确认-2026-11-07.md index 95cfd44..e0a1649 100644 --- a/docs/微博/微博微豆-CK接口与兑换链路确认-2026-11-07.md +++ b/docs/微博/微博微豆-CK接口与兑换链路确认-2026-11-07.md @@ -43,8 +43,8 @@ CK + F | +-> 微豆兑换: GET /aj/mall/list 查询商城列表与余额 - GET /aj/mall/detail 查询商品详情 - GET /aj/game/exchangegoods 执行兑换 + GET /aj/mall/detail 查询商品详情(价格/余额/库存/按钮状态预检) + POST /aj/game/exchangegoods 执行兑换(form body + x-xsrf-token) GET /aj/mall/list 复核余额和库存 GET /aj/mall/exchange 查询兑换记录 ``` @@ -620,27 +620,50 @@ goods_desc ```http GET https://vipclub.e.weibo.com/aj/mall/detail?F=&goods_id=&_t= +_failtoast: true ``` 响应包含: ```text -goods_info -weidou_balance -payment_button -nickname -game_nickname +data.goods_info.id / goods_name / price / remain_count / goods_desc / goods_image +data.weidou_balance # int +data.payment_button.text / clickable / type="exchange" +data.nickname +data.game_nickname ``` -只有 `payment_button.clickable=true` 且 `payment_button.type=exchange` 时,前端才允许兑换。 +只有 `payment_button.clickable=true` 且 `payment_button.type=exchange` 时,前端才允许兑换。服务端兑换前也应先请求该接口做预检: + +- `price`、`weidou_balance` 缺失或无法解析为整数时取消兑换,不能把缺失字段当 0; +- `payment_button.clickable` 不为 `true` 时取消兑换,并优先展示 `payment_button.text`; +- `price` 与页面价格不一致 → 取消;`remain_count == 0` → 库存不足;`weidou_balance < price` → 余额不足。 + +`/aj/mall/list` 的 `data.weidou_balance` 同样是 int,不要按对象字段读取。 ### 7.2 执行兑换 +兑换是 **POST**,不是 GET。用 GET 请求会命中路由兜底,返回 `{"code":400404,"msg":"程序员小哥哥迷路了"}`。 + ```http -GET https://vipclub.e.weibo.com/aj/game/exchangegoods?F=&goods_id=&_t= +POST https://vipclub.e.weibo.com/aj/game/exchangegoods?F=&goods_id=&_t= +Content-Type: application/x-www-form-urlencoded +x-xsrf-token: +Origin: https://vipclub.e.weibo.com +Referer: https://vipclub.e.weibo.com/game/mall?F= +_failtoast: true +Cookie: <微博 CK> + +F=&goods_id=&_t= ``` -请求参数只有 `F`、`goods_id`、`_t`,没有额外确认 Token。 +要点: + +- Query 与 form Body 都带 `F`、`goods_id`、`_t`(毫秒时间戳)。 +- `x-xsrf-token` 取自同一 Cookie Jar 里的 `XSRF-TOKEN`(同名跨域 Cookie 并存时取 domain 最具体的那个)。存在时必须带上;缺失时降级为不带该 Header,兼容历史 CK。 +- 响应 `code` 缺失或类型异常(非 `int`,含 `true`/`false`)时按“兑换结果未知”处理:先查兑换记录,不要立即重试。 +- 不要覆盖 `User-Agent`,沿用会话默认移动端 UA 即可。 +- 除 `F`、`goods_id`、`_t` 外没有额外确认 Token。 成功响应: @@ -657,9 +680,14 @@ GET https://vipclub.e.weibo.com/aj/game/exchangegoods?F=&goods_id=& - `data.weidou_balance` 从 `100` 变为 `0`; - goods 37 的 `remain_count` 从 `4639` 变为 `4638`。 -因此 `code=100000` 表示请求成功,但仍应刷新商城列表确认余额和库存变化。 +因此 `code=100000` 表示请求成功,但仍应刷新商城列表确认余额变化。复核约定: -注意:这是使用 GET 执行状态变更的接口。不能做自动重试、并发点击或把一次成功当成幂等。 +- 只有「余额确认变化」才算 `verified=true`; +- 库存 `remain_count` 变化只作附带信息,不能单独证明兑换成功; +- 余额入账可能延迟,可最多轮询 3 次 `GET /aj/mall/list`(间隔约 0.4 秒),仅在余额未变化时重试; +- 仍无法确认时返回 `verified=false` 并提示去查兑换记录,不能把未知余额写成 0 落库。 + +注意:这是状态变更接口。不能做自动重试、并发点击或把一次成功当成幂等。只有连接超时(请求未发出)可以安全重试,其余网络错误一律先查兑换记录。 ### 7.3 兑换记录 @@ -682,6 +710,11 @@ data.totalCount 本次在兑换前查询两次,结果均为空列表。兑换后没有再请求该接口,因此兑换成功后的记录字段仍需补抓一次。 +字段说明(来源:`2026-12-03` 抓包实测): + +- `reward_status`:`2026-12-03` 抓包实测兑换成功后为 `2`(等同于“已发放”),其它取值语义未确认; +- 代码中 `REWARD_STATUS_LABELS` 只映射 `2 → 已发放`,其余回退展示“状态码 N”。 + ## 8. 同一页面的辅助接口 以下接口出现在页面加载流程中,但不是上述业务的必需前置: @@ -701,7 +734,7 @@ data.totalCount 3. `_t` 使用当前毫秒时间,不复用抓包值。 4. `uid`、`vuid`、`cashier_id`、`tab_id`、`itemid`、`appkey` 和 `single_reward` 来自页面响应,业务代码只保留活动配置。 5. 充值金额以 `single_reward` 为准:1 元填 `100`。 -6. 兑换接口是 GET 状态变更,必须设置本地防重锁并禁止自动重试。 +6. 兑换接口是 POST 状态变更,必须设置本地防重锁并禁止自动重试。 7. 支付二维码从 `createorder.data.url` 对应的收银台 HTML 中解析,不要重新计算 `qr.weibo.cn` 的 `sign`。 8. 不记录或回显完整 Cookie、支付 URL、二维码短链、uid、vuid、昵称和订单号。 9. 已导入 CK 的单行复制走 `POST /api/weibo/accounts/{account_id}/ck/copy`,由独立权限 `weibo:account:ck_export` 控制;列表/详情不返回 CK 明文,复制动作写 `weibo:account:ck_export` 审计,但审计 detail 只记账号 ID 与 UID,不写 CK 本体。 @@ -719,10 +752,11 @@ data.totalCount | code | 处理 | | --- | --- | | `100000` | 成功 | -| `100002` | 登录失效,停止任务并要求更新 CK | +| `100002` | 参数/校验错误(实测 `msg=参数错误`,如 GoodsID required),不是登录失效 | | `100004` | 进入微博错误页,停止任务 | -| `400002` | `未登陆`,CK 无效 | +| `400002` | `未登陆`,CK 无效(真实未登录) | | `400000` | `user not login`,CK 无效 | +| `400404` | 路由不存在(例如用 GET 调 `exchangegoods`),说明请求方式或路径写错 | | 其他 | 保留服务端 `msg` 和 `trace_id`,不要盲目重试状态变更接口 | ### 10.1 登录页 HTML 与 `retcode=6102` @@ -761,6 +795,6 @@ GET https://vipclub.weibo.com/aj/paycomponent/userinfo - 是否只需要 `SUB`,还是必须完整 Cookie Jar。 - 本次未抓 `is_bound=false` 的绑定响应。 - 本次未抓兑换后的 `/aj/mall/exchange` 记录。 -- `/aj/game/exchangegoods` 在余额不足、重复兑换、角色未绑定时的错误码。 +- 兑换失败的业务分支仍未全部实测:已确认 `100002`(参数错误)、`400002`(未登陆)、`400404`(GET 走错路由),余额不足、重复兑换、角色未绑定时返回的具体 code 仍需补抓。 - 支付订单在支付宝侧取消、超时、退款后的业务状态。 - 各活动的 `F`、`itemid`、`source_itemid`、`cashier_id`、`tab_id` 是否跨活动变化;实现时应从页面动态读取。 diff --git a/pyproject.toml b/pyproject.toml index 522ab61..9b22b37 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "live-hub-py" -version = "0.4.29" +version = "0.4.31" description = "直播账号运营 Web 后台" readme = "README.md" requires-python = ">=3.12,<3.13" diff --git a/tests/test_weibo_accounts.py b/tests/test_weibo_accounts.py index 169f6c3..07f9f14 100644 --- a/tests/test_weibo_accounts.py +++ b/tests/test_weibo_accounts.py @@ -13,7 +13,9 @@ from core.weibo import ( WeiboAuthError, WeiboBindError, WeiboBindQrCode, + WeiboExchangeError, WeiboExchangeResult, + WeiboExchangeUncertainError, WeiboHomeSnapshot, WeiboPaymentStatus, WeiboRechargeError, @@ -90,11 +92,28 @@ class StubWeiboClient: ) scheme_errors: ClassVar[dict[str, str]] = {} payment_error: ClassVar[WeiboRechargeError | None] = None + exchange_error: ClassVar[Exception | None] = None calls: ClassVar[list[tuple[str, str]]] = [] def __init__(self, cookie: str = "", **_kwargs): self.cookie = cookie + def exchange_goods(self, goods_id, *, expected_price, activity=""): + _ = activity + self.calls.append(("exchange", f"{goods_id}")) + if self.exchange_error is not None: + raise self.exchange_error + return WeiboExchangeResult( + goods_id=goods_id, + goods_name="会员1天卡", + price=expected_price, + balance_before=200, + balance_after=50, + remain_before=10, + remain_after=9, + verified=True, + ) + def fetch_home(self, activity: str = ""): self.calls.append(("home", activity)) if "expired" in self.cookie: @@ -144,6 +163,7 @@ def stub_client(monkeypatch): StubWeiboClient.calls = [] StubWeiboClient.scheme_errors = {} StubWeiboClient.payment_error = None + StubWeiboClient.exchange_error = None StubWeiboClient.snapshot = WeiboHomeSnapshot( uid="4014000001", nickname="测试微博", @@ -1714,7 +1734,7 @@ def test_manual_exchange_requires_confirm_and_serializes_result( goods_name="微博会员1天卡", price=100, balance_before=200, - balance_after=100, + balance_after=50, remain_before=10, remain_after=9, verified=True, @@ -1738,5 +1758,128 @@ def test_manual_exchange_requires_confirm_and_serializes_result( ).model_dump() assert result["goods_id"] == 37 - assert result["balance_after"] == 100 + assert result["balance_after"] == 50 assert result["verified"] is True + + +def _exchange_account(db, current_user): + account_out = import_cookies( + WeiboCookieImport(text="SCF=a; SUB=b", tag=""), + db=db, + current=current_user, + ).accounts[0] + return db.query(WeiboAccount).filter(WeiboAccount.id == account_out.id).one() + + +def test_exchange_service_rejects_concurrent_same_account(db, current_user): + account = _exchange_account(db, current_user) + + with weibo_service.account_exchange_lock(account.id): + with pytest.raises(WeiboExchangeError) as exc_info: + weibo_service.exchange_weibo_goods( + db, + account, + goods_id=37, + expected_price=100, + ) + assert "正在兑换中" in str(exc_info.value) + + assert [call for call in StubWeiboClient.calls if call[0] == "exchange"] == [] + + +def test_exchange_service_releases_lock_after_success(db, current_user): + account = _exchange_account(db, current_user) + + first = weibo_service.exchange_weibo_goods( + db, + account, + goods_id=37, + expected_price=100, + ) + second = weibo_service.exchange_weibo_goods( + db, + account, + goods_id=37, + expected_price=100, + ) + + assert first.goods_id == second.goods_id == 37 + assert [call for call in StubWeiboClient.calls if call[0] == "exchange"] == [ + ("exchange", "37"), + ("exchange", "37"), + ] + db.refresh(account) + assert account.weidou_balance == 50 + assert account.id not in weibo_service._EXCHANGE_LOCKS + + +def test_exchange_service_releases_lock_after_failure(db, current_user): + account = _exchange_account(db, current_user) + StubWeiboClient.exchange_error = WeiboAuthError("未登陆") + + with pytest.raises(WeiboAuthError, match="未登陆"): + weibo_service.exchange_weibo_goods( + db, + account, + goods_id=37, + expected_price=100, + ) + + assert account.ck_check_status == "invalid" + assert account.id not in weibo_service._EXCHANGE_LOCKS + + StubWeiboClient.exchange_error = None + result = weibo_service.exchange_weibo_goods( + db, + account, + goods_id=37, + expected_price=100, + ) + + assert result.goods_id == 37 + assert [call for call in StubWeiboClient.calls if call[0] == "exchange"] == [ + ("exchange", "37"), + ("exchange", "37"), + ] + + +def test_exchange_balance_writeback_commit_failure_is_uncertain( + monkeypatch, db, current_user +): + """回写提交失败要降级成“结果未知”,不能变 500,且锁必须释放。""" + + account = _exchange_account(db, current_user) + + def boom() -> None: + raise RuntimeError("commit boom") + + monkeypatch.setattr(db, "commit", boom) + + with pytest.raises(WeiboExchangeUncertainError) as exc_info: + weibo_service.exchange_weibo_goods( + db, + account, + goods_id=37, + expected_price=100, + ) + + assert "余额回写失败" in str(exc_info.value) + assert account.id not in weibo_service._EXCHANGE_LOCKS + + +def test_exchange_route_returns_409_when_account_busy(db, current_user): + account = _exchange_account(db, current_user) + + with ( + weibo_service.account_exchange_lock(account.id), + pytest.raises(HTTPException) as exc_info, + ): + weibo_router.exchange_goods( + account.id, + WeiboExchangeRequest(goods_id=37, expected_price=100, confirm=True), + db=db, + current=current_user, + ) + + assert exc_info.value.status_code == 409 + assert "正在兑换中" in str(exc_info.value.detail) diff --git a/tests/test_weibo_client.py b/tests/test_weibo_client.py index 521f039..630dcd8 100644 --- a/tests/test_weibo_client.py +++ b/tests/test_weibo_client.py @@ -672,48 +672,83 @@ def test_get_payment_status(): assert session.calls[0][2]["data"]["pay_id"] == "pay-1" -def test_exchange_goods_executes_once_and_verifies_balance_and_stock(): - before = { +GOODS_ID = 37 + + +def _detail_payload( + *, + price: Any = 100, + balance: Any = 200, + remain: Any = 10, + clickable: Any = True, + button_text: str = "立即兑换", + button_type: Any = "exchange", +) -> dict: + return { "code": 100000, + "msg": "success", "data": { - "weidou_balance": 200, - "list": [ - { - "id": 37, - "goods_name": "微博会员1天卡", - "price": 100, - "remain_count": 10, - "is_sold_out": False, - } - ], + "goods_info": { + "id": GOODS_ID, + "goods_name": "微博会员1天卡", + "price": price, + "remain_count": remain, + "goods_desc": "兑换后立即生效", + }, + "payment_button": { + "text": button_text, + "clickable": clickable, + "type": button_type, + }, + "weidou_balance": balance, + "nickname": "测试微博", + "game_nickname": "测试角色", }, } - after = { - "code": 100000, - "data": { - "weidou_balance": 100, - "list": [ - { - "id": 37, - "goods_name": "微博会员1天卡", - "price": 100, - "remain_count": 9, - "is_sold_out": False, - } - ], - }, + + +def _mall_list_payload( + *, + balance: Any = 200, + remain: Any = 10, + drop_balance: bool = False, +) -> dict: + data: dict[str, Any] = { + "list": [ + { + "id": GOODS_ID, + "goods_name": "微博会员1天卡", + "price": 100, + "remain_count": remain, + "is_sold_out": False, + } + ], } + if not drop_balance: + data["weidou_balance"] = balance + return {"code": 100000, "msg": "success", "data": data} + + +def _exchange_calls(session: FakeSession) -> list: + return [call for call in session.calls if call[1].endswith("/game/exchangegoods")] + + +def _detail_calls(session: FakeSession) -> list: + return [call for call in session.calls if call[1].endswith("/mall/detail")] + + +def test_exchange_goods_posts_form_with_xsrf_and_verifies_balance(): session = FakeSession( [ - before, + _detail_payload(), {"code": 100000, "msg": "success", "data": None}, - after, + _mall_list_payload(balance=100, remain=9), ] ) - client = WeiboClient("SUB=valid", session=session) + client = WeiboClient("SUB=valid; XSRF-TOKEN=xsrf-token-1", session=session) result = client.exchange_goods( - 37, + GOODS_ID, expected_price=100, activity="bowen_tjg", ) @@ -724,63 +759,396 @@ def test_exchange_goods_executes_once_and_verifies_balance_and_stock(): assert result.remain_before == 10 assert result.remain_after == 9 assert result.verified is True - exchange_calls = [ - call for call in session.calls if call[1].endswith("/game/exchangegoods") - ] + assert result.verify_error == "" + + exchange_calls = _exchange_calls(session) assert len(exchange_calls) == 1 - assert exchange_calls[0][2]["params"]["goods_id"] == 37 + method, url, kwargs = exchange_calls[0] + assert method == "POST" + assert url.endswith("/game/exchangegoods") + assert kwargs["params"]["goods_id"] == GOODS_ID + assert kwargs["params"]["F"] == "bowen_tjg" + assert "_t" in kwargs["params"] + assert kwargs["data"]["goods_id"] == GOODS_ID + assert kwargs["data"]["F"] == "bowen_tjg" + headers = {key.lower(): value for key, value in kwargs["headers"].items()} + assert headers["x-xsrf-token"] == "xsrf-token-1" + assert headers["content-type"].startswith("application/x-www-form-urlencoded") + assert headers["origin"] == "https://vipclub.e.weibo.com" + assert headers["_failtoast"] == "true" + + detail_calls = _detail_calls(session) + assert len(detail_calls) == 1 + assert session.calls.index(detail_calls[0]) < session.calls.index(exchange_calls[0]) -def test_exchange_goods_rejects_insufficient_balance_before_write(): +def test_exchange_goods_cancels_when_payment_button_not_clickable(): session = FakeSession( [ - { - "code": 100000, - "data": { - "weidou_balance": 99, - "list": [ - { - "id": 37, - "goods_name": "微博会员1天卡", - "price": 100, - "remain_count": 10, - "is_sold_out": False, - } - ], - }, - } + _detail_payload(clickable=False, button_text="已达兑换上限"), + _mall_list_payload(), ] ) client = WeiboClient("SUB=valid", session=session) + with pytest.raises(WeiboExchangeError, match="已达兑换上限"): + client.exchange_goods(GOODS_ID, expected_price=100) + + assert _exchange_calls(session) == [] + + +def test_exchange_goods_cancels_when_detail_preflight_fails(): + session = FakeSession([{"code": 100500, "msg": "商品不存在"}]) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeError, match="已取消"): + client.exchange_goods(GOODS_ID, expected_price=100) + + assert _exchange_calls(session) == [] + + +def test_exchange_goods_rejects_insufficient_balance_before_write(): + session = FakeSession([_detail_payload(balance=99)]) + client = WeiboClient("SUB=valid", session=session) + with pytest.raises(WeiboExchangeError, match="余额不足"): - client.exchange_goods(37, expected_price=100) + client.exchange_goods(GOODS_ID, expected_price=100) - assert not any(call[1].endswith("/game/exchangegoods") for call in session.calls) + assert _exchange_calls(session) == [] -def test_exchange_goods_marks_transport_failure_as_uncertain(): +def test_exchange_goods_marks_connection_error_as_uncertain(): session = FakeSession( [ - { - "code": 100000, - "data": { - "weidou_balance": 200, - "list": [ - { - "id": 37, - "goods_name": "微博会员1天卡", - "price": 100, - "remain_count": 10, - "is_sold_out": False, - } - ], - }, - }, + _detail_payload(), requests.ConnectionError("connection reset"), ] ) client = WeiboClient("SUB=valid", session=session) with pytest.raises(WeiboExchangeUncertainError, match="结果未知"): - client.exchange_goods(37, expected_price=100) + client.exchange_goods(GOODS_ID, expected_price=100) + + +def test_exchange_goods_treats_100002_as_explicit_rejection(): + session = FakeSession( + [ + _detail_payload(), + {"code": 100002, "msg": "参数错误"}, + ] + ) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeError, match="参数错误") as exc_info: + client.exchange_goods(GOODS_ID, expected_price=100) + + assert not isinstance(exc_info.value, WeiboAuthError) + + +def test_exchange_goods_treats_400002_as_auth_failure(): + session = FakeSession( + [ + _detail_payload(), + {"code": 400002, "msg": "未登陆"}, + ] + ) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboAuthError, match="未登陆"): + client.exchange_goods(GOODS_ID, expected_price=100) + + +def test_exchange_goods_does_not_verify_on_stock_change_only(): + session = FakeSession( + [ + _detail_payload(), + {"code": 100000, "msg": "success", "data": None}, + _mall_list_payload(balance=200, remain=9), + _mall_list_payload(balance=200, remain=8), + _mall_list_payload(balance=200, remain=7), + ] + ) + client = WeiboClient("SUB=valid", session=session) + + result = client.exchange_goods(GOODS_ID, expected_price=100) + + assert result.verified is False + assert result.verify_error + assert result.balance_after is None + assert result.remain_after == 7 + + +def test_exchange_goods_keeps_balance_after_none_when_balance_missing(): + session = FakeSession( + [ + _detail_payload(), + {"code": 100000, "msg": "success", "data": None}, + _mall_list_payload(drop_balance=True), + _mall_list_payload(drop_balance=True), + _mall_list_payload(drop_balance=True), + ] + ) + client = WeiboClient("SUB=valid", session=session) + + result = client.exchange_goods(GOODS_ID, expected_price=100) + + assert result.balance_after is None + assert result.verified is False + assert result.verify_error + + +def test_exchange_goods_marks_connect_timeout_as_not_submitted(): + session = FakeSession( + [ + _detail_payload(), + requests.exceptions.ConnectTimeout("connect timeout"), + ] + ) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeError, match="未提交") as exc_info: + client.exchange_goods(GOODS_ID, expected_price=100) + + assert not isinstance(exc_info.value, WeiboExchangeUncertainError) + + +def test_exchange_goods_passes_auth_error_through_on_detail_preflight(): + session = FakeSession([{"code": 400002, "msg": "未登陆"}]) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboAuthError, match="未登陆") as exc_info: + client.exchange_goods(GOODS_ID, expected_price=100) + + assert not isinstance(exc_info.value, WeiboExchangeError) + + +def test_exchange_goods_treats_403_as_rejected_without_verify(): + session = FakeSession( + [ + _detail_payload(), + FakeResponse({"code": 1}, status_code=403), + ] + ) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeError, match="403"): + client.exchange_goods(GOODS_ID, expected_price=100) + + # 只应发生 detail + 提交两次请求,403 之后不再复核。 + assert len(session.calls) == 2 + assert len(_detail_calls(session)) == 1 + assert len(_exchange_calls(session)) == 1 + + +def test_exchange_goods_treats_500_as_uncertain(): + session = FakeSession( + [ + _detail_payload(), + FakeResponse({"code": 1}, status_code=500), + ] + ) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeUncertainError, match="结果未知"): + client.exchange_goods(GOODS_ID, expected_price=100) + + +@pytest.mark.parametrize("clickable", [1, "1", "true", "True", True]) +def test_exchange_goods_accepts_truthy_clickable(clickable): + session = FakeSession( + [ + _detail_payload(clickable=clickable), + {"code": 100000, "msg": "success", "data": None}, + _mall_list_payload(balance=100, remain=9), + ] + ) + client = WeiboClient("SUB=valid", session=session) + + result = client.exchange_goods(GOODS_ID, expected_price=100) + + assert result.verified is True + assert len(_exchange_calls(session)) == 1 + + +@pytest.mark.parametrize("clickable", ["0", 0, False, None]) +def test_exchange_goods_rejects_falsy_clickable(clickable): + session = FakeSession([_detail_payload(clickable=clickable)]) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeError, match="不允许兑换"): + client.exchange_goods(GOODS_ID, expected_price=100) + + assert _exchange_calls(session) == [] + + +def test_exchange_goods_cancels_when_payment_button_missing(): + payload = _detail_payload() + del payload["data"]["payment_button"] + session = FakeSession([payload]) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeError, match="未返回兑换按钮状态"): + client.exchange_goods(GOODS_ID, expected_price=100) + + assert _exchange_calls(session) == [] + + +def test_exchange_goods_verify_uses_shorter_timeout(): + session = FakeSession( + [ + _detail_payload(), + {"code": 100000, "msg": "success", "data": None}, + _mall_list_payload(balance=100, remain=9), + ] + ) + client = WeiboClient("SUB=valid", session=session) + + client.exchange_goods(GOODS_ID, expected_price=100) + + mall_calls = [call for call in session.calls if call[1].endswith("/mall/list")] + assert mall_calls + for _method, _url, kwargs in mall_calls: + assert kwargs["timeout"] == 8.0 + for _method, _url, kwargs in _detail_calls(session) + _exchange_calls(session): + assert kwargs["timeout"] == client.timeout + + +@pytest.mark.parametrize( + "payload", + [ + {}, + {"msg": "success"}, + {"code": None}, + {"code": ["100000"]}, + {"code": {"value": 100000}}, + {"code": "100000"}, + {"code": True}, + {"code": False}, + ], + ids=[ + "empty", + "missing-code", + "none-code", + "list-code", + "dict-code", + "str-code", + "true-code", + "false-code", + ], +) +def test_submit_exchange_treats_missing_or_bad_code_as_uncertain(payload): + session = FakeSession([_detail_payload(), payload]) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeUncertainError, match="结果未知"): + client.exchange_goods(GOODS_ID, expected_price=100) + + assert len(_exchange_calls(session)) == 1 + + +def test_exchange_goods_cancels_when_remain_count_missing(): + payload = _detail_payload() + del payload["data"]["goods_info"]["remain_count"] + session = FakeSession([payload]) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeError, match="已取消兑换") as exc_info: + client.exchange_goods(GOODS_ID, expected_price=100) + + assert not isinstance(exc_info.value, WeiboExchangeUncertainError) + assert _exchange_calls(session) == [] + + +@pytest.mark.parametrize( + "button_type", + ["recharge", None, "", "exchangegoods"], + ids=["recharge", "missing", "empty", "other"], +) +def test_exchange_goods_cancels_when_payment_button_type_unusable(button_type): + payload = _detail_payload(button_type=button_type) + if button_type is None: + del payload["data"]["payment_button"]["type"] + session = FakeSession([payload]) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeError, match="兑换按钮类型") as exc_info: + client.exchange_goods(GOODS_ID, expected_price=100) + + assert not isinstance(exc_info.value, WeiboExchangeUncertainError) + assert _exchange_calls(session) == [] + + +def test_exchange_goods_accepts_payment_button_type_with_padding(): + session = FakeSession( + [ + _detail_payload(button_type=" exchange "), + {"code": 100000, "msg": "success", "data": None}, + _mall_list_payload(balance=100, remain=9), + ] + ) + client = WeiboClient("SUB=valid", session=session) + + result = client.exchange_goods(GOODS_ID, expected_price=100) + + assert result.verified is True + assert len(_exchange_calls(session)) == 1 + + +def test_exchange_goods_cancels_when_price_is_fractional(): + session = FakeSession([_detail_payload(price=100.9)]) + client = WeiboClient("SUB=valid", session=session) + + with pytest.raises(WeiboExchangeError, match="已取消兑换"): + client.exchange_goods(GOODS_ID, expected_price=100) + + assert _exchange_calls(session) == [] + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (100.9, None), + (float("inf"), None), + (float("nan"), None), + (100.0, 100), + (100, 100), + (True, None), + ("100", 100), + (" 100 ", 100), + ("100.5", None), + ("100.0", None), + ("", None), + (None, None), + ([100], None), + ], +) +def test_as_int_rejects_fractional_and_exotic_values(value, expected): + from core.weibo.client import _as_int + + assert _as_int(value) == expected + + +def test_xsrf_headers_prefers_most_specific_domain_cookie(): + session = FakeSession([]) + session.cookies.set("XSRF-TOKEN", "wide-domain", domain=".weibo.com") + session.cookies.set("XSRF-TOKEN", "narrow-domain", domain="vipclub.e.weibo.com") + session.cookies.set("XSRF-TOKEN", "other-domain", domain=".example.com") + client = WeiboClient("SUB=valid", session=session) + + assert client._xsrf_headers() == {"x-xsrf-token": "narrow-domain"} + + +def test_xsrf_headers_accepts_parent_domain_cookie_only(): + session = FakeSession([]) + session.cookies.set("XSRF-TOKEN", "wide-domain", domain=".weibo.com") + session.cookies.set("XSRF-TOKEN", "other-domain", domain=".example.com") + client = WeiboClient("SUB=valid", session=session) + + assert client._xsrf_headers() == {"x-xsrf-token": "wide-domain"} + + +def test_xsrf_headers_returns_empty_when_cookie_missing(): + session = FakeSession([]) + client = WeiboClient("SUB=valid", session=session) + + assert client._xsrf_headers() == {} diff --git a/uv.lock b/uv.lock index e5c407a..e0e0690 100644 --- a/uv.lock +++ b/uv.lock @@ -381,7 +381,7 @@ wheels = [ [[package]] name = "live-hub-py" -version = "0.4.29" +version = "0.4.31" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/web/backend/routers/weibo.py b/web/backend/routers/weibo.py index 892e91e..8d91be5 100644 --- a/web/backend/routers/weibo.py +++ b/web/backend/routers/weibo.py @@ -11,7 +11,12 @@ from sqlalchemy import func, or_ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session, defer, joinedload -from core.weibo import WeiboAuthError, WeiboError, WeiboExchangeUncertainError +from core.weibo import ( + WeiboAuthError, + WeiboError, + WeiboExchangeError, + WeiboExchangeUncertainError, +) from ..database import get_db from ..deps import get_current_user @@ -1460,6 +1465,9 @@ def exchange_goods( ) except WeiboExchangeUncertainError as exc: raise HTTPException(status_code=502, detail=str(exc)) from exc + except WeiboExchangeError as exc: + # 服务端明确拒绝或本地预检失败:兑换未提交,按 409 返回可直接展示的文案。 + raise HTTPException(status_code=409, detail=str(exc)) from exc except (WeiboError, ValueError) as exc: raise _manual_http_error(exc) from exc _record_audit_safely( diff --git a/web/backend/services/weibo_service.py b/web/backend/services/weibo_service.py index ba3c15b..0fd582e 100644 --- a/web/backend/services/weibo_service.py +++ b/web/backend/services/weibo_service.py @@ -2,6 +2,8 @@ from __future__ import annotations +import threading +from contextlib import contextmanager from dataclasses import dataclass from datetime import UTC, datetime @@ -12,7 +14,9 @@ from core.weibo import ( WeiboAuthError, WeiboClient, WeiboError, + WeiboExchangeError, WeiboExchangeResult, + WeiboExchangeUncertainError, WeiboHomeSnapshot, WeiboPaymentStatus, WeiboRechargeOrder, @@ -22,6 +26,31 @@ from core.weibo import ( from ..models import User, WeiboAccount, WeiboRechargeRecord, WeiboWorkbenchAccount from .weibo_image_service import embed_weibo_goods_images +_EXCHANGE_LOCKS: dict[int, threading.Lock] = {} +_EXCHANGE_LOCKS_GUARD = threading.Lock() + + +@contextmanager +def account_exchange_lock(account_id: int): + """按账号的非阻塞兑换锁,防同一账号双击/并发导致重复扣微豆。 + + 锁只在本进程内有效(生产 uvicorn 为单 worker),多进程/多实例部署时 + 不做跨进程保证;拿不到锁时立即报错,不排队等待。 + """ + + with _EXCHANGE_LOCKS_GUARD: + lock = _EXCHANGE_LOCKS.setdefault(account_id, threading.Lock()) + acquired = lock.acquire(blocking=False) + if not acquired: + raise WeiboExchangeError("该账号正在兑换中,请等待当前兑换结束后再试") + try: + yield + finally: + with _EXCHANGE_LOCKS_GUARD: + lock.release() + if _EXCHANGE_LOCKS.get(account_id) is lock: + _EXCHANGE_LOCKS.pop(account_id, None) + @dataclass(frozen=True, slots=True) class WeiboImportIssue: @@ -470,20 +499,30 @@ def exchange_weibo_goods( expected_price: int, activity: str = "", ) -> WeiboExchangeResult: - """预检并执行一次微博微豆兑换,然后刷新账号余额。""" + """预检并执行一次微博微豆兑换,然后刷新账号余额。 + + 同一账号的并发兑换请求会被拒绝(进程内按账号加锁)。 + """ try: - result = WeiboClient(account.cookie or "").exchange_goods( - goods_id, - expected_price=expected_price, - activity=_effective_activity(account, activity), - ) + with account_exchange_lock(account.id): + result = WeiboClient(account.cookie or "").exchange_goods( + goods_id, + expected_price=expected_price, + activity=_effective_activity(account, activity), + ) + if result.balance_after is not None: + account.weidou_balance = result.balance_after + try: + db.commit() + except Exception as exc: # 余额回写失败不能掩盖“兑换已提交” + db.rollback() + raise WeiboExchangeUncertainError( + "兑换已提交,但余额回写失败,请查兑换记录复核" + ) from exc except (WeiboError, ValueError) as exc: _mark_manual_failure(db, account, exc) raise - if result.balance_after is not None: - account.weidou_balance = result.balance_after - db.commit() return result diff --git a/web/frontend/src/pages/WeiboAccountsPage.tsx b/web/frontend/src/pages/WeiboAccountsPage.tsx index d06142e..aadcefb 100644 --- a/web/frontend/src/pages/WeiboAccountsPage.tsx +++ b/web/frontend/src/pages/WeiboAccountsPage.tsx @@ -95,6 +95,21 @@ const WEIBO_BATCH_RECHARGE_POLL_INTERVAL_MS = 8_000; const WEIBO_BATCH_EXCHANGE_MAX = 50; const WEIBO_BATCH_EXCHANGE_CONCURRENCY = 3; +// 微博官方页面不展示该字段,2 是抓包实测的成功发放值,其余值语义未确认,因此保留原始状态码。 +const REWARD_STATUS_LABELS: Record = { 2: '已发放' }; + +const renderRewardStatus = (value: number | null | undefined) => { + if (value == null) return '-'; + const label = REWARD_STATUS_LABELS[value]; + if (label) + return ( + + {label} + + ); + return 状态码 {value}; +}; + function normalizeImageURL(value: string): string { const imageURL = value.trim(); if (!imageURL || imageURL.startsWith('data:image/')) return imageURL; @@ -299,6 +314,7 @@ export default function WeiboAccountsPage({ const [batchRechargeZoom, setBatchRechargeZoom] = useState(null); const batchRechargeEntriesRef = useRef([]); + const exchangeInFlightRef = useRef(false); const batchRechargePollingRef = useRef(false); const batchRechargeCheckRef = useRef< (entry: BatchRechargeEntry) => Promise @@ -923,11 +939,16 @@ export default function WeiboAccountsPage({ const handleExchange = async (goods: WeiboMallListResult['goods'][number]) => { if (!featureAccount) return; + if (exchangeInFlightRef.current) { + message.info('已有兑换进行中,请稍候'); + return; + } if (!featureAccount.is_enabled) { message.warning('账号已停用,请先启用'); return; } setExchangingGoodsId(goods.id); + exchangeInFlightRef.current = true; try { const result = await weiboApi.exchangeGoods( featureAccount.id, @@ -948,6 +969,7 @@ export default function WeiboAccountsPage({ message.error(getErrorMessage(error)); } finally { setExchangingGoodsId(null); + exchangeInFlightRef.current = false; } }; @@ -1956,7 +1978,8 @@ export default function WeiboAccountsPage({ !featureAccount?.is_enabled || goods.is_sold_out || goods.remain_count === 0 || - goods.price > balance; + goods.price > balance || + exchangingGoodsId !== null; return ( value ?? '-', + render: renderRewardStatus, }, ]; @@ -2054,7 +2077,8 @@ export default function WeiboAccountsPage({ workbenchSelectedGoods.is_sold_out || workbenchSelectedGoods.remain_count === 0 || workbenchSelectedGoods.price > - (mallResult?.weidou_balance ?? featureAccount?.weidou_balance ?? 0); + (mallResult?.weidou_balance ?? featureAccount?.weidou_balance ?? 0) || + exchangingGoodsId !== null; const tagOptions = useMemo( () => knownTags.map((tag) => ({ value: tag })), [knownTags],