feat(report): 博主名字后面带上账号池的账号状态
账号池服务(192.168.20.220:18050 的 /api/account_pool/accounts)返回每个号的 `nickname` 和 `account_status`(账号正常 / 账号异常 / 作品异常 / 账号安全待提升)。 报表按昵称匹配,在名字后面加括号显示:`周周逛苏州(账号异常)`。 **由后端去取,浏览器不直连** —— token 不该下发到前端,跨域也麻烦。地址和 token 走 环境变量 `MC_ACCOUNT_POOL_URL` / `MC_ACCOUNT_POOL_TOKEN`(已加到服务器 .env, 不进仓库);没配就静默跳过。 细节: * 缓存 60 秒 —— 报表会被反复刷新,而账号状态是分钟级的;刷新一次就多打一次外部 接口没有意义; * 外部服务失败时**保留上一份缓存**,没有缓存就返回空;报表本身绝不能因此打不开; * 同名不同号时把状态并起来(`A / B`),不静默只留一个; * 只在抖音平台附加 —— 那套池子管的是抖音号,小红书同名账号不该被误标。 测试 16 条(新增:按昵称附加状态、外部服务挂掉时报表照出)。
This commit is contained in:
@@ -19,7 +19,9 @@
|
||||
"""Task CRUD and dashboard queries for the monitoring layer."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
@@ -1451,6 +1453,72 @@ async def mark_events_read(session: AsyncSession, task_id: Optional[int] = None)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 账号池状态(外部服务)
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# 报表要在博主名字后面带上「账号正常 / 账号异常 / 账号安全待提升」这类状态,数据来自
|
||||
# 另一套账号池服务。**由后端去取,不让浏览器直连**:token 不该发到前端,而且跨域也麻烦。
|
||||
#
|
||||
# 地址和 token 走环境变量;没配就静默跳过(报表照常出,只是没有状态)。
|
||||
# 缓存 60 秒:报表会被反复刷新,而账号状态是分钟级的。
|
||||
|
||||
_ACCOUNT_STATUS_TTL_SECONDS = 60.0
|
||||
_account_status_cache: Optional[Tuple[float, Dict[str, str]]] = None
|
||||
|
||||
|
||||
def _reset_account_status_cache() -> None:
|
||||
"""测试钩子:丢掉缓存,避免用例之间互相污染。"""
|
||||
global _account_status_cache
|
||||
_account_status_cache = None
|
||||
|
||||
|
||||
async def _fetch_account_pool() -> List[Dict[str, Any]]:
|
||||
url = os.getenv("MC_ACCOUNT_POOL_URL", "").strip()
|
||||
if not url:
|
||||
return []
|
||||
token = os.getenv("MC_ACCOUNT_POOL_TOKEN", "").strip()
|
||||
headers = {"X-Account-Token": token} if token else {}
|
||||
async with httpx.AsyncClient(timeout=3.0) as client:
|
||||
response = await client.get(url, headers=headers)
|
||||
response.raise_for_status()
|
||||
return (response.json() or {}).get("accounts") or []
|
||||
|
||||
|
||||
async def account_status_map() -> Dict[str, str]:
|
||||
"""昵称 → 账号状态。取不到就返回空 dict —— 报表不能因为外部服务挂了而打不开。"""
|
||||
global _account_status_cache
|
||||
|
||||
now = time.monotonic()
|
||||
if (
|
||||
_account_status_cache is not None
|
||||
and now - _account_status_cache[0] < _ACCOUNT_STATUS_TTL_SECONDS
|
||||
):
|
||||
return _account_status_cache[1]
|
||||
|
||||
try:
|
||||
accounts = await _fetch_account_pool()
|
||||
except Exception as exc: # noqa: BLE001 - 外部服务,任何失败都只降级
|
||||
print(f"[monitor.matrix] 账号池读取失败,本次不带状态:{exc}", flush=True)
|
||||
# 失败不清空旧缓存:服务抖一下不该让报表上的状态全消失。
|
||||
return _account_status_cache[1] if _account_status_cache else {}
|
||||
|
||||
merged: Dict[str, List[str]] = {}
|
||||
for account in accounts:
|
||||
nickname = (account.get("nickname") or "").strip()
|
||||
status = (account.get("account_status") or "").strip()
|
||||
if not nickname or not status:
|
||||
continue
|
||||
# 同名不同号时把状态并起来,别静默只留一个。
|
||||
bucket = merged.setdefault(nickname, [])
|
||||
if status not in bucket:
|
||||
bucket.append(status)
|
||||
|
||||
statuses = {name: " / ".join(values) for name, values in merged.items()}
|
||||
_account_status_cache = (now, statuses)
|
||||
return statuses
|
||||
|
||||
|
||||
async def daily_tag_matrix(
|
||||
session: AsyncSession,
|
||||
platform: str,
|
||||
@@ -1674,6 +1742,12 @@ async def daily_tag_matrix(
|
||||
creators = [{"hash": hash_, "name": name} for hash_, name in known.items()]
|
||||
creators.sort(key=lambda item: item["name"])
|
||||
|
||||
# 账号池状态只有抖音那套池子有;取不到就是空串,前端不加括号。
|
||||
if platform == adapters.PLATFORM_DY:
|
||||
statuses = await account_status_map()
|
||||
for creator in creators:
|
||||
creator["account_status"] = statuses.get(creator["name"].strip(), "")
|
||||
|
||||
return {
|
||||
"platform": platform,
|
||||
"days": days,
|
||||
|
||||
Reference in New Issue
Block a user