Compare commits
88
Commits
e4affe9170
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c2c8faf1d | ||
|
|
34a962f75a | ||
|
|
c06848ae98 | ||
|
|
cd2a276630 | ||
|
|
b05491e9de | ||
|
|
d30ccb196a | ||
|
|
3a5b973bc2 | ||
|
|
e369478ff1 | ||
|
|
be22b30a83 | ||
|
|
809692a957 | ||
|
|
6513e5d4e8 | ||
|
|
1353a26def | ||
|
|
e87c3a8560 | ||
|
|
d9fa5ecb99 | ||
|
|
7d552c1206 | ||
|
|
1dca78b6db | ||
|
|
2b19808f6b | ||
|
|
a46caf59f4 | ||
|
|
32cb9b1952 | ||
|
|
19b45908e3 | ||
|
|
213be57055 | ||
|
|
1474e5e3eb | ||
|
|
8e398a5ba1 | ||
|
|
be917ae6d4 | ||
|
|
525a75a5f3 | ||
|
|
6ea8f24041 | ||
|
|
ae9af5e53f | ||
|
|
74fc19a8e3 | ||
|
|
d95e5ec8e2 | ||
|
|
4665dac667 | ||
|
|
4a15c1485c | ||
|
|
9f8186c2aa | ||
|
|
36407cafc5 | ||
|
|
15c52553d0 | ||
|
|
ffafd90073 | ||
|
|
c095530879 | ||
|
|
2153207bf9 | ||
|
|
8dbb709b7e | ||
|
|
92976f1097 | ||
|
|
a472622e46 | ||
|
|
50eb5ba189 | ||
|
|
bfa025e4ce | ||
|
|
6c6d4260c5 | ||
|
|
24b7a221f3 | ||
|
|
4cb6c8b9cf | ||
|
|
3b0cdbe5ea | ||
|
|
8355a63037 | ||
|
|
9d81b505c3 | ||
|
|
8305243b33 | ||
|
|
b4822e4765 | ||
|
|
aaf943c662 | ||
|
|
ad92b5bc33 | ||
|
|
0a8f6e64c9 | ||
|
|
f6276ec314 | ||
|
|
6aba3a73c1 | ||
|
|
736ba9b12d | ||
|
|
d023393bb2 | ||
|
|
556680c613 | ||
|
|
86e7fbd507 | ||
|
|
36f41450ae | ||
|
|
af21288dde | ||
|
|
1b69fa57f2 | ||
|
|
c83669087b | ||
|
|
ab6bbac596 | ||
|
|
b9aa590814 | ||
|
|
5c7577cab0 | ||
|
|
44277600e4 | ||
|
|
65fc16ddc9 | ||
|
|
d52b6942ac | ||
|
|
dbfbf32225 | ||
|
|
eed4c79b7d | ||
|
|
df1246ab79 | ||
|
|
f4373c098e | ||
|
|
a42f8e8b2f | ||
|
|
61808444ad | ||
|
|
e0581682e1 | ||
|
|
3c4daae0ac | ||
|
|
d02fec5914 | ||
|
|
20e672834c | ||
|
|
0a88474c92 | ||
|
|
5552e2a2b8 | ||
|
|
9e13a7f686 | ||
|
|
9f70cd0924 | ||
|
|
95b1be2c2e | ||
|
|
3b6a437e6c | ||
|
|
4f83a075f6 | ||
|
|
7442bc10b8 | ||
|
|
21ff01b894 |
+17
-1
@@ -183,4 +183,20 @@ agent_zone
|
||||
debug_tools
|
||||
|
||||
database/*.db
|
||||
.omx/
|
||||
.omx/
|
||||
|
||||
# 别人放在这儿的参考项目(mac-agent-os)。它是独立仓库、21MB,不属于本项目 ——
|
||||
# 一旦被 `git add -A` 扫进来就是永久留在历史里(踩过一次:1601 个文件里 1429 个是它)。
|
||||
# 要读它就直接读磁盘上的目录,别提交。
|
||||
mac-agent-os-main/
|
||||
|
||||
# 服务器上重建前端时,容器里的 npm 往挂载目录写的缓存。是构建产物,不该进仓库 ——
|
||||
# 它长期以「未跟踪」状态躺在工作区,正是会被 `git add -A` 顺手带走的类型。
|
||||
webui/.npm/
|
||||
# 我用来在服务器上跑命令的一次性脚本(不属于这个项目)
|
||||
.remote_run.py
|
||||
.vnc_*.sh
|
||||
.vnc_check.py
|
||||
.vnc_probe.py
|
||||
.vncshot.png
|
||||
.q.sql
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ RUN set -eux; \
|
||||
apt-get install -y --no-install-recommends \
|
||||
build-essential pkg-config default-libmysqlclient-dev git \
|
||||
libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 libxcb1 libgomp1 \
|
||||
tzdata nodejs npm; \
|
||||
tzdata nodejs npm fonts-wqy-zenhei; \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -0,0 +1,874 @@
|
||||
# 内容抓取模块 · 开发技术说明
|
||||
|
||||
> 面向接手开发的团队 · 2026-10-10
|
||||
> 全部内容基于**逐行读源码**整理,不是推测
|
||||
> 范围:**只写内容抓取模块**,不涉及其他业务
|
||||
|
||||
---
|
||||
|
||||
## 一、这个模块是干什么的
|
||||
|
||||
从主流内容平台(抖音 / 小红书 / B站 / 知乎 / 任意网页)**采集内容数据**:
|
||||
- 视频/笔记的元数据(标题、作者、发布时间、正文)
|
||||
- 互动数据(点赞、评论、分享、播放)
|
||||
- 评论列表
|
||||
- 作者主页的全部作品列表
|
||||
|
||||
采到的数据落进本地 SQLite,供后续分析/运营使用。
|
||||
|
||||
---
|
||||
|
||||
## 二、整体架构(重要:三层降级是核心)
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────┐
|
||||
│ HTTP 层 routes/scrape.py(22 个端点) │
|
||||
└───────────────────────┬──────────────────────────────────┘
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────┐
|
||||
│ 引擎层 services/scrape_engine.py │
|
||||
│ · URL 解析 → 标准化目标 │
|
||||
│ · 按平台选适配器 │
|
||||
│ · 同步 / 异步调度 │
|
||||
│ · 结果落库(去重) │
|
||||
└───────────────────────┬──────────────────────────────────┘
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────┐
|
||||
│ 适配器层 services/adapters/*.py(每个平台一个) │
|
||||
│ 基类 ScrapeAdapter 定义统一接口 + 工具降级 │
|
||||
└───────────────────────┬──────────────────────────────────┘
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────┐
|
||||
│ 工具层(★ 三层降级,这是本模块的核心设计) │
|
||||
│ Level 1 OpenCLI 外部 Node CLI(主路径) │
|
||||
│ Level 2 agent-browser Playwright + 真实 Chrome │
|
||||
│ Level 3 web_crawler 通用网页兜底 │
|
||||
└───────────────────────┬──────────────────────────────────┘
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────┐
|
||||
│ 存储层 services/scrape_db.py(SQLite,4 张表) │
|
||||
└──────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 为什么这么设计
|
||||
|
||||
抓取的最大风险是**单一方式失效**:目标平台改版、接口封禁、登录态过期。
|
||||
所以**同一份数据有三条获取路径**,第一条失败自动降级到第二条,
|
||||
**上层完全不感知**(对 engine 来说只是"拿到数据了")。
|
||||
|
||||
---
|
||||
|
||||
## 三、工具层详解(最关键的一层)
|
||||
|
||||
### 3.1 Level 1 — OpenCLI
|
||||
|
||||
**它是什么**:一个**第三方 Node.js CLI 工具**,包名 `@jackwener/opencli`。
|
||||
|
||||
```
|
||||
实际安装位置(本机实测):
|
||||
~/.workbuddy/binaries/node/versions/22.22.2/bin/opencli
|
||||
→ 软链到 ../lib/node_modules/@jackwener/opencli/dist/src/main.js
|
||||
```
|
||||
|
||||
**怎么调用**(`services/adapters/__init__.py` 的 `_run_opencli`):
|
||||
|
||||
```python
|
||||
OPENCLI = os.environ.get("OPENCLI_PATH",
|
||||
str(Path.home() / ".workbuddy" / "binaries" / "node" /
|
||||
"versions" / "22.22.2" / "bin" / "opencli"))
|
||||
|
||||
async def _run_opencli(self, args: list, timeout: int = 60):
|
||||
cmd = [self.OPENCLI] + args
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd, stdout=PIPE, stderr=PIPE)
|
||||
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||||
...
|
||||
return self._parse_output(stdout.decode().strip())
|
||||
```
|
||||
|
||||
**调用示例**(抖音,`douyin_scrape.py`):
|
||||
```bash
|
||||
opencli douyin user-videos <sec_uid> --limit 20 --with_comments true -f json
|
||||
opencli douyin stats <aweme_id> -f json
|
||||
```
|
||||
|
||||
**⛔ 移植注意**:这个二进制**不在仓库里**,是外部依赖。移植时必须:
|
||||
- 要么在目标机装 `npm i -g @jackwener/opencli`
|
||||
- 要么改 `OPENCLI_PATH` 环境变量指向它的位置
|
||||
|
||||
### 3.2 Level 2 — agent-browser("套用真实浏览器"的做法)
|
||||
|
||||
**这是你问的重点。设计原则写在 `browser_helpers.py` 文件头**:
|
||||
|
||||
```
|
||||
⛔ 绝不使用 Camoufox(养号专用,Firefox 内核 + 特殊指纹)
|
||||
✅ 使用 Playwright 启动【真实 Chrome】(Chromium 内核,正常指纹)
|
||||
```
|
||||
|
||||
**具体怎么"套真实浏览器"**(`browser_helpers.py` 的 `_get_browser`):
|
||||
|
||||
```python
|
||||
_CHROME_PATHS = [
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", # ← 系统真 Chrome
|
||||
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
||||
]
|
||||
_CHROME_PATH = None
|
||||
for p in _CHROME_PATHS:
|
||||
if Path(p).exists():
|
||||
_CHROME_PATH = p # 自动探测,找到就用系统已装的 Chrome
|
||||
break
|
||||
|
||||
launch_kwargs = {
|
||||
"headless": headless,
|
||||
"args": [
|
||||
"--disable-blink-features=AutomationControlled", # ★ 反检测关键
|
||||
"--no-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-gpu",
|
||||
"--window-size=1280,720",
|
||||
],
|
||||
}
|
||||
if _CHROME_PATH:
|
||||
launch_kwargs["executable_path"] = _CHROME_PATH # ★ 用系统 Chrome,不用 Playwright 自带
|
||||
```
|
||||
|
||||
**四个关键设计点**:
|
||||
|
||||
| 点 | 做法 | 为什么 |
|
||||
|---|---|---|
|
||||
| **用什么内核** | 系统真实 Chrome(`executable_path` 指定) | Playwright 自带 Chromium 有明显特征;真实 Chrome 是正常用户指纹 |
|
||||
| **怎么隐藏自动化** | `--disable-blink-features=AutomationControlled` | 这是最常被检测的自动化标志位 |
|
||||
| **实例管理** | 模块级单例 `_browser` + `asyncio.Lock` | 避免每次请求都启动浏览器(启动 ~1-2 秒) |
|
||||
| **会话隔离** | 每次 `browser.new_context()` | 每个任务独立 cookie 环境,互不污染 |
|
||||
|
||||
**页面加载策略**(`page_evaluate`):
|
||||
```python
|
||||
await page.goto(url, wait_until="domcontentloaded", timeout=timeout)
|
||||
await page.wait_for_load_state("networkidle", timeout=timeout) # 等动态渲染
|
||||
await asyncio.sleep(1) # 再等 1 秒保险
|
||||
result = await page.evaluate(js_code) # 执行 JS 提取
|
||||
```
|
||||
|
||||
**UA 伪装**(每次 context 都设置):
|
||||
```python
|
||||
context = await browser.new_context(
|
||||
user_agent=("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/125.0.0.0 Safari/537.36"),
|
||||
viewport={"width": 1280, "height": 720},
|
||||
locale="zh-CN", # 中文环境,符合目标用户画像
|
||||
)
|
||||
```
|
||||
|
||||
**两个公开函数**:
|
||||
```python
|
||||
page_evaluate(url, js_code, timeout, headless) # 打开页面执行 JS,返回 dict
|
||||
page_extract(url, selectors, timeout, headless) # 按 CSS 选择器提取文本
|
||||
```
|
||||
|
||||
**Profile 持久化**(可选,环境变量控制):
|
||||
```python
|
||||
_USER_DATA_DIR = os.environ.get(
|
||||
"SCRAPE_CHROME_USER_DATA",
|
||||
str(Path.home() / "workbuddy-agent-os" / "agent-local" /
|
||||
"runtime" / "scrape_chrome_profile"))
|
||||
```
|
||||
→ 想保持登录态就指定这个目录;不指定就用临时 context。
|
||||
|
||||
### 3.3 Level 3 — web_crawler
|
||||
|
||||
通用网页抓取兜底(`web_scrape.py`),用于非主流平台的页面。
|
||||
|
||||
### 3.4 降级怎么触发(`ScrapeAdapter._try_tools`)
|
||||
|
||||
```python
|
||||
async def _try_tools(self, tool_level: int, funcs: list) -> tuple:
|
||||
"""funcs: [(工具名, 可调用对象), ...],按顺序尝试"""
|
||||
tools = [f for f in funcs[:tool_level]] # 按 level 截断
|
||||
for name, fn in tools:
|
||||
try:
|
||||
result = await fn()
|
||||
if result is not None:
|
||||
return True, result, name # ★ 成功即返回,不再降级
|
||||
except Exception as e:
|
||||
logger.warning(f" ⚠️ [{self.platform}] 工具 {name} 失败: {e}")
|
||||
return False, None, tools[-1][0] if tools else "none"
|
||||
```
|
||||
|
||||
**关键语义**:
|
||||
- `tool_level=1` → 只用 OpenCLI
|
||||
- `tool_level=2` → OpenCLI → agent-browser(**默认**)
|
||||
- `tool_level=3` → 三层全开
|
||||
- **第一个成功就停**;返回 `(成功?, 结果, 用了哪个工具)`
|
||||
|
||||
---
|
||||
|
||||
## 四、适配器层(每平台一个)
|
||||
|
||||
### 4.1 统一接口(`services/adapters/__init__.py` 的基类)
|
||||
|
||||
**每个平台适配器必须实现 4 个方法**:
|
||||
|
||||
```python
|
||||
class ScrapeAdapter:
|
||||
platform = "" # 子类覆写,如 "douyin"
|
||||
adapter_name = ""
|
||||
|
||||
async def collect_item(self, target, depth="light", tool_level=2) -> dict:
|
||||
"""抓单条内容详情"""
|
||||
async def collect_user(self, user_id, limit=20) -> list[dict]:
|
||||
"""抓某个用户/作者的全部作品"""
|
||||
async def collect_comments(self, item_id, limit=20) -> list[dict]:
|
||||
"""抓评论"""
|
||||
async def collect_search(self, keyword, limit=20) -> list[dict]:
|
||||
"""按关键词搜索"""
|
||||
```
|
||||
|
||||
**基类提供的公共能力**:
|
||||
- `_try_tools(tool_level, funcs)` — 降级执行(见 3.4)
|
||||
- `_run_opencli(args, timeout)` — 调 OpenCLI + 解析输出
|
||||
- `_parse_output(text)` — **输出格式三层兜底解析**(见下)
|
||||
- `_parse_lines(text)` — 纯文本兜底解析
|
||||
|
||||
### 4.2 输出格式三层兜底(细节,容易踩坑)
|
||||
|
||||
OpenCLI 的输出格式**不保证稳定**,所以解析做了三层:
|
||||
|
||||
```python
|
||||
def _parse_output(self, text: str):
|
||||
# 1. JSON 检测(以 [ 或 { 开头)→ json.loads
|
||||
if text.startswith("[") or text.startswith("{"):
|
||||
try:
|
||||
return json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("JSON 解析失败,尝试 YAML 兜底")
|
||||
|
||||
# 2. YAML 解析(PyYAML 可用时)
|
||||
try:
|
||||
import yaml
|
||||
parsed = yaml.safe_load(text)
|
||||
if parsed is not None:
|
||||
return parsed
|
||||
except ImportError:
|
||||
logger.debug("PyYAML 未安装,跳过 YAML")
|
||||
|
||||
# 3. 纯文本兜底:按行解析 key:value
|
||||
return self._parse_lines(text)
|
||||
```
|
||||
|
||||
`_parse_lines` 甚至**专门处理了 `top_comments` 块**(评论在纯文本里的多行结构)。
|
||||
|
||||
**⛔ 移植注意**:如果目标环境没有 PyYAML,会静默降级到第三层
|
||||
(能跑,但嵌套结构会丢)。
|
||||
|
||||
### 4.3 各平台降级链(实测,**差异很大**)
|
||||
|
||||
```python
|
||||
# 抖音(douyin_scrape.py)—— 两条路径
|
||||
await self._try_tools(tool_level, [
|
||||
("opencli", lambda: self._opencli_user_videos(...)),
|
||||
("agent-browser", lambda: self._browser_user_profile(...)), # ← 有浏览器降级
|
||||
])
|
||||
|
||||
# 小红书 / B站 / 知乎 —— ⚠️ 只有一条路径
|
||||
await self._try_tools(2, [
|
||||
("opencli", lambda: self._opencli_user_notes(...)), # ← 没有降级!
|
||||
])
|
||||
|
||||
# 通用网页(web_scrape.py)—— 不用 OpenCLI
|
||||
await self._try_tools(tool_level, [
|
||||
("web_crawler", lambda: self._web_crawl(target)),
|
||||
("agent-browser", lambda: self._browser_extract(target)),
|
||||
])
|
||||
```
|
||||
|
||||
**对照表**:
|
||||
|
||||
| 平台 | 降级链 | 有浏览器降级? | 备注 |
|
||||
|---|---|---|---|
|
||||
| **抖音** | `opencli` → `agent-browser` | ✅ | 唯一做了完整降级的平台 |
|
||||
| **小红书** | `opencli`(单条) | ❌ | OpenCLI 挂了就抓不了 |
|
||||
| **B站** | `opencli`(单条) | ❌ | 同上 |
|
||||
| **知乎** | `opencli`(单条) | ❌ | 同上 |
|
||||
| **通用网页** | `web_crawler` → `agent-browser` | ✅ | 走另一套(不用 OpenCLI) |
|
||||
|
||||
**⚠️ 这是模块的真实局限**:三个平台**只有一条路径**,没有降级能力。
|
||||
接手时如果要提升健壮性,**最值得做的就是给它们补上浏览器降级**
|
||||
(照抖音的 `_browser_*` 方法写即可)。
|
||||
|
||||
**另一个细节**:`collect_user` 传的是**硬编码的 `2`**(不是 `tool_level` 参数),
|
||||
而 `collect_item` 才用传入的 `tool_level`:
|
||||
```python
|
||||
async def collect_user(self, user_id, limit=20): # 没有 tool_level 参数
|
||||
await self._try_tools(2, [...]) # ← 写死 2
|
||||
async def collect_item(self, target, depth, tool_level=2):
|
||||
await self._try_tools(tool_level, [...]) # ← 用参数
|
||||
```
|
||||
→ **用户在前端设 `tool_level=1` 时,"抓用户主页"这条路仍会走到浏览器**。
|
||||
|
||||
### 4.35 登录态机制(★ 这是"如何用真实浏览器"的另一半)
|
||||
|
||||
**问题**:抖音的数据接口需要登录态(cookie),怎么拿到?
|
||||
|
||||
**答案**:`mediacrawler_adapter.py` 的做法 —— **用户在真实 Chrome 登录,程序通过 CDP 读解密后的 cookie**。
|
||||
|
||||
#### 为什么不能直接读 cookie 文件
|
||||
|
||||
代码注释原文(第 29 行):
|
||||
```
|
||||
# Chrome 新版把 cookie 值加密存在 SQLite 里,必须通过 CDP 读解密后的值。
|
||||
```
|
||||
|
||||
Chrome v80+ 把 cookie **加密**存在 SQLite(`Cookies` 文件),
|
||||
直接读文件拿到的是**密文**。必须让 **Chrome 自己解密** → 通过 **CDP 协议**问它。
|
||||
|
||||
#### 三步实现
|
||||
|
||||
**① 通过 CDP 读 cookie**(`_get_cookies`,第 68 行)
|
||||
```python
|
||||
async def _get_cookies() -> dict:
|
||||
"""从 CDP 连接读取 Chrome cookie(解密后的值)"""
|
||||
ctx = await _ensure_cdp() # 确保 CDP 连接
|
||||
all_cookies = await ctx.cookies() # ← 让 Chrome 解密并返回
|
||||
...
|
||||
```
|
||||
|
||||
**② 转成 HTTP Header**(`_cookie_str`,第 86 行)
|
||||
```python
|
||||
def _cookie_str(cookies: dict) -> str:
|
||||
return "; ".join(f"{k}={v}" for k, v in cookies.items())
|
||||
```
|
||||
|
||||
**③ 带 cookie 直调抖音 API**(`_http_get`,第 93 行)
|
||||
```python
|
||||
def _http_get(url: str, cookies: dict, timeout: int = 15) -> dict:
|
||||
headers = {
|
||||
"User-Agent": "...Chrome/150.0.0.0 Safari/537.36",
|
||||
"Cookie": _cookie_str(cookies), # ★
|
||||
"Referer": "https://www.douyin.com/",
|
||||
"Origin": "https://www.douyin.com",
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
#### 登录态判断
|
||||
|
||||
```python
|
||||
cookies = await _get_cookies()
|
||||
has_session = bool(cookies.get("sessionid")) # ← 有 sessionid 就算已登录
|
||||
```
|
||||
对应 HTTP 端点 `GET /api/scrape/check-login`。
|
||||
|
||||
#### 让用户登录(巧妙的做法)
|
||||
|
||||
代码注释(第 433 行):
|
||||
```python
|
||||
# ── 打开登录页(用 AppleScript 控制 Chrome,不需要 CDP) ──
|
||||
"""在 Chrome 中打开抖音首页,让用户登录
|
||||
登录后 cookie 自动保存到 Chrome profile,两个 Chrome 都会检测。"""
|
||||
```
|
||||
|
||||
**→ 用 AppleScript 打开真实 Chrome**(不是 Playwright 控制的),
|
||||
用户**在真实浏览器里手动登录** → cookie 存进 Chrome profile →
|
||||
之后程序通过 CDP 读。
|
||||
|
||||
**这样最自然**:用户看到的是他熟悉的 Chrome,扫码登录,
|
||||
✅ 不会被平台识别为"自动化登录"。
|
||||
|
||||
**⛔ 移植注意**:`open_login_page()` 用的是 **AppleScript**(`osascript`),
|
||||
**macOS 专有**。Linux/Windows 要改实现(可以用 `open` 命令或直接 Playwright 打开)。
|
||||
|
||||
#### 一个隐藏技巧(避免暴露自动化)
|
||||
|
||||
代码注释(第 227-229 行):
|
||||
```python
|
||||
# 获取热评(复用已有 Chrome 页面,不创建新标签页)
|
||||
# Chrome 已有 douyin.com 页面,直接用它的 JS 上下文执行 fetch
|
||||
# ⚠️ 不要 new_page() — 那会在 Chrome 中闪出新标签页
|
||||
```
|
||||
|
||||
**→ 复用用户已经打开的页面**执行 fetch,而不是新开标签页
|
||||
(新标签页会闪一下,且更易被识别)。
|
||||
|
||||
---
|
||||
|
||||
### 4.4 抖音的特有实现(两份代码,别搞混)
|
||||
|
||||
**⚠️ 项目里有**两个**抖音相关模块**,职责不同:
|
||||
|
||||
**① `services/adapters/douyin_scrape.py`(181 行)**
|
||||
- 走**工具降级**(OpenCLI → 浏览器)
|
||||
- 浏览器路径用 JS 从页面 **DOM 文本**提取数据:
|
||||
```javascript
|
||||
// _browser_video_page 的 JS(正则从页面文本抓「获赞/粉丝/关注」)
|
||||
const body = document.body.innerText || '';
|
||||
const uidM = body.match(/抖音号[::]\s*(\S+)/);
|
||||
const nickM = body.match(/@(\S+)/);
|
||||
function extractNum(label) {
|
||||
var m = body.match(new RegExp('(\\d+(?:\\.\\d+)?[万w]?)\\s*' + label));
|
||||
...
|
||||
}
|
||||
return { aweme_id, title, author_nickname, douyin_id, digg_count, fans, following };
|
||||
```
|
||||
|
||||
**② `services/mediacrawler_adapter.py`(457 行)**
|
||||
- **不走工具降级**,完全独立的实现
|
||||
- 文件头注释(原文):
|
||||
> 全新架构:**不再依赖 CDP/Playwright/浏览器页面**。
|
||||
> 直接从 Chrome profile 读取 cookie,通过 HTTP 请求调用抖音 API。
|
||||
> 全程无窗口、无标签页、无闪烁。
|
||||
- 用于**追踪视频/作者**这类需要高频刷新的场景(详见子代理报告)
|
||||
|
||||
**⛔ 关键澄清**:`mediacrawler_adapter.py` **虽然叫 mediacrawler,但不依赖
|
||||
MediaCrawler 这个开源项目**——它只是借用名字,实际是"读 Chrome cookie + HTTP 调 API"。
|
||||
|
||||
---
|
||||
|
||||
## 五、引擎层(`services/scrape_engine.py`,361 行)
|
||||
|
||||
### 5.1 URL 解析(`resolve_target`,第 56 行)
|
||||
|
||||
**7 类目标自动识别**(实测代码):
|
||||
|
||||
```python
|
||||
抖音短链 v.douyin.com/xxx → type=shortlink
|
||||
抖音视频 douyin.com/video/{id} → type=video
|
||||
抖音用户 douyin.com/user/{sec_uid} → type=user
|
||||
小红书 xiaohongshu.com/explore/{id} → type=note
|
||||
B站视频 bilibili.com/video/{BV} → type=video
|
||||
B站用户 bilibili.com/space/{mid} → type=user
|
||||
知乎 zhihu.com/answer/{id} | /question/ → type=item
|
||||
通用网页 http(s)://... → type=page
|
||||
纯 sec_uid MS4w 开头 或 len>20 → douyin/user
|
||||
纯数字 len>=15 → douyin/video(aweme_id)
|
||||
纯数字 其他 → zhihu/item
|
||||
```
|
||||
|
||||
**短链解析**(`_resolve_shortlink`,第 136 行):用 `curl -sI` 拿 `Location` 头,
|
||||
再用正则从跳转 URL 里抠出 `aweme_id`。
|
||||
|
||||
### 5.2 执行主流程(`run`,第 163 行)
|
||||
|
||||
```
|
||||
run(request)
|
||||
├─ 1. resolve_urls(targets) → 标准化目标列表
|
||||
├─ 2. 短链逐个解析
|
||||
├─ 3. 判断同步 / 异步
|
||||
│ async_mode = request.async_mode 或 len(targets) > 50
|
||||
│
|
||||
├─ 【异步分支】
|
||||
│ · run_id = uuid[:8]
|
||||
│ · 内存状态 {status, total, completed, results, errors}
|
||||
│ · asyncio.create_task(_run_async(...))
|
||||
│ · 立即返回 {status:"async", run_id} ← 前端轮询
|
||||
│
|
||||
└─ 【同步分支】
|
||||
· db.create_task("single", ...)
|
||||
· for target: _scrape_one() → _save_item()
|
||||
· db.update_task_status("completed", summary)
|
||||
· 返回 {status, task_id, duration, total, success, errors, data}
|
||||
```
|
||||
|
||||
### 5.3 单目标抓取(`_scrape_one`,第 261 行)
|
||||
|
||||
```python
|
||||
adapter = self._get_adapter(platform) # 按平台取适配器(带缓存)
|
||||
if target["type"] == "user":
|
||||
return await adapter.collect_user(target["target_id"]) # 返回 list
|
||||
elif target["type"] in ("video", "note"):
|
||||
return await adapter.collect_item(target["target_id"], depth, tool_level)
|
||||
else:
|
||||
return None
|
||||
```
|
||||
|
||||
**返回值语义**(重要):
|
||||
- `dict` → 单条内容
|
||||
- `list` → 多条(用户主页的所有作品)
|
||||
- `None` → 失败
|
||||
|
||||
### 5.4 落库(`_save_item`,第 292 行)
|
||||
|
||||
```python
|
||||
db_id = self.db.insert_item(
|
||||
task_id=..., platform=..., item_id=..., url=..., title=...,
|
||||
author_name=..., author_id=..., published_at=..., text_content=...,
|
||||
tags=..., stats=..., extra=..., media=...)
|
||||
|
||||
comments = item.get("comments", [])
|
||||
if comments and db_id:
|
||||
self.db.insert_comments(db_id, comments) # ★ 评论独立表
|
||||
```
|
||||
|
||||
### 5.5 异步模式(`_run_async`,第 315 行)
|
||||
|
||||
- ✅ **同时写内存 + 落库**(内存态供轮询,落库供持久化)
|
||||
- 内存态在 `self._tasks[run_id]`(**进程重启即丢**)
|
||||
- 查询用 `get_async_result(run_id)`
|
||||
|
||||
### 5.6 ⚠️ 已知的局限(接手时要清楚)
|
||||
|
||||
| 局限 | 说明 |
|
||||
|---|---|
|
||||
| **没有限流/并发控制** | `for target in ready:` 是**纯串行**,目标多时会慢;也没有请求间隔(可能触发平台风控) |
|
||||
| **异步态存内存** | 重启 Dashboard 后 `_tasks` 丢失(但库里有记录,前端看不到进度) |
|
||||
| **无重试** | 单目标失败只记 `errors`,不重试 |
|
||||
| **adapter 实例缓存** | `self._adapters` 进程内缓存(无清理) |
|
||||
|
||||
---
|
||||
|
||||
### 5.7 一个完整请求的生命周期(跟着走一遍最快懂)
|
||||
|
||||
以"采集某抖音作者的全部视频"为例:
|
||||
|
||||
```
|
||||
① 前端
|
||||
POST /api/scrape/run
|
||||
{"targets": ["r606391422378804368"], "tool_level": 2}
|
||||
│
|
||||
▼
|
||||
② routes/scrape.py:44 api_scrape_run()
|
||||
组装 request → engine.run(request)
|
||||
│
|
||||
▼
|
||||
③ scrape_engine.py:163 run()
|
||||
├─ resolve_urls(["r6063..."])
|
||||
│ → resolve_target() 识别:以 MS4w 开头 → 抖音 sec_uid
|
||||
│ → [{"platform":"douyin","type":"user","target_id":"r6063...","status":"resolved"}]
|
||||
│
|
||||
├─ 同步或异步?len(targets)=1,不大于 50 → 同步
|
||||
│
|
||||
├─ db.create_task("single","douyin",...) → task_id = 1
|
||||
│
|
||||
├─ for target: _scrape_one(target,"douyin","light",2)
|
||||
│ │
|
||||
│ ▼
|
||||
│ scrape_engine.py:261
|
||||
│ _get_adapter("douyin") → DouyinScrapeAdapter() (进程内缓存)
|
||||
│ type=="user" → adapter.collect_user("r6063...")
|
||||
│ │
|
||||
│ ▼
|
||||
│ douyin_scrape.py:21 collect_user()
|
||||
│ _try_tools(2, [("opencli", ...), ("agent-browser", ...)])
|
||||
│ │
|
||||
│ ├─ 尝试 1:_opencli_user_videos()
|
||||
│ │ _run_opencli(["douyin","user-videos","r6063...",
|
||||
│ │ "--limit","20","--with_comments","true","-f","json"])
|
||||
│ │ → subprocess 执行 opencli(Node CLI)
|
||||
│ │ → _parse_output() ← JSON → YAML → 纯文本 三层兜底
|
||||
│ │ → 成功返回 list[dict] → _try_tools 立刻返回,不再降级
|
||||
│ │
|
||||
│ └─ 尝试 1 失败(OpenCLI 没装/超时/报错)
|
||||
│ → 尝试 2:_browser_user_profile()
|
||||
│ → Playwright 启真实 Chrome → 打开页面 → JS 提取
|
||||
│
|
||||
│ → 每条数据 _to_schema() 转成统一格式
|
||||
│ → 返回 list
|
||||
│
|
||||
├─ for item: _save_item(task_id=1, item)
|
||||
│ db.insert_item(...) → db_id((platform,item_id) 唯一,重复则忽略)
|
||||
│ db.insert_comments(db_id, comments) ← 评论另存
|
||||
│
|
||||
├─ db.update_task_status(1, "completed", summary={success:N, errors:0})
|
||||
│
|
||||
└─ return {status:"completed", task_id:1, duration, total, success, errors, data:[...]}
|
||||
│
|
||||
▼
|
||||
④ 前端拿到 data,渲染列表
|
||||
```
|
||||
|
||||
**异步分支的差异**(目标 > 50 个,或显式 `async_mode=true`):
|
||||
```
|
||||
run() 立即返回 {status:"async", run_id:"ab12cd34"}
|
||||
↓(后台)
|
||||
asyncio.create_task(_run_async(run_id, targets, ...))
|
||||
↓
|
||||
建持久化任务 → 逐个 _scrape_one + _save_item
|
||||
↓
|
||||
进度写内存 self._tasks[run_id](供轮询)
|
||||
结果写 SQLite(供持久化)
|
||||
↓
|
||||
前端轮询 get_async_result(run_id) 看进度
|
||||
```
|
||||
|
||||
**⚠️ 注意**:异步进度**只在内存**,Dashboard 重启就丢
|
||||
(库里数据还在,但前端看不到进度了)。
|
||||
|
||||
---
|
||||
|
||||
## 六、存储层(`services/scrape_db.py`,415 行)
|
||||
|
||||
### 6.1 数据库位置
|
||||
|
||||
```python
|
||||
DEFAULT_DB = AGENT_LOCAL / "data" / "scrape.db"
|
||||
```
|
||||
(`AGENT_LOCAL` 是环境变量;默认 `~/workbuddy-agent-os/agent-local`)
|
||||
|
||||
### 6.2 四张表(实测 `CREATE TABLE`)
|
||||
|
||||
```sql
|
||||
-- ① 采集任务(一次 run 一条)
|
||||
scrape_tasks(
|
||||
id, type, -- single / batch / scheduled
|
||||
platform, target, -- 目标(批量时是 JSON 数组)
|
||||
depth, tool_level, machine,
|
||||
status, -- pending / running / completed / failed
|
||||
total_targets, completed_targets,
|
||||
summary, -- 摘要 JSON
|
||||
created_at
|
||||
)
|
||||
|
||||
-- ② 采集到的内容
|
||||
scrape_items(
|
||||
id, task_id → scrape_tasks,
|
||||
platform, item_id, -- 平台内唯一 ID
|
||||
url, title, author_name, author_id,
|
||||
published_at, collected_at, text_content, tags,
|
||||
... -- 还有 stats / extra / media 等
|
||||
)
|
||||
|
||||
-- ③ 评论
|
||||
scrape_comments(id, item_db_id → scrape_items,
|
||||
author_name, text, likes, replied_at)
|
||||
|
||||
-- ④ 采集源(长期跟踪)
|
||||
scrape_sources(
|
||||
id, platform, source_type, -- user / hashtag / keyword / url_list / api
|
||||
target, display_name,
|
||||
category, -- 自定义分类
|
||||
notes,
|
||||
schedule, -- CRON(定期采集)
|
||||
depth, tool_level, last_collected,
|
||||
status -- active / paused
|
||||
)
|
||||
```
|
||||
|
||||
### 6.3 方法清单(22 个,实测)
|
||||
|
||||
```
|
||||
任务:create_task / update_task_status / get_task / list_tasks
|
||||
内容:insert_item / get_item_id / item_exists / get_item / list_items
|
||||
评论:insert_comments / get_comments
|
||||
采集源:upsert_source / update_source / list_sources / get_due_sources /
|
||||
update_source_collected / delete_source
|
||||
统计:count_by_platform / count_today / sources_count / task_stats
|
||||
```
|
||||
|
||||
### 6.4 去重机制
|
||||
|
||||
`insert_item` **依赖 `(platform, item_id)` 唯一约束** —— 重复插入时
|
||||
用 `INSERT OR IGNORE` 模式(验证文档 L1-2 有测例)。
|
||||
|
||||
---
|
||||
|
||||
## 七、HTTP 层(`routes/scrape.py`,711 行 / 22 端点)
|
||||
|
||||
### 7.1 端点清单(实测)
|
||||
|
||||
```
|
||||
采集
|
||||
POST /api/scrape/run 发起采集(targets + depth + tool_level)
|
||||
POST /api/scrape/resolve 只解析 URL,不采集
|
||||
POST /api/scrape/douyin-stats 抖音数据查询
|
||||
|
||||
查询
|
||||
GET /api/scrape/title 取标题
|
||||
GET /api/scrape/result 结果
|
||||
GET /api/scrape/tasks 任务列表
|
||||
GET /api/scrape/items 内容列表
|
||||
GET /api/scrape/items/{id} 单项详情
|
||||
GET /api/scrape/stats 统计
|
||||
|
||||
采集源管理
|
||||
POST /api/scrape/sources 新建源
|
||||
GET /api/scrape/sources 源列表
|
||||
DEL /api/scrape/sources/{id} 删源
|
||||
|
||||
追踪(视频 / 作者)
|
||||
POST /api/scrape/track-video 追踪视频
|
||||
GET /api/scrape/tracked-videos 已追踪视频
|
||||
POST /api/scrape/delete-tracked/{id}
|
||||
POST /api/scrape/refresh-video/{id} 刷新单个视频
|
||||
POST /api/scrape/track-author 追踪作者
|
||||
GET /api/scrape/tracked-authors 已追踪作者
|
||||
POST /api/scrape/refresh-author/{id}
|
||||
GET /api/scrape/author-history/{id}
|
||||
|
||||
主题 / 登录
|
||||
POST /api/scrape/import-topics 批量导入主题
|
||||
GET /api/scrape/check-login 检测登录态
|
||||
GET /api/scrape/open-login 打开登录
|
||||
```
|
||||
|
||||
### 7.2 关键实现(实测)
|
||||
|
||||
**`POST /api/scrape/run`**(第 43 行)—— 前端发起采集的唯一入口:
|
||||
```python
|
||||
@router.post("/run")
|
||||
async def api_scrape_run(data: dict = {}):
|
||||
targets = data.get("targets", data.get("target", []))
|
||||
if isinstance(targets, str):
|
||||
targets = [targets] # 兼容单个字符串
|
||||
request = {
|
||||
"targets": targets,
|
||||
"platform": data.get("platform", "auto"),
|
||||
"depth": data.get("depth", "light"),
|
||||
"tool_level": data.get("tool_level", 2), # ← 默认 2(OpenCLI + 浏览器)
|
||||
"machine": data.get("machine", ""),
|
||||
"multi_machine": data.get("multi_machine", False),
|
||||
"async_mode": data.get("async_mode", False),
|
||||
}
|
||||
engine = _get_engine() # 模块级单例
|
||||
result = await engine.run(request)
|
||||
return {"status": "ok", **result}
|
||||
```
|
||||
|
||||
**登录态两端点**(第 692 / 703 行)—— 都委托给 `mediacrawler_adapter`:
|
||||
```python
|
||||
GET /api/scrape/check-login → mediacrawler_adapter.check_login_status()
|
||||
POST /api/scrape/open-login → mediacrawler_adapter.open_login_page()
|
||||
```
|
||||
|
||||
### 7.3 引擎实例
|
||||
|
||||
路由层用**模块级单例**拿 engine(`_get_engine()`),
|
||||
所以 `engine._tasks`(异步态)和 `engine._adapters`(适配器缓存)
|
||||
在整个 Dashboard 进程内共享。
|
||||
|
||||
---
|
||||
|
||||
## 七·五、Dashboard 插件(`plugins/crawl.py`,91 行)
|
||||
|
||||
抓取模块**作为 Dashboard 插件**注册(提供概览统计,不是核心逻辑):
|
||||
|
||||
```python
|
||||
class CrawlDashboardPlugin(DashboardPlugin):
|
||||
name = "crawl"
|
||||
label = "内容抓取"
|
||||
icon = "📡"
|
||||
order = 35
|
||||
```
|
||||
|
||||
**它做三件事**:
|
||||
1. `summary()` — 概览:总抓取数 / 今日新增 / 抓取源(从 `ScrapeDB` 读)
|
||||
2. `detail(machine)` — 指定机器的详情
|
||||
3. `actions()` — 快捷操作(跳转 `scrape` 视图)
|
||||
|
||||
**注意**:它有个**兜底设计** —— 如果 `ScrapeDB` 不可用(数据库损坏/权限),
|
||||
会退化成**统计知识库里的 md 文件数**,而不是报错。
|
||||
|
||||
**⛔ 移植注意**:如果目标项目没有这套插件框架,`plugins/crawl.py`
|
||||
可以直接丢弃(它只是 Dashboard 的展示层,不影响抓取功能本身)。
|
||||
|
||||
---
|
||||
|
||||
## 八、前端(`frontend/src/views/scrape.js`,131 KB)
|
||||
|
||||
⚠️ **这是模块里最大的单文件**(131 KB)。功能覆盖:22 个端点的界面。
|
||||
|
||||
**建议接手团队**:不要照搬这个前端,按第七节的 HTTP 契约重写。
|
||||
理由:131 KB 单文件难维护,且和本项目的视图框架耦合。
|
||||
|
||||
---
|
||||
|
||||
## 九、验证方案(项目里已有现成的)
|
||||
|
||||
`services/scrape_validation.md`(314 行)已经写了 **7 个 Level 的验证清单**:
|
||||
|
||||
```
|
||||
L0 基础设施(3 项) Python import / SQLite 建库 / FastAPI 路由注册
|
||||
L1 数据库层(3 项) 建任务 / 写入+去重 / 评论入库
|
||||
L2 适配器 Mock(3 项) 工具降级逻辑 / 一级失败二级成功
|
||||
L3 适配器真实(3 项) 抖音用户采集 / 小红书 / 详情+评论 ← 需 OpenCLI + 登录态
|
||||
L4 引擎层(3 项) 解析 URL / 执行采集 / 异步轮询
|
||||
L5 API 层(4 项) curl 打 4 个端点
|
||||
L6 前端(4 项) 浏览器里操作
|
||||
L7 异常(1+ 项) OpenCLI 不可用时应抛清晰错误
|
||||
```
|
||||
|
||||
**⚠️ 但要注意**:该文档写于 2026-07-16,**里面的方法名已过时**:
|
||||
```
|
||||
文档写 resolve_targets ← 不存在
|
||||
代码里是 resolve_urls ← 实际
|
||||
文档写 get_result ← 不存在
|
||||
代码里是 get_async_result ← 实际
|
||||
```
|
||||
**以代码为准**。
|
||||
|
||||
---
|
||||
|
||||
## 十、移植清单(换环境要改什么)
|
||||
|
||||
| # | 依赖 | 位置 | 处理 |
|
||||
|---|---|---|---|
|
||||
| 1 | **OpenCLI**(Node CLI) | `adapters/__init__.py` 的 `OPENCLI` 常量 | 目标机 `npm i -g @jackwener/opencli`,或设 `OPENCLI_PATH` |
|
||||
| 2 | **真实 Chrome** | `browser_helpers.py` 的 `_CHROME_PATHS` | Linux/Windows 要改路径(如 `/usr/bin/google-chrome`) |
|
||||
| 3 | **Playwright** | pip | `pip install playwright && playwright install chromium` |
|
||||
| 4 | **PyYAML** | pip(可选但强烈建议) | 不装会降级到纯文本解析(丢嵌套结构) |
|
||||
| 5 | **AGENT_LOCAL** 环境变量 | `scrape_db.py:18` | 定义了才能定位 `scrape.db` |
|
||||
| 6 | **平台登录态** | Chrome profile | 目标机需手动登录一次目标平台 |
|
||||
| 7 | `SCRAPE_CHROME_USER_DATA` | 环境变量(可选) | 要持久化登录态时指定 |
|
||||
|
||||
### 最小可运行子集(只要"能采集")
|
||||
|
||||
```
|
||||
services/scrape_db.py 数据库(4 表)
|
||||
services/adapters/__init__.py 基类 + 降级 + OpenCLI 调用 + 输出解析
|
||||
services/adapters/browser_helpers.py 浏览器降级
|
||||
services/adapters/<目标平台>_scrape.py 目标平台适配器
|
||||
```
|
||||
—— 这 4 个文件就能跑通单平台采集,不需要 engine/routes/前端。
|
||||
|
||||
---
|
||||
|
||||
## 十一、接手建议(按顺序)
|
||||
|
||||
```
|
||||
第 1 步 装 OpenCLI + Playwright + 真实 Chrome,跑 validation.md 的 L0/L1
|
||||
(这两级零外部依赖,能验证环境对不对)
|
||||
|
||||
第 2 步 跑 L2(Mock 测试)—— 验证降级逻辑,不需要真实平台
|
||||
这时你已经能理解 _try_tools 的语义
|
||||
|
||||
第 3 步 登录目标平台,跑 L3(真实采集)—— 第一次真正拿数据
|
||||
如果 OpenCLI 不通,会看到它降级到浏览器,日志里有 ⚠️
|
||||
|
||||
第 4 步 跑 L4/L5(引擎 + API)
|
||||
|
||||
第 5 步 替换前端(不要照搬 131 KB)
|
||||
|
||||
第 6 步 加你要的东西:限流 / 重试 / 并发控制(现在都没有)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 十二、这个模块还没做的事(接手可以补)
|
||||
|
||||
```
|
||||
① 限流与请求间隔 —— 现在纯串行、无间隔,目标多时可能触发平台风控
|
||||
② 失败重试 —— 现在失败只记 errors
|
||||
③ 并发控制 —— 没有信号量,大量目标只能串行
|
||||
④ 异步态持久化 —— run 进度存内存,重启即丢
|
||||
⑤ 登录态自动检测 —— check-login 端点有,但采集前没强制校验
|
||||
⑥ 代理支持 —— 没有看到代理配置(多账号场景会需要)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 附录:本说明的取证方式(可复现)
|
||||
|
||||
```bash
|
||||
cd 05_tools/10_dashboard
|
||||
# 架构
|
||||
head -20 services/adapters/__init__.py
|
||||
# 浏览器("套真实浏览器"的做法)
|
||||
sed -n '1,70p' services/adapters/browser_helpers.py
|
||||
# 降级机制
|
||||
grep -n "_try_tools" -A 14 services/adapters/__init__.py
|
||||
# 引擎流程
|
||||
grep -nE "^ (async )?def " services/scrape_engine.py
|
||||
# 表结构
|
||||
grep -n "CREATE TABLE" -A 12 services/scrape_db.py
|
||||
# 端点
|
||||
grep -nE "^@router\." routes/scrape.py
|
||||
```
|
||||
+42
-1
@@ -39,7 +39,7 @@ from dotenv import load_dotenv
|
||||
load_dotenv(PROJECT_ROOT / ".env")
|
||||
|
||||
import uvicorn
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse
|
||||
@@ -162,6 +162,32 @@ app.include_router(settings_router, prefix="/api", dependencies=[Depends(require
|
||||
app.include_router(websocket_router, prefix="/api")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def static_cache_headers(request, call_next):
|
||||
"""给前端产物加缓存头。
|
||||
|
||||
**`index.html` 必须 no-cache。** 它没有内容哈希,浏览器会按启发式规则把它缓存住
|
||||
(Starlette 的 StaticFiles 只发 ETag / Last-Modified,不发 Cache-Control),于是
|
||||
打开的还是上一次那份 index.html,指向的还是上一次那个 js 包 —— 现象就是「代码明明
|
||||
发了,界面上却看不见新功能」,只能靠 Ctrl+F5 自救,而每次前端发布会再来一遍。
|
||||
|
||||
带哈希的 `/assets/` 反过来:文件名一变就是新 URL,可以放心让它永久缓存。
|
||||
只处理非 /api 的路径 —— 接口响应自己那套(缓存由客户端和 React Query 管)。
|
||||
"""
|
||||
response = await call_next(request)
|
||||
path = request.url.path
|
||||
if path.startswith("/api/"):
|
||||
return response
|
||||
|
||||
if path.startswith("/assets/") or path.startswith("/logos/"):
|
||||
response.headers.setdefault(
|
||||
"Cache-Control", "public, max-age=31536000, immutable"
|
||||
)
|
||||
elif (response.headers.get("content-type") or "").startswith("text/html"):
|
||||
response.headers.setdefault("Cache-Control", "no-cache")
|
||||
return response
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def serve_frontend():
|
||||
"""Return frontend page"""
|
||||
@@ -175,6 +201,21 @@ async def serve_frontend():
|
||||
}
|
||||
|
||||
|
||||
# 独立的报表页。**刻意不放进 api/webui** —— 那个目录是 gitignore 的 Vite 产物,
|
||||
# 每次构建都会把它清掉。这里的文件是仓库里的源码,直接原样发出去。
|
||||
# 页面本身不含数据,数据走 /api/monitor/matrix(带鉴权),所以这个壳不需要再拦一道。
|
||||
REPORTS_DIR = os.path.join(os.path.dirname(__file__), "reports")
|
||||
|
||||
|
||||
@app.get("/report/matrix")
|
||||
async def serve_matrix_report():
|
||||
"""日期 × 博主 的标签矩阵。"""
|
||||
path = os.path.join(REPORTS_DIR, "matrix.html")
|
||||
if not os.path.exists(path):
|
||||
raise HTTPException(status_code=404, detail="报表页面不存在")
|
||||
return FileResponse(path)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health_check():
|
||||
return {"status": "ok"}
|
||||
|
||||
+29
-3
@@ -82,8 +82,9 @@ class PlatformAdapter:
|
||||
# 也允许直接粘贴裸 id —— 但两边的 id 形状不同,所以分开。
|
||||
creator_bare_re: Pattern
|
||||
note_bare_re: Pattern
|
||||
# 短链(v.douyin.com 这种)无法在不发请求的情况下还原出 id,解析时单独报错,
|
||||
# 好过存一个聚不出目标的值进去。
|
||||
# **分享短链的域名**。保存目标时要联网跟一次跳转,把真实地址解出来 ——
|
||||
# 不解的话存进去的是一串短码,采集时拿它去请求,什么也抓不到(真事:任务 22)。
|
||||
# 注意这让「解析」不再是纯函数:见 service.prepare_target。
|
||||
short_link_hosts: Tuple[str, ...]
|
||||
|
||||
note_fields: Mapping[str, str]
|
||||
@@ -107,6 +108,17 @@ class PlatformAdapter:
|
||||
人能直接点开看的那一个。"""
|
||||
return f"{self.web_base}{self.note_path}/{note_id}"
|
||||
|
||||
def creator_url(self, creator_id: str) -> str:
|
||||
"""博主主页的可点击链接。
|
||||
|
||||
``creator_id`` 是**平台上的那个主页 id**(抖音是 sec_uid),不是 ``creator_hash``
|
||||
—— 哈希是单向的,拼不出地址来。拿不到 id 的地方(小红书那条路根本不落创作者
|
||||
资料)就返回空串,界面上不画按钮,而不是给一个点开 404 的链接。
|
||||
"""
|
||||
if not creator_id:
|
||||
return ""
|
||||
return f"{self.web_base}{self.creator_path}/{creator_id}"
|
||||
|
||||
def note_field(self, record: Dict[str, Any], name: str) -> Any:
|
||||
"""按规范名读作品记录里的原始值(没有就是 None)。"""
|
||||
return record.get(self.note_fields.get(name, name))
|
||||
@@ -144,7 +156,7 @@ XHS = PlatformAdapter(
|
||||
),
|
||||
creator_bare_re=_XHS_BARE_RE,
|
||||
note_bare_re=_XHS_BARE_RE,
|
||||
short_link_hosts=(),
|
||||
short_link_hosts=("xhslink.cn", "xhslink.com"),
|
||||
note_fields={
|
||||
"note_id": "note_id",
|
||||
"title": "title",
|
||||
@@ -240,6 +252,20 @@ def has_adapter(platform: str) -> bool:
|
||||
return platform in ADAPTERS
|
||||
|
||||
|
||||
def creator_url(platform: str, creator_id: str) -> str:
|
||||
"""博主主页链接,**空串是有意义的返回值**。
|
||||
|
||||
平台不认识、或者没拿到主页 id,就返回空串 —— 界面据此不画那个按钮。给一个点开
|
||||
404 的链接,比不画按钮糟得多。
|
||||
|
||||
单独开这个模块级函数(而不是让调用方自己 ``adapter(...)`` 包一层 try),是为了让
|
||||
「哪些情况该空着」只有一处判断。
|
||||
"""
|
||||
if not creator_id or not has_adapter(platform):
|
||||
return ""
|
||||
return adapter(platform).creator_url(creator_id)
|
||||
|
||||
|
||||
def artifact_dir(platform: str) -> str:
|
||||
"""该平台的爬虫会把 jsonl 落在哪个子目录下。
|
||||
|
||||
|
||||
@@ -144,6 +144,95 @@ SETTING_SPECS: List[SettingSpec] = [
|
||||
minimum=0,
|
||||
maximum=600,
|
||||
),
|
||||
SettingSpec(
|
||||
name="identity_mode",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_STR,
|
||||
label="多身份采集",
|
||||
help=(
|
||||
"single=只用一份登录态(默认);pool=把目标分给身份池里的多个账号。"
|
||||
"池模式是**串行分片**,不是并行 —— 同一个出口 IP 上并发多个 cookie 更容易被风控。"
|
||||
),
|
||||
default="single",
|
||||
choices=["single", "pool"],
|
||||
),
|
||||
SettingSpec(
|
||||
name="identity_min_available",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_INT,
|
||||
label="最少可用身份数",
|
||||
help="池模式下可用身份少于这个数就不跑这一轮 —— 别拿一个号硬扛全部目标。",
|
||||
default=1,
|
||||
minimum=1,
|
||||
maximum=20,
|
||||
),
|
||||
SettingSpec(
|
||||
name="identity_switch_delay_sec",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_INT,
|
||||
label="身份切换间隔(秒)",
|
||||
help="换下一个账号之前等多久。同一出口上连续切换登录态更像异常流量。",
|
||||
default=30,
|
||||
minimum=0,
|
||||
maximum=600,
|
||||
),
|
||||
SettingSpec(
|
||||
name="identity_concurrency",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_INT,
|
||||
label="身份并发数",
|
||||
help=(
|
||||
"默认 1(串行)。**只有给每个账号配了独立出口 IP 才建议调大** —— "
|
||||
"同一 IP 上并发多个身份,平台视角是一台设备在不停换访客。"
|
||||
),
|
||||
default=1,
|
||||
minimum=1,
|
||||
maximum=8,
|
||||
),
|
||||
SettingSpec(
|
||||
name="daily_digest_enabled",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_BOOL,
|
||||
label="每天推送视频情况图",
|
||||
help="到点后把**前一天**发布的视频整理成一张表格图片,发到企业微信群(用的是上面的 Webhook)。",
|
||||
default=False,
|
||||
),
|
||||
SettingSpec(
|
||||
name="daily_digest_time",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_STR,
|
||||
label="推送时间",
|
||||
help="24 小时制 HH:MM,例如 09:00。报的是前一天的数据;那一天推过就不会重复推。",
|
||||
default="09:00",
|
||||
),
|
||||
SettingSpec(
|
||||
name="superdir_token",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_SECRET,
|
||||
label="超级编导 Token",
|
||||
help=(
|
||||
"抖音监控里「超级编导导入」用的。超级编导客户端登录后,token 在它的 token.json"
|
||||
" 的 configToken 字段里;过期后(报 4017 账号已在别处登录)重新抄一份。"
|
||||
"只有抖音工作区会用到。"
|
||||
),
|
||||
),
|
||||
SettingSpec(
|
||||
name="superdir_username",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_STR,
|
||||
label="超级编导账号",
|
||||
help="手机号或邮箱。填了账号和密码之后,Token 失效时(4017/5006)会自动重新登录续期。",
|
||||
),
|
||||
SettingSpec(
|
||||
name="superdir_password",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_SECRET,
|
||||
label="超级编导密码",
|
||||
help=(
|
||||
"只存本机数据库、不会回显。账号或密码错了会报 1002(连续失败可能锁号),"
|
||||
"先去超级编导客户端确认密码。"
|
||||
),
|
||||
),
|
||||
SettingSpec(
|
||||
name="enable_ip_proxy",
|
||||
scope=SCOPE_PLATFORM,
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""扫博主主页,找出**最早一条视频**的发布时间。
|
||||
|
||||
抖音的作品列表按时间倒序、按游标翻页:要知道「这个号第一条视频是什么时候发的」,
|
||||
只能一页页翻到最后一页。一个号几十上百条作品就是十几次请求,接口还时不时超时 ——
|
||||
所以这件事不能放在采集主流程里,更不能放在矩阵页的请求里。做法是:
|
||||
|
||||
* 扫一次存进 ``monitor_creator_first_video``,30 天内不再扫(老作品不会变);
|
||||
* 由调度器在**后台任务**里慢慢扫,不占调度循环;
|
||||
* 矩阵只读缓存,读不到就退回库里最早的一条作品。
|
||||
|
||||
翻到 ``MAX_PAGES`` 页还没到底(作品上千条)就带着已有结果收工,标记为不完整 ——
|
||||
为了一个日期打几十次请求不划算,翻到的部分里最早那条已经足够接近。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from . import adapters, douyin_api
|
||||
from .db import get_session
|
||||
from .models import (
|
||||
MonitorCreatorFirstVideo,
|
||||
MonitorCreatorStat,
|
||||
MonitorNote,
|
||||
MonitorTask,
|
||||
)
|
||||
|
||||
PAGE_SIZE = 20
|
||||
# 最多翻 50 页 = 1000 条作品。
|
||||
MAX_PAGES = 50
|
||||
# 单个博主最多扫这么久;到点带着已有结果收工,标记不完整。
|
||||
MAX_SECONDS_PER_CREATOR = 180
|
||||
# 两次请求之间歇一下:主页接口不是我们的,连着打更容易被限流。
|
||||
REQUEST_GAP_SECONDS = 0.5
|
||||
# 扫到的值 30 天内复用。
|
||||
TTL_MS = 30 * 24 * 60 * 60_000
|
||||
# 失败之后多久重试(用把 checked_at 往前拨的方式表达)。
|
||||
RETRY_MS = 6 * 60 * 60_000
|
||||
# 一批最多处理多少个博主。调度器每个 tick 都来问一次,扫完了自然不再有 due。
|
||||
BATCH_SIZE = 20
|
||||
|
||||
|
||||
async def due_creators(
|
||||
session: AsyncSession,
|
||||
platform: str,
|
||||
now: int,
|
||||
limit: int = BATCH_SIZE,
|
||||
) -> List[Tuple[str, str]]:
|
||||
"""需要(重新)扫的 ``(creator_hash, creator_id)``,最近活跃的优先。"""
|
||||
task_ids = select(MonitorTask.id).where(MonitorTask.platform == platform)
|
||||
|
||||
candidates: Dict[Tuple[str, str], int] = {}
|
||||
note_rows = await session.execute(
|
||||
select(
|
||||
MonitorNote.creator_hash,
|
||||
MonitorNote.creator_id,
|
||||
func.max(MonitorNote.last_seen_at),
|
||||
)
|
||||
.where(MonitorNote.task_id.in_(task_ids), MonitorNote.creator_id != "")
|
||||
.group_by(MonitorNote.creator_hash, MonitorNote.creator_id)
|
||||
)
|
||||
for creator_hash, creator_id, seen_at in note_rows.all():
|
||||
candidates[(creator_hash, creator_id)] = seen_at or 0
|
||||
|
||||
# 作品模式早期入库的笔记没有 creator_id,但快照里可能有 —— 两边都收进来。
|
||||
stat_rows = await session.execute(
|
||||
select(MonitorCreatorStat.creator_hash, MonitorCreatorStat.creator_id)
|
||||
.where(
|
||||
MonitorCreatorStat.task_id.in_(task_ids),
|
||||
MonitorCreatorStat.creator_id != "",
|
||||
)
|
||||
.group_by(MonitorCreatorStat.creator_hash, MonitorCreatorStat.creator_id)
|
||||
)
|
||||
for creator_hash, creator_id in stat_rows.all():
|
||||
candidates.setdefault((creator_hash, creator_id), 0)
|
||||
|
||||
cached = {
|
||||
row.creator_id: row
|
||||
for row in await session.scalars(
|
||||
select(MonitorCreatorFirstVideo).where(
|
||||
MonitorCreatorFirstVideo.platform == platform
|
||||
)
|
||||
)
|
||||
}
|
||||
due = [
|
||||
key
|
||||
for key in candidates
|
||||
if key[1] not in cached
|
||||
or now - (cached[key[1]].checked_at or 0) >= TTL_MS
|
||||
]
|
||||
due.sort(key=lambda key: candidates[key], reverse=True)
|
||||
return due[:limit]
|
||||
|
||||
|
||||
async def _scan(creator_id: str) -> Tuple[Optional[int], int, bool]:
|
||||
"""从最新一页翻到最后一页,返回 ``(最早时间毫秒, 页数, 是否翻到底)``。"""
|
||||
identity = await douyin_api.browser_identity()
|
||||
cursor = 0
|
||||
oldest: Optional[int] = None
|
||||
pages = 0
|
||||
complete = False
|
||||
started = time.monotonic()
|
||||
|
||||
while pages < MAX_PAGES:
|
||||
videos, next_cursor, has_more = await douyin_api.author_videos_page(
|
||||
creator_id, cursor, PAGE_SIZE, identity=identity
|
||||
)
|
||||
pages += 1
|
||||
|
||||
stamps = [
|
||||
adapters.DY.to_ms(video.get("create_time")) for video in videos
|
||||
]
|
||||
stamps = [stamp for stamp in stamps if stamp]
|
||||
if stamps:
|
||||
page_oldest = min(stamps)
|
||||
oldest = page_oldest if oldest is None else min(oldest, page_oldest)
|
||||
|
||||
if not has_more or not videos:
|
||||
complete = True
|
||||
break
|
||||
# 游标不动就是到了尽头(接口偶尔 has_more 和游标对不上),别死循环。
|
||||
if not next_cursor or next_cursor == cursor:
|
||||
break
|
||||
cursor = next_cursor
|
||||
|
||||
if time.monotonic() - started >= MAX_SECONDS_PER_CREATOR:
|
||||
break
|
||||
await asyncio.sleep(REQUEST_GAP_SECONDS)
|
||||
|
||||
return oldest, pages, complete
|
||||
|
||||
|
||||
async def scan_one(
|
||||
session: AsyncSession,
|
||||
platform: str,
|
||||
creator_hash: str,
|
||||
creator_id: str,
|
||||
now: Optional[int] = None,
|
||||
) -> bool:
|
||||
"""扫一个博主并写缓存。返回是否成功(失败也落一行,记录原因和下次重试时间)。"""
|
||||
now = now or get_current_timestamp()
|
||||
row = await session.scalar(
|
||||
select(MonitorCreatorFirstVideo).where(
|
||||
MonitorCreatorFirstVideo.platform == platform,
|
||||
MonitorCreatorFirstVideo.creator_id == creator_id,
|
||||
)
|
||||
)
|
||||
if row is None:
|
||||
row = MonitorCreatorFirstVideo(
|
||||
platform=platform,
|
||||
creator_id=creator_id,
|
||||
creator_hash=creator_hash,
|
||||
checked_at=0,
|
||||
)
|
||||
session.add(row)
|
||||
|
||||
try:
|
||||
oldest, pages, complete = await _scan(creator_id)
|
||||
except Exception as exc: # noqa: BLE001 - 接口抖动不该炸掉整批
|
||||
row.creator_hash = creator_hash
|
||||
row.error = str(exc)[:500]
|
||||
# checked_at 往前拨,让这一行在 RETRY_MS 之后重新进入待扫队列;
|
||||
# 不拨到 now 是因为那会把它锁 30 天。
|
||||
row.checked_at = now - TTL_MS + RETRY_MS
|
||||
return False
|
||||
|
||||
row.creator_hash = creator_hash
|
||||
row.first_published_at = oldest
|
||||
row.scanned_pages = pages
|
||||
row.complete = complete
|
||||
row.checked_at = now
|
||||
row.error = ""
|
||||
return True
|
||||
|
||||
|
||||
async def refresh_batch(
|
||||
platform: str = adapters.PLATFORM_DY, limit: int = BATCH_SIZE
|
||||
) -> Dict[str, int]:
|
||||
"""扫一批到期的博主。由调度器的后台任务调用。"""
|
||||
now = get_current_timestamp()
|
||||
async with get_session() as session:
|
||||
due = await due_creators(session, platform, now, limit)
|
||||
|
||||
scanned = failed = 0
|
||||
for creator_hash, creator_id in due:
|
||||
async with get_session() as session:
|
||||
ok = await scan_one(
|
||||
session, platform, creator_hash, creator_id,
|
||||
now=get_current_timestamp(),
|
||||
)
|
||||
if ok:
|
||||
scanned += 1
|
||||
else:
|
||||
failed += 1
|
||||
return {"due": len(due), "scanned": scanned, "failed": failed}
|
||||
+9
-1
@@ -44,7 +44,7 @@ from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from typing import AsyncIterator, Optional
|
||||
|
||||
from sqlalchemy import Column, event, text
|
||||
from sqlalchemy import Column, LargeBinary, Text, event, text
|
||||
from sqlalchemy.dialects import mysql
|
||||
from sqlalchemy.schema import CreateColumn
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
@@ -256,9 +256,17 @@ def _column_ddl(column: Column) -> str:
|
||||
separately because a model's ``default=`` is applied by the ORM and never
|
||||
reaches the DDL -- and a NOT NULL column added to a populated table needs a
|
||||
value for the rows already sitting there.
|
||||
|
||||
**TEXT/BLOB columns never get a DEFAULT.** MySQL 5.7 rejects it outright
|
||||
("BLOB, TEXT, GEOMETRY or JSON column can't have a default value"), and this
|
||||
runs during startup: the whole service fails to boot and the container
|
||||
crash-loops. MySQL still fills existing rows with the type's implicit default,
|
||||
which is what we want anyway.
|
||||
"""
|
||||
ddl = str(CreateColumn(column).compile(dialect=mysql.dialect()))
|
||||
if not column.nullable and column.server_default is None:
|
||||
if isinstance(column.type, (Text, LargeBinary)):
|
||||
return ddl
|
||||
seed = _implicit_default(column)
|
||||
if seed is not None:
|
||||
ddl += f" DEFAULT {seed}"
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""「昨天的视频情况」—— 生成一张表格图片,发到企业微信。
|
||||
|
||||
**为什么是图片而不是文字。** 企业微信的 markdown 在手机上不支持表格,用空格对齐的
|
||||
文本会被挤成一团;运营要的是扫一眼各号的数据,所以直接画成图。
|
||||
|
||||
**为什么报的是昨天。** 早上九点推前一天的账:当天还没过完,上午发「今天的」只会是
|
||||
半张表,而且到晚上数据已经翻了几倍,早上那一眼就白看了。取「昨天」也避开了一个
|
||||
坑 —— 跨零点时 `date.today()` 和用户心里的「今天」经常不是一天。
|
||||
|
||||
**为什么没有播放量。** 抖音的 `statistics.play_count` 对普通作品恒为 0(见
|
||||
`platforms.py` 的说明),所以表里不摆这一列 —— 宁可少一列,也不要一整列 0。
|
||||
"""
|
||||
|
||||
import io
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Sequence
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from . import notify
|
||||
from .models import MonitorNote, MonitorNoteMetric, MonitorTask
|
||||
|
||||
# 按出现顺序找第一个能用的。容器里装的是 wqy(见 Dockerfile);开发机上是微软雅黑。
|
||||
FONT_CANDIDATES = (
|
||||
"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
|
||||
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
||||
"/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
|
||||
"C:/Windows/Fonts/msyh.ttc",
|
||||
"C:/Windows/Fonts/simhei.ttf",
|
||||
)
|
||||
|
||||
# --- 版式 -------------------------------------------------------------------
|
||||
WIDTH = 1080
|
||||
MARGIN = 24
|
||||
TITLE_FONT = 30
|
||||
BODY_FONT = 19
|
||||
SMALL_FONT = 16
|
||||
HEADER_H = 40
|
||||
ROW_H = 44
|
||||
MAX_ROWS = 40 # 再多就只是一张长图,手机上一屏看不完;超出部分用文字交代
|
||||
|
||||
# 列:左边界 + 宽度。右边界 = MARGIN + sum(widths) = WIDTH - MARGIN
|
||||
COLS = (
|
||||
("博主", 24, 215, "left"),
|
||||
("标题", 239, 515, "left"),
|
||||
("点赞", 754, 80, "right"),
|
||||
("评论", 834, 70, "right"),
|
||||
("收藏", 904, 70, "right"),
|
||||
("分享", 974, 82, "right"),
|
||||
)
|
||||
|
||||
BG = (255, 255, 255)
|
||||
INK = (15, 23, 42)
|
||||
MUTED = (100, 116, 139)
|
||||
LINE = (226, 232, 240)
|
||||
HEAD_BG = (15, 23, 42)
|
||||
HEAD_INK = (255, 255, 255)
|
||||
ALT_BG = (248, 250, 252)
|
||||
ACCENT = (14, 165, 233)
|
||||
|
||||
|
||||
def default_day() -> date:
|
||||
"""这张图默认报哪一天 —— 昨天。
|
||||
|
||||
定时推送、手动发送、预览都走这里,三处口径必须一致,否则「预览看着没问题、
|
||||
早上收到的是另一张」。
|
||||
"""
|
||||
return date.today() - timedelta(days=1)
|
||||
|
||||
|
||||
def _font_path() -> Optional[str]:
|
||||
for candidate in FONT_CANDIDATES:
|
||||
if Path(candidate).is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def _font(size: int) -> ImageFont.FreeTypeFont:
|
||||
path = _font_path()
|
||||
if path is None:
|
||||
raise RuntimeError(
|
||||
"找不到中文字体,无法生成图片。容器需要 fonts-wqy-zenhei(见 Dockerfile)。"
|
||||
)
|
||||
try:
|
||||
return ImageFont.truetype(path, size, index=0)
|
||||
except OSError:
|
||||
return ImageFont.truetype(path, size)
|
||||
|
||||
|
||||
def _fit(draw: ImageDraw.ImageDraw, text: str, font, max_width: int) -> str:
|
||||
"""超出列宽就截断并加省略号 —— 不能让文字压到下一列上。"""
|
||||
if draw.textlength(text, font=font) <= max_width:
|
||||
return text
|
||||
trimmed = text
|
||||
while trimmed and draw.textlength(trimmed + "…", font=font) > max_width:
|
||||
trimmed = trimmed[:-1]
|
||||
return trimmed + "…" if trimmed else "…"
|
||||
|
||||
|
||||
def _number(value: Optional[int]) -> str:
|
||||
if value is None:
|
||||
return "—"
|
||||
return f"{value:,}"
|
||||
|
||||
|
||||
async def daily_rows(
|
||||
session: AsyncSession, platform: str, day: Optional[date] = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""某一天发布的作品 + 各自最近一轮的指标,按点赞降序。
|
||||
|
||||
「当天」按**发布时间**算(不是首次采到):这张图回答的是「他们那天发了什么」。
|
||||
不传 ``day`` 就是昨天,见 :func:`default_day`。
|
||||
"""
|
||||
target_day = day or default_day()
|
||||
start = int(datetime.combine(target_day, datetime.min.time()).timestamp() * 1000)
|
||||
end = start + 86_400_000
|
||||
|
||||
task_ids = list(
|
||||
await session.scalars(select(MonitorTask.id).where(MonitorTask.platform == platform))
|
||||
)
|
||||
if not task_ids:
|
||||
return []
|
||||
|
||||
notes = (
|
||||
await session.execute(
|
||||
select(
|
||||
MonitorNote.task_id,
|
||||
MonitorNote.note_id,
|
||||
MonitorNote.title,
|
||||
MonitorNote.creator_name,
|
||||
MonitorNote.hashtags,
|
||||
MonitorNote.published_at,
|
||||
)
|
||||
.where(
|
||||
MonitorNote.task_id.in_(task_ids),
|
||||
MonitorNote.published_at.is_not(None),
|
||||
MonitorNote.published_at >= start,
|
||||
MonitorNote.published_at < end,
|
||||
)
|
||||
.order_by(MonitorNote.published_at.desc())
|
||||
)
|
||||
).all()
|
||||
if not notes:
|
||||
return []
|
||||
|
||||
note_ids = {row.note_id for row in notes}
|
||||
metric_rows = (
|
||||
await session.execute(
|
||||
select(
|
||||
MonitorNoteMetric.task_id,
|
||||
MonitorNoteMetric.note_id,
|
||||
MonitorNoteMetric.run_id,
|
||||
MonitorNoteMetric.liked_count,
|
||||
MonitorNoteMetric.comment_count,
|
||||
MonitorNoteMetric.collected_count,
|
||||
MonitorNoteMetric.share_count,
|
||||
).where(
|
||||
MonitorNoteMetric.task_id.in_(task_ids),
|
||||
MonitorNoteMetric.note_id.in_(note_ids),
|
||||
)
|
||||
)
|
||||
).all()
|
||||
latest: Dict[tuple, Any] = {}
|
||||
for metric in metric_rows:
|
||||
key = (metric.task_id, metric.note_id)
|
||||
current = latest.get(key)
|
||||
if current is None or metric.run_id > current.run_id:
|
||||
latest[key] = metric
|
||||
|
||||
rows: List[Dict[str, Any]] = []
|
||||
seen: set = set()
|
||||
for note in notes:
|
||||
# 同一个作品挂在多个任务下时只算一次。
|
||||
if note.note_id in seen:
|
||||
continue
|
||||
seen.add(note.note_id)
|
||||
metric = latest.get((note.task_id, note.note_id))
|
||||
rows.append(
|
||||
{
|
||||
"note_id": note.note_id,
|
||||
"creator": note.creator_name or "",
|
||||
"title": note.title or "",
|
||||
"hashtags": note.hashtags or "",
|
||||
"likes": metric.liked_count if metric else None,
|
||||
"comments": metric.comment_count if metric else None,
|
||||
"collected": metric.collected_count if metric else None,
|
||||
"shares": metric.share_count if metric else None,
|
||||
}
|
||||
)
|
||||
|
||||
# 点赞降序,取不到指标的沉底 —— 图的最上面应该是最值得看的。
|
||||
rows.sort(key=lambda item: (item["likes"] is None, -(item["likes"] or 0)))
|
||||
return rows
|
||||
|
||||
|
||||
def render_table(
|
||||
rows: Sequence[Dict[str, Any]], day: date, platform_label: str = "抖音"
|
||||
) -> bytes:
|
||||
"""把当天的数据画成 PNG。没有数据也画一张 —— 「今天没发」本身就是要报的信息。"""
|
||||
title_font = _font(TITLE_FONT)
|
||||
body_font = _font(BODY_FONT)
|
||||
small_font = _font(SMALL_FONT)
|
||||
|
||||
shown = list(rows[:MAX_ROWS])
|
||||
overflow = max(0, len(rows) - len(shown))
|
||||
|
||||
head_height = 120
|
||||
table_h = HEADER_H + ROW_H * len(shown) if shown else 120
|
||||
footer_h = 56
|
||||
height = head_height + table_h + footer_h
|
||||
|
||||
image = Image.new("RGB", (WIDTH, height), BG)
|
||||
draw = ImageDraw.Draw(image)
|
||||
|
||||
# --- 标题 ---
|
||||
draw.text(
|
||||
(MARGIN, 26),
|
||||
f"{platform_label} · {day.isoformat()} 视频情况",
|
||||
font=title_font,
|
||||
fill=INK,
|
||||
)
|
||||
if rows:
|
||||
totals = {
|
||||
"条数": len(rows),
|
||||
"点赞": sum(row["likes"] or 0 for row in rows),
|
||||
"评论": sum(row["comments"] or 0 for row in rows),
|
||||
"收藏": sum(row["collected"] or 0 for row in rows),
|
||||
"分享": sum(row["shares"] or 0 for row in rows),
|
||||
}
|
||||
summary = " · ".join(f"{key} {value:,}" for key, value in totals.items())
|
||||
else:
|
||||
summary = "今天没有新作品"
|
||||
draw.text((MARGIN, 76), summary, font=small_font, fill=MUTED)
|
||||
|
||||
# --- 表头 ---
|
||||
top = head_height
|
||||
draw.rectangle((MARGIN, top, WIDTH - MARGIN, top + HEADER_H), fill=HEAD_BG)
|
||||
for name, x, width, align in COLS:
|
||||
if align == "right":
|
||||
draw.text(
|
||||
(x + width - 10, top + 10),
|
||||
name,
|
||||
font=small_font,
|
||||
fill=HEAD_INK,
|
||||
anchor="ra",
|
||||
)
|
||||
else:
|
||||
draw.text((x + 6, top + 10), name, font=small_font, fill=HEAD_INK)
|
||||
|
||||
# --- 数据行 ---
|
||||
y = top + HEADER_H
|
||||
if not shown:
|
||||
draw.text(
|
||||
(WIDTH // 2, y + 34),
|
||||
"今天没有新作品",
|
||||
font=body_font,
|
||||
fill=MUTED,
|
||||
anchor="ma",
|
||||
)
|
||||
y += 100
|
||||
for index, row in enumerate(shown):
|
||||
if index % 2 == 1:
|
||||
draw.rectangle((MARGIN, y, WIDTH - MARGIN, y + ROW_H), fill=ALT_BG)
|
||||
draw.line((MARGIN, y + ROW_H, WIDTH - MARGIN, y + ROW_H), fill=LINE, width=1)
|
||||
|
||||
baseline = y + 12
|
||||
for name, x, width, align in COLS:
|
||||
# 字体宽度估不准,左右各留一点:满宽的名字会直接贴上下一列,读起来像连成
|
||||
# 一个词(「周周苏州家庭服务见闻蹲一个老苏州说说」)。
|
||||
if name == "博主":
|
||||
text = _fit(draw, row["creator"] or "—", body_font, width - 20)
|
||||
draw.text((x + 6, baseline), text, font=body_font, fill=INK)
|
||||
elif name == "标题":
|
||||
text = _fit(draw, row["title"] or "—", body_font, width - 20)
|
||||
draw.text((x + 6, baseline), text, font=body_font, fill=INK)
|
||||
else:
|
||||
key = {"点赞": "likes", "评论": "comments", "收藏": "collected", "分享": "shares"}[name]
|
||||
value = row[key]
|
||||
draw.text(
|
||||
(x + width - 10, baseline + 2),
|
||||
_number(value),
|
||||
font=small_font,
|
||||
fill=INK if value else MUTED,
|
||||
anchor="ra",
|
||||
)
|
||||
y += ROW_H
|
||||
|
||||
# --- 页脚 ---
|
||||
footer = f"共 {len(rows)} 条"
|
||||
if overflow:
|
||||
footer += f",图中只列点赞最高的 {len(shown)} 条,另有 {overflow} 条未列出"
|
||||
footer += " · 播放量抖音未提供,故未统计"
|
||||
draw.text((MARGIN, y + 16), footer, font=small_font, fill=MUTED)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG", optimize=True)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
async def send_daily_digest(
|
||||
session: AsyncSession, platform: str, day: Optional[date] = None
|
||||
) -> tuple[bool, str, int]:
|
||||
"""生成并发送。返回 (ok, detail, 作品条数)。不传 ``day`` 就是昨天。"""
|
||||
target_day = day or default_day()
|
||||
rows = await daily_rows(session, platform, target_day)
|
||||
webhook = await notify.get_webhook_url(session)
|
||||
if not webhook:
|
||||
return False, "Webhook 未配置", len(rows)
|
||||
|
||||
label = "抖音" if platform == "dy" else "小红书"
|
||||
image_bytes = render_table(rows, target_day, label)
|
||||
ok, detail = await notify.send_wecom_image(webhook, image_bytes)
|
||||
return ok, detail, len(rows)
|
||||
@@ -0,0 +1,698 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright (c) 2025 [email protected]
|
||||
#
|
||||
# This file is part of MediaCrawler project.
|
||||
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/api/monitor/douyin_api.py
|
||||
# GitHub: https://github.com/NanmiCoder
|
||||
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
|
||||
#
|
||||
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
|
||||
# 1. 不得用于任何商业用途。
|
||||
# 2. 使用时应遵守对应平台的使用条款和robots.txt规则。
|
||||
# 3. 不得进行大规模爬取或对平台造成运营干扰。
|
||||
# 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。
|
||||
# 5. 不得用于任何非法或不当的用途。
|
||||
#
|
||||
# 详细许可条款请参阅项目根目录下的LICENSE文件。
|
||||
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
|
||||
|
||||
"""抖音 Web 接口客户端 —— 直接发 HTTP,不起爬虫子进程。
|
||||
|
||||
**为什么另起一套。** 爬虫那条路(``media_platform/douyin``)会构造一大串浏览器指纹
|
||||
参数:``browser_platform=MacIntel``、``os_name=Mac OS``、``browser_version=125.0.0.0``……
|
||||
而 ``User-Agent`` 是从页面现读的(在服务器上是 Linux + Chrome 155)。参数说自己是 Mac,
|
||||
UA 说自己是 Linux —— 抖音网关对这种自相矛盾的请求的处理方式是:**不报错、不给原因,
|
||||
回一个 200 + 空 body**。爬虫那边把它翻译成 ``Exception("account blocked")``,看起来像
|
||||
账号被封,其实什么都不是。
|
||||
|
||||
这份客户端只发必要参数(``device_platform`` / ``aid`` 那两三个),走浏览器自己也在用的
|
||||
那条调用路径。它的做法来自 mac-agent-os 项目的 ``mediacrawler_adapter.py``,实测可用。
|
||||
|
||||
两个关键点:
|
||||
|
||||
* **cookie 走 CDP 现读。** Chrome 把 cookie 值加密存在 SQLite 里,只有 CDP 拿得到
|
||||
解密后的值;而且浏览器里那份比库里存的旧快照新 —— 站点会自己轮换会话。
|
||||
* **产物形状照抄 store。** ``aweme_id`` / ``aweme_url`` / ``cover_url`` / ``aweme_type`` /
|
||||
``create_time``(**秒**,由 adapters 换算成毫秒)…… 这样 ingest 那条链路一个字都不用改。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import config
|
||||
import httpx
|
||||
from tools import utils
|
||||
from tools.user_hash import anonymize_user_id
|
||||
|
||||
# 请求头。**要像一个浏览器**,而且必须是**同一个浏览器**:见 BrowserIdentity。
|
||||
_BASE_HEADERS = {
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||
"Referer": "https://www.douyin.com/",
|
||||
"Origin": "https://www.douyin.com",
|
||||
}
|
||||
|
||||
# 网关的业务前置校验头。缺了它,抖音边缘网关的 ArgusSecurityPlugin 会直接回
|
||||
# 403 并写明 "Blocked by ArgusSecurityPlugin Uifid Not Found" —— 难得一次它会说原因。
|
||||
# 当前网关并不校验这个头的**值**,填什么都行;一旦升级到真校验,就得改成让页面里的
|
||||
# SDK 自己生成(见 media_platform/douyin/client.py 里同一条注释)。
|
||||
ARGUS_HEADER_VALUE = "1"
|
||||
|
||||
API_ORIGIN = "https://www.douyin.com"
|
||||
PROFILE_PATH = "/aweme/v1/web/user/profile/other/"
|
||||
POSTS_PATH = "/aweme/v1/web/aweme/post/"
|
||||
DETAIL_PATH = "/aweme/v1/web/aweme/detail/"
|
||||
COMMENT_PATH = "/aweme/v1/web/comment/list/"
|
||||
|
||||
# 一次请求的超时。抖音这两个接口正常都在一秒内返回。
|
||||
REQUEST_TIMEOUT_SECONDS = 20.0
|
||||
|
||||
# 问浏览器要 UA / client hints 的超时。**这个必须有。**
|
||||
# ``page.evaluate`` 打在一个渲染进程已经卡住的标签页上会**永远不返回**,而问身份是采集的
|
||||
# 第一步 —— 它一挂,整个 run 就永远停在「运行中」(真踩过:标签页 URL 是空的,
|
||||
# cookies() 正常,evaluate 一直不回来)。
|
||||
EVALUATE_TIMEOUT_SECONDS = 8.0
|
||||
# 单页最多要多少条。接口自己有上限,要多了也没用。
|
||||
MAX_PAGE_SIZE = 20
|
||||
|
||||
|
||||
class DouyinApiError(RuntimeError):
|
||||
"""请求失败,或登录态不可用。"""
|
||||
|
||||
|
||||
def _cdp_url() -> str:
|
||||
"""浏览器 DevTools 端点。与扫码登录那边共用同一个开关。"""
|
||||
return os.getenv("MC_CDP_URL") or f"http://127.0.0.1:{config.CDP_DEBUG_PORT}"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BrowserIdentity:
|
||||
"""一个请求要像浏览器所需要的全部身份信息,**且必须来自同一个浏览器**。
|
||||
|
||||
只拿 cookie 是不够的。UA 声称自己是 Chrome 155、却不带 Chrome 155 该有的
|
||||
``sec-ch-ua``,网关一眼就能看出这不是浏览器 —— 它的回应是 **200 + 空 body**:
|
||||
不报错、不给原因,只看得到「抓到 0 条」。所以这三样必须成套地从同一处取。
|
||||
"""
|
||||
|
||||
cookie: str
|
||||
user_agent: str
|
||||
client_hints: Dict[str, str]
|
||||
# 身份池里的标识:``"browser"`` / ``"id:<n>"`` / ``"legacy"``。只用于日志与分片,
|
||||
# 不参与请求。放在最后且有默认值,现有构造点不用改。
|
||||
identity_key: str = "legacy"
|
||||
|
||||
def headers(self) -> Dict[str, str]:
|
||||
headers = {
|
||||
"User-Agent": self.user_agent,
|
||||
**self.client_hints,
|
||||
**_BASE_HEADERS,
|
||||
"x-tt-argus": ARGUS_HEADER_VALUE,
|
||||
"Cookie": self.cookie,
|
||||
}
|
||||
# uifid 是设备标识,网关要它;cookie 里没有就不带(送空值反而更像异常请求)。
|
||||
uifid = _cookie_value(self.cookie, "UIFID") or _cookie_value(
|
||||
self.cookie, "UIFID_TEMP"
|
||||
)
|
||||
if uifid:
|
||||
headers["uifid"] = uifid
|
||||
return headers
|
||||
|
||||
|
||||
# 身份信息的短时缓存:一次采集要发好几个请求,没必要每次都连一遍 CDP。
|
||||
_IDENTITY_TTL_SECONDS = 120.0
|
||||
_identity_cache: Optional[Tuple[float, BrowserIdentity]] = None
|
||||
|
||||
|
||||
async def _safe_evaluate(page: Any, expression: str) -> Any:
|
||||
"""在页面上求值,带超时;任何失败都返回 None。
|
||||
|
||||
**不要直接调 ``page.evaluate``** —— 在渲染进程卡住的标签页上它会永远不返回(见
|
||||
``EVALUATE_TIMEOUT_SECONDS`` 那段)。
|
||||
"""
|
||||
try:
|
||||
return await asyncio.wait_for(
|
||||
page.evaluate(expression), timeout=EVALUATE_TIMEOUT_SECONDS
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def _identity_from_pages(context: Any) -> Tuple[str, Dict[str, str]]:
|
||||
"""问出 UA 和 client hints。
|
||||
|
||||
不假设第一个标签页是好的 —— 它可能停在 URL 为空、渲染进程已卡住的状态(实测过)。
|
||||
所以逐个试、每个都带超时;优先抖音页面,全都不行就临时开一个干净页问完关掉。
|
||||
|
||||
拿不到就返回空 —— 调用方据此退回库里那份 cookie,而不是拿一组编出来的指纹去请求
|
||||
(那比没有更糟,见 BrowserIdentity 的说明)。
|
||||
"""
|
||||
from media_platform.douyin.help import client_hint_headers
|
||||
|
||||
pages = list(context.pages)
|
||||
pages.sort(key=lambda page: 0 if "douyin" in (page.url or "") else 1)
|
||||
for page in pages:
|
||||
user_agent = await _safe_evaluate(page, "() => navigator.userAgent")
|
||||
if user_agent:
|
||||
hints = client_hint_headers(
|
||||
await _safe_evaluate(page, "() => navigator.userAgentData || null")
|
||||
)
|
||||
return user_agent, hints or {}
|
||||
|
||||
temp = None
|
||||
try:
|
||||
temp = await asyncio.wait_for(
|
||||
context.new_page(), timeout=EVALUATE_TIMEOUT_SECONDS
|
||||
)
|
||||
user_agent = await _safe_evaluate(temp, "() => navigator.userAgent")
|
||||
hints = client_hint_headers(
|
||||
await _safe_evaluate(temp, "() => navigator.userAgentData || null")
|
||||
)
|
||||
return user_agent or "", hints or {}
|
||||
except Exception:
|
||||
return "", {}
|
||||
finally:
|
||||
if temp is not None:
|
||||
try:
|
||||
await temp.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 起 Playwright 客户端最多等这么久。起不来就当浏览器不可用,回退到库里的 cookie ——
|
||||
# 比把整轮采集钉死在这里强。
|
||||
_START_TIMEOUT_SECONDS = 20.0
|
||||
|
||||
|
||||
async def _abandon_after(coro, timeout: float) -> bool:
|
||||
"""跑一个收尾动作,最多等 ``timeout`` 秒;到点就放手。返回是否正常结束。
|
||||
|
||||
**不能用 ``asyncio.wait_for``。** 它的超时会先取消、再**等取消完成** —— 而这里
|
||||
要收拾的恰恰是「不响应取消」的那种卡死,用它等于什么都没做,依旧会永远等下去。
|
||||
``asyncio.wait`` 到点就返回,不管那个协程还在不在跑。
|
||||
"""
|
||||
task = asyncio.ensure_future(coro)
|
||||
done, _pending = await asyncio.wait({task}, timeout=timeout)
|
||||
if task in done:
|
||||
try:
|
||||
task.result()
|
||||
except Exception: # noqa: BLE001 - 收尾失败无所谓
|
||||
pass
|
||||
return True
|
||||
task.cancel()
|
||||
return False
|
||||
|
||||
|
||||
async def _start_playwright(timeout: float = _START_TIMEOUT_SECONDS):
|
||||
"""起一个 Playwright 客户端;起不来或起得太慢就返回 None。"""
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
task = asyncio.ensure_future(async_playwright().start())
|
||||
done, _pending = await asyncio.wait({task}, timeout=timeout)
|
||||
if task not in done:
|
||||
task.cancel()
|
||||
return None
|
||||
try:
|
||||
return task.result()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
async def _read_browser() -> Optional[BrowserIdentity]:
|
||||
"""连上 CDP 浏览器,一次取齐 cookie、UA、client hints。
|
||||
|
||||
读不到返回 None(浏览器没开/没登录),由调用方决定怎么报 —— 不抛异常。
|
||||
"""
|
||||
from media_platform.douyin.help import client_hint_headers
|
||||
|
||||
playwright = None
|
||||
try:
|
||||
playwright = await _start_playwright()
|
||||
if playwright is None:
|
||||
return None
|
||||
browser = await playwright.chromium.connect_over_cdp(_cdp_url(), timeout=15000)
|
||||
if not browser.contexts:
|
||||
return None
|
||||
# contexts[0] 是真实 profile。**不要 new_context()** —— 那是无痕式的,读不到登录态。
|
||||
context = browser.contexts[0]
|
||||
cookies = await asyncio.wait_for(
|
||||
context.cookies(), timeout=EVALUATE_TIMEOUT_SECONDS
|
||||
)
|
||||
|
||||
# UA 和 hints 要从页面里问 —— 它们是浏览器自己的事实,写死迟早对不上。
|
||||
user_agent, hints = await _identity_from_pages(context)
|
||||
except Exception as exc:
|
||||
utils.logger.warning(f"[douyin_api] 读浏览器身份失败:{exc}")
|
||||
return None
|
||||
finally:
|
||||
if playwright is not None:
|
||||
# 只断开连接。**绝不能 browser.close()** —— 对这个 CDP 连接而言那会关掉
|
||||
# 操作者自己的浏览器。
|
||||
#
|
||||
# **而且必须能放手。** 这里原先只是 `await playwright.stop()`,没有超时:
|
||||
# driver 一旦卡住,`stop()` 永不返回,于是 `_read_browser` 永不返回、
|
||||
# `collect` 永不返回,外面 `asyncio.wait_for` 的超时取消也等不到它结束 ——
|
||||
# 整轮采集永远停在「运行中」,产物目录全空。实测库里挂了 7 条这样的幽灵,
|
||||
# 最久 48 小时。用 _abandon_after 到点就走。
|
||||
await _abandon_after(playwright.stop(), EVALUATE_TIMEOUT_SECONDS)
|
||||
|
||||
douyin_cookies = {
|
||||
cookie["name"]: cookie["value"]
|
||||
for cookie in cookies
|
||||
if "douyin" in cookie.get("domain", "") or "amemv" in cookie.get("domain", "")
|
||||
}
|
||||
return BrowserIdentity(
|
||||
cookie=_cookie_from_dict(douyin_cookies),
|
||||
user_agent=user_agent or "",
|
||||
client_hints=hints,
|
||||
)
|
||||
|
||||
|
||||
async def browser_identity(cookie: str = "", force: bool = False) -> BrowserIdentity:
|
||||
"""拿到一份可用的身份:**优先浏览器里那份**,其次退回传进来的 cookie(库里存的)。
|
||||
|
||||
优先浏览器的原因:站点会自己轮换会话,库里存的是粘贴那一刻的快照,浏览器里那份才是
|
||||
当前有效的;而 UA/hints 更是只有浏览器自己知道。
|
||||
"""
|
||||
global _identity_cache
|
||||
|
||||
now = time.monotonic()
|
||||
if not force and _identity_cache is not None:
|
||||
cached_at, cached = _identity_cache
|
||||
if now - cached_at < _IDENTITY_TTL_SECONDS:
|
||||
return cached
|
||||
|
||||
identity = await _read_browser()
|
||||
if identity is None or not _has_session(identity.cookie):
|
||||
# 浏览器里没有可用会话,退回调用方给的那份。UA/hints 编不出来就不编 ——
|
||||
# 一组和 UA 对不上的 hints 比没有更糟。
|
||||
identity = BrowserIdentity(
|
||||
cookie=_cookie_header(cookie), user_agent="", client_hints={}
|
||||
)
|
||||
_identity_cache = (now, identity)
|
||||
return identity
|
||||
|
||||
|
||||
def forget_identity() -> None:
|
||||
"""丢掉缓存的身份。cookie 变了、或测试之间要隔离时调用。"""
|
||||
global _identity_cache
|
||||
_identity_cache = None
|
||||
|
||||
|
||||
async def shared_fingerprint() -> Tuple[str, Dict[str, str]]:
|
||||
"""只从浏览器读 UA + client hints,**不要它的 cookie**。
|
||||
|
||||
给「粘贴 cookie」的身份兜底:cookie 来自哪个浏览器我们不知道,至少让 UA 和
|
||||
``sec-ch-ua`` 成套。读不到返回空 —— 调用方应当拒绝创建没有 UA 的身份,因为
|
||||
评论接口的 ``a_bogus`` 要拿 UA 去签名,空 UA 签出来的请求一定被挡。
|
||||
"""
|
||||
identity = await _read_browser()
|
||||
if identity is None:
|
||||
return "", {}
|
||||
return identity.user_agent, identity.client_hints
|
||||
|
||||
|
||||
def _cookie_header(cookie: str) -> str:
|
||||
"""把 ``a=1; b=2`` 形式的 cookie 串规整成请求头用的形状。"""
|
||||
pairs = []
|
||||
for part in (cookie or "").split(";"):
|
||||
if "=" in part:
|
||||
name, _, value = part.partition("=")
|
||||
name = name.strip()
|
||||
if name:
|
||||
pairs.append(f"{name}={value.strip()}")
|
||||
return "; ".join(pairs)
|
||||
|
||||
|
||||
def _cookie_from_dict(cookies: Dict[str, str]) -> str:
|
||||
return "; ".join(f"{name}={value}" for name, value in cookies.items())
|
||||
|
||||
|
||||
def _cookie_value(cookie: str, name: str) -> str:
|
||||
"""从一个 cookie 串里取某个键的值。"""
|
||||
for part in (cookie or "").split(";"):
|
||||
key, _, value = part.partition("=")
|
||||
if key.strip() == name:
|
||||
return value.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _sign(params: Dict[str, Any], path: str, user_agent: str) -> Dict[str, Any]:
|
||||
"""给一组参数补上 ``a_bogus`` 签名,返回新 dict。
|
||||
|
||||
**按需 import**:那个模块在 import 的那一瞬间就把 ``libs/douyin.js`` 交给 execjs
|
||||
编译(还要读相对路径),把它拖进监控层的热路径不合适。
|
||||
|
||||
签名算在**不含 a_bogus 的那串 query 上**,追加到末尾 —— 和爬虫那条路一致,也是
|
||||
实测能过的形态。
|
||||
"""
|
||||
from media_platform.douyin.help import get_a_bogus_from_js
|
||||
|
||||
try:
|
||||
return {
|
||||
**params,
|
||||
"a_bogus": get_a_bogus_from_js(path, urlencode(params), user_agent),
|
||||
}
|
||||
except Exception as exc: # execjs 起不来 / JS 抛错,都算签名失败
|
||||
raise DouyinApiError(f"算 a_bogus 签名失败:{exc}") from exc
|
||||
|
||||
|
||||
async def _get(
|
||||
path: str,
|
||||
params: Dict[str, Any],
|
||||
identity: BrowserIdentity,
|
||||
*,
|
||||
signed: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
"""发一个 GET,返回 JSON。
|
||||
|
||||
只带调用方给的参数 —— **不要往里加 webid / msToken / browser_version 那一堆**,
|
||||
那正是爬虫那条路失败的原因。
|
||||
|
||||
``signed=True`` 时补一个 ``a_bogus``。**只有评论接口需要它**:作品、详情、博主资料
|
||||
三个不带签名也照常返回,而给它们加签名是没验证过的改动,不做。
|
||||
"""
|
||||
if signed:
|
||||
params = _sign(params, path, identity.user_agent)
|
||||
|
||||
url = f"{API_ORIGIN}{path}"
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT_SECONDS) as client:
|
||||
response = await client.get(
|
||||
url,
|
||||
params=params,
|
||||
headers=identity.headers(),
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
raise DouyinApiError(f"HTTP {response.status_code}:{response.text[:120]}")
|
||||
|
||||
# 「200 + 空 body」是抖音网关拒绝请求时的典型回应(见模块说明)。必须当成错误报出来,
|
||||
# 否则会一路往下变成「这个博主没作品」。
|
||||
if not response.text.strip():
|
||||
raise DouyinApiError(
|
||||
"接口返回了空内容 —— 通常是登录态失效,或请求被网关判成了非浏览器"
|
||||
)
|
||||
|
||||
try:
|
||||
return response.json()
|
||||
except ValueError as exc:
|
||||
raise DouyinApiError(f"返回的不是 JSON:{response.text[:120]}") from exc
|
||||
|
||||
|
||||
def _as_int(value: Any) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _opt_int(value: Any) -> Optional[int]:
|
||||
"""``_as_int`` 的「不知道就是不知道」版:字段缺失时留 None,不写 0。
|
||||
|
||||
粉丝数用 0 顶替字段缺失,界面上就成了「粉丝 0」—— 和「没采到」是两件事。
|
||||
"""
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def normalize_aweme(aweme: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""把接口返回的一条作品,翻译成 store 落盘的那套键名。
|
||||
|
||||
键名必须和 ``store/douyin`` 一致 —— 跨过这一层之后,ingest 就不知道数据是从爬虫
|
||||
来的还是从接口来的。
|
||||
"""
|
||||
author = aweme.get("author") or {}
|
||||
statistics = aweme.get("statistics") or {}
|
||||
aweme_id = str(aweme.get("aweme_id") or "")
|
||||
cover = ((aweme.get("video") or {}).get("cover") or {}).get("url_list") or [""]
|
||||
uid = str(author.get("uid") or "")
|
||||
nickname = author.get("nickname") or ""
|
||||
|
||||
# 话题列表。**`desc` 会被抖音截断** —— 尾部是「……版本过低,升级后可展示全部信息」,
|
||||
# 后面的话题根本不在 desc 里。标签规则只匹配标题的话,那些话题永远命中不了
|
||||
# (实测:一条作品的 desc 截断在「#噶痔疮 #…」,而完整话题列表里还有 #szgtgg)。
|
||||
# `text_extra` 是结构化的,不受截断影响。
|
||||
hashtags = " ".join(
|
||||
f"#{item.get('hashtag_name')}"
|
||||
for item in (aweme.get("text_extra") or [])
|
||||
if isinstance(item, dict) and item.get("hashtag_name")
|
||||
)
|
||||
|
||||
return {
|
||||
"aweme_id": aweme_id,
|
||||
"aweme_type": str(aweme.get("aweme_type") or ""),
|
||||
# store 那边 title 取的是 desc。
|
||||
"title": aweme.get("desc") or "",
|
||||
"desc": aweme.get("desc") or "",
|
||||
"hashtags": hashtags,
|
||||
# **秒**。adapters.time_scale 会把它换成毫秒,和 store 写出来的形态一致。
|
||||
"create_time": _as_int(aweme.get("create_time")),
|
||||
"creator_hash": anonymize_user_id(uid or author.get("sec_uid") or ""),
|
||||
# 主页 id(sec_uid)。**哈希拼不出主页地址**,而详情接口的返回里现成就有这一段
|
||||
# —— 不带出来,库里抖音作品的主页链接就全是空的。
|
||||
"creator_id": str(author.get("sec_uid") or ""),
|
||||
"nickname": nickname,
|
||||
# 作者账号级指标。详情接口的 ``author`` 里现成就有,**白拿的**:作品模式
|
||||
# (超级编导导入就是)只拉作品详情、从不问 ``user/profile``,不从这里带出来,
|
||||
# 那些任务里所有博主的粉丝数就都是空的。
|
||||
#
|
||||
# ``aweme_count`` 实测是 null(详情返回里没有作品总数),所以 works 只能留空 ——
|
||||
# 为了一个作品数给每个博主多打一次资料接口,不划算。
|
||||
"creator_fans": _opt_int(author.get("follower_count")),
|
||||
"creator_total_favorited": _opt_int(author.get("total_favorited")),
|
||||
"creator_works": _opt_int(author.get("aweme_count")),
|
||||
"creator_following": _opt_int(author.get("following_count")),
|
||||
"liked_count": str(_as_int(statistics.get("digg_count"))),
|
||||
"comment_count": str(_as_int(statistics.get("comment_count"))),
|
||||
"collected_count": str(_as_int(statistics.get("collect_count"))),
|
||||
"share_count": str(_as_int(statistics.get("share_count"))),
|
||||
"aweme_url": f"https://www.douyin.com/video/{aweme_id}",
|
||||
"cover_url": cover[0] if cover else "",
|
||||
"source_keyword": "",
|
||||
}
|
||||
|
||||
|
||||
async def author_videos_page(
|
||||
sec_user_id: str,
|
||||
max_cursor: int = 0,
|
||||
count: int = MAX_PAGE_SIZE,
|
||||
*,
|
||||
cookie: str = "",
|
||||
identity: Optional[BrowserIdentity] = None,
|
||||
) -> Tuple[List[Dict[str, Any]], int, bool]:
|
||||
"""一页博主作品,返回 ``(作品, 下一页游标, 还有没有更多)``。
|
||||
|
||||
翻页是**按时间游标**的(``max_cursor``),不是 offset —— 所以想拿「最早一条」
|
||||
只能一页页翻到底,没有直接跳最后一页的办法(见 ``creator_scan``)。
|
||||
"""
|
||||
# 身份池传进来的身份直接用 —— 不要再去读浏览器,那会把别的账号的 cookie 顶进来。
|
||||
identity = identity or await browser_identity(cookie)
|
||||
if not _has_session(identity.cookie):
|
||||
raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有")
|
||||
|
||||
payload = await _get(
|
||||
POSTS_PATH,
|
||||
{
|
||||
"sec_user_id": sec_user_id,
|
||||
"count": max(1, min(count, MAX_PAGE_SIZE)),
|
||||
"max_cursor": max_cursor,
|
||||
"device_platform": "webapp",
|
||||
"aid": 6383,
|
||||
},
|
||||
identity,
|
||||
)
|
||||
|
||||
awemes = payload.get("aweme_list") or []
|
||||
if not awemes and payload.get("status_code") not in (0, None):
|
||||
raise DouyinApiError(
|
||||
f"接口拒绝了请求(status_code={payload.get('status_code')})"
|
||||
)
|
||||
next_cursor = _as_int(payload.get("max_cursor"))
|
||||
has_more = bool(payload.get("has_more"))
|
||||
return [normalize_aweme(aweme) for aweme in awemes], next_cursor, has_more
|
||||
|
||||
|
||||
async def author_videos(
|
||||
sec_user_id: str,
|
||||
count: int = MAX_PAGE_SIZE,
|
||||
*,
|
||||
cookie: str = "",
|
||||
identity: Optional[BrowserIdentity] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""某个博主最新发布的作品(按发布时间倒序),已翻译成 store 的键名。
|
||||
|
||||
用 ``sec_user_id`` 而不是数字 uid:监控任务里存的就是主页链接里的那段 sec_uid,
|
||||
而且这个接口两种都收(爬虫那边用的也是 sec_user_id)。
|
||||
"""
|
||||
videos, _cursor, _has_more = await author_videos_page(
|
||||
sec_user_id, 0, count, cookie=cookie, identity=identity
|
||||
)
|
||||
return videos
|
||||
|
||||
|
||||
async def video_detail(
|
||||
aweme_id: str,
|
||||
*,
|
||||
cookie: str = "",
|
||||
identity: Optional[BrowserIdentity] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""单条作品的详情,已翻译成 store 的键名。
|
||||
|
||||
这个接口**没有**被那道真校验挡着(实测 200 / 45425 字节),所以在拿不到作品列表时,
|
||||
它是「刷新已知作品指标」的唯一途径。
|
||||
"""
|
||||
identity = identity or await browser_identity(cookie)
|
||||
if not _has_session(identity.cookie):
|
||||
raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有")
|
||||
|
||||
payload = await _get(
|
||||
DETAIL_PATH,
|
||||
{"aweme_id": aweme_id, "device_platform": "webapp", "aid": 6383},
|
||||
identity,
|
||||
)
|
||||
aweme = payload.get("aweme_detail") or {}
|
||||
if not aweme:
|
||||
raise DouyinApiError(
|
||||
f"接口没返回作品(status_code={payload.get('status_code')})"
|
||||
)
|
||||
return normalize_aweme(aweme)
|
||||
|
||||
|
||||
async def author_profile(
|
||||
sec_user_id: str,
|
||||
*,
|
||||
cookie: str = "",
|
||||
identity: Optional[BrowserIdentity] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""博主主页指标:昵称 / 粉丝数 / 总获赞 / 作品数。"""
|
||||
identity = identity or await browser_identity(cookie)
|
||||
if not _has_session(identity.cookie):
|
||||
raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有")
|
||||
|
||||
payload = await _get(
|
||||
PROFILE_PATH,
|
||||
{"sec_user_id": sec_user_id, "device_platform": "webapp", "aid": 6383},
|
||||
identity,
|
||||
)
|
||||
user = payload.get("user") or {}
|
||||
if not user:
|
||||
raise DouyinApiError(
|
||||
f"接口没返回用户数据(status_code={payload.get('status_code')})"
|
||||
)
|
||||
return {
|
||||
# 自报家门。快照表的唯一键是 (任务, creator_hash, 轮次),而作品是靠
|
||||
# `anonymize_user_id(author.uid)` 得到这个哈希的 —— 这里走同一条路,两边才对得上,
|
||||
# 否则快照会和作品分成两个人,界面上永远查不到。
|
||||
"creator_hash": anonymize_user_id(
|
||||
str(user.get("uid") or user.get("sec_uid") or "")
|
||||
),
|
||||
"nickname": user.get("nickname") or "",
|
||||
# 主页 id —— 单独存一份,用来拼「跳到他主页」的链接。哈希拼不出地址。
|
||||
"creator_id": str(user.get("sec_uid") or ""),
|
||||
"unique_id": user.get("unique_id") or "",
|
||||
"fans": _as_int(user.get("follower_count")),
|
||||
"total_favorited": _as_int(user.get("total_favorited")),
|
||||
"works": _as_int(user.get("aweme_count")),
|
||||
"following": _as_int(user.get("following_count")),
|
||||
}
|
||||
|
||||
|
||||
def normalize_comment(comment: Dict[str, Any], aweme_id: str) -> Dict[str, Any]:
|
||||
"""把接口返回的一条评论,翻译成 store 落盘的那套键名。
|
||||
|
||||
HTTP 路线和页面路线共用它 —— 同一套键名,ingest 才不用关心数据是怎么来的。
|
||||
刻意**不带** ``sub_comment_count`` / ``parent_comment_id`` 的猜测值:接口给了就用,
|
||||
没给就留空,不编。
|
||||
"""
|
||||
user = comment.get("user") or {}
|
||||
return {
|
||||
"comment_id": str(comment.get("cid") or ""),
|
||||
"aweme_id": aweme_id,
|
||||
"content": comment.get("text") or "",
|
||||
"nickname": user.get("nickname") or "",
|
||||
"creator_hash": anonymize_user_id(
|
||||
str(user.get("uid") or user.get("sec_uid") or "")
|
||||
),
|
||||
# 同为秒;adapters 会换算。
|
||||
"create_time": _as_int(comment.get("create_time")),
|
||||
"like_count": str(_as_int(comment.get("digg_count"))),
|
||||
"sub_comment_count": str(_as_int(comment.get("reply_comment_total"))),
|
||||
# 顶层评论在抖音里是 "0";adapters.parent_comment_id 会归一成空串。
|
||||
"parent_comment_id": str(comment.get("reply_id") or "0"),
|
||||
}
|
||||
|
||||
|
||||
async def video_comments(
|
||||
aweme_id: str,
|
||||
count: int = 20,
|
||||
*,
|
||||
cookie: str = "",
|
||||
identity: Optional[BrowserIdentity] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""一条作品的评论,翻译成 store 的评论键名。
|
||||
|
||||
刻意不带 ``sub_comment_count`` / ``parent_comment_id`` 的猜测值 —— 接口给了就用,
|
||||
没给就留空,不编。
|
||||
"""
|
||||
identity = identity or await browser_identity(cookie)
|
||||
if not _has_session(identity.cookie):
|
||||
raise DouyinApiError("抖音登录态不可用")
|
||||
|
||||
payload = await _get(
|
||||
COMMENT_PATH,
|
||||
{
|
||||
"aweme_id": aweme_id,
|
||||
"count": max(1, min(count, MAX_PAGE_SIZE)),
|
||||
"cursor": 0,
|
||||
"device_platform": "webapp",
|
||||
"aid": 6383,
|
||||
},
|
||||
identity,
|
||||
# 这个接口**必须**签名。不签的话网关回 200 + 空 body,会被读成「这条没评论」,
|
||||
# 而它其实只是被挡了 —— 和登录失效长得一模一样。(实测:带上签名 200/9960 字节
|
||||
# 真评论,不带就是空的。)
|
||||
signed=True,
|
||||
)
|
||||
|
||||
records = [
|
||||
normalize_comment(comment, aweme_id)
|
||||
for comment in payload.get("comments") or []
|
||||
]
|
||||
return records
|
||||
|
||||
|
||||
def _has_session(cookie: str) -> bool:
|
||||
return "sessionid=" in (cookie or "")
|
||||
|
||||
|
||||
async def check_login(cookie: str = "") -> Dict[str, Any]:
|
||||
"""浏览器/库里现在有没有可用的抖音登录态。给设置页用。"""
|
||||
identity = await browser_identity(cookie)
|
||||
if _has_session(identity.cookie):
|
||||
source = "browser" if identity.user_agent else "stored"
|
||||
return {"ok": True, "source": source, "cookie_length": len(identity.cookie)}
|
||||
return {"ok": False, "source": "", "cookie_length": 0}
|
||||
|
||||
|
||||
async def main() -> None: # pragma: no cover - 手工排查用
|
||||
"""``python -m api.monitor.douyin_api <sec_user_id>``"""
|
||||
import sys
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
print(await check_login())
|
||||
return
|
||||
sec = sys.argv[1]
|
||||
print(await author_profile(sec))
|
||||
for record in await author_videos(sec, count=5):
|
||||
print(record["create_time"], record["title"][:30], record["liked_count"])
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,391 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright (c) 2025 [email protected]
|
||||
#
|
||||
# This file is part of MediaCrawler project.
|
||||
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/api/monitor/douyin_fetch.py
|
||||
# GitHub: https://github.com/NanmiCoder
|
||||
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
|
||||
#
|
||||
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
|
||||
# 1. 不得用于任何商业用途。
|
||||
# 2. 使用时应遵守对应平台的使用条款和robots.txt规则。
|
||||
# 3. 不得进行大规模爬取或对平台造成运营干扰。
|
||||
# 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。
|
||||
# 5. 不得用于任何非法或不当的用途。
|
||||
#
|
||||
# 详细许可条款请参阅项目根目录下的LICENSE文件。
|
||||
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
|
||||
|
||||
"""抖音采集:直接走 Web 接口,不起爬虫子进程。
|
||||
|
||||
与 ``media_platform/douyin`` 那条路的分工:
|
||||
|
||||
* 那边起一个 Playwright 子进程、构造一大串**自相矛盾的浏览器指纹参数**(参数说自己是
|
||||
Mac + Chrome 125,UA 说自己是 Linux + Chrome 155),网关回一个 200 + 空 body,
|
||||
然后被翻译成 ``Exception("account blocked")`` —— 看起来像账号被封,其实什么都不是。
|
||||
* 这边不起子进程、只发必要参数,用浏览器里那份登录态。见 ``douyin_api``。
|
||||
|
||||
采到的东西写成 ``store/douyin`` 那套 jsonl 形状,所以 **ingest 完全不知道数据是怎么来的**
|
||||
—— 重采样、差分、事件、通知、报表全都照旧。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
||||
|
||||
from tools import utils
|
||||
|
||||
from . import adapters, douyin_api
|
||||
from .models import MODE_CREATOR, MODE_NOTE, MonitorTask
|
||||
|
||||
# 拉多少条作品。接口单页上限就是 20,要多了也没用。
|
||||
DEFAULT_VIDEO_LIMIT = 20
|
||||
|
||||
|
||||
async def collect(
|
||||
out_dir: Path,
|
||||
*,
|
||||
platform: str,
|
||||
mode: str,
|
||||
limit: int,
|
||||
want_comments: bool,
|
||||
comment_limit: int,
|
||||
targets: Sequence[Any],
|
||||
known_aweme_ids: Iterable[str] = (),
|
||||
cookie: str = "",
|
||||
identities: Sequence[Any] = (),
|
||||
concurrency: int = 1,
|
||||
switch_delay_seconds: float = 0.0,
|
||||
) -> Dict[str, Any]:
|
||||
"""跑一轮抖音采集,把产物写进 ``out_dir`` 下 store 那个目录里。
|
||||
|
||||
参数是散的、不收 ORM 对象:调用方那边 ``task`` 在会话关掉之后就 detached 了,
|
||||
传对象进来迟早会踩到「属性已过期」。
|
||||
|
||||
``identities`` 非空时进入**身份池模式**:目标按 Rendezvous Hashing 分给各个身份,
|
||||
逐个分片执行。默认串行 —— 同一个出口 IP 上并发多个 cookie 比单账号高频更可疑;
|
||||
``concurrency`` 只是留了个口子,有独立出口 IP 之前别调大。
|
||||
|
||||
**不抛异常**:失败也把(可能为空的)产物落下去,并把原因放进 ``errors`` 交给调用方。
|
||||
让调用方去决定这是「一轮正常但没数据」还是「一轮失败」—— 这个判断不该藏在这里。
|
||||
"""
|
||||
notes: List[Dict[str, Any]] = []
|
||||
comments: List[Dict[str, Any]] = []
|
||||
# 博主**账号级**指标(粉丝 / 总获赞 / 作品数)。作品列表之外单独要一次,
|
||||
# 只有博主模式才有 —— 作品模式的目标是一件作品,没有"这个博主是谁"可问。
|
||||
profiles: List[Dict[str, Any]] = []
|
||||
errors: List[str] = []
|
||||
shards: List[Dict[str, Any]] = []
|
||||
|
||||
# **整个 collect 只去重一次的、跨目标的集合**:退化路径会把「库里已知的全部作品」
|
||||
# 在每个目标下都刷一遍,多个目标就会出现同一件作品好几条记录 —— 而一对一快照的
|
||||
# 唯一键是 (task_id, note_id, run_id),同一条作品在一轮里出现两次会直接撞键。
|
||||
seen_aweme: set = set()
|
||||
|
||||
if identities:
|
||||
from . import identities as identity_pool
|
||||
|
||||
plan = identity_pool.assign(targets, [item.identity_key for item in identities])
|
||||
batches = [
|
||||
(item, plan[item.identity_key])
|
||||
for item in identities
|
||||
if plan[item.identity_key]
|
||||
]
|
||||
|
||||
async def run_batch(identity, shard):
|
||||
return await _collect_batch(
|
||||
shard,
|
||||
identity=identity,
|
||||
mode=mode,
|
||||
limit=limit,
|
||||
want_comments=want_comments,
|
||||
comment_limit=comment_limit,
|
||||
cookie=cookie,
|
||||
known_aweme_ids=known_aweme_ids,
|
||||
seen_aweme=seen_aweme,
|
||||
)
|
||||
|
||||
if concurrency > 1 and len(batches) > 1:
|
||||
results = await asyncio.gather(*(run_batch(i, s) for i, s in batches))
|
||||
else:
|
||||
results = []
|
||||
for index, (identity, shard) in enumerate(batches):
|
||||
results.append(await run_batch(identity, shard))
|
||||
# 换账号之间留一点空档:连续在同一个 IP 上换登录态更像异常流量。
|
||||
if index < len(batches) - 1 and switch_delay_seconds > 0:
|
||||
await asyncio.sleep(switch_delay_seconds)
|
||||
|
||||
for (identity, shard), result in zip(batches, results):
|
||||
notes.extend(result["notes"])
|
||||
comments.extend(result["comments"])
|
||||
profiles.extend(result["profiles"])
|
||||
errors.extend(result["errors"])
|
||||
shards.append(
|
||||
{
|
||||
"key": identity.identity_key,
|
||||
"targets": result["targets"],
|
||||
"notes": len(result["notes"]),
|
||||
"comments": len(result["comments"]),
|
||||
"errors": list(result["errors"]),
|
||||
}
|
||||
)
|
||||
else:
|
||||
result = await _collect_batch(
|
||||
targets,
|
||||
identity=None,
|
||||
mode=mode,
|
||||
limit=limit,
|
||||
want_comments=want_comments,
|
||||
comment_limit=comment_limit,
|
||||
cookie=cookie,
|
||||
known_aweme_ids=known_aweme_ids,
|
||||
seen_aweme=seen_aweme,
|
||||
)
|
||||
notes.extend(result["notes"])
|
||||
comments.extend(result["comments"])
|
||||
profiles.extend(result["profiles"])
|
||||
errors.extend(result["errors"])
|
||||
|
||||
# 并发跑分片时,两个分片可能各自刷新到同一件已知作品 —— 落盘前去一次重,
|
||||
# 否则唯一键 (task_id, note_id, run_id) 会撞。
|
||||
deduped: List[Dict[str, Any]] = []
|
||||
seen_note_ids: set = set()
|
||||
for note in notes:
|
||||
note_id = note.get("aweme_id")
|
||||
if note_id and note_id in seen_note_ids:
|
||||
continue
|
||||
if note_id:
|
||||
seen_note_ids.add(note_id)
|
||||
deduped.append(note)
|
||||
|
||||
jsonl_dir = _write_artifacts(out_dir, platform, mode, deduped, comments, profiles)
|
||||
return {
|
||||
"notes": len(deduped),
|
||||
"comments": len(comments),
|
||||
"errors": errors,
|
||||
"jsonl_dir": str(jsonl_dir),
|
||||
"shards": shards,
|
||||
}
|
||||
|
||||
|
||||
async def _collect_batch(
|
||||
targets: Sequence[Any],
|
||||
*,
|
||||
identity: Any,
|
||||
mode: str,
|
||||
limit: int,
|
||||
want_comments: bool,
|
||||
comment_limit: int,
|
||||
cookie: str,
|
||||
known_aweme_ids: Iterable[str],
|
||||
seen_aweme: set,
|
||||
) -> Dict[str, Any]:
|
||||
"""一个身份负责的那一片目标。错误只往自己的列表里记,由调用方合并。"""
|
||||
notes: List[Dict[str, Any]] = []
|
||||
comments: List[Dict[str, Any]] = []
|
||||
profiles: List[Dict[str, Any]] = []
|
||||
errors: List[str] = []
|
||||
|
||||
for target in targets:
|
||||
external_id = target.external_id
|
||||
|
||||
# 两种模式的目标是不同的东西,不能走同一条路:
|
||||
# 作品模式 —— 目标本身就是作品 id,直接取详情(**这个接口没被挡,今天就能用**)。
|
||||
# 博主模式 —— 目标是主页 sec_uid,要先拉作品列表;那个接口被真校验挡着,退化到
|
||||
# 刷新库里已知的作品(新作品发现不了)。
|
||||
if mode == MODE_NOTE:
|
||||
try:
|
||||
videos = [
|
||||
await douyin_api.video_detail(
|
||||
external_id, cookie=cookie, identity=identity
|
||||
)
|
||||
]
|
||||
except douyin_api.DouyinApiError as exc:
|
||||
errors.append(f"拉取作品 {external_id} 失败:{exc}")
|
||||
videos = []
|
||||
# 作品详情里带着作者的粉丝/总获赞。作品模式**不会**单独问博主资料 ——
|
||||
# 不从这里收一份,这类任务(超级编导导入的都在这里)的博主粉丝数永远是空的。
|
||||
for video in videos:
|
||||
profile = _profile_from_author(video)
|
||||
if profile is not None:
|
||||
profiles.append(profile)
|
||||
else:
|
||||
videos = await _creator_works(
|
||||
external_id,
|
||||
limit,
|
||||
known_aweme_ids,
|
||||
seen_aweme,
|
||||
cookie,
|
||||
errors,
|
||||
identity,
|
||||
)
|
||||
profile = await _creator_profile(
|
||||
external_id, videos, cookie, errors, identity
|
||||
)
|
||||
if profile is not None:
|
||||
profiles.append(profile)
|
||||
|
||||
for video in videos:
|
||||
aweme_id = video.get("aweme_id")
|
||||
if not aweme_id or aweme_id in seen_aweme:
|
||||
continue
|
||||
seen_aweme.add(aweme_id)
|
||||
notes.append(video)
|
||||
|
||||
if want_comments:
|
||||
try:
|
||||
comments.extend(
|
||||
await douyin_api.video_comments(
|
||||
aweme_id,
|
||||
count=comment_limit,
|
||||
cookie=cookie,
|
||||
identity=identity,
|
||||
)
|
||||
)
|
||||
except douyin_api.DouyinApiError as exc:
|
||||
errors.append(f"拉取作品 {aweme_id} 的评论失败:{exc}")
|
||||
|
||||
return {
|
||||
"notes": notes,
|
||||
"comments": comments,
|
||||
"profiles": profiles,
|
||||
"errors": errors,
|
||||
"targets": len(targets),
|
||||
}
|
||||
|
||||
|
||||
def _profile_from_author(video: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
"""把作品详情里那份 author 拼成一条账号快照;什么都不全就返回 None。
|
||||
|
||||
只在**有值**时收:author 对象偶尔是精简版(只有 uid/nickname),那种情况下写一条
|
||||
全 NULL 的快照没有意义,还会让界面显示「采集时间有、数字没有」。
|
||||
"""
|
||||
creator_hash = str(video.get("creator_hash") or "")
|
||||
if not creator_hash:
|
||||
return None
|
||||
|
||||
stats = (
|
||||
video.get("creator_fans"),
|
||||
video.get("creator_total_favorited"),
|
||||
video.get("creator_works"),
|
||||
video.get("creator_following"),
|
||||
)
|
||||
if all(value is None for value in stats):
|
||||
return None
|
||||
|
||||
return {
|
||||
"creator_hash": creator_hash,
|
||||
"creator_id": str(video.get("creator_id") or ""),
|
||||
"nickname": str(video.get("nickname") or ""),
|
||||
"fans": video.get("creator_fans"),
|
||||
"total_favorited": video.get("creator_total_favorited"),
|
||||
"works": video.get("creator_works"),
|
||||
"following": video.get("creator_following"),
|
||||
}
|
||||
|
||||
|
||||
async def _creator_profile(
|
||||
sec_user_id: str,
|
||||
videos: Sequence[Dict[str, Any]],
|
||||
cookie: str,
|
||||
errors: List[str],
|
||||
identity: Any = None,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""问一次博主的账号级指标。拿不到就算了 —— **不能因为顺手的附加信息失败,
|
||||
就把这一轮本来采到的作品也判成失败。**
|
||||
|
||||
creator_hash 优先取作品自带的那个:作品是靠 ``anonymize_user_id(author.uid)`` 得到
|
||||
哈希的,而快照表和作品必须对得上号,否则界面上永远查不出这个博主的粉丝数。只有当一件
|
||||
作品都没采到时(列表被挡且没有已知作品可刷新),才退回资料接口自己算的哈希 ——
|
||||
那种情况下也只剩它了。
|
||||
"""
|
||||
try:
|
||||
profile = await douyin_api.author_profile(
|
||||
sec_user_id, cookie=cookie, identity=identity
|
||||
)
|
||||
except douyin_api.DouyinApiError as exc:
|
||||
errors.append(f"拉取博主 {sec_user_id} 的资料失败:{exc}")
|
||||
return None
|
||||
|
||||
if videos:
|
||||
profile["creator_hash"] = videos[0].get("creator_hash") or profile["creator_hash"]
|
||||
if not profile.get("creator_hash"):
|
||||
# 哈希都算不出来的快照没人能查到,落下去只是垃圾。
|
||||
errors.append(f"博主 {sec_user_id} 的资料里没有可用的身份标识,跳过账号指标")
|
||||
return None
|
||||
return profile
|
||||
|
||||
|
||||
async def _creator_works(
|
||||
sec_user_id: str,
|
||||
limit: int,
|
||||
known_aweme_ids: Iterable[str],
|
||||
seen_aweme: set,
|
||||
cookie: str,
|
||||
errors: List[str],
|
||||
identity: Any = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""一个博主的作品:先要列表,列表被挡时退化成刷新已知作品。
|
||||
|
||||
作品列表(``aweme/post``)被抖音单独加了真校验 —— 不带 ``x-tt-argus`` 回 403,
|
||||
带上 dummy 值回 200 + 空 body。所以这里拿不到**新**作品,只能保住已知的。
|
||||
"""
|
||||
try:
|
||||
return await douyin_api.author_videos(
|
||||
sec_user_id, count=limit, cookie=cookie, identity=identity
|
||||
)
|
||||
except douyin_api.DouyinApiError as exc:
|
||||
errors.append(f"拉取博主 {sec_user_id} 的作品列表失败:{exc}")
|
||||
|
||||
refreshed: List[Dict[str, Any]] = []
|
||||
for aweme_id in known_aweme_ids:
|
||||
if aweme_id in seen_aweme:
|
||||
continue
|
||||
try:
|
||||
refreshed.append(
|
||||
await douyin_api.video_detail(
|
||||
aweme_id, cookie=cookie, identity=identity
|
||||
)
|
||||
)
|
||||
except douyin_api.DouyinApiError as detail_exc:
|
||||
errors.append(f"刷新作品 {aweme_id} 失败:{detail_exc}")
|
||||
return refreshed
|
||||
|
||||
|
||||
def _write_artifacts(
|
||||
out_dir: Path,
|
||||
platform: str,
|
||||
mode: str,
|
||||
notes: List[Dict[str, Any]],
|
||||
comments: List[Dict[str, Any]],
|
||||
profiles: Sequence[Dict[str, Any]] = (),
|
||||
) -> Path:
|
||||
"""按爬虫那套目录与文件名写 jsonl。
|
||||
|
||||
目录名取 ``adapters.artifact_dir``(抖音是 ``douyin``,而不是平台 id ``dy``)——
|
||||
和 ingest 找文件用的是同一个来源,两边不会走散。
|
||||
"""
|
||||
jsonl_dir = out_dir / adapters.artifact_dir(platform) / "jsonl"
|
||||
jsonl_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
kind = "creator" if mode == MODE_CREATOR else "detail"
|
||||
date = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
_write_jsonl(jsonl_dir / f"{kind}_contents_{date}.jsonl", notes)
|
||||
# 评论文件即使没有评论也建出来:ingest 靠「文件在不在」区分「这一轮没评论」和
|
||||
# 「这一轮什么都没抓到」,两种情况的含义完全不同。
|
||||
_write_jsonl(jsonl_dir / f"{kind}_comments_{date}.jsonl", comments)
|
||||
# 博主资料同样无条件写:空文件表示"问了但没问到",没有文件表示"这次根本没问"
|
||||
# (作品模式)。两者在 ingest 那边走的是同一条路(都不落快照),但留空文件能让
|
||||
# 事后翻 run 目录时看出到底问没问过。
|
||||
_write_jsonl(jsonl_dir / f"{kind}_profile_{date}.jsonl", list(profiles))
|
||||
return jsonl_dir
|
||||
|
||||
|
||||
def _write_jsonl(path: Path, records: List[Dict[str, Any]]) -> None:
|
||||
with path.open("w", encoding="utf-8") as handle:
|
||||
for record in records:
|
||||
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
utils.logger.info(f"[douyin_fetch] 写出 {len(records)} 条 -> {path.name}")
|
||||
@@ -0,0 +1,184 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""身份池:多个登录态之间的选取、分片与健康状态。
|
||||
|
||||
**为什么是「串行分片」而不是「并行抓取」。** 抖音按 *账号 + IP + 设备指纹* 联合判定,
|
||||
在同一个出口 IP 上并发跑多个 cookie,比单账号高频请求更容易被判成异常 —— 平台视角是
|
||||
一台设备在不停换访客。所以默认一次只跑一个身份,靠**把目标分给不同账号**来降低每个
|
||||
账号的请求量;并发数由调用方决定(默认 1),有独立出口 IP 之前别调大。
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any, Dict, List, Optional, Sequence
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from . import douyin_api
|
||||
from .models import (
|
||||
IDENTITY_SOURCE_BROWSER,
|
||||
IDENTITY_STATUS_COOLDOWN,
|
||||
IDENTITY_STATUS_EXPIRED,
|
||||
IDENTITY_STATUS_OK,
|
||||
MonitorIdentity,
|
||||
)
|
||||
|
||||
IDENTITY_KEY_BROWSER = "browser"
|
||||
# 连续失败几次才进冷却。一次失败可能只是网络抖动,不值得把账号停半小时。
|
||||
COOLDOWN_AFTER_FAILURES = 2
|
||||
COOLDOWN_BASE_MS = 30 * 60_000
|
||||
COOLDOWN_MAX_MS = 180 * 60_000
|
||||
|
||||
|
||||
def key_for(row: MonitorIdentity) -> str:
|
||||
"""身份在本轮里的稳定标识。``browser`` 只有一个,其它按行 id。"""
|
||||
if row.source == IDENTITY_SOURCE_BROWSER:
|
||||
return IDENTITY_KEY_BROWSER
|
||||
return f"id:{row.id}"
|
||||
|
||||
|
||||
def is_available(row: MonitorIdentity, now: Optional[int] = None) -> bool:
|
||||
if not row.enabled or row.status == IDENTITY_STATUS_EXPIRED:
|
||||
return False
|
||||
now = now or get_current_timestamp()
|
||||
return not row.cooldown_until or row.cooldown_until <= now
|
||||
|
||||
|
||||
async def load_available(
|
||||
session: AsyncSession, platform: str, now: Optional[int] = None
|
||||
) -> List[MonitorIdentity]:
|
||||
now = now or get_current_timestamp()
|
||||
rows = (
|
||||
await session.scalars(
|
||||
select(MonitorIdentity)
|
||||
.where(MonitorIdentity.platform == platform)
|
||||
.order_by(MonitorIdentity.id)
|
||||
)
|
||||
).all()
|
||||
return [row for row in rows if is_available(row, now)]
|
||||
|
||||
|
||||
async def resolve(row: MonitorIdentity) -> douyin_api.BrowserIdentity:
|
||||
"""把一行身份变成请求真正要用的那份。
|
||||
|
||||
失败抛 ``ValueError``(消息直接给人看),由调用方决定是跳过这个身份还是整轮失败。
|
||||
"""
|
||||
if row.source == IDENTITY_SOURCE_BROWSER:
|
||||
identity = await douyin_api.browser_identity(force=True)
|
||||
if "sessionid=" not in (identity.cookie or ""):
|
||||
raise ValueError("浏览器里没有可用的抖音登录态")
|
||||
return douyin_api.BrowserIdentity(
|
||||
cookie=identity.cookie,
|
||||
user_agent=identity.user_agent,
|
||||
client_hints=identity.client_hints,
|
||||
identity_key=key_for(row),
|
||||
)
|
||||
|
||||
try:
|
||||
hints = json.loads(row.client_hints or "{}")
|
||||
except ValueError:
|
||||
hints = {}
|
||||
if not row.cookie.strip():
|
||||
raise ValueError("这份身份没有 cookie")
|
||||
if not row.user_agent.strip():
|
||||
# 评论接口的 a_bogus 把 UA 算进去,空 UA 签出来的请求一定被挡。
|
||||
raise ValueError("这份身份没有 UA —— 评论签名要用它")
|
||||
return douyin_api.BrowserIdentity(
|
||||
cookie=row.cookie,
|
||||
user_agent=row.user_agent,
|
||||
client_hints=hints if isinstance(hints, dict) else {},
|
||||
identity_key=key_for(row),
|
||||
)
|
||||
|
||||
|
||||
def _score(identity_key: str, external_id: str) -> int:
|
||||
digest = hashlib.blake2b(
|
||||
f"{identity_key}:{external_id}".encode("utf-8"), digest_size=8
|
||||
).digest()
|
||||
return int.from_bytes(digest, "big")
|
||||
|
||||
|
||||
def assign(targets: Sequence[Any], keys: Sequence[str]) -> Dict[str, List[Any]]:
|
||||
"""用 Rendezvous Hashing 把目标分给身份。
|
||||
|
||||
比取模好在:加一个身份时只有约 1/(n+1) 的目标会迁移,而不是全部重排;同一组
|
||||
身份和目标的分配结果是确定的,便于排查和 A/B。
|
||||
|
||||
身份列表为空时返回空 —— 调用方应当先确保至少有一个可用身份。
|
||||
"""
|
||||
buckets: Dict[str, List[Any]] = {key: [] for key in keys}
|
||||
if not keys:
|
||||
return buckets
|
||||
for target in targets:
|
||||
external = getattr(target, "external_id", None) or str(target)
|
||||
best = max(keys, key=lambda key: _score(key, external))
|
||||
buckets[best].append(target)
|
||||
return buckets
|
||||
|
||||
|
||||
async def record_result(
|
||||
session: AsyncSession,
|
||||
row: MonitorIdentity,
|
||||
*,
|
||||
ok: bool,
|
||||
error: str = "",
|
||||
now: Optional[int] = None,
|
||||
) -> None:
|
||||
"""一轮分片跑完之后更新健康状态。
|
||||
|
||||
**空 body / 403 只算限流,不算 cookie 失效** —— 前者冷却后还能用,后者才需要
|
||||
人工重新粘贴。这一层区分放在调用方:``ok=False`` 走冷却,``expired=True`` 才置
|
||||
``expired``。
|
||||
"""
|
||||
now = now or get_current_timestamp()
|
||||
row.last_checked_at = now
|
||||
|
||||
if ok:
|
||||
row.status = IDENTITY_STATUS_OK
|
||||
row.consecutive_failures = 0
|
||||
row.cooldown_until = None
|
||||
row.last_ok_at = now
|
||||
row.last_error = None
|
||||
row.updated_at = now
|
||||
return
|
||||
|
||||
row.consecutive_failures = (row.consecutive_failures or 0) + 1
|
||||
row.last_error = (error or "")[:500]
|
||||
row.updated_at = now
|
||||
if row.consecutive_failures >= COOLDOWN_AFTER_FAILURES:
|
||||
delay = min(
|
||||
COOLDOWN_BASE_MS * (2 ** (row.consecutive_failures - COOLDOWN_AFTER_FAILURES)),
|
||||
COOLDOWN_MAX_MS,
|
||||
)
|
||||
row.status = IDENTITY_STATUS_COOLDOWN
|
||||
row.cooldown_until = now + delay
|
||||
|
||||
|
||||
def mark_expired(row: MonitorIdentity, error: str, now: Optional[int] = None) -> None:
|
||||
"""明确的登录态失效:需要人工重新粘贴,冷却没用。"""
|
||||
now = now or get_current_timestamp()
|
||||
row.status = IDENTITY_STATUS_EXPIRED
|
||||
row.last_checked_at = now
|
||||
row.last_error = (error or "")[:500]
|
||||
row.updated_at = now
|
||||
|
||||
|
||||
def to_dict(row: MonitorIdentity) -> Dict[str, Any]:
|
||||
"""对外形状。**绝不含 cookie 原文**,只给 has_cookie。"""
|
||||
return {
|
||||
"id": row.id,
|
||||
"platform": row.platform,
|
||||
"label": row.label,
|
||||
"source": row.source,
|
||||
"has_cookie": bool(row.cookie),
|
||||
"user_agent": row.user_agent,
|
||||
"status": row.status,
|
||||
"enabled": row.enabled,
|
||||
"consecutive_failures": row.consecutive_failures,
|
||||
"cooldown_until": row.cooldown_until,
|
||||
"last_checked_at": row.last_checked_at,
|
||||
"last_ok_at": row.last_ok_at,
|
||||
"last_error": row.last_error,
|
||||
}
|
||||
+183
-4
@@ -38,14 +38,14 @@ import json
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Sequence
|
||||
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy import func, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from . import adapters
|
||||
from . import adapters, tagrules
|
||||
from .platforms import PLATFORM_XHS
|
||||
from .models import (
|
||||
EVENT_AUTH_FAILURE,
|
||||
@@ -56,10 +56,12 @@ from .models import (
|
||||
EVENT_NO_DATA,
|
||||
EVENT_RUN_FAILED,
|
||||
MonitorComment,
|
||||
MonitorCreatorStat,
|
||||
MonitorEvent,
|
||||
MonitorNote,
|
||||
MonitorNoteMetric,
|
||||
MonitorRun,
|
||||
MonitorTarget,
|
||||
MonitorTask,
|
||||
RUN_FAILED,
|
||||
RUN_PARTIAL,
|
||||
@@ -219,6 +221,19 @@ def find_run_files(
|
||||
)
|
||||
|
||||
|
||||
def find_profile_files(out_dir: Path, platform: str = PLATFORM_XHS) -> List[Path]:
|
||||
"""博主**账号级**指标那几行 jsonl(``creator_profile_*.jsonl``)。
|
||||
|
||||
单独一个函数而不是往 ``find_run_files`` 的返回值里塞第三个列表:那个返回值的两个
|
||||
位置是有意义的(contents/comments),加一个会把所有调用点和解包语句都牵动一遍,
|
||||
而这份产物是**可选**的 —— 小红书那条路(爬虫进程)根本不产生它。
|
||||
"""
|
||||
jsonl_dir = out_dir / adapters.artifact_dir(platform) / "jsonl"
|
||||
if not jsonl_dir.is_dir():
|
||||
return []
|
||||
return sorted(jsonl_dir.glob("*_profile_*.jsonl"))
|
||||
|
||||
|
||||
def _misplaced_output_dirs(out_dir: Path, expected: str) -> List[str]:
|
||||
"""在 out_dir 下找「有产物、但目录名不是期望的那个」的目录。
|
||||
|
||||
@@ -293,6 +308,30 @@ async def _previous_run_started_at(
|
||||
_AUTH_PROOF_WINDOW_MS = 6 * 60 * 60 * 1000
|
||||
|
||||
|
||||
async def _targets_that_are_not_ids(session: AsyncSession, task_id: int) -> List[str]:
|
||||
"""找出那些**明显不是 ID** 的目标值 —— 也就是原样存下来的、没解析开的链接。
|
||||
|
||||
判定刻意收得很紧:只看「是不是长得像一串 URL」。宽松一点(比如拿平台的 bare-id 正则
|
||||
去套)会误伤本来就合法的老目标,而这条消息是在**一轮已经失败之后**才出现的 ——
|
||||
把方向说错,比什么都不说更糟。
|
||||
|
||||
这条存在的原因:链接校验关掉之后(见 ``service.parse_target_input``),认不出的链接
|
||||
会被原样存成 ``external_id``,而它正是采集时唯一拿去请求的东西。结果就是「永远抓不到
|
||||
东西」,并且会被读成登录态失效。
|
||||
"""
|
||||
rows = await session.scalars(
|
||||
select(MonitorTarget.external_id).where(
|
||||
MonitorTarget.task_id == task_id,
|
||||
MonitorTarget.enabled.is_(True),
|
||||
)
|
||||
)
|
||||
return [
|
||||
value
|
||||
for value in rows.all()
|
||||
if value and ("://" in value or value.lower().startswith("http"))
|
||||
]
|
||||
|
||||
|
||||
async def _another_task_succeeded_recently(session: AsyncSession, task_id: int) -> bool:
|
||||
"""Whether a different task fetched data recently, proving the login is valid."""
|
||||
since = get_current_timestamp() - _AUTH_PROOF_WINDOW_MS
|
||||
@@ -333,6 +372,7 @@ async def _ingest_notes(
|
||||
records: List[Dict[str, Any]],
|
||||
is_baseline: bool,
|
||||
adapter: adapters.PlatformAdapter,
|
||||
platform: str,
|
||||
) -> int:
|
||||
"""Upsert notes, write metric snapshots, and emit new-note/delta events.
|
||||
|
||||
@@ -341,11 +381,24 @@ async def _ingest_notes(
|
||||
"""
|
||||
now = get_current_timestamp()
|
||||
new_count = 0
|
||||
# 同一轮里重复出现的作品只处理一次。**指标快照的唯一键是 (task_id, note_id, run_id)**,
|
||||
# 同一件作品在一轮里进来两次会让第二次插入直接撞键、整个 run 崩掉 —— 产物里重复并不
|
||||
# 罕见(多个目标指向同一个人、或退化路径重复刷新)。
|
||||
seen_in_run: set = set()
|
||||
# 这一轮看到的 (博主哈希 -> 昵称)。**昵称是博主级的属性,而作品是逐条刷的** ——
|
||||
# 一个博主只有落在采集窗口里的那几条会被重刷,掉出窗口的那些会一直留着旧名字。
|
||||
# 所以收完这一轮之后,再拿它把该博主在本任务下的作品统一改一遍(见循环之后)。
|
||||
fresh_names: Dict[str, str] = {}
|
||||
# 这一轮**第一次见到**的作品((note_id, title)),出了循环之后按规则自动打标签。
|
||||
first_seen_notes: List[Tuple[str, str]] = []
|
||||
|
||||
for record in records:
|
||||
note_id = adapter.note_field(record, "note_id")
|
||||
if not note_id:
|
||||
continue
|
||||
if note_id in seen_in_run:
|
||||
continue
|
||||
seen_in_run.add(note_id)
|
||||
|
||||
note = await session.scalar(
|
||||
select(MonitorNote).where(
|
||||
@@ -355,17 +408,29 @@ async def _ingest_notes(
|
||||
)
|
||||
|
||||
title = (adapter.note_field(record, "title") or "")[:500]
|
||||
hashtags = (adapter.note_field(record, "hashtags") or "")[:2000]
|
||||
# 标签规则匹配的是**标题 + 话题列表**。desc 会被抖音截断,后半段话题只在
|
||||
# text_extra 里 —— 只看标题会漏掉它们。
|
||||
tag_text = f"{title} {hashtags}".strip()
|
||||
cover = adapter.cover(record)
|
||||
fresh_name = adapter.note_field(record, "creator_name") or ""
|
||||
if fresh_name:
|
||||
fresh_names[adapter.note_field(record, "creator_hash") or ""] = fresh_name
|
||||
|
||||
if note is None:
|
||||
# **只在这一支里**收,也就是作品第一次入库时。自动打标签只贴不摘,所以
|
||||
# 每轮都跑的话,用户手动摘掉的标签下一轮就会长回来。
|
||||
first_seen_notes.append((note_id, tag_text))
|
||||
note = MonitorNote(
|
||||
task_id=run.task_id,
|
||||
note_id=note_id,
|
||||
title=title,
|
||||
hashtags=hashtags,
|
||||
note_url=adapter.note_field(record, "note_url") or "",
|
||||
cover=cover,
|
||||
creator_hash=adapter.note_field(record, "creator_hash") or "",
|
||||
creator_name=adapter.note_field(record, "creator_name") or "",
|
||||
creator_id=(adapter.note_field(record, "creator_id") or "")[:128],
|
||||
source_kind=adapter.note_field(record, "source_kind") or "",
|
||||
# 经 to_ms 换算:小红书给毫秒、抖音给秒,差 1000 倍。
|
||||
published_at=adapter.to_ms(adapter.note_field(record, "published_at")),
|
||||
@@ -390,6 +455,9 @@ async def _ingest_notes(
|
||||
# Only refresh descriptive fields; seen-tracking is updated below.
|
||||
if title:
|
||||
note.title = title
|
||||
# 话题列表可能上一轮还没采到(desc 截断 / 老数据),补上。
|
||||
if hashtags:
|
||||
note.hashtags = hashtags
|
||||
# 封面地址**带签名、会过期**,所以每轮都用最新的覆盖它。原先只在首次入库
|
||||
# 时写一次,结果旧作品的封面地址烂在库里 —— 隔天开始全是 403,而且再怎么
|
||||
# 重跑也修不回来。落盘那份由 covers.cache_pending 负责(网络操作不在本模块)。
|
||||
@@ -399,6 +467,11 @@ async def _ingest_notes(
|
||||
creator_name = adapter.note_field(record, "creator_name")
|
||||
if creator_name:
|
||||
note.creator_name = creator_name
|
||||
# 主页 id 同理。老数据里是空串,重采一次就补上了 —— 所以这里必须每轮都刷,
|
||||
# 只在首次入库时写的话,补录之前入库的作品永远没有主页链接。
|
||||
creator_id = adapter.note_field(record, "creator_id")
|
||||
if creator_id:
|
||||
note.creator_id = str(creator_id)[:128]
|
||||
# 发布时间也刷。正常情况下它不会变,但**换算单位改过之后**(抖音是秒、
|
||||
# 小红书是毫秒),已经入库的那批只能靠重采修回来。
|
||||
published = adapter.to_ms(adapter.note_field(record, "published_at"))
|
||||
@@ -409,6 +482,29 @@ async def _ingest_notes(
|
||||
|
||||
await _snapshot_metrics(session, run, note_id, record, now, is_baseline)
|
||||
|
||||
# 这一轮第一次见到的作品,按标签上的关键词规则自动贴上。
|
||||
# **只对新作品跑**:自动打标签只贴不摘,每轮都跑的话用户手动摘掉的标签会长回来。
|
||||
await tagrules.apply_tag_rules_for_task(
|
||||
session, run.task_id, platform, first_seen_notes
|
||||
)
|
||||
|
||||
# 把这一轮的昵称铺到该博主的**全部**作品上,不只这一轮采到的那几条。
|
||||
# 不做的话,博主改名之后库里会一半是新名字、一半是旧名字:界面按作品名分组时取的是
|
||||
# 其中任意一个(max),导出和 SQL 更是直接看到旧名字。带上 `!= name` 是为了让没变化
|
||||
# 的那些不产生写入。
|
||||
for creator_hash, name in fresh_names.items():
|
||||
if not creator_hash:
|
||||
continue
|
||||
await session.execute(
|
||||
update(MonitorNote)
|
||||
.where(
|
||||
MonitorNote.task_id == run.task_id,
|
||||
MonitorNote.creator_hash == creator_hash,
|
||||
MonitorNote.creator_name != name,
|
||||
)
|
||||
.values(creator_name=name)
|
||||
)
|
||||
|
||||
return new_count
|
||||
|
||||
|
||||
@@ -586,6 +682,50 @@ async def _ingest_comments(
|
||||
return new_count
|
||||
|
||||
|
||||
async def _ingest_creator_stats(
|
||||
session: AsyncSession,
|
||||
run: MonitorRun,
|
||||
records: Sequence[Dict[str, Any]],
|
||||
) -> int:
|
||||
"""把这一轮问到的博主账号级指标落成快照,返回条数。
|
||||
|
||||
和作品指标一样是**每轮一条**:账号级的粉丝数是缓慢变化的量,「今天比昨天多了 300」
|
||||
才是有用的信号,单看一个绝对值没有意义 —— 所以这里只管记,分析交给查询端。
|
||||
|
||||
**没解析出来的值留 NULL,不写 0**:0 在趋势图上是一条砸到底的线,和「不知道」完全是
|
||||
两回事(见 ``parse_count`` 的注释)。
|
||||
"""
|
||||
now = get_current_timestamp()
|
||||
written = 0
|
||||
seen: set = set()
|
||||
|
||||
for record in records:
|
||||
creator_hash = str(record.get("creator_hash") or "").strip()
|
||||
if not creator_hash or creator_hash in seen:
|
||||
# 一个任务可以配多个目标,退化路径下它们可能指向同一个博主 —— 而唯一键是
|
||||
# (task_id, creator_hash, run_id),重复插入会撞键把整轮炸掉。
|
||||
continue
|
||||
seen.add(creator_hash)
|
||||
|
||||
session.add(
|
||||
MonitorCreatorStat(
|
||||
task_id=run.task_id,
|
||||
run_id=run.id,
|
||||
creator_hash=creator_hash,
|
||||
nickname=str(record.get("nickname") or "")[:128],
|
||||
creator_id=str(record.get("creator_id") or "")[:128],
|
||||
fans=parse_count(record.get("fans")),
|
||||
total_favorited=parse_count(record.get("total_favorited")),
|
||||
works_count=parse_count(record.get("works")),
|
||||
following=parse_count(record.get("following")),
|
||||
captured_at=now,
|
||||
)
|
||||
)
|
||||
written += 1
|
||||
|
||||
return written
|
||||
|
||||
|
||||
async def ingest_run(
|
||||
session: AsyncSession,
|
||||
run: MonitorRun,
|
||||
@@ -632,6 +772,16 @@ async def ingest_run(
|
||||
run.notes_fetched = len(contents)
|
||||
run.comments_fetched = len(comments)
|
||||
|
||||
# 账号级快照**在「一条作品都没采到」的早退之前**落。博主的粉丝数并不会因为他这个
|
||||
# 月的新作品列表被风控挡住就不存在 —— 那正是最该看到「粉丝还在涨、但新作品没在发现」
|
||||
# 的时刻,跳过它等于在最需要它的那轮把数据丢掉。
|
||||
profiles = [
|
||||
record
|
||||
for path in find_profile_files(out_dir, task.platform)
|
||||
for record in _read_jsonl(path)
|
||||
]
|
||||
await _ingest_creator_stats(session, run, profiles)
|
||||
|
||||
# A bad cookie does NOT fail the process: XHS cookie login is never validated,
|
||||
# so an unauthenticated session just returns zero notes with exit 0 -- and
|
||||
# usually does not even create an output file. Treating that as "the creator
|
||||
@@ -666,6 +816,33 @@ async def ingest_run(
|
||||
comments_fetched=len(comments),
|
||||
)
|
||||
|
||||
# 再排除「目标本身就不是个 ID」。链接校验关掉之后,认不出来的链接会被**原样**存成
|
||||
# external_id(见 service.parse_target_input),而 external_id 是采集时唯一拿去
|
||||
# 请求的东西 —— 于是永远抓不到,还会被读成「登录态失效」。
|
||||
#
|
||||
# 这一条放在兄弟任务那条**之前**:它比那一条具体,而且确定得多 —— 兄弟任务那条
|
||||
# 赌的是「过去 6 小时里有没有别的任务成功过」,而 6 小时是很长的窗口,隔壁任务晚
|
||||
# 几秒成功就撞不上(真事:任务 1 的成功比这一轮的失败晚 6 秒,于是报成了登录失效)。
|
||||
broken = await _targets_that_are_not_ids(session, run.task_id)
|
||||
if broken:
|
||||
run.error_message = (
|
||||
f"Target {broken[0]} looks like an unparsed URL, not a target id"
|
||||
)
|
||||
await _emit(
|
||||
session,
|
||||
run,
|
||||
EVENT_NO_DATA,
|
||||
f"本次未抓到任何作品:目标「{broken[0]}」看起来是一串**没解析开的链接**,"
|
||||
f"不是博主/作品 ID。请重新粘贴完整链接 —— 登录态和它没关系。",
|
||||
severity="error",
|
||||
payload={"out_dir": str(out_dir), "targets": broken},
|
||||
)
|
||||
return IngestResult(
|
||||
status=RUN_PARTIAL,
|
||||
error=run.error_message,
|
||||
comments_fetched=len(comments),
|
||||
)
|
||||
|
||||
# Blaming the cookie is only honest if nothing else is authenticating.
|
||||
# A sibling task that just succeeded proves the login works, so the
|
||||
# fault is with this target (bad/expired per-creator token, an empty
|
||||
@@ -715,7 +892,9 @@ async def ingest_run(
|
||||
comments_fetched=len(comments),
|
||||
is_baseline=is_baseline,
|
||||
)
|
||||
result.new_notes = await _ingest_notes(session, run, contents, is_baseline, adapter)
|
||||
result.new_notes = await _ingest_notes(
|
||||
session, run, contents, is_baseline, adapter, task.platform
|
||||
)
|
||||
if task.enable_comments:
|
||||
result.new_comments = await _ingest_comments(
|
||||
session, run, comments, is_baseline, previous_started_at, adapter
|
||||
|
||||
@@ -117,6 +117,25 @@ class MonitorTask(MonitorBase):
|
||||
notify_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
notify_failures: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
|
||||
# 超级编导自动追加:每隔 N 分钟查一次这段时间**新发布**的作品,追加到本任务。
|
||||
# 只有抖音的作品模式任务能开(目标是作品 id;博主模式的目标是主页)。
|
||||
#
|
||||
# ``next_at`` 是调度钟,成功失败都往后推(失败按较短的退避重试);
|
||||
# ``last_at`` 是**成功**的窗口起点,失败时不动 —— 这样接口挂了两个小时,恢复后
|
||||
# 那两小时的作品还在窗口里,不会悄悄漏掉。
|
||||
superdir_auto_enabled: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, default=False
|
||||
)
|
||||
superdir_auto_interval_minutes: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=120
|
||||
)
|
||||
superdir_auto_next_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
superdir_auto_last_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
superdir_auto_last_added: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
superdir_auto_last_error: Mapped[str] = mapped_column(
|
||||
String(500), nullable=False, default=""
|
||||
)
|
||||
|
||||
# Scheduler state. Persisted so the schedule survives an API restart.
|
||||
next_run_at: Mapped[Optional[int]] = mapped_column(BigInteger, index=True)
|
||||
last_run_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
@@ -224,6 +243,13 @@ class MonitorNote(MonitorBase):
|
||||
)
|
||||
note_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True)
|
||||
title: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
# 话题列表(`#a #b`)。**不能只靠 title 打标签**:抖音的 desc 会被截断,后半段
|
||||
# 话题不在里面;`text_extra` 才是完整的那份。小红书暂不提供,存空串。
|
||||
#
|
||||
# **用 VARCHAR 不用 TEXT**:MySQL 5.7 不允许 TEXT/BLOB 列带 DEFAULT,而自动补列
|
||||
# 会给 NOT NULL 列拼一个 DEFAULT —— 用 TEXT 的话 ALTER 直接报 1101,应用启动失败、
|
||||
# 容器反复重启。话题列表本来也不会很长,2000 够用。
|
||||
hashtags: Mapped[str] = mapped_column(String(2000), nullable=False, default="")
|
||||
note_url: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
cover: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
# 创作者匿名哈希。爬虫刻意不落原始 user_id(见 tools/user_hash.py),
|
||||
@@ -232,6 +258,10 @@ class MonitorNote(MonitorBase):
|
||||
# 创作者昵称,**已由爬虫脱敏**(张***三 这种)。存的是脱敏后的值,与项目一贯的
|
||||
# 匿名化姿态一致;不存的话分组只能显示一串哈希,根本认不出是谁。
|
||||
creator_name: Mapped[str] = mapped_column(String(200), nullable=False, default="")
|
||||
# 平台上的主页 id(抖音是 sec_uid)。`creator_hash` 是单向的,拼不出主页地址,
|
||||
# 所以那些**只有作品、没有账号快照**的博主(作品模式 / 超级编导导入)也得在这里
|
||||
# 留一份 id,组头上的「去他主页」才有得跳。小红书那条路不提供,存空串。
|
||||
creator_id: Mapped[str] = mapped_column(String(128), nullable=False, default="")
|
||||
source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default="")
|
||||
published_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
|
||||
@@ -320,6 +350,171 @@ class MonitorEvent(MonitorBase):
|
||||
is_read: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
class MonitorCreatorAlias(MonitorBase):
|
||||
"""给博主起的备注。
|
||||
|
||||
作品栏和评论栏都按 ``creator_hash`` 把作品归到博主名下,可那是个哈希;
|
||||
``creator_name`` 是平台上的昵称(而且粉丝少的号常常没有)。两样都认不出"这是谁"。
|
||||
备注是**人自己起的名字**(「竞品A」「自家号-3」),用来把账号对上人。
|
||||
|
||||
键取 ``(platform, creator_hash)``:哈希对同一个 uid 是稳定的,所以同一个博主出现在
|
||||
多个任务里时备注也是同一个,不用每个任务各填一遍。
|
||||
"""
|
||||
|
||||
__tablename__ = "monitor_creator_alias"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("platform", "creator_hash", name="uq_creator_alias"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
platform: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
|
||||
creator_hash: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
alias: Mapped[str] = mapped_column(String(128), nullable=False, default="")
|
||||
updated_at: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
|
||||
|
||||
class MonitorCreatorStat(MonitorBase):
|
||||
"""博主的**账号级**快照:粉丝数 / 总获赞 / 作品数 / 关注数。
|
||||
|
||||
这是作品列表给不了的东西:作品级指标说"这一条视频涨了多少赞",账号级说"这个人
|
||||
整个账号的粉丝是在涨还是在掉"。两者不互相替代。
|
||||
|
||||
粒度取 ``(任务, 博主, 轮次)``,和作品指标一样的形状 —— 于是趋势、差分、报表那套
|
||||
现成的逻辑换个表就能用。
|
||||
|
||||
目前**只有抖音**会写它:小红书那条走的是爬虫子进程,而它的 ``save_creator()`` 在
|
||||
教学版里是空函数,根本没落过创作者资料。所以表里只有抖音的博主。
|
||||
"""
|
||||
|
||||
__tablename__ = "monitor_creator_stat"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"task_id", "creator_hash", "run_id", name="uq_creator_stat"
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
task_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("monitor_task.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
run_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
creator_hash: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
nickname: Mapped[str] = mapped_column(String(128), nullable=False, default="")
|
||||
# 平台上的**主页 id**(抖音是 sec_uid),用来拼博主主页的跳转链接。
|
||||
# creator_hash 是单向的,拼不出地址 —— 所以这个必须单独存。
|
||||
# 拿不到的地方(小红书那条路不落创作者资料)留空,界面就不画那个按钮。
|
||||
creator_id: Mapped[str] = mapped_column(String(128), nullable=False, default="")
|
||||
|
||||
# 都可能为 None:平台没给就留空,**不要伪造成 0** —— 0 是"掉到零",和"不知道"
|
||||
# 在趋势图上是完全不同的两回事。
|
||||
fans: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
total_favorited: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
works_count: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
following: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
|
||||
captured_at: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
|
||||
|
||||
|
||||
class MonitorCreatorFirstVideo(MonitorBase):
|
||||
"""博主主页**最早一条视频**的发布时间缓存。
|
||||
|
||||
抖音的作品列表是按时间倒序、按游标翻页的 —— 想知道「这个号第一条视频是什么时候
|
||||
发的」,只能一页页翻到最后一页(几十上百条作品 = 十几次请求),而且接口时不时超时。
|
||||
所以扫一次、存下来,30 天内不再扫:老作品不会变,这个值几乎是个常量。
|
||||
|
||||
矩阵页只读这张表,不在这里发任何请求。
|
||||
"""
|
||||
|
||||
__tablename__ = "monitor_creator_first_video"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("platform", "creator_id", name="uq_creator_first_video"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
platform: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
|
||||
# 主页 id(抖音是 sec_uid)。哈希是单向的,查不了主页。
|
||||
creator_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True)
|
||||
creator_hash: Mapped[str] = mapped_column(String(64), nullable=False, default="")
|
||||
# 毫秒。**没扫到时留 NULL**,界面上退回「库里最早的一条作品」。
|
||||
first_published_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
scanned_pages: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
# 是否翻到了最后一页。到了上限(作品特别多)时为 False,值只是「翻到的部分里最早的」。
|
||||
complete: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
checked_at: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0, index=True)
|
||||
error: Mapped[str] = mapped_column(String(500), nullable=False, default="")
|
||||
|
||||
|
||||
class MonitorNoteAlias(MonitorBase):
|
||||
"""给**作品**起的备注。
|
||||
|
||||
和 ``MonitorCreatorAlias`` 是一对:博主那条回答"这是谁",这条回答"这条我要盯着"。
|
||||
键取 ``(platform, note_id)`` —— 作品 id 本身就带平台语义,但显式带上 platform 才能和
|
||||
博主备注用同一套查询形状。
|
||||
"""
|
||||
|
||||
__tablename__ = "monitor_note_alias"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("platform", "note_id", name="uq_note_alias"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
platform: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
|
||||
note_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True)
|
||||
alias: Mapped[str] = mapped_column(String(128), nullable=False, default="")
|
||||
updated_at: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
|
||||
|
||||
class MonitorTag(MonitorBase):
|
||||
"""作品标签的**词表** —— 在设置里维护,贴标签时从这里选。
|
||||
|
||||
刻意做成一张表而不是一个设置项:设置里那个注册表存的是标量(一个数、一段文字),
|
||||
而这是一组能增能删能改名的条目。
|
||||
|
||||
**全局一套,不按平台分。** 「重点」「竞品」这种分类是给人自己用的心智,不该在小红书
|
||||
和抖音各定义一遍;而且同一个词在两个平台上含义不同的话,反而不好比。
|
||||
"""
|
||||
|
||||
__tablename__ = "monitor_tag"
|
||||
__table_args__ = (UniqueConstraint("name", name="uq_tag_name"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
# 一个**调色板里的名字**(cyan/pink/green/…),不是颜色值。Tailwind 的类名是静态
|
||||
# 提取的,拼不出 `text-${color}` 那种动态类,所以这里存的是查表用的键。
|
||||
color: Mapped[str] = mapped_column(String(16), nullable=False, default="")
|
||||
# 自动打标签的关键词,**逗号分隔**(中英文逗号都收)。作品标题里出现其中任意一个,
|
||||
# 这条标签就自动贴上 —— 命中几个贴几个。
|
||||
#
|
||||
# 关键词和标签名是**两回事**:标签叫「大字报」,关键词可能是 `szgtdzb`。
|
||||
# 所以存成一个字符串而不是另开一张表:它就是这个标签自带的一小串匹配式,
|
||||
# 没有独立的生命周期,也不需要在别处被引用。
|
||||
keywords: Mapped[str] = mapped_column(String(512), nullable=False, default="")
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
created_at: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
|
||||
|
||||
class MonitorNoteTag(MonitorBase):
|
||||
"""作品 ↔ 标签。
|
||||
|
||||
键取 ``(platform, note_id)``,和作品备注同一个口径:作品 id 本身带平台语义,但显式
|
||||
带上 platform 才能和别处用同一套查询形状。
|
||||
|
||||
**多对多**:一条作品可以既是「重点」又是「竞品」—— 标签本来就是可以叠加的分类,
|
||||
一个不够用的话人就会去备注里写自由文字,那这个功能就白做了。
|
||||
"""
|
||||
|
||||
__tablename__ = "monitor_note_tag"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("platform", "note_id", "tag_id", name="uq_note_tag"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
platform: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
|
||||
note_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True)
|
||||
tag_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
|
||||
created_at: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
|
||||
|
||||
class MonitorSetting(MonitorBase):
|
||||
"""Key/value store. Holds the XHS cookie for unattended runs."""
|
||||
|
||||
@@ -367,6 +562,61 @@ SETTING_UPSTREAM_STATE = "system.upstream_check_state"
|
||||
# 更新推一遍,直到有人去合并为止;而上游真又动了的时候应该再推一次。
|
||||
SETTING_UPSTREAM_NOTIFIED_TIP = "system.upstream_notified_tip"
|
||||
|
||||
# --- 身份池 -----------------------------------------------------------------
|
||||
|
||||
IDENTITY_STATUS_OK = "ok"
|
||||
IDENTITY_STATUS_COOLDOWN = "cooldown"
|
||||
IDENTITY_STATUS_EXPIRED = "expired"
|
||||
IDENTITY_STATUS_DISABLED = "disabled"
|
||||
|
||||
IDENTITY_SOURCE_STORED = "stored"
|
||||
IDENTITY_SOURCE_BROWSER = "browser"
|
||||
|
||||
|
||||
class MonitorIdentity(MonitorBase):
|
||||
"""一个可用于采集的登录态。
|
||||
|
||||
**为什么 cookie 必须和 UA 一起存**:抖音的 ``a_bogus`` 签名把 UA 算进去
|
||||
(``libs/douyin.js``),而网关又把 cookie / UA / sec-ch-ua 当成同一台设备的
|
||||
指纹。只存 cookie、套用另一套 UA,签名和指纹都对不上,接口只会回 200 + 空 body。
|
||||
|
||||
``source="browser"`` 表示用 CDP 浏览器**当前**登录态,此时 ``cookie`` 留空、每次
|
||||
运行时现读;``source="stored"`` 才是粘贴进来的那一份。
|
||||
"""
|
||||
|
||||
__tablename__ = "monitor_identity"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("platform", "label", name="uq_monitor_identity_label"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
platform: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="dy", index=True
|
||||
)
|
||||
label: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
source: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default=IDENTITY_SOURCE_STORED
|
||||
)
|
||||
# **永不回显**:接口只返回 has_cookie。
|
||||
cookie: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
user_agent: Mapped[str] = mapped_column(String(512), nullable=False, default="")
|
||||
client_hints: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
|
||||
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default=IDENTITY_STATUS_OK
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
# 冷却退避用:连续失败 N 次后冷却,成功后清零。
|
||||
consecutive_failures: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
cooldown_until: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
last_checked_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
last_ok_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
last_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
|
||||
created_at: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
updated_at: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
|
||||
|
||||
# Pre-namespacing keys, kept only so the startup migration can find and move
|
||||
# them. Nothing should read these directly.
|
||||
LEGACY_SETTING_KEY_RENAMES = {
|
||||
|
||||
@@ -27,6 +27,8 @@ Two rules shape this module:
|
||||
and swallowed.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
@@ -97,6 +99,49 @@ async def send_wecom(webhook_url: str, content: str) -> tuple[bool, str]:
|
||||
return True, "发送成功"
|
||||
|
||||
|
||||
# 企业微信图片消息的上限就是 2MB;超了会被直接拒掉,所以发送前先挡一道。
|
||||
WECOM_IMAGE_MAX_BYTES = 2 * 1024 * 1024
|
||||
|
||||
|
||||
async def send_wecom_image(webhook_url: str, image_bytes: bytes) -> tuple[bool, str]:
|
||||
"""Post an image to a WeCom group robot.
|
||||
|
||||
WeCom wants the raw base64 **and** the MD5 of the original bytes (not of the
|
||||
base64 string) -- getting that wrong produces a bare `errcode=40058` with no
|
||||
hint about which field is wrong.
|
||||
"""
|
||||
if not webhook_url:
|
||||
return False, "Webhook 未配置"
|
||||
if not image_bytes:
|
||||
return False, "图片内容为空"
|
||||
if len(image_bytes) > WECOM_IMAGE_MAX_BYTES:
|
||||
return False, f"图片太大({len(image_bytes)} 字节),企业微信上限 2MB"
|
||||
|
||||
payload = {
|
||||
"msgtype": "image",
|
||||
"image": {
|
||||
"base64": base64.b64encode(image_bytes).decode("ascii"),
|
||||
"md5": hashlib.md5(image_bytes).hexdigest(),
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=WEBHOOK_TIMEOUT_SECONDS) as client:
|
||||
response = await client.post(webhook_url, json=payload)
|
||||
response.raise_for_status()
|
||||
body = response.json()
|
||||
except httpx.HTTPError as exc:
|
||||
return False, f"请求失败:{exc}"
|
||||
except json.JSONDecodeError:
|
||||
return False, "返回内容不是合法 JSON,请检查 Webhook 地址"
|
||||
|
||||
errcode = body.get("errcode")
|
||||
if errcode != 0:
|
||||
return False, f"企业微信返回 errcode={errcode} {body.get('errmsg', '')}"
|
||||
|
||||
return True, "发送成功"
|
||||
|
||||
|
||||
async def get_webhook_url(session: AsyncSession) -> str:
|
||||
from .models import SETTING_WECOM_WEBHOOK
|
||||
|
||||
|
||||
+189
-45
@@ -28,6 +28,8 @@ import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable, List, Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from ..schemas import (
|
||||
@@ -38,7 +40,8 @@ from ..schemas import (
|
||||
SaveDataOptionEnum,
|
||||
)
|
||||
from ..services import crawler_manager
|
||||
from . import adapters, app_settings, covers, notify
|
||||
from . import adapters, app_settings, covers, douyin_fetch, notify
|
||||
from . import identities as identity_pool
|
||||
from .db import get_session
|
||||
from .ingest import IngestResult, diagnose_failure, ingest_run
|
||||
from .models import (
|
||||
@@ -47,6 +50,8 @@ from .models import (
|
||||
RUN_PENDING,
|
||||
RUN_RUNNING,
|
||||
RUN_TIMEOUT,
|
||||
MonitorIdentity,
|
||||
MonitorNote,
|
||||
MonitorRun,
|
||||
MonitorTarget,
|
||||
MonitorTask,
|
||||
@@ -194,56 +199,195 @@ async def execute_task(task_id: int, trigger: str = "manual") -> IngestResult:
|
||||
max_notes_count = task.max_notes_count
|
||||
max_comments_count = task.max_comments_count
|
||||
timeout_seconds = task.run_timeout_seconds
|
||||
# 抖音的作品列表接口被那道真校验挡着(见 douyin_fetch),拿不到列表时就靠这些
|
||||
# 已知的 aweme_id 逐条刷新 —— 新作品发现不了,但已有作品的指标还能继续更新。
|
||||
known_aweme_ids = list(
|
||||
await session.scalars(
|
||||
select(MonitorNote.note_id).where(MonitorNote.task_id == task.id)
|
||||
)
|
||||
)
|
||||
|
||||
# --- Phase 2: run the crawler outside any transaction ---------------------
|
||||
cookie_file = out_dir / ".cookies"
|
||||
_write_cookie_file(cookie_file, cookie)
|
||||
|
||||
request = CrawlerStartRequest(
|
||||
platform=_PLATFORM_ENUM[platform],
|
||||
login_type=LoginTypeEnum.COOKIE,
|
||||
crawler_type=CrawlerTypeEnum.CREATOR if mode == MODE_CREATOR else CrawlerTypeEnum.DETAIL,
|
||||
creator_ids=",".join(urls) if mode == MODE_CREATOR else "",
|
||||
specified_ids=",".join(urls) if mode != MODE_CREATOR else "",
|
||||
start_page=1,
|
||||
enable_comments=enable_comments,
|
||||
enable_sub_comments=strategy["enable_sub_comments"],
|
||||
enable_media=False,
|
||||
save_option=SaveDataOptionEnum.JSONL,
|
||||
cookies="",
|
||||
headless=True,
|
||||
max_notes_count=max_notes_count,
|
||||
max_comments_count=max_comments_count,
|
||||
# Isolate this run's output: the crawler names files by date only, so
|
||||
# otherwise same-day runs would append into one shared file.
|
||||
save_data_path=str(out_dir),
|
||||
# Attach to the browser already running on CDP_DEBUG_PORT when the
|
||||
# operator enabled it; otherwise launch a private, throwaway browser.
|
||||
enable_cdp_mode=cdp_enabled,
|
||||
# Only injecting web_session is not enough to sign requests from a cold
|
||||
# browser profile.
|
||||
inject_all_cookies=True,
|
||||
save_login_state=True,
|
||||
cookies_file=str(cookie_file),
|
||||
max_concurrency_num=1,
|
||||
# Strategy + proxy, surfaced on the Settings page.
|
||||
crawler_max_sleep_sec=strategy["crawl_sleep_sec"],
|
||||
enable_ip_proxy=strategy["enable_ip_proxy"],
|
||||
ip_proxy_pool_count=strategy["proxy_pool_count"],
|
||||
ip_proxy_provider_name=strategy["proxy_provider"],
|
||||
static_proxy_url=strategy["static_proxy_url"] or None,
|
||||
)
|
||||
# 身份池只在抖音上有意义(小红书走子进程)。池模式是**串行分片**:把目标分给
|
||||
# 多个账号,降低每个账号的请求量,不是并行提速。
|
||||
identity_rows = []
|
||||
identity_min_available = 1
|
||||
identity_switch_delay = 0
|
||||
identity_concurrency = 1
|
||||
if platform == adapters.PLATFORM_DY:
|
||||
identity_mode = await app_settings.get_value(
|
||||
session, "identity_mode", platform, "single"
|
||||
)
|
||||
if identity_mode == "pool":
|
||||
identity_rows = await identity_pool.load_available(session, platform)
|
||||
identity_min_available = int(
|
||||
await app_settings.get_value(
|
||||
session, "identity_min_available", platform, 1
|
||||
)
|
||||
)
|
||||
identity_switch_delay = int(
|
||||
await app_settings.get_value(
|
||||
session, "identity_switch_delay_sec", platform, 30
|
||||
)
|
||||
)
|
||||
identity_concurrency = int(
|
||||
await app_settings.get_value(
|
||||
session, "identity_concurrency", platform, 1
|
||||
)
|
||||
)
|
||||
|
||||
# --- Phase 2: run the collection outside any transaction ------------------
|
||||
# 抖音走**进程内 HTTP 客户端**,不起 Playwright 子进程:那边会构造一大串自相矛盾的
|
||||
# 浏览器指纹参数(参数说 Mac + Chrome 125、UA 说 Linux + Chrome 155),网关回一个
|
||||
# 200 + 空 body,然后被翻译成「account blocked」—— 看着像账号被封,其实什么都不是。
|
||||
# 见 douyin_fetch / douyin_api。
|
||||
# 先落「运行中」—— **两条路都要**。原先这一行只写在爬虫那条分支里,于是抖音那条路上
|
||||
# run 一直停在 pending;一旦中途出事(异常、进程被重启),界面上就是一个永远
|
||||
# 「排队中」的幽灵,而且 recover() 也只清理 running、收不到它。
|
||||
async with get_session() as session:
|
||||
run = await session.get(MonitorRun, run_id)
|
||||
if run is not None:
|
||||
run.status = RUN_RUNNING
|
||||
run.started_at = get_current_timestamp()
|
||||
|
||||
try:
|
||||
exit_code = await crawler_manager.run_and_wait(request, timeout=timeout_seconds)
|
||||
finally:
|
||||
_remove_cookie_file(cookie_file)
|
||||
# 身份行在会话关掉之后是 detached 的,但 expire_on_commit=False,字段还能读。
|
||||
# 解析放到这里(会话之外)—— source="browser" 要连 CDP,可能慢。
|
||||
resolved_identities = []
|
||||
resolved_ids = []
|
||||
for row in identity_rows:
|
||||
try:
|
||||
resolved_identities.append(await identity_pool.resolve(row))
|
||||
resolved_ids.append(row.id)
|
||||
except ValueError as exc:
|
||||
print(f"[monitor.runner] 身份「{row.label}」本轮不可用:{exc}", flush=True)
|
||||
|
||||
in_process_tail: List[str] = []
|
||||
if platform == adapters.PLATFORM_DY:
|
||||
if identity_rows and len(resolved_identities) < identity_min_available:
|
||||
# 快速失败:宁可这一轮不跑,也别拿一个号硬扛全部目标。
|
||||
fetched = {
|
||||
"notes": 0,
|
||||
"comments": 0,
|
||||
"errors": [
|
||||
f"可用抖音身份不足:{len(resolved_identities)}/{identity_min_available}"
|
||||
"(其余的已失效或在冷却中)"
|
||||
],
|
||||
"jsonl_dir": "",
|
||||
"shards": [],
|
||||
}
|
||||
else:
|
||||
try:
|
||||
# 也要有超时。爬虫那条路靠 run_and_wait(timeout=...) 兜底,这条路没有子进程、
|
||||
# 没人管 —— 里面**任何一次卡住都会让 run 永远停在「运行中」**(真踩过:
|
||||
# page.evaluate 打在一个卡死的标签页上不返回)。
|
||||
fetched = await asyncio.wait_for(
|
||||
douyin_fetch.collect(
|
||||
out_dir,
|
||||
platform=platform,
|
||||
mode=mode,
|
||||
limit=max_notes_count,
|
||||
want_comments=enable_comments,
|
||||
comment_limit=max_comments_count,
|
||||
targets=targets,
|
||||
known_aweme_ids=known_aweme_ids,
|
||||
cookie=cookie,
|
||||
identities=resolved_identities,
|
||||
concurrency=identity_concurrency,
|
||||
switch_delay_seconds=identity_switch_delay,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
fetched = {
|
||||
"notes": 0,
|
||||
"comments": 0,
|
||||
"errors": [f"抖音采集超过 {timeout_seconds} 秒仍未完成,已放弃这一轮"],
|
||||
"jsonl_dir": "",
|
||||
"shards": [],
|
||||
}
|
||||
|
||||
# 每个身份的健康按它自己那一片的结果算:有产物就算成功(哪怕带着退化错误),
|
||||
# 一条没采到且全是错误才算失败。
|
||||
if resolved_ids:
|
||||
shards_by_key = {
|
||||
shard.get("key"): shard for shard in (fetched.get("shards") or [])
|
||||
}
|
||||
async with get_session() as session:
|
||||
for row_id in resolved_ids:
|
||||
row = await session.get(MonitorIdentity, row_id)
|
||||
if row is None:
|
||||
continue
|
||||
shard = shards_by_key.get(identity_pool.key_for(row))
|
||||
if shard is None:
|
||||
continue
|
||||
await identity_pool.record_result(
|
||||
session,
|
||||
row,
|
||||
ok=bool(shard["notes"]) or not shard["errors"],
|
||||
error=";".join(shard["errors"]),
|
||||
)
|
||||
in_process_tail = list(fetched["errors"])
|
||||
# 一条都没采到 = 这一轮失败,并把**真因**当作退出诊断传下去。否则它会掉进
|
||||
# ingest 的「疑似登录失效」分支 —— 又骗人一次,正是这套东西一直在犯的毛病。
|
||||
exit_code = 1 if (fetched["errors"] and not fetched["notes"]) else 0
|
||||
if fetched["errors"] and fetched["notes"]:
|
||||
# 有产物但带着错误,说明走了退化路径(比如作品列表被挡,只刷新了已知作品)。
|
||||
# 这一轮状态是成功,但**不是**一切正常 —— 得留下痕迹,否则没人知道新作品
|
||||
# 其实没在发现。
|
||||
print(
|
||||
"[monitor.runner] 抖音采集部分失败:"
|
||||
+ ";".join(fetched["errors"])[:300]
|
||||
)
|
||||
else:
|
||||
cookie_file = out_dir / ".cookies"
|
||||
_write_cookie_file(cookie_file, cookie)
|
||||
|
||||
request = CrawlerStartRequest(
|
||||
platform=_PLATFORM_ENUM[platform],
|
||||
login_type=LoginTypeEnum.COOKIE,
|
||||
crawler_type=CrawlerTypeEnum.CREATOR if mode == MODE_CREATOR else CrawlerTypeEnum.DETAIL,
|
||||
creator_ids=",".join(urls) if mode == MODE_CREATOR else "",
|
||||
specified_ids=",".join(urls) if mode != MODE_CREATOR else "",
|
||||
start_page=1,
|
||||
enable_comments=enable_comments,
|
||||
enable_sub_comments=strategy["enable_sub_comments"],
|
||||
enable_media=False,
|
||||
save_option=SaveDataOptionEnum.JSONL,
|
||||
cookies="",
|
||||
headless=True,
|
||||
max_notes_count=max_notes_count,
|
||||
max_comments_count=max_comments_count,
|
||||
# Isolate this run's output: the crawler names files by date only, so
|
||||
# otherwise same-day runs would append into one shared file.
|
||||
save_data_path=str(out_dir),
|
||||
# Attach to the browser already running on CDP_DEBUG_PORT when the
|
||||
# operator enabled it; otherwise launch a private, throwaway browser.
|
||||
enable_cdp_mode=cdp_enabled,
|
||||
# Only injecting web_session is not enough to sign requests from a cold
|
||||
# browser profile.
|
||||
inject_all_cookies=True,
|
||||
save_login_state=True,
|
||||
cookies_file=str(cookie_file),
|
||||
max_concurrency_num=1,
|
||||
# Strategy + proxy, surfaced on the Settings page.
|
||||
crawler_max_sleep_sec=strategy["crawl_sleep_sec"],
|
||||
enable_ip_proxy=strategy["enable_ip_proxy"],
|
||||
ip_proxy_pool_count=strategy["proxy_pool_count"],
|
||||
ip_proxy_provider_name=strategy["proxy_provider"],
|
||||
static_proxy_url=strategy["static_proxy_url"] or None,
|
||||
)
|
||||
|
||||
try:
|
||||
exit_code = await crawler_manager.run_and_wait(request, timeout=timeout_seconds)
|
||||
finally:
|
||||
_remove_cookie_file(cookie_file)
|
||||
|
||||
# 失败时的诊断来源。抖音那条路没有子进程,尾巴就是它自己报的错 —— **别去读
|
||||
# crawler_manager 的尾巴**,那里面是上一轮别的平台留下的东西,会张冠李戴。
|
||||
output_tail = (
|
||||
in_process_tail
|
||||
if platform == adapters.PLATFORM_DY
|
||||
else crawler_manager.get_output_tail()
|
||||
)
|
||||
|
||||
# --- Phase 3: ingest ------------------------------------------------------
|
||||
async with get_session() as session:
|
||||
@@ -261,7 +405,7 @@ async def execute_task(task_id: int, trigger: str = "manual") -> IngestResult:
|
||||
run.error_message = "Run was killed by timeout or failed to start"
|
||||
# -1 同时代表「超时」和「根本没起来」,两者要查的东西完全不同。输出尾巴里
|
||||
# 有异常就带上它,否则运行历史里只能看到这句没有信息量的话。
|
||||
cause = diagnose_failure(crawler_manager.get_output_tail())
|
||||
cause = diagnose_failure(output_tail)
|
||||
if cause:
|
||||
run.error_message = f"{run.error_message};原因:{cause}"
|
||||
result = IngestResult(status=RUN_TIMEOUT, error=run.error_message)
|
||||
@@ -271,7 +415,7 @@ async def execute_task(task_id: int, trigger: str = "manual") -> IngestResult:
|
||||
# 把爬虫输出的尾巴交给 ingest:退出码本身说明不了问题,运行历史里要显示的
|
||||
# 是真正的报错(比如抖音的 DataFetchError: account blocked)。
|
||||
result = await ingest_run(
|
||||
session, run, task, out_dir, output_tail=crawler_manager.get_output_tail()
|
||||
session, run, task, out_dir, output_tail=output_tail
|
||||
)
|
||||
|
||||
# A run that authenticated fine is the only useful signal that the
|
||||
|
||||
+282
-8
@@ -44,21 +44,93 @@ import random
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import or_, select
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from ..services import crawler_manager
|
||||
from . import app_settings, schedule, upstream
|
||||
from . import adapters, app_settings, creator_scan, schedule, superdir, upstream
|
||||
from .db import get_session
|
||||
from .models import MonitorRun, MonitorTask, RUN_INTERRUPTED, RUN_RUNNING
|
||||
from .models import (
|
||||
MODE_NOTE,
|
||||
RUN_INTERRUPTED,
|
||||
RUN_PENDING,
|
||||
RUN_RUNNING,
|
||||
MonitorRun,
|
||||
MonitorTask,
|
||||
)
|
||||
from .runner import execute_task
|
||||
from .settings import get_cookie
|
||||
from .settings import get_cookie, get_setting, platform_key, set_setting
|
||||
|
||||
POLL_INTERVAL_SECONDS = 20
|
||||
# Spread tasks sharing an interval so they do not all come due on the same tick.
|
||||
# Applied to interval mode only -- see the advance step below.
|
||||
JITTER_SECONDS = 60
|
||||
# 超时之后再等这么久才动手回收。采集那边到点后还要收尾写库,别和它抢。
|
||||
REAP_GRACE_SECONDS = 300
|
||||
|
||||
|
||||
def _time_reached(now: datetime, send_at: str) -> bool:
|
||||
"""``HH:MM`` 到了没有。
|
||||
|
||||
配置写错(空串、``"22"``、``"九点"``)时按 09:00 算 —— 一个手滑的配置不该让
|
||||
推送永远发不出去。
|
||||
"""
|
||||
try:
|
||||
hour_text, minute_text = send_at.split(":", 1)
|
||||
target = (int(hour_text), int(minute_text))
|
||||
except (AttributeError, ValueError):
|
||||
target = (9, 0)
|
||||
return (now.hour, now.minute) >= target
|
||||
|
||||
|
||||
async def reap_stale_runs() -> int:
|
||||
"""把「早就该结束却还挂在 running」的 run 收掉,返回收了几个。
|
||||
|
||||
**为什么不能只靠 ``asyncio.wait_for`` 的超时。** 它超时后会去**取消**采集协程,
|
||||
而取消要等协程真正结束。抖音那条路会卡在 Playwright 的调用上
|
||||
(``douyin_api._read_browser`` 里 ``playwright.stop()`` 原先没包超时,driver
|
||||
一卡就永不返回),这种协程不响应取消 —— 于是 ``wait_for`` 自己也永远不返回,
|
||||
``except asyncio.TimeoutError`` 根本轮不到,run 就永远停在「运行中」。
|
||||
实测:7 条这样的幽灵,最久的挂了 48 小时,产物目录全空。
|
||||
|
||||
``recover()`` 只在进程启动时跑一次,进程不重启就没人来收。所以这里按 tick 扫。
|
||||
|
||||
判据用**任务自己配的** ``run_timeout_seconds``(默认 3600),不是写死时长 ——
|
||||
每个任务允许跑多久本来就不一样。
|
||||
"""
|
||||
now = get_current_timestamp()
|
||||
reaped = 0
|
||||
async with get_session() as session:
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(MonitorRun, MonitorTask.run_timeout_seconds)
|
||||
.join(MonitorTask, MonitorTask.id == MonitorRun.task_id)
|
||||
.where(MonitorRun.status == RUN_RUNNING)
|
||||
)
|
||||
).all()
|
||||
for run, timeout_seconds in rows:
|
||||
if run.started_at is None:
|
||||
continue
|
||||
limit_ms = (
|
||||
max(1, int(timeout_seconds or 3600)) + REAP_GRACE_SECONDS
|
||||
) * 1000
|
||||
if now - run.started_at < limit_ms:
|
||||
continue
|
||||
run.status = RUN_INTERRUPTED
|
||||
run.finished_at = now
|
||||
run.error_message = (
|
||||
f"超过 {timeout_seconds} 秒仍未结束,已判定为卡死并回收"
|
||||
"(采集协程没有响应取消,通常卡在浏览器调用上)"
|
||||
)
|
||||
reaped += 1
|
||||
|
||||
if reaped:
|
||||
print(
|
||||
f"[monitor.scheduler] 回收了 {reaped} 个卡死的 run(超过各自超时仍未结束)",
|
||||
flush=True,
|
||||
)
|
||||
return reaped
|
||||
|
||||
|
||||
class MonitorScheduler:
|
||||
@@ -70,6 +142,13 @@ class MonitorScheduler:
|
||||
# Avoids logging "no cookie" on every single tick. Per platform, because
|
||||
# warning once for Xiaohongshu must not silence the warning for Douyin.
|
||||
self._warned_no_cookie: set = set()
|
||||
# 超级编导自动追加是网络操作,单独一个后台任务,不占调度循环。
|
||||
self._superdir_task: Optional[asyncio.Task] = None
|
||||
# 正在跑的采集(task_id -> asyncio.Task)。**必须留强引用**,否则任务可能被
|
||||
# GC 回收;顺带让测试和停机可以等它们结束。
|
||||
self._running_tasks: dict[int, asyncio.Task] = {}
|
||||
# 扫「最早一条视频」的后台任务。慢、且不急,单飞即可。
|
||||
self._first_video_task: Optional[asyncio.Task] = None
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._loop_task is not None and not self._loop_task.done():
|
||||
@@ -94,6 +173,12 @@ class MonitorScheduler:
|
||||
print(f"[monitor.scheduler] recovery failed: {exc}")
|
||||
|
||||
while not self._stopping.is_set():
|
||||
# 先收尸再调度:卡死的 run 不该继续占着界面的「运行中」,也不该让
|
||||
# 它的任务看起来还在跑。见 reap_stale_runs 的说明。
|
||||
try:
|
||||
await reap_stale_runs()
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] stale run reap failed: {exc}")
|
||||
try:
|
||||
await self.tick()
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
@@ -104,8 +189,100 @@ class MonitorScheduler:
|
||||
await self._maybe_check_upstream()
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] upstream check failed: {exc}")
|
||||
# 每日推送和采集、上游检查互不相干,各占一段 try。
|
||||
try:
|
||||
await self._maybe_send_digest()
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] daily digest failed: {exc}")
|
||||
# 超级编导自动追加。和采集、推送都无关,单独一段 try。
|
||||
try:
|
||||
await self._maybe_sync_superdir()
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] 超级编导自动追加失败: {exc}")
|
||||
# 扫博主主页「最早一条视频」。慢且不紧急,后台慢慢来。
|
||||
try:
|
||||
await self._maybe_scan_first_videos()
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] 扫描最早视频失败: {exc}")
|
||||
await asyncio.sleep(POLL_INTERVAL_SECONDS)
|
||||
|
||||
async def _maybe_scan_first_videos(self) -> None:
|
||||
if self._first_video_task is not None and not self._first_video_task.done():
|
||||
return
|
||||
self._first_video_task = asyncio.create_task(self._scan_first_videos())
|
||||
|
||||
async def _scan_first_videos(self) -> None:
|
||||
try:
|
||||
result = await creator_scan.refresh_batch(adapters.PLATFORM_DY)
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] 扫描最早视频失败: {exc}")
|
||||
return
|
||||
if result.get("scanned") or result.get("failed"):
|
||||
print(
|
||||
f"[monitor.scheduler] 最早视频扫描:"
|
||||
f"到期 {result['due']},成功 {result['scanned']},失败 {result['failed']}"
|
||||
)
|
||||
|
||||
async def _maybe_sync_superdir(self) -> None:
|
||||
"""到点的任务补一批超级编导新发布的作品。
|
||||
|
||||
**放到后台任务里跑**:它要发第三方接口的请求(慢的时候一次好几秒),
|
||||
堵在调度循环里会推迟其他任务的采集。上一次还没跑完就跳过这一 tick ——
|
||||
不需要排队,下一次自然还会来。
|
||||
"""
|
||||
if self._superdir_task is not None and not self._superdir_task.done():
|
||||
return
|
||||
self._superdir_task = asyncio.create_task(self._sync_superdir())
|
||||
|
||||
async def _sync_superdir(self) -> None:
|
||||
try:
|
||||
now = get_current_timestamp()
|
||||
async with get_session() as session:
|
||||
due = list(
|
||||
await session.scalars(
|
||||
select(MonitorTask.id).where(
|
||||
MonitorTask.platform == adapters.PLATFORM_DY,
|
||||
MonitorTask.mode == MODE_NOTE,
|
||||
MonitorTask.superdir_auto_enabled.is_(True),
|
||||
or_(
|
||||
MonitorTask.superdir_auto_next_at.is_(None),
|
||||
MonitorTask.superdir_auto_next_at <= now,
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] 读取超级编导自动追加任务失败: {exc}")
|
||||
return
|
||||
|
||||
for task_id in due:
|
||||
await self._sync_one_superdir(task_id)
|
||||
|
||||
async def _sync_one_superdir(self, task_id: int) -> None:
|
||||
async with get_session() as session:
|
||||
task = await session.get(MonitorTask, task_id)
|
||||
if task is None or not task.superdir_auto_enabled:
|
||||
return
|
||||
try:
|
||||
result = await superdir.sync_task(session, task)
|
||||
except Exception as exc:
|
||||
# 失败**不推** last_at:接口挂了一小时,恢复后这一小时的作品还在
|
||||
# 查询窗口里。只把调度钟往后挪。挪多久看错误类型 —— 账号密码错了
|
||||
# 就几乎等于「等人来修」,继续每 30 分钟试一次会把号锁掉。
|
||||
task.superdir_auto_last_error = str(exc)[:500]
|
||||
task.superdir_auto_next_at = (
|
||||
get_current_timestamp() + superdir.retry_delay_ms(exc)
|
||||
)
|
||||
print(
|
||||
f"[monitor.scheduler] 超级编导自动追加失败 task={task_id}: {exc}"
|
||||
)
|
||||
return
|
||||
if result["added"]:
|
||||
print(
|
||||
f"[monitor.scheduler] 超级编导自动追加 task={task_id} "
|
||||
f"新增 {result['added']} 条(共 {result['total']})"
|
||||
)
|
||||
|
||||
async def _maybe_check_upstream(self) -> None:
|
||||
"""到点就 fetch 一次上游仓库,看它有没有新提交。
|
||||
|
||||
@@ -141,17 +318,78 @@ class MonitorScheduler:
|
||||
elif not result.get("ok"):
|
||||
print(f"[monitor.scheduler] 上游检查失败:{result.get('error')}")
|
||||
|
||||
async def _maybe_send_digest(self) -> None:
|
||||
"""到点推一张**昨天**的视频情况图到企业微信。
|
||||
|
||||
每个平台独立配置。**按「这一天发过没有」判断,而不是按「距上次多久」** ——
|
||||
进程重启、tick 抖动都不会让它重复推;记的是被报的那一天,不是发送时刻,
|
||||
所以早上九点失败、十点补发成功之后,十一点的 tick 不会再发一遍。
|
||||
"""
|
||||
from . import adapters, digest
|
||||
|
||||
now = datetime.now()
|
||||
# 和 send_daily_digest 走同一个口径,免得「配置说昨天、发出去是今天」。
|
||||
target_day = digest.default_day()
|
||||
marker = target_day.isoformat()
|
||||
|
||||
for platform in (adapters.PLATFORM_DY, adapters.PLATFORM_XHS):
|
||||
async with get_session() as session:
|
||||
if not await app_settings.get_value(
|
||||
session, "daily_digest_enabled", platform, False
|
||||
):
|
||||
continue
|
||||
send_at = str(
|
||||
await app_settings.get_value(
|
||||
session, "daily_digest_time", platform, "09:00"
|
||||
)
|
||||
).strip()
|
||||
last_sent = await get_setting(
|
||||
session, platform_key(platform, "daily_digest_last_sent")
|
||||
)
|
||||
|
||||
if last_sent == marker or not _time_reached(now, send_at):
|
||||
continue
|
||||
|
||||
async with get_session() as session:
|
||||
ok, detail, count = await digest.send_daily_digest(
|
||||
session, platform, target_day
|
||||
)
|
||||
|
||||
if ok:
|
||||
async with get_session() as session:
|
||||
await set_setting(
|
||||
session, platform_key(platform, "daily_digest_last_sent"), marker
|
||||
)
|
||||
print(
|
||||
f"[monitor.scheduler] 已推送 {platform} {marker} 的视频情况图"
|
||||
f"({count} 条)",
|
||||
flush=True,
|
||||
)
|
||||
else:
|
||||
# 不写 last_sent:下一拍还会重试,直到发出去为止。
|
||||
print(
|
||||
f"[monitor.scheduler] 视频情况图发送失败({platform},{marker}):"
|
||||
f"{detail}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
async def recover(self) -> None:
|
||||
"""Clean up state left behind by a server restart.
|
||||
|
||||
A run still marked ``running`` cannot be running -- its subprocess died
|
||||
with the previous process. Marking it interrupted stops it from blocking
|
||||
the UI as a phantom in-flight run.
|
||||
|
||||
**``pending`` 同样是残留**:那一行是上一轮建的,可它后面的采集根本没机会开始
|
||||
(进程被重启,或者采集那条路抛了异常),所以它永远不会自己往前走。只清 running
|
||||
的话,它会永远挂在界面上显示「排队中」—— 用户看到的就是任务卡住了。
|
||||
"""
|
||||
async with get_session() as session:
|
||||
stale = (
|
||||
await session.scalars(
|
||||
select(MonitorRun).where(MonitorRun.status == RUN_RUNNING)
|
||||
select(MonitorRun).where(
|
||||
MonitorRun.status.in_((RUN_RUNNING, RUN_PENDING))
|
||||
)
|
||||
)
|
||||
).all()
|
||||
for run in stale:
|
||||
@@ -258,11 +496,47 @@ class MonitorScheduler:
|
||||
|
||||
task_id = task.id
|
||||
|
||||
try:
|
||||
await execute_task(task_id, trigger="scheduled")
|
||||
except Exception as exc:
|
||||
self._start_execution(task_id)
|
||||
|
||||
def _start_execution(self, task_id: int) -> asyncio.Task:
|
||||
"""把采集丢到后台跑,**不让它堵住调度循环**。
|
||||
|
||||
``execute_task`` 里的超时用的是 ``asyncio.wait_for``,它到点会取消采集协程、
|
||||
然后**等取消完成**。抖音那条路偶尔卡在不响应取消的浏览器调用上 —— 内联
|
||||
``await`` 会把整个循环一起钉死 65 分钟:其他任务不触发、自动追加不跑、每日
|
||||
推送也错过。实测任务 25 的 8 次运行里有 4 次就是这样。
|
||||
|
||||
放到后台之后,``reap_stale_runs`` 仍会把卡死的 run 标记回收,循环照常 tick。
|
||||
"""
|
||||
running = self._running_tasks.get(task_id)
|
||||
if running is not None and not running.done():
|
||||
# 同一个任务已经有采集在跑(比如手动触发的还没结束),不要再起一个。
|
||||
return running
|
||||
|
||||
task = asyncio.create_task(execute_task(task_id, trigger="scheduled"))
|
||||
self._running_tasks[task_id] = task
|
||||
task.add_done_callback(lambda done: self._execution_done(task_id, done))
|
||||
return task
|
||||
|
||||
def _execution_done(self, task_id: int, task: asyncio.Task) -> None:
|
||||
if self._running_tasks.get(task_id) is task:
|
||||
self._running_tasks.pop(task_id, None)
|
||||
if task.cancelled():
|
||||
return
|
||||
exc = task.exception()
|
||||
if exc is not None:
|
||||
print(f"[monitor.scheduler] task {task_id} failed: {exc}")
|
||||
|
||||
async def drain(self) -> None:
|
||||
"""等后台采集结束。测试与优雅停机用。"""
|
||||
while True:
|
||||
pending = [
|
||||
task for task in self._running_tasks.values() if not task.done()
|
||||
]
|
||||
if not pending:
|
||||
return
|
||||
await asyncio.gather(*pending, return_exceptions=True)
|
||||
|
||||
|
||||
# Global singleton, mirroring the crawler_manager pattern.
|
||||
monitor_scheduler = MonitorScheduler()
|
||||
|
||||
+1074
-19
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,790 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""超级编导(SuperDir)→ 抖音监控任务:把一段时间里分发的作品链接捞出来。
|
||||
|
||||
「超级编导」是内容分发平台,不是抖音接口。运营在它上面建**分发活动**,达人扫码领任务、
|
||||
发布作品,作品链接和播放数据最后都落在它的数据中心里。这里的活儿就是把某段时间创建的
|
||||
活动下的作品链接取出来,直接变成一个抖音监控任务 —— 不用再一条条粘贴。
|
||||
|
||||
三个坑,写在最前面(每一条都实测踩过,见 ``D:/SuperDir/_api/docs/query_by_date.md``):
|
||||
|
||||
1. **活动列表不支持按日期过滤。** 传 ``start_time`` / ``start_date`` 都会被静默忽略,
|
||||
只能全量翻页、本地按 ``created_at`` 筛。所以这个接口的成本随**活动总量**涨,不随
|
||||
查询区间涨;活动多了以后预览会慢下来,这是接口形状决定的,不是这里写得低效。
|
||||
2. **视频链接在 ``data_center/page`` 里,且必须带 ``video_status=-1``。** 不带时默认 0,
|
||||
接口返回 ``total:0`` —— 看起来像「这段时间没发东西」,其实是参数默认值在骗人。
|
||||
3. **``share_url`` 是双斜杠**(``https://www.douyin.com/video//{id}``)。直接当监控目标
|
||||
存会解析失败(见 ``adapters.DY.note_url_res``),所以建任务时只取作品 id。
|
||||
|
||||
时间一律按**东八区**算:``created_at`` 是「本地时区」的 Unix 秒,而容器通常跑在 UTC。
|
||||
拿容器的 localtime 去算日期边界,查询区间会整体错开 8 小时 —— 早上建的「今天」会把
|
||||
昨晚的活动算进来,晚上查又会漏掉当天。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import date, datetime, time as day_time, timedelta, timezone
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncIterator,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Dict,
|
||||
List,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
)
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from . import adapters, app_settings, service, video_link
|
||||
from .models import MODE_NOTE, MonitorTarget, MonitorTask
|
||||
from .settings import platform_key, set_setting
|
||||
|
||||
BASE_URL = "https://api.superdir.cn"
|
||||
|
||||
# 这些是超级编导自己的约定,不是抖音的:bizid=3 是超级编导这个产品,
|
||||
# business-code 不传会被当成别的业务线,os=1 是 Windows 客户端。
|
||||
BIZ_ID = "3"
|
||||
BUSINESS_CODE = "superdir"
|
||||
OS = "1"
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) superdir-sdk/1.0"
|
||||
|
||||
TIMEOUT_SECONDS = 30
|
||||
# 网络层抖动(容器刚起来时 DNS 常说翻脸)重试两次;接口明确回了错误码就不重试了 ——
|
||||
# 4017「账号已在别处登录」这种,重试多少次都是同一个结果。
|
||||
REQUEST_RETRIES = 2
|
||||
# 活动列表的 page_size 上限实测是 100。
|
||||
ACTIVITY_PAGE_SIZE = 100
|
||||
MAX_ACTIVITY_PAGES = 100
|
||||
# 作品的 page_size 放到 200:一个活动通常几十条,一页就够。
|
||||
VIDEO_PAGE_SIZE = 200
|
||||
MAX_VIDEO_PAGES = 50
|
||||
|
||||
# 并发数。**实测单个请求就要 1–4 秒**(活动列表那三页各约 4 秒),串行做一轮
|
||||
# 5 天区间的查询要 20 秒 —— 界面上就是一个一直转的「查询中」。
|
||||
# 翻页和按活动取作品彼此独立,并起来做能压到 5–6 秒;再高的并发对人家接口不礼貌,
|
||||
# 收益也看不出来(瓶颈在服务端响应,不在我们发请求的速度)。
|
||||
ACTIVITY_CONCURRENCY = 4
|
||||
VIDEO_CONCURRENCY = 6
|
||||
# 一次预览/建任务最多这么多条作品。不是接口限制,是监控任务的现实:作品模式每轮要
|
||||
# 逐条请求详情接口,几百条就是几百次请求,抖音那边很容易当异常流量。
|
||||
MAX_TARGETS = 1000
|
||||
MAX_RANGE_DAYS = 31
|
||||
|
||||
# 自动追加每次查询的窗口往回**多覆盖**一小时。数据中心对刚发布的作品有索引延迟:
|
||||
# 卡在两次查询边界上的那一条,如果窗口首尾相接就会被漏掉。重叠部分靠去重消化。
|
||||
SYNC_OVERLAP_SECONDS = 3600
|
||||
# 一次自动追加最多处理这么多条。超过说明窗口开得太久(进程停过几天),先加能加的,
|
||||
# 剩下的留到下一次 —— 这比整批拒绝、然后每 30 分钟重试一次要有用。
|
||||
MAX_SYNC_VIDEOS = 500
|
||||
# 自动追加失败后的重试间隔。不能用正常的间隔:接口挂一小时的话,等两小时才重试
|
||||
# 意味着恢复后还要再等两小时。
|
||||
SYNC_FAILURE_RETRY_MS = 30 * 60_000
|
||||
# 账号密码本身错了(1002 密码错误 / 10006 没设密码 / 4026 版本头)时,**不要再自动重试**。
|
||||
# 超级编导对密码尝试有次数限制(实测提示「今日剩余尝试次数 4 次」),每 30 分钟撞一次
|
||||
# 会在当天把账号锁掉。改成等一个人来改密码:设置页保存新凭据会把调度钟拨回现在。
|
||||
CREDENTIAL_ERROR_CODES = {1002, 10006, 4026}
|
||||
CREDENTIAL_RETRY_DISABLED_MS = 30 * 24 * 60 * 60_000
|
||||
|
||||
|
||||
def retry_delay_ms(exc: BaseException) -> int:
|
||||
"""这次失败之后隔多久再试。凭据错误几乎等于「等人来修」,不能用短退避。"""
|
||||
if isinstance(exc, SuperDirError) and exc.code in CREDENTIAL_ERROR_CODES:
|
||||
return CREDENTIAL_RETRY_DISABLED_MS
|
||||
return SYNC_FAILURE_RETRY_MS
|
||||
|
||||
# 中国没有夏令时,固定 +8 比 zoneinfo 稳 —— 镜像里不一定装了 tzdata。
|
||||
CN_TZ = timezone(timedelta(hours=8))
|
||||
|
||||
LOGIN_PATH = "/member/xt_user/password/login"
|
||||
# 登录类接口必须带 version 头,否则统一返回 4026「有新版本可用」。
|
||||
LOGIN_VERSION = "1.9.78.0"
|
||||
|
||||
# token 失效/被顶掉时云端返回的错误码。撞上它们就用设置里的账号密码重新登录一次。
|
||||
# 4017/5006 是文档里写明「登录已过期」的两个;其余几个是同一个登录态/套餐分组里的
|
||||
# —— 多试一次续期不花钱,续完还不行就把新错误原样抛出去。
|
||||
_AUTH_ERROR_CODES = {4011, 4012, 4017, 5006, 5007, 4023}
|
||||
|
||||
# 接口错误码 -> 人话。别让界面上只出现一个 4011。
|
||||
_CODE_HINTS = {
|
||||
4011: "token 没配置或为空",
|
||||
4017: "token 已失效(登录过期或在别处登录过),会自动用账号密码续期",
|
||||
5006: "token 已失效,会自动用账号密码续期",
|
||||
1002: "密码不对;连续失败可能锁号,先去超级编导客户端确认密码",
|
||||
10006: "账号不存在或还没有设置密码",
|
||||
4026: "登录接口要求客户端版本号,可能是服务端升级了",
|
||||
}
|
||||
|
||||
|
||||
class SuperDirError(Exception):
|
||||
"""超级编导接口报错,或者根本没配置 token。"""
|
||||
|
||||
def __init__(self, code: Any, message: str):
|
||||
self.code = code
|
||||
self.message = message
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
def _error(payload: Dict[str, Any]) -> SuperDirError:
|
||||
raw_code = payload.get("code")
|
||||
try:
|
||||
code: Any = int(raw_code)
|
||||
except (TypeError, ValueError):
|
||||
code = raw_code
|
||||
message = str(payload.get("message") or "接口没有说明原因")
|
||||
hint = _CODE_HINTS.get(code)
|
||||
if hint:
|
||||
message = f"{message}({hint})"
|
||||
return SuperDirError(code, f"超级编导接口报错 [{code}]:{message}")
|
||||
|
||||
|
||||
def _as_int(value: Any) -> int:
|
||||
try:
|
||||
return int(value or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def parse_day(value: Any) -> date:
|
||||
"""``YYYY-MM-DD`` -> date。格式不对抛 ValueError(路由层转成 400)。"""
|
||||
try:
|
||||
return date.fromisoformat(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("日期格式应为 YYYY-MM-DD")
|
||||
|
||||
|
||||
def _day_start(day: date) -> int:
|
||||
return int(datetime.combine(day, day_time.min, tzinfo=CN_TZ).timestamp())
|
||||
|
||||
|
||||
def _day_end(day: date) -> int:
|
||||
"""当天 23:59:59。``time.max`` 是 23:59:59.999999,取整后正好落在这一秒。"""
|
||||
return int(datetime.combine(day, day_time.max, tzinfo=CN_TZ).timestamp())
|
||||
|
||||
|
||||
async def get_token(session: AsyncSession, platform: str = adapters.PLATFORM_DY) -> str:
|
||||
return str(
|
||||
await app_settings.get_value(session, "superdir_token", platform, "") or ""
|
||||
).strip()
|
||||
|
||||
|
||||
# 续期要加锁:超级编导是**单登录态**,新登录会把旧 token 顶掉。并发续期只会互相作废。
|
||||
_renew_lock = asyncio.Lock()
|
||||
|
||||
|
||||
async def _login(username: str, password: str) -> Dict[str, Any]:
|
||||
"""账号密码登录,返回 ``data``(里面有 token / team_id)。"""
|
||||
async with _client_session() as client:
|
||||
return await _request(
|
||||
LOGIN_PATH,
|
||||
{"username": username, "password": password},
|
||||
"",
|
||||
client,
|
||||
method="POST",
|
||||
extra_headers={"version": LOGIN_VERSION},
|
||||
)
|
||||
|
||||
|
||||
async def renew_token(
|
||||
session: AsyncSession,
|
||||
platform: str = adapters.PLATFORM_DY,
|
||||
*,
|
||||
stale_token: str = "",
|
||||
) -> str:
|
||||
"""用设置里的账号密码换一个新 token,写回设置并返回它。
|
||||
|
||||
拿到锁之后先看一眼是不是别人已经续过了 —— 并发的两个请求同时撞上 4017 时,
|
||||
第二个不该再登录一次(那会把第一个刚拿到的 token 又顶掉)。
|
||||
"""
|
||||
async with _renew_lock:
|
||||
current = await get_token(session, platform)
|
||||
if current and current != stale_token:
|
||||
return current
|
||||
|
||||
username = str(
|
||||
await app_settings.get_value(session, "superdir_username", platform, "") or ""
|
||||
).strip()
|
||||
password = str(
|
||||
await app_settings.get_value(session, "superdir_password", platform, "") or ""
|
||||
)
|
||||
if not username or not password:
|
||||
raise SuperDirError(
|
||||
"",
|
||||
"超级编导 Token 已失效,而且没有配置账号密码 —— 到「设置」页填"
|
||||
"「超级编导账号」和「超级编导密码」,或重新粘贴 Token",
|
||||
)
|
||||
|
||||
data = await _login(username, password)
|
||||
token = str(data.get("token") or "")
|
||||
if not token:
|
||||
raise SuperDirError("", "超级编导登录成功但没有返回 token")
|
||||
await set_setting(session, platform_key(platform, "superdir_token"), token)
|
||||
print("[monitor.superdir] token 已自动续期", flush=True)
|
||||
return token
|
||||
|
||||
|
||||
async def _run_with_token(
|
||||
session: AsyncSession,
|
||||
platform: str,
|
||||
operation: Callable[[str], Awaitable[Any]],
|
||||
) -> Any:
|
||||
"""用当前 token 跑一次;撞上登录失效就续期后**整段**重试一次。
|
||||
|
||||
重试放在整段而不是单个请求里:一次预览会并发发十几个请求,token 失效时它们会
|
||||
同时报 4017 —— 在请求层重试就变成十几个并发登录,而超级编导新登录会把旧 token
|
||||
顶掉,互相打架。整段重试只有一个续期点。
|
||||
"""
|
||||
token = await get_token(session, platform)
|
||||
try:
|
||||
return await operation(token)
|
||||
except SuperDirError as exc:
|
||||
if exc.code not in _AUTH_ERROR_CODES:
|
||||
raise
|
||||
token = await renew_token(session, platform, stale_token=token)
|
||||
return await operation(token)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _client_session() -> AsyncIterator[httpx.AsyncClient]:
|
||||
"""一次查询共用一条连接池。
|
||||
|
||||
**这不是可选的优化,是能不能用的区别。** 容器里解析 ``api.superdir.cn`` 实测要
|
||||
5 秒(宿主机的 DNS 根本解析不了这个域名,容器走的是转发),而每个请求都新建
|
||||
client 的话,每个请求都要重新解析 + 重新握手:一次查询几十个请求就是几分钟,
|
||||
界面上一直转「查询中」。复用一个 client 之后走 keep-alive,实测 0.1 秒级。
|
||||
|
||||
连接数按并发上限给:翻页 4 路 + 取作品 6 路,再留两个余量。
|
||||
"""
|
||||
limits = httpx.Limits(
|
||||
max_connections=ACTIVITY_CONCURRENCY + VIDEO_CONCURRENCY + 2,
|
||||
max_keepalive_connections=ACTIVITY_CONCURRENCY + VIDEO_CONCURRENCY,
|
||||
)
|
||||
async with httpx.AsyncClient(timeout=TIMEOUT_SECONDS, limits=limits) as client:
|
||||
yield client
|
||||
|
||||
|
||||
async def _request(
|
||||
path: str,
|
||||
params: Dict[str, Any],
|
||||
token: str,
|
||||
client: httpx.AsyncClient,
|
||||
*,
|
||||
method: str = "GET",
|
||||
extra_headers: Optional[Dict[str, str]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""发一个请求,返回 ``data``。业务错误码抛出 SuperDirError。
|
||||
|
||||
``method="POST"`` 时 ``params`` 作为 JSON body 发出去(登录接口用)。
|
||||
"""
|
||||
headers = {
|
||||
"Accept": "application/json",
|
||||
"token": token,
|
||||
"bizid": BIZ_ID,
|
||||
"os": OS,
|
||||
"business-code": BUSINESS_CODE,
|
||||
"req-id": uuid.uuid4().hex[:8] + str(int(datetime.now().timestamp())),
|
||||
"User-Agent": USER_AGENT,
|
||||
}
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
|
||||
last_error: Optional[Exception] = None
|
||||
for attempt in range(REQUEST_RETRIES + 1):
|
||||
try:
|
||||
if method == "POST":
|
||||
response = await client.post(
|
||||
BASE_URL + path, json=params, headers=headers
|
||||
)
|
||||
else:
|
||||
response = await client.get(
|
||||
BASE_URL + path, params=params, headers=headers
|
||||
)
|
||||
except httpx.TransportError as exc:
|
||||
last_error = exc
|
||||
if attempt >= REQUEST_RETRIES:
|
||||
break
|
||||
await asyncio.sleep(1.0 * (attempt + 1))
|
||||
continue
|
||||
|
||||
# 5xx 重试;4xx 是请求本身的问题,重试解决不了。
|
||||
if response.status_code >= 500 and attempt < REQUEST_RETRIES:
|
||||
last_error = SuperDirError(
|
||||
response.status_code, f"超级编导服务端错误(HTTP {response.status_code})"
|
||||
)
|
||||
await asyncio.sleep(1.0 * (attempt + 1))
|
||||
continue
|
||||
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
raise SuperDirError(
|
||||
response.status_code,
|
||||
f"超级编导返回了非 JSON 内容(HTTP {response.status_code})",
|
||||
)
|
||||
|
||||
code = payload.get("code")
|
||||
if code in (0, "0", None):
|
||||
return payload.get("data") or {}
|
||||
raise _error(payload)
|
||||
|
||||
raise SuperDirError("", f"连不上超级编导:{last_error}")
|
||||
|
||||
|
||||
async def _paginate(
|
||||
path: str,
|
||||
params: Dict[str, Any],
|
||||
token: str,
|
||||
client: httpx.AsyncClient,
|
||||
*,
|
||||
page_size: int,
|
||||
max_pages: int,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""把 ``page/page_size`` 翻完。
|
||||
|
||||
同时用两种方式判断到底了:``items`` 不满一页,或者累计条数够了 ``total``。
|
||||
只信其中一种的话,接口偶尔少返几条就会多翻一页(无害),或者提前停(会漏数据)。
|
||||
"""
|
||||
items: List[Dict[str, Any]] = []
|
||||
for page in range(1, max_pages + 1):
|
||||
data = await _request(
|
||||
path, {**params, "page": page, "page_size": page_size}, token, client
|
||||
)
|
||||
page_items = data.get("items") or []
|
||||
items.extend(page_items)
|
||||
total = data.get("total")
|
||||
if not page_items or len(page_items) < page_size:
|
||||
break
|
||||
if isinstance(total, int) and page * page_size >= total:
|
||||
break
|
||||
return items
|
||||
|
||||
|
||||
async def _fetch_activities(
|
||||
token: str, client: httpx.AsyncClient
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""拉全部分发活动,**先问第一页拿到 total,剩下的页并发翻**。
|
||||
|
||||
这个接口不支持日期过滤,每次查询都得把整个历史翻一遍(实测 277 个活动 = 3 页),
|
||||
而它恰恰是最慢的:每页约 4 秒,串行就是 12 秒起步。所以这里不用通用的
|
||||
``_paginate``,而是自己控制并发。
|
||||
|
||||
任何一页失败都让整次查询失败,**不返回半份活动列表** —— 少一页就是少一批活动和
|
||||
作品,看上去却像「这段时间就这些」,比报错难查得多。
|
||||
"""
|
||||
path = "/member/douyin/share_activity/page"
|
||||
params = {"page_size": ACTIVITY_PAGE_SIZE}
|
||||
first = await _request(path, {**params, "page": 1}, token, client)
|
||||
items = list(first.get("items") or [])
|
||||
total = first.get("total")
|
||||
|
||||
if not items or len(items) < ACTIVITY_PAGE_SIZE:
|
||||
return items
|
||||
if not isinstance(total, int):
|
||||
# 接口没给 total:退回逐页翻(实测一直给,只是不做这个假设)。
|
||||
page = 2
|
||||
while page <= MAX_ACTIVITY_PAGES:
|
||||
data = await _request(path, {**params, "page": page}, token, client)
|
||||
page_items = data.get("items") or []
|
||||
items.extend(page_items)
|
||||
if len(page_items) < ACTIVITY_PAGE_SIZE:
|
||||
break
|
||||
page += 1
|
||||
return items
|
||||
|
||||
pages = min(
|
||||
(total + ACTIVITY_PAGE_SIZE - 1) // ACTIVITY_PAGE_SIZE, MAX_ACTIVITY_PAGES
|
||||
)
|
||||
if pages <= 1:
|
||||
return items
|
||||
|
||||
semaphore = asyncio.Semaphore(ACTIVITY_CONCURRENCY)
|
||||
|
||||
async def fetch(page: int) -> List[Dict[str, Any]]:
|
||||
async with semaphore:
|
||||
data = await _request(path, {**params, "page": page}, token, client)
|
||||
return data.get("items") or []
|
||||
|
||||
results = await asyncio.gather(*(fetch(page) for page in range(2, pages + 1)))
|
||||
for page_items in results:
|
||||
items.extend(page_items)
|
||||
return items
|
||||
|
||||
|
||||
async def _fetch_videos(
|
||||
token: str, activity_id: Any, client: httpx.AsyncClient
|
||||
) -> List[Dict[str, Any]]:
|
||||
# video_status=-1(全部)**必须带**,不传时默认 0,接口会返回空列表。
|
||||
return await _paginate(
|
||||
"/member/douyin/data_center/page",
|
||||
{"video_status": -1, "activity_id": int(activity_id)},
|
||||
token,
|
||||
client,
|
||||
page_size=VIDEO_PAGE_SIZE,
|
||||
max_pages=MAX_VIDEO_PAGES,
|
||||
)
|
||||
|
||||
|
||||
def _is_public(video: Dict[str, Any]) -> bool:
|
||||
"""只收公开作品。
|
||||
|
||||
``video_status``:2 私密 / 4 审核中 / 5 公开。私密和审核中的链接点不开,拉进监控
|
||||
每轮都会失败一次 —— 那不像「有数据」,更像任务坏了。没给这个字段的就当公开,
|
||||
宁可多收也不要凭空丢掉(字段是老版本接口可能没有)。
|
||||
"""
|
||||
status = video.get("video_status")
|
||||
return status in (None, "", 5, "5")
|
||||
|
||||
|
||||
def _row(activity: Dict[str, Any], video: Dict[str, Any], aweme_id: str) -> Dict[str, Any]:
|
||||
return {
|
||||
"activity_id": _as_int(activity.get("id")),
|
||||
"activity_title": str(activity.get("title") or ""),
|
||||
"activity_created_at": _as_int(activity.get("created_at")),
|
||||
"aweme_id": aweme_id,
|
||||
"nickname": str(video.get("nickname") or ""),
|
||||
"title": str(video.get("title") or ""),
|
||||
"share_url": str(video.get("share_url") or "").strip(),
|
||||
"published_at": _as_int(video.get("published_at")),
|
||||
"play_count": _as_int(video.get("play_count")),
|
||||
"digg_count": _as_int(video.get("digg_count")),
|
||||
"comment_count": _as_int(video.get("comment_count")),
|
||||
"share_count": _as_int(video.get("share_count")),
|
||||
}
|
||||
|
||||
|
||||
async def preview(
|
||||
session: AsyncSession,
|
||||
start: str,
|
||||
end: str,
|
||||
platform: str = adapters.PLATFORM_DY,
|
||||
) -> Dict[str, Any]:
|
||||
"""把区间内创建的分发活动下的作品链接列出来,**不写库**。
|
||||
|
||||
单个活动取作品失败只记进 ``failed_activities``,其余照常返回 —— 一个活动接口抖一下
|
||||
就把整屏结果打掉,用户只能重查一遍,而这并不能让那个活动变好。
|
||||
"""
|
||||
start_day = parse_day(start)
|
||||
end_day = parse_day(end)
|
||||
if end_day < start_day:
|
||||
raise ValueError("结束日期不能早于开始日期")
|
||||
if (end_day - start_day).days + 1 > MAX_RANGE_DAYS:
|
||||
raise ValueError(f"一次最多查 {MAX_RANGE_DAYS} 天,请缩小时间范围")
|
||||
|
||||
token = await get_token(session, platform)
|
||||
if not token:
|
||||
# 没配 token 也不算死路:账号密码配了就直接登录换一个。
|
||||
await renew_token(session, platform)
|
||||
|
||||
start_ts, end_ts = _day_start(start_day), _day_end(end_day)
|
||||
|
||||
# 整次查询共用一条连接池 —— 容器里每次新建连接都要重新做 5 秒的 DNS 解析,
|
||||
# 逐请求新建 client 会让一次查询从几秒变成几分钟(见 _client_session)。
|
||||
async with _client_session() as client:
|
||||
|
||||
async def run(token: str) -> Any:
|
||||
activities = [
|
||||
activity
|
||||
for activity in await _fetch_activities(token, client)
|
||||
if start_ts <= _as_int(activity.get("created_at")) <= end_ts
|
||||
]
|
||||
activities.sort(
|
||||
key=lambda activity: _as_int(activity.get("created_at"))
|
||||
)
|
||||
|
||||
usable = [
|
||||
activity
|
||||
for activity in activities
|
||||
if activity.get("id") not in (None, "")
|
||||
]
|
||||
semaphore = asyncio.Semaphore(VIDEO_CONCURRENCY)
|
||||
|
||||
async def fetch(activity: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
async with semaphore:
|
||||
return await _fetch_videos(token, activity.get("id"), client)
|
||||
|
||||
# 活动之间的作品集互不依赖,并发取;单个失败只记在那一个活动上。
|
||||
results = await asyncio.gather(
|
||||
*(fetch(activity) for activity in usable), return_exceptions=True
|
||||
)
|
||||
return activities, usable, results
|
||||
|
||||
# token 过期时在这里自动续期并重跑整段;`token` 是参数,不是外层的变量。
|
||||
activities, usable, results = await _run_with_token(session, platform, run)
|
||||
|
||||
rows: List[Dict[str, Any]] = []
|
||||
seen: set = set()
|
||||
skipped = 0
|
||||
failed: List[Dict[str, Any]] = []
|
||||
|
||||
for activity, videos in zip(usable, results):
|
||||
if isinstance(videos, BaseException):
|
||||
failed.append(
|
||||
{
|
||||
"activity_id": _as_int(activity.get("id")),
|
||||
"title": str(activity.get("title") or ""),
|
||||
"error": str(videos),
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
for video in videos:
|
||||
share_url = str(video.get("share_url") or "").strip()
|
||||
aweme_id = video_link.aweme_id_from_url(share_url)
|
||||
if not aweme_id:
|
||||
# 还没发布的作品没有 share_url;链接形状变了也会走到这里。
|
||||
skipped += 1
|
||||
continue
|
||||
if not _is_public(video):
|
||||
skipped += 1
|
||||
continue
|
||||
# 同一条作品可能挂在两个活动下(分发活动被复制过),只留一条。
|
||||
if aweme_id in seen:
|
||||
continue
|
||||
seen.add(aweme_id)
|
||||
rows.append(_row(activity, video, aweme_id))
|
||||
|
||||
rows.sort(key=lambda row: row["published_at"] or row["activity_created_at"], reverse=True)
|
||||
total = len(rows)
|
||||
truncated = total > MAX_TARGETS
|
||||
rows = rows[:MAX_TARGETS]
|
||||
|
||||
return {
|
||||
"start": start_day.isoformat(),
|
||||
"end": end_day.isoformat(),
|
||||
"activities": len(activities),
|
||||
# 匹配到的活动原样带回去。**0 条作品时它就是唯一能解释为什么的东西**:
|
||||
# 活动建了但还没人发布(尤其是排期在未来的活动),界面不能只显示一个「0」。
|
||||
# 注意活动名里的日期("10.23")是活动名,不是创建时间 —— 这两者经常被当成一回事。
|
||||
"matched_activities": [
|
||||
{
|
||||
"id": _as_int(activity.get("id")),
|
||||
"title": str(activity.get("title") or ""),
|
||||
"created_at": _as_int(activity.get("created_at")),
|
||||
"total_count": _as_int(activity.get("total_count")),
|
||||
"published_count": _as_int(activity.get("published_count")),
|
||||
}
|
||||
for activity in activities
|
||||
],
|
||||
"videos": total,
|
||||
"creators": len({row["nickname"] for row in rows if row["nickname"]}),
|
||||
"skipped": skipped,
|
||||
"truncated": truncated,
|
||||
"failed_activities": failed,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
def _aweme_ids(links: Sequence[str]) -> List[str]:
|
||||
"""把链接/分享文案换成裸作品 id,去重并保持顺序。
|
||||
|
||||
目标是**裸作品 id**,不是 ``share_url``:超级编导给的链接是双斜杠形态,
|
||||
``prepare_target`` 认不出来,会原样存成 ``external_id`` —— 那样每一轮都会拿一整条
|
||||
链接去请求作品详情,永远拿不到东西。id 是在这里抠出来的,形状已经确认过。
|
||||
"""
|
||||
ids: List[str] = []
|
||||
seen: set = set()
|
||||
for raw in links:
|
||||
value = str(raw or "").strip()
|
||||
if not value:
|
||||
continue
|
||||
aweme_id = video_link.aweme_id_from_url(value)
|
||||
if not aweme_id or aweme_id in seen:
|
||||
continue
|
||||
seen.add(aweme_id)
|
||||
ids.append(aweme_id)
|
||||
return ids
|
||||
|
||||
|
||||
async def _fetch_published(
|
||||
token: str, client: httpx.AsyncClient, start_ts: int, end_ts: int
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""按**发布时间**取作品,不分活动。
|
||||
|
||||
``start_time/end_time`` 实测是按发布时间过滤的(Unix 秒),这正是自动追加要的:
|
||||
一条活动可能早就建好,作品却是今天才发 —— 按活动创建时间筛会整批漏掉。
|
||||
"""
|
||||
return await _paginate(
|
||||
"/member/douyin/data_center/page",
|
||||
{
|
||||
"video_status": -1,
|
||||
"start_time": int(start_ts),
|
||||
"end_time": int(end_ts),
|
||||
},
|
||||
token,
|
||||
client,
|
||||
page_size=VIDEO_PAGE_SIZE,
|
||||
max_pages=max(1, (MAX_SYNC_VIDEOS + VIDEO_PAGE_SIZE - 1) // VIDEO_PAGE_SIZE + 1),
|
||||
)
|
||||
|
||||
|
||||
async def sync_task(session: AsyncSession, task: MonitorTask) -> Dict[str, Any]:
|
||||
"""查一次**今天发布的**作品(加上停摆期间漏掉的),追加到 ``task``。
|
||||
|
||||
调用方负责提交会话。字段更新也在这里做:成功才把 ``last_at`` 推到现在,失败时
|
||||
保持原值 —— 接口挂了三个小时,恢复后那三个小时的作品仍在窗口里,不会静默漏掉。
|
||||
|
||||
返回 ``{"fetched": 可用的条数, "added": 真正新增的条数, "total": 任务现有目标数}``。
|
||||
"""
|
||||
if task.platform != adapters.PLATFORM_DY:
|
||||
raise ValueError("自动追加只支持抖音任务")
|
||||
if task.mode != MODE_NOTE:
|
||||
raise ValueError("自动追加只能用在作品模式的监控任务上")
|
||||
|
||||
token = await get_token(session, task.platform)
|
||||
if not token:
|
||||
# 没有 token 但配了账号密码:直接续一个,不要求用户先粘 token。
|
||||
await renew_token(session, task.platform)
|
||||
|
||||
now_ms = get_current_timestamp()
|
||||
interval_ms = max(1, int(task.superdir_auto_interval_minutes or 120)) * 60_000
|
||||
|
||||
# 窗口起点取**今天 00:00(东八区)**,不是「任务创建时间」,也不是「上一个间隔」:
|
||||
# 活动可以提前几天建好(今天把后面几天的活动都建了),视频却是之后才陆续发布 ——
|
||||
# 按活动/任务创建时间筛,这些晚发的作品整批都看不到。重复的部分靠 append 去重。
|
||||
#
|
||||
# 唯一的例外是「停摆过」:上次成功检查在前天或更早时,从那时往前多算一小时,
|
||||
# 把空档补上;否则只查今天,停机那几天的新作品就永远漏了。
|
||||
today_start_ms = int(
|
||||
datetime.combine(
|
||||
datetime.now(CN_TZ).date(), day_time.min, tzinfo=CN_TZ
|
||||
).timestamp()
|
||||
* 1000
|
||||
)
|
||||
since_ms = today_start_ms
|
||||
if task.superdir_auto_last_at:
|
||||
since_ms = min(
|
||||
today_start_ms,
|
||||
task.superdir_auto_last_at - SYNC_OVERLAP_SECONDS * 1000,
|
||||
)
|
||||
|
||||
async def run(token: str) -> List[Dict[str, Any]]:
|
||||
async with _client_session() as client:
|
||||
return await _fetch_published(
|
||||
token, client, since_ms // 1000, now_ms // 1000
|
||||
)
|
||||
|
||||
videos = await _run_with_token(session, task.platform, run)
|
||||
|
||||
links: List[str] = []
|
||||
seen: set = set()
|
||||
for video in videos:
|
||||
if not _is_public(video):
|
||||
continue
|
||||
share_url = str(video.get("share_url") or "").strip()
|
||||
aweme_id = video_link.aweme_id_from_url(share_url)
|
||||
if not aweme_id or aweme_id in seen:
|
||||
continue
|
||||
seen.add(aweme_id)
|
||||
links.append(share_url)
|
||||
if len(links) >= MAX_SYNC_VIDEOS:
|
||||
break
|
||||
|
||||
if links:
|
||||
_, added, total = await append_task(
|
||||
session, task.id, links, platform=task.platform
|
||||
)
|
||||
else:
|
||||
added = 0
|
||||
total = int(
|
||||
await session.scalar(
|
||||
select(func.count())
|
||||
.select_from(MonitorTarget)
|
||||
.where(MonitorTarget.task_id == task.id)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
|
||||
task.superdir_auto_last_at = now_ms
|
||||
task.superdir_auto_last_added = added
|
||||
task.superdir_auto_last_error = ""
|
||||
task.superdir_auto_next_at = now_ms + interval_ms
|
||||
return {"fetched": len(links), "added": added, "total": total}
|
||||
|
||||
|
||||
async def create_task(
|
||||
session: AsyncSession,
|
||||
links: Sequence[str],
|
||||
name: str = "",
|
||||
*,
|
||||
platform: str = adapters.PLATFORM_DY,
|
||||
enable_comments: bool = False,
|
||||
) -> Tuple[Any, int]:
|
||||
"""按链接建一个作品模式的监控任务。"""
|
||||
targets = _aweme_ids(links)
|
||||
|
||||
if not targets:
|
||||
raise ValueError("没有可用的视频链接")
|
||||
if len(targets) > MAX_TARGETS:
|
||||
raise ValueError(f"一次最多建 {MAX_TARGETS} 条,请缩小时间范围")
|
||||
|
||||
task = await service.create_task(
|
||||
session,
|
||||
{
|
||||
"name": (name or "").strip() or f"超级编导导入 · {len(targets)} 条作品",
|
||||
"platform": platform,
|
||||
"mode": MODE_NOTE,
|
||||
"targets": targets,
|
||||
# 批量导入动辄上百条,评论默认不抓 —— 每篇再拉一轮评论,请求量会翻倍,
|
||||
# 而这批作品本来就是看播放/点赞的。要的话在任务编辑里打开。
|
||||
"enable_comments": enable_comments,
|
||||
"enabled": True,
|
||||
},
|
||||
)
|
||||
return task, len(targets)
|
||||
|
||||
|
||||
async def append_task(
|
||||
session: AsyncSession,
|
||||
task_id: int,
|
||||
links: Sequence[str],
|
||||
*,
|
||||
platform: str = adapters.PLATFORM_DY,
|
||||
) -> Tuple[Any, int, int]:
|
||||
"""把链接追加到一个已有的作品任务里,返回 ``(task, 新增条数, 总条数)``。
|
||||
|
||||
这是「一个任务一直更新」的关键:超级编导每天都会出新作品,如果每次都建一个新任务,
|
||||
监控列表很快就会变成一堆互不相关的任务,每个都只看一小批。追加到同一个任务里,
|
||||
作品、指标和变化都在一处。
|
||||
|
||||
已存在的目标**原样保留**(``raw_value`` 可能是当初别处粘进来的链接),只往里加新的。
|
||||
评论开关、采集间隔这些任务设置也不动 —— 补链接不该顺手改掉别的配置。
|
||||
"""
|
||||
task = await session.get(MonitorTask, task_id)
|
||||
if task is None:
|
||||
raise ValueError(f"任务 {task_id} 不存在")
|
||||
if task.platform != platform:
|
||||
raise ValueError("这个任务不是抖音的,不能导入超级编导的作品")
|
||||
if task.mode != MODE_NOTE:
|
||||
raise ValueError("只能追加到「作品」模式的监控任务(博主模式下目标是主页,不是作品)")
|
||||
|
||||
incoming = _aweme_ids(links)
|
||||
if not incoming:
|
||||
raise ValueError("没有可用的视频链接")
|
||||
|
||||
# 显式查一次,不碰 ``task.targets`` 关系:同一个会话里刚建完的任务再 get 回来时,
|
||||
# 关系可能是「未加载」状态,在 async 下访问它就是个坑。
|
||||
existing_targets = list(
|
||||
await session.scalars(
|
||||
select(MonitorTarget).where(MonitorTarget.task_id == task_id)
|
||||
)
|
||||
)
|
||||
existing = [target.raw_value or target.external_id for target in existing_targets]
|
||||
existing_ids = {target.external_id for target in existing_targets}
|
||||
added = [aweme_id for aweme_id in incoming if aweme_id not in existing_ids]
|
||||
|
||||
total = len(existing_ids) + len(added)
|
||||
if total > MAX_TARGETS:
|
||||
raise ValueError(
|
||||
f"追加后会有 {total} 条,超过单个任务上限 {MAX_TARGETS};请分成两个任务"
|
||||
)
|
||||
if not added:
|
||||
return task, 0, len(existing_ids)
|
||||
|
||||
await service.update_task(session, task_id, {"targets": existing + added})
|
||||
return task, len(added), total
|
||||
@@ -0,0 +1,156 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright (c) 2025 [email protected]
|
||||
#
|
||||
# This file is part of MediaCrawler project.
|
||||
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/api/monitor/tagrules.py
|
||||
# GitHub: https://github.com/NanmiCoder
|
||||
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
|
||||
#
|
||||
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
|
||||
# 1. 不得用于任何商业用途。
|
||||
# 2. 使用时应遵守对应平台的使用条款和robots.txt规则。
|
||||
# 3. 不得进行大规模爬取或对平台造成运营干扰。
|
||||
# 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。
|
||||
# 5. 不得用于任何非法或不当的用途。
|
||||
#
|
||||
# 详细许可条款请参阅项目根目录下的LICENSE文件。
|
||||
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
|
||||
|
||||
"""自动打标签的规则 —— 「标题里出现这几个词,就贴上这条标签」。
|
||||
|
||||
**单独一个模块**,不是因为它大,是因为调用方分属两头:`ingest` 在作品第一次入库时要跑,
|
||||
路由在有人改规则时要跑。而 `ingest` **不能** import `service`(service → runner → ingest
|
||||
会成环),所以共用部分只能落在没有依赖的这一层。
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from .models import MonitorNote, MonitorNoteTag, MonitorTag, MonitorTask
|
||||
|
||||
|
||||
def split_keywords(raw: str) -> List[str]:
|
||||
"""把「逗号分隔的关键词」切成干净的列表。中英文逗号都收,去空、去重、保序。"""
|
||||
seen: List[str] = []
|
||||
for part in re.split(r"[,,]", raw or ""):
|
||||
word = part.strip()
|
||||
if word and word not in seen:
|
||||
seen.append(word)
|
||||
return seen
|
||||
|
||||
|
||||
def tags_matching(title: str, tags: Sequence[MonitorTag]) -> List[int]:
|
||||
"""一段文本命中了哪些标签的规则。**纯函数**,所以能单独测。
|
||||
|
||||
传进来的 ``title`` 实际是**标题 + 话题列表**(见 ``ingest`` 的 ``tag_text``)——
|
||||
抖音的 ``desc`` 会在话题列表中途截断,后半段只能在 ``text_extra`` 里拿到,只看标题
|
||||
会漏贴。
|
||||
|
||||
匹配的是**子串**(不分大小写),不是只匹配 ``#话题#`` —— 话题本来就长在标题里,而像
|
||||
``szgtdzb`` 这种代号未必包在井号里。一段文本可以命中**多条**规则,命中几条就贴几个标签。
|
||||
|
||||
代价是关键词定得太宽会误伤(把「苏州」设成关键词,几乎每条都会被贴上),设置页里
|
||||
写了这句提醒。
|
||||
"""
|
||||
haystack = (title or "").casefold()
|
||||
if not haystack:
|
||||
return []
|
||||
return [
|
||||
tag.id
|
||||
for tag in tags
|
||||
if any(word.casefold() in haystack for word in split_keywords(tag.keywords))
|
||||
]
|
||||
|
||||
|
||||
async def apply_tag_rules(
|
||||
session: AsyncSession,
|
||||
notes: Sequence[Tuple[str, str, str]],
|
||||
only_tag_id: Optional[int] = None,
|
||||
) -> int:
|
||||
"""按规则给这些作品贴标签,返回新贴了几条。
|
||||
|
||||
``notes`` 是 ``(platform, note_id, title)`` 三元组 —— 平台得跟着走,因为
|
||||
``monitor_note_tag`` 按 ``(platform, note_id)`` 存键,而标签词表本身**不**分平台。
|
||||
|
||||
``only_tag_id`` 只重跑一条规则。改某个标签的关键词时用这个:那一下只该重新识别这
|
||||
一个标签,不该顺手把**别的**规则也重跑一遍 —— 那会把用户手动摘掉的其他标签又贴回来。
|
||||
|
||||
**只贴不摘。**
|
||||
"""
|
||||
query = select(MonitorTag)
|
||||
if only_tag_id is not None:
|
||||
query = query.where(MonitorTag.id == only_tag_id)
|
||||
rules = [tag for tag in (await session.scalars(query)).all() if split_keywords(tag.keywords)]
|
||||
if not rules or not notes:
|
||||
return 0
|
||||
|
||||
note_ids = [note_id for _, note_id, _ in notes]
|
||||
already = set(
|
||||
(
|
||||
await session.execute(
|
||||
select(MonitorNoteTag.note_id, MonitorNoteTag.tag_id).where(
|
||||
MonitorNoteTag.note_id.in_(note_ids)
|
||||
)
|
||||
)
|
||||
).all()
|
||||
)
|
||||
|
||||
now = get_current_timestamp()
|
||||
added = 0
|
||||
for platform, note_id, title in notes:
|
||||
for tag_id in tags_matching(title, rules):
|
||||
if (note_id, tag_id) in already:
|
||||
continue
|
||||
already.add((note_id, tag_id))
|
||||
session.add(
|
||||
MonitorNoteTag(
|
||||
platform=platform, note_id=note_id, tag_id=tag_id, created_at=now
|
||||
)
|
||||
)
|
||||
added += 1
|
||||
return added
|
||||
|
||||
|
||||
async def apply_tag_rules_for_task(
|
||||
session: AsyncSession, task_id: int, platform: str, notes: Sequence[Tuple[str, str]]
|
||||
) -> int:
|
||||
"""作品**第一次入库**时调用:``notes`` 是 ``(note_id, title)``。"""
|
||||
return await apply_tag_rules(
|
||||
session, [(platform, note_id, title) for note_id, title in notes]
|
||||
)
|
||||
|
||||
|
||||
async def reapply_tag_rules(
|
||||
session: AsyncSession, only_tag_id: Optional[int] = None
|
||||
) -> int:
|
||||
"""拿**库里已有的全部作品**重跑一遍规则。
|
||||
|
||||
改规则时要跑这一次,否则新加的关键词对已经采到的作品永远不生效 —— 而「我刚配好
|
||||
关键词,结果一条都没贴上」正是这个功能最容易被当成坏掉了的样子。
|
||||
"""
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(
|
||||
MonitorTask.platform,
|
||||
MonitorNote.note_id,
|
||||
MonitorNote.title,
|
||||
MonitorNote.hashtags,
|
||||
).join(MonitorTask, MonitorTask.id == MonitorNote.task_id)
|
||||
)
|
||||
).all()
|
||||
# 匹配的是**标题 + 话题列表**:抖音的 desc 会被截断,后半段话题只在 hashtags 里。
|
||||
return await apply_tag_rules(
|
||||
session,
|
||||
[(r[0], r[1], f"{r[2] or ''} {r[3] or ''}".strip()) for r in rows],
|
||||
only_tag_id,
|
||||
)
|
||||
|
||||
|
||||
def keywords_by_tag(tags: Sequence[MonitorTag]) -> Dict[int, List[str]]:
|
||||
"""给界面/调试用:标签 id -> 关键词列表。"""
|
||||
return {tag.id: split_keywords(tag.keywords) for tag in tags if tag.keywords}
|
||||
@@ -0,0 +1,166 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""视频链接 → 博主主页链接。
|
||||
|
||||
运营手上经常只有一条作品的分享链接(甚至只是「复制打开抖音」那一整段文案),却要
|
||||
把发它的号加进监控 —— 监控任务认的是主页里的 ``sec_uid``,不认作品 id。
|
||||
|
||||
所以这里的全部工作就是三步,一步都不能省:
|
||||
|
||||
1. 从一段文本里**抠出链接**(分享文案里链接前后都是字,按行切根本切不开);
|
||||
2. **短链展开** —— ``v.douyin.com/xxx`` 只有一个跳转头,不展开就看不到作品 id;
|
||||
3. 用作品详情接口换出 ``author.sec_uid``(实测返回里有),再拼成主页地址。
|
||||
|
||||
**为什么不用分享页 HTML 解析**:``iesdouyin.com/share/video/{id}`` 里的
|
||||
``_ROUTER_DATA`` 是内部结构,改版就断,而且拿不到登录态下的完整字段。详情接口本来
|
||||
就是采集在用的那条路,登录态、UA、签名都已经配好。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from typing import Any, Dict, List
|
||||
|
||||
import httpx
|
||||
|
||||
from . import adapters, douyin_api, service
|
||||
|
||||
# 一次最多解析这么多条。限流不是怕算不过来 —— 是怕一不小心粘进来几百条,把详情接口
|
||||
# 打成一串风控信号。前端一次贴十几条是正常用量。
|
||||
MAX_LINKS = 20
|
||||
# 每两条之间歇一下。同一个登录态连续请求,节律太密比数量更容易被识别。
|
||||
REQUEST_GAP_SECONDS = 0.4
|
||||
# 网络层失败后隔多久重试那一次。
|
||||
_DETAIL_RETRY_SLEEP_SECONDS = 1.0
|
||||
|
||||
_URL_RE = re.compile(r"https?://[^\s,。;、))\"'<>]+")
|
||||
# 19 位作品 id,但放宽到 15–20:平台偶尔给别的位数,只按 19 位写会漏。
|
||||
_BARE_ID_RE = re.compile(r"^\d{15,20}$")
|
||||
# 斜杠**可能有两个**:超级编导导出的链接就是 ``https://www.douyin.com/video//769...``。
|
||||
# 只认一个斜杠的话,这些链接会被判成「认不出作品 id」,而它们在浏览器里点开是正常的。
|
||||
_AWEME_ID_RES = (
|
||||
re.compile(r"/(?:share/)?video/+(\d{15,20})"),
|
||||
re.compile(r"[?&]modal_id=(\d{15,20})"),
|
||||
)
|
||||
|
||||
|
||||
def extract_candidates(text: str) -> List[str]:
|
||||
"""从粘进来的文本里取出链接或裸 id,保持原顺序。
|
||||
|
||||
一行里出现多个链接时全部取出:分享文案经常把「网页版」和「App」两个链接一起带上。
|
||||
既不是链接也不是纯数字的行直接丢掉 —— 它们要么是中文说明,要么是用户误粘的东西,
|
||||
逐条报错只会把真正有用的几条埋掉。
|
||||
"""
|
||||
candidates: List[str] = []
|
||||
for line in (text or "").splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped:
|
||||
continue
|
||||
urls = _URL_RE.findall(stripped)
|
||||
if urls:
|
||||
candidates.extend(urls)
|
||||
continue
|
||||
if _BARE_ID_RE.match(stripped):
|
||||
candidates.append(stripped)
|
||||
return candidates
|
||||
|
||||
|
||||
def aweme_id_from_url(value: str) -> str:
|
||||
"""从(已经展开过的)地址里抠作品 id;认不出返回空串。"""
|
||||
for pattern in _AWEME_ID_RES:
|
||||
match = pattern.search(value)
|
||||
if match:
|
||||
return match.group(1)
|
||||
stripped = value.strip()
|
||||
if _BARE_ID_RE.match(stripped):
|
||||
return stripped
|
||||
return ""
|
||||
|
||||
|
||||
async def _detail(aweme_id: str) -> Dict[str, Any]:
|
||||
"""取一次作品详情,网络层抖动(DNS/连接/超时)重试一次。
|
||||
|
||||
实测容器刚起来时第一发会撞上 ``[Errno -3] Temporary failure in name resolution``,
|
||||
隔半秒就正常 —— 批量解析时这种一次性的失败只会让某一行莫名其妙地红掉,用户还得
|
||||
整段重贴。**「200 + 空 body」不重试**:那是风控信号,重试只会让它更确定。
|
||||
"""
|
||||
try:
|
||||
return await douyin_api.video_detail(aweme_id)
|
||||
except httpx.TransportError:
|
||||
await asyncio.sleep(_DETAIL_RETRY_SLEEP_SECONDS)
|
||||
return await douyin_api.video_detail(aweme_id)
|
||||
|
||||
|
||||
async def _aweme_id(value: str) -> str:
|
||||
"""短链先展开,再抠 id。"""
|
||||
expanded = value
|
||||
if value.startswith("http"):
|
||||
expanded = await service.expand_short_link(value, adapters.PLATFORM_DY)
|
||||
return aweme_id_from_url(expanded)
|
||||
|
||||
|
||||
def _blank(value: str) -> Dict[str, Any]:
|
||||
return {
|
||||
"input": value,
|
||||
"aweme_id": "",
|
||||
"ok": False,
|
||||
"nickname": "",
|
||||
"sec_uid": "",
|
||||
"profile_url": "",
|
||||
"error": "",
|
||||
}
|
||||
|
||||
|
||||
async def resolve(text: str) -> Dict[str, Any]:
|
||||
"""把一段文本里的视频链接逐条换成博主主页。
|
||||
|
||||
返回 ``{"results": [...], "truncated": bool}``。单条失败**不影响**其余几条 ——
|
||||
批量粘贴时挂一条就把整批丢掉,比不提供这个功能还难用。
|
||||
"""
|
||||
candidates = extract_candidates(text)
|
||||
truncated = len(candidates) > MAX_LINKS
|
||||
candidates = candidates[:MAX_LINKS]
|
||||
|
||||
results: List[Dict[str, Any]] = []
|
||||
seen: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
for index, value in enumerate(candidates):
|
||||
if index:
|
||||
await asyncio.sleep(REQUEST_GAP_SECONDS)
|
||||
item = _blank(value)
|
||||
results.append(item)
|
||||
|
||||
try:
|
||||
aweme_id = await _aweme_id(value)
|
||||
except Exception as exc: # 短链展开是网络操作,失败也要落到这一条上
|
||||
item["error"] = f"链接展开失败:{exc}"
|
||||
continue
|
||||
|
||||
if not aweme_id:
|
||||
item["error"] = "认不出作品 id(支持抖音视频链接、分享短链、15–20 位作品 id)"
|
||||
continue
|
||||
item["aweme_id"] = aweme_id
|
||||
|
||||
# 同一条作品粘了两遍:直接复用上一次的结果,不再打一次接口。
|
||||
if aweme_id in seen:
|
||||
item.update({k: v for k, v in seen[aweme_id].items() if k != "input"})
|
||||
continue
|
||||
|
||||
try:
|
||||
record = await _detail(aweme_id)
|
||||
except Exception as exc:
|
||||
item["error"] = str(exc) or "接口没有返回这条作品"
|
||||
continue
|
||||
|
||||
sec_uid = str(record.get("creator_id") or "")
|
||||
item.update(
|
||||
{
|
||||
"ok": bool(sec_uid),
|
||||
"nickname": str(record.get("nickname") or ""),
|
||||
"sec_uid": sec_uid,
|
||||
"profile_url": adapters.creator_url(adapters.PLATFORM_DY, sec_uid),
|
||||
}
|
||||
)
|
||||
if not sec_uid:
|
||||
item["error"] = "接口返回里没有 sec_uid,拿不到主页地址"
|
||||
seen[aweme_id] = item
|
||||
|
||||
return {"results": results, "truncated": truncated}
|
||||
@@ -0,0 +1,757 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>标签矩阵 · 综合采集平台</title>
|
||||
<!--
|
||||
独立的报表页,不走 Vite 构建:这样它不会被前端产物覆盖,也不用为它加一条路由。
|
||||
|
||||
数据来自 /api/monitor/matrix(同一套鉴权,靠同源 cookie)。
|
||||
转置在前端做 —— MySQL 5.7 没有 PIVOT,列数又随博主变化,SQL 里拼不出来。
|
||||
-->
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0a0e14;
|
||||
--bg-soft: #111823;
|
||||
--line: #1e2a3a;
|
||||
--text: #e6f1ff;
|
||||
--muted: #7b8ba3;
|
||||
--cyan: #22d3ee;
|
||||
--pink: #f472b6;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 13px/1.5 system-ui, -apple-system, "Segoe UI", "PingFang SC",
|
||||
"Microsoft YaHei", sans-serif;
|
||||
}
|
||||
header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
padding: 12px 16px;
|
||||
/* 刻意不用 backdrop-filter:这个表头是 sticky 的,滚动时模糊要每帧重算,
|
||||
在没有 GPU 加速的机器上很贵。纯色就够。 */
|
||||
background: #0b1118;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
h1 { font-size: 15px; font-weight: 600; margin: 0; }
|
||||
h1 span { color: var(--cyan); }
|
||||
.spacer { flex: 1; }
|
||||
label { color: var(--muted); font-size: 12px; }
|
||||
select, input, button, a.btn {
|
||||
background: var(--bg-soft);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 5px 9px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
}
|
||||
select { max-width: 200px; }
|
||||
input[type="number"] { width: 78px; cursor: text; }
|
||||
select:hover, input:hover, button:hover, a.btn:hover { border-color: var(--cyan); }
|
||||
input:focus { outline: none; border-color: var(--cyan); }
|
||||
#status { color: var(--muted); font-size: 12px; }
|
||||
#status.error { color: var(--pink); }
|
||||
|
||||
.wrap { overflow: auto; max-height: calc(100vh - 58px); }
|
||||
table {
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
background: #0d131c;
|
||||
border-bottom: 1px solid var(--line);
|
||||
border-right: 1px solid var(--line);
|
||||
padding: 8px 10px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
color: var(--muted);
|
||||
}
|
||||
/* 左上角那一格要同时钉住两个方向 */
|
||||
thead th:first-child {
|
||||
left: 0;
|
||||
z-index: 15;
|
||||
color: var(--cyan);
|
||||
}
|
||||
tbody th {
|
||||
position: sticky;
|
||||
left: 0;
|
||||
z-index: 5;
|
||||
background: #0d131c;
|
||||
border-right: 1px solid var(--line);
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 7px 10px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
}
|
||||
tbody td {
|
||||
position: relative;
|
||||
border-right: 1px solid var(--line);
|
||||
border-bottom: 1px solid var(--line);
|
||||
/* 底部留一条给左下角的作品条数,别让它压到标签上。 */
|
||||
padding: 4px 8px 15px;
|
||||
white-space: nowrap;
|
||||
vertical-align: top;
|
||||
min-width: 112px;
|
||||
}
|
||||
tbody tr:hover th, tbody tr:hover td { background: #131c28; }
|
||||
|
||||
/* 一格的主角:点赞 / 评论。标签是分类,数字才是「这条发得怎么样」。 */
|
||||
.cell-metrics {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 2px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.cell-metrics span { font-size: 12px; }
|
||||
.cell-metrics b {
|
||||
margin-right: 2px;
|
||||
color: var(--muted);
|
||||
font-weight: 400;
|
||||
font-size: 10px;
|
||||
}
|
||||
.cell-metrics .like { color: var(--pink); }
|
||||
.cell-metrics .comment { color: var(--cyan); }
|
||||
|
||||
/* 左下角的作品条数:是参照信息,压暗、贴角,不参与主视觉。 */
|
||||
.cell-count {
|
||||
position: absolute;
|
||||
left: 5px;
|
||||
bottom: 1px;
|
||||
min-width: 14px;
|
||||
padding: 0 3px;
|
||||
border-radius: 3px;
|
||||
background: rgba(123, 139, 163, 0.14);
|
||||
color: var(--muted);
|
||||
font-size: 10px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.tag {
|
||||
display: inline-block;
|
||||
margin: 1px 3px 1px 0;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(34, 211, 238, 0.35);
|
||||
background: rgba(34, 211, 238, 0.1);
|
||||
color: var(--cyan);
|
||||
font-size: 11px;
|
||||
}
|
||||
.tag:nth-of-type(2n) {
|
||||
border-color: rgba(244, 114, 182, 0.35);
|
||||
background: rgba(244, 114, 182, 0.1);
|
||||
color: var(--pink);
|
||||
}
|
||||
.untagged { color: var(--muted); font-size: 11px; }
|
||||
.empty { color: #2a3646; }
|
||||
|
||||
/* 博主名字左边的参照信息:粉丝 / 总获赞 / 第一条视频日期。
|
||||
都压暗、贴边,不该和名字抢视线。 */
|
||||
.fans, .likes, .first {
|
||||
display: inline-block;
|
||||
min-width: 36px;
|
||||
margin-right: 6px;
|
||||
padding: 0 4px;
|
||||
border-radius: 4px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-align: right;
|
||||
}
|
||||
.fans { background: rgba(34, 211, 238, 0.08); }
|
||||
.likes { background: rgba(244, 114, 182, 0.08); }
|
||||
.first {
|
||||
min-width: 70px;
|
||||
background: rgba(123, 139, 163, 0.10);
|
||||
text-align: center;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
/* 条件格式命中的格子。用 inset 描边而不是 box-shadow 扩散:不改变布局,
|
||||
也不会触发整行重排。 */
|
||||
tbody td.hit {
|
||||
background: rgba(244, 114, 182, 0.16);
|
||||
box-shadow: inset 0 0 0 1px rgba(244, 114, 182, 0.55);
|
||||
}
|
||||
tbody tr:hover td.hit { background: rgba(244, 114, 182, 0.24); }
|
||||
.legend {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
padding: 8px 16px 14px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
.legend b { color: var(--text); font-weight: 500; }
|
||||
#login {
|
||||
display: none;
|
||||
margin: 40px auto;
|
||||
max-width: 360px;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-soft);
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
}
|
||||
#login a { color: var(--cyan); }
|
||||
|
||||
/* 悬停提示。跟着格子走。**可交互**:里面的标题是链接,要能点。
|
||||
防闪烁靠「离开格子后延迟 250ms 再收」+ 进入提示就取消(见 scheduleHide)。 */
|
||||
#tip {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 100;
|
||||
pointer-events: auto;
|
||||
max-width: 320px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: #0f1620;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
|
||||
font-size: 11px;
|
||||
line-height: 1.7;
|
||||
color: var(--text);
|
||||
}
|
||||
#tip .tip-head { color: var(--cyan); font-weight: 600; margin-bottom: 2px; }
|
||||
#tip .tip-metrics { font-variant-numeric: tabular-nums; }
|
||||
#tip .tip-metrics span { margin-right: 10px; white-space: nowrap; }
|
||||
#tip .tip-metrics b { color: var(--muted); font-weight: 400; }
|
||||
#tip .tip-tags { color: var(--muted); }
|
||||
/* 逐条明细:并集看不出「哪个标签属于哪条视频」,这里补上。 */
|
||||
#tip .tip-notes {
|
||||
margin-top: 5px;
|
||||
padding-top: 5px;
|
||||
border-top: 1px solid var(--line);
|
||||
white-space: normal;
|
||||
}
|
||||
#tip .tip-note { margin-bottom: 4px; line-height: 1.55; }
|
||||
#tip .tip-note-title { color: var(--text); }
|
||||
/* 标题就是作品链接,点一下在抖音打开。 */
|
||||
#tip a.tip-note-title {
|
||||
color: var(--cyan);
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
#tip a.tip-note-title:hover { text-decoration: underline; }
|
||||
/* 每条作品自己的指标。缩进到标题文字下面,一眼对得上是哪条。 */
|
||||
#tip .tip-note-meta {
|
||||
padding-left: 14px;
|
||||
color: var(--muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
#tip .tip-note-metrics { margin-right: 8px; }
|
||||
#tip .tip-note-tags { color: var(--pink); }
|
||||
#tip .tip-note-more { color: var(--muted); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>标签<span>矩阵</span></h1>
|
||||
<label>平台
|
||||
<select id="platform">
|
||||
<option value="dy">抖音</option>
|
||||
<option value="xhs">小红书</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>任务
|
||||
<select id="task">
|
||||
<option value="">全部任务</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>范围
|
||||
<select id="days">
|
||||
<option value="7">最近 7 天</option>
|
||||
<option value="14">最近 14 天</option>
|
||||
<option value="30">最近 30 天</option>
|
||||
</select>
|
||||
</label>
|
||||
<label title="满足条件的格子会高亮">高亮
|
||||
<select id="cfMetric">
|
||||
<option value="likes">点赞</option>
|
||||
<option value="comments">评论</option>
|
||||
<option value="collected">收藏</option>
|
||||
<option value="shares">分享</option>
|
||||
<option value="count">条数</option>
|
||||
</select>
|
||||
≥ <input id="cfValue" type="number" min="0" step="1" placeholder="数值" />
|
||||
</label>
|
||||
<button id="refresh">刷新</button>
|
||||
<span id="status"></span>
|
||||
<span class="spacer"></span>
|
||||
<a class="btn" href="/">返回控制台</a>
|
||||
</header>
|
||||
|
||||
<div id="login">
|
||||
请先在<a href="/">控制台</a>登录,再回到这个页面。
|
||||
</div>
|
||||
|
||||
<div class="wrap" id="wrap"></div>
|
||||
<div id="tip"></div>
|
||||
<div class="legend">
|
||||
<span><b>名字左边</b> = 粉丝数 / 主页总获赞 / 主页最早一条视频的发布日期(可能不在监控目标里)</span>
|
||||
<span><b>赞 / 评</b> = 当天这些作品的点赞 / 评论</span>
|
||||
<span><b>左下角数字</b> = 当天作品条数</span>
|
||||
<span><b>悬停后点标题</b> = 在抖音打开这条作品</span>
|
||||
<span><b>无标签</b> = 发了但没打标签</span>
|
||||
<span><b>空白</b> = 当天没发作品</span>
|
||||
<span>鼠标停到格子上可以看当天的点赞 / 评论 / 收藏 / 分享</span>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const params = new URLSearchParams(location.search);
|
||||
const platformSel = document.getElementById('platform');
|
||||
const taskSel = document.getElementById('task');
|
||||
const daysSel = document.getElementById('days');
|
||||
const statusEl = document.getElementById('status');
|
||||
const wrap = document.getElementById('wrap');
|
||||
const login = document.getElementById('login');
|
||||
const tip = document.getElementById('tip');
|
||||
const cfMetricSel = document.getElementById('cfMetric');
|
||||
const cfValueInput = document.getElementById('cfValue');
|
||||
// 条件格式只在本地重渲染,不重新请求 —— 指标已经随格子一起返回了。
|
||||
let lastData = null;
|
||||
// 离开格子之后延迟收起提示的计时器:提示里的标题是链接,鼠标要从格子挪进去点。
|
||||
let hideTimer = null;
|
||||
|
||||
function setStatus(text, isError) {
|
||||
statusEl.textContent = text;
|
||||
statusEl.className = isError ? 'error' : '';
|
||||
}
|
||||
|
||||
function fmt(value) {
|
||||
if (value === null || value === undefined) return '—';
|
||||
return Number(value).toLocaleString('zh-CN');
|
||||
}
|
||||
|
||||
/** 格子里的数字要短:一万以上用「万」,否则一行放不下赞和评两个数。 */
|
||||
function compact(value) {
|
||||
if (value === null || value === undefined) return '—';
|
||||
const number = Number(value);
|
||||
if (!Number.isFinite(number)) return '—';
|
||||
if (Math.abs(number) >= 100000000) {
|
||||
return (number / 100000000).toFixed(1).replace(/\.0$/, '') + '亿';
|
||||
}
|
||||
if (Math.abs(number) >= 10000) {
|
||||
return (number / 10000).toFixed(1).replace(/\.0$/, '') + '万';
|
||||
}
|
||||
return number.toLocaleString('zh-CN');
|
||||
}
|
||||
|
||||
function dateParts(ms) {
|
||||
const date = new Date(ms);
|
||||
const pad = (value) => String(value).padStart(2, '0');
|
||||
return {
|
||||
date: date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()),
|
||||
time: pad(date.getHours()) + ':' + pad(date.getMinutes()),
|
||||
};
|
||||
}
|
||||
|
||||
function metricNode(label, kind, value) {
|
||||
const span = document.createElement('span');
|
||||
span.className = kind;
|
||||
const name = document.createElement('b');
|
||||
name.textContent = label;
|
||||
span.appendChild(name);
|
||||
span.appendChild(document.createTextNode(compact(value)));
|
||||
return span;
|
||||
}
|
||||
|
||||
function hideTip() {
|
||||
clearTimeout(hideTimer);
|
||||
tip.style.display = 'none';
|
||||
}
|
||||
|
||||
/** 离开格子时不立刻收 —— 留一点时间让鼠标移进提示里点标题。 */
|
||||
function scheduleHide() {
|
||||
clearTimeout(hideTimer);
|
||||
hideTimer = setTimeout(hideTip, 250);
|
||||
}
|
||||
|
||||
function cfThreshold() {
|
||||
const raw = cfValueInput.value.trim();
|
||||
if (raw === '') return null;
|
||||
const value = Number(raw);
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function cfHit(cell) {
|
||||
if (!cell) return false;
|
||||
const threshold = cfThreshold();
|
||||
if (threshold === null) return false;
|
||||
const value = cell[cfMetricSel.value];
|
||||
return value !== null && value !== undefined && value >= threshold;
|
||||
}
|
||||
|
||||
function syncCfUrl() {
|
||||
const url = new URL(location.href);
|
||||
const threshold = cfThreshold();
|
||||
if (threshold === null) {
|
||||
url.searchParams.delete('cf');
|
||||
} else {
|
||||
url.searchParams.set('cf', cfMetricSel.value + ':' + threshold);
|
||||
}
|
||||
history.replaceState(null, '', url);
|
||||
}
|
||||
|
||||
function buildTip(cell, day, creatorName) {
|
||||
// 用 DOM 拼,不用 innerHTML —— 昵称是平台来的文本,不能当 HTML 解释。
|
||||
tip.textContent = '';
|
||||
const head = document.createElement('div');
|
||||
head.className = 'tip-head';
|
||||
head.textContent = day + ' · ' + creatorName;
|
||||
tip.appendChild(head);
|
||||
|
||||
const metrics = document.createElement('div');
|
||||
metrics.className = 'tip-metrics';
|
||||
const pairs = [
|
||||
['条数', cell.count],
|
||||
['点赞', cell.likes],
|
||||
['评论', cell.comments],
|
||||
['收藏', cell.collected],
|
||||
['分享', cell.shares],
|
||||
];
|
||||
for (const [label, value] of pairs) {
|
||||
const span = document.createElement('span');
|
||||
const name = document.createElement('b');
|
||||
name.textContent = label;
|
||||
span.appendChild(name);
|
||||
span.appendChild(document.createTextNode(' ' + fmt(value)));
|
||||
metrics.appendChild(span);
|
||||
}
|
||||
tip.appendChild(metrics);
|
||||
|
||||
const tags = document.createElement('div');
|
||||
tags.className = 'tip-tags';
|
||||
tags.textContent =
|
||||
'标签:' + (cell.tags && cell.tags.length ? cell.tags.join(' / ') : '无标签');
|
||||
tip.appendChild(tags);
|
||||
|
||||
// 逐条列出作品标题和它自己的标签。并集看不出「哪个标签属于哪条视频」,
|
||||
// 一条作品时也一样 —— 标题本身就是要看的东西,不能只在两条以上时才给。
|
||||
const details = cell.details || [];
|
||||
if (details.length > 0) {
|
||||
const list = document.createElement('div');
|
||||
list.className = 'tip-notes';
|
||||
const limit = 12;
|
||||
for (let index = 0; index < Math.min(details.length, limit); index += 1) {
|
||||
const item = details[index];
|
||||
const row = document.createElement('div');
|
||||
row.className = 'tip-note';
|
||||
|
||||
// 标题就是链接:点一下跳去抖音看原视频。没有地址的老数据就还是纯文字。
|
||||
const titleText = index + 1 + '. ' + item.title;
|
||||
let title;
|
||||
if (item.url) {
|
||||
title = document.createElement('a');
|
||||
title.href = item.url;
|
||||
title.target = '_blank';
|
||||
title.rel = 'noopener noreferrer';
|
||||
title.title = '在抖音打开';
|
||||
} else {
|
||||
title = document.createElement('div');
|
||||
}
|
||||
title.className = 'tip-note-title';
|
||||
title.textContent = titleText;
|
||||
row.appendChild(title);
|
||||
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'tip-note-meta';
|
||||
const metrics = document.createElement('span');
|
||||
metrics.className = 'tip-note-metrics';
|
||||
metrics.textContent =
|
||||
'赞 ' + compact(item.likes) +
|
||||
' · 评 ' + compact(item.comments) +
|
||||
' · 藏 ' + compact(item.collected) +
|
||||
' · 转 ' + compact(item.shares);
|
||||
meta.appendChild(metrics);
|
||||
const noteTags = document.createElement('span');
|
||||
noteTags.className = 'tip-note-tags';
|
||||
noteTags.textContent =
|
||||
item.tags && item.tags.length ? item.tags.join(' / ') : '无标签';
|
||||
meta.appendChild(noteTags);
|
||||
row.appendChild(meta);
|
||||
|
||||
list.appendChild(row);
|
||||
}
|
||||
if (details.length > limit) {
|
||||
const more = document.createElement('div');
|
||||
more.className = 'tip-note-more';
|
||||
more.textContent = '…还有 ' + (details.length - limit) + ' 条';
|
||||
list.appendChild(more);
|
||||
}
|
||||
tip.appendChild(list);
|
||||
}
|
||||
}
|
||||
|
||||
function showTip(event) {
|
||||
const td = event.currentTarget;
|
||||
const cell = td._cell;
|
||||
if (!cell) return;
|
||||
clearTimeout(hideTimer);
|
||||
buildTip(cell, td.dataset.day, td.dataset.creator);
|
||||
tip.style.display = 'block';
|
||||
|
||||
// 先显示再量尺寸,否则 offsetWidth 是 0。
|
||||
const rect = td.getBoundingClientRect();
|
||||
const width = tip.offsetWidth;
|
||||
const height = tip.offsetHeight;
|
||||
let left = rect.left + rect.width / 2 - width / 2;
|
||||
left = Math.max(8, Math.min(left, window.innerWidth - width - 8));
|
||||
let top = rect.bottom + 8;
|
||||
if (top + height > window.innerHeight - 8) {
|
||||
top = rect.top - height - 8;
|
||||
}
|
||||
tip.style.left = left + 'px';
|
||||
tip.style.top = Math.max(8, top) + 'px';
|
||||
}
|
||||
|
||||
function cellNode(cell, day, creatorName) {
|
||||
const td = document.createElement('td');
|
||||
if (!cell) {
|
||||
const dot = document.createElement('span');
|
||||
dot.className = 'empty';
|
||||
dot.textContent = '·';
|
||||
td.appendChild(dot);
|
||||
return td;
|
||||
}
|
||||
// 主角:点赞 / 评论。数字未知时显示「—」,不是 0。
|
||||
const metrics = document.createElement('div');
|
||||
metrics.className = 'cell-metrics';
|
||||
metrics.appendChild(metricNode('赞', 'like', cell.likes));
|
||||
metrics.appendChild(metricNode('评', 'comment', cell.comments));
|
||||
td.appendChild(metrics);
|
||||
|
||||
if (!cell.tags || cell.tags.length === 0) {
|
||||
const none = document.createElement('span');
|
||||
none.className = 'untagged';
|
||||
none.textContent = '无标签';
|
||||
td.appendChild(none);
|
||||
} else {
|
||||
for (const tag of cell.tags) {
|
||||
const chip = document.createElement('span');
|
||||
chip.className = 'tag';
|
||||
chip.textContent = tag;
|
||||
td.appendChild(chip);
|
||||
}
|
||||
}
|
||||
|
||||
// 作品条数放左下角。
|
||||
const count = document.createElement('span');
|
||||
count.className = 'cell-count';
|
||||
count.textContent = cell.count;
|
||||
count.title = '当天共 ' + cell.count + ' 条作品';
|
||||
td.appendChild(count);
|
||||
|
||||
td._cell = cell;
|
||||
td.dataset.day = day;
|
||||
td.dataset.creator = creatorName;
|
||||
if (cfHit(cell)) td.classList.add('hit');
|
||||
td.addEventListener('mouseenter', showTip);
|
||||
td.addEventListener('mouseleave', scheduleHide);
|
||||
return td;
|
||||
}
|
||||
|
||||
function render(data) {
|
||||
lastData = data;
|
||||
wrap.innerHTML = '';
|
||||
if (!data.dates.length) {
|
||||
setStatus('这个范围内没有作品');
|
||||
return;
|
||||
}
|
||||
const scope =
|
||||
data.task_id && taskSel.selectedOptions.length
|
||||
? ' · ' + taskSel.selectedOptions[0].textContent
|
||||
: '';
|
||||
setStatus(data.dates.length + ' 天 · ' + data.creators.length + ' 个博主' + scope);
|
||||
|
||||
const table = document.createElement('table');
|
||||
const thead = document.createElement('thead');
|
||||
const headRow = document.createElement('tr');
|
||||
// 左上角那一格钉住两个方向 —— 横着滚日期、竖着滚博主都要能看到它。
|
||||
const corner = document.createElement('th');
|
||||
corner.textContent = '博主 \\ 日期';
|
||||
headRow.appendChild(corner);
|
||||
for (const day of data.dates) {
|
||||
const th = document.createElement('th');
|
||||
th.textContent = day;
|
||||
headRow.appendChild(th);
|
||||
}
|
||||
thead.appendChild(headRow);
|
||||
table.appendChild(thead);
|
||||
|
||||
const tbody = document.createElement('tbody');
|
||||
for (const creator of data.creators) {
|
||||
const tr = document.createElement('tr');
|
||||
const th = document.createElement('th');
|
||||
// 账号池给的状态挂在名字后面的括号里,例如「周周逛苏州(账号异常)」。
|
||||
const label = creator.account_status
|
||||
? creator.name + '(' + creator.account_status + ')'
|
||||
: creator.name;
|
||||
// 粉丝数放在**名字左边**,一眼能看出这个号多大。没有快照的博主
|
||||
// (作品模式刚导入还没跑过一轮)就不画 —— 不写 0,那会被读成「没有粉丝」。
|
||||
const fansKnown = creator.fans !== null && creator.fans !== undefined;
|
||||
const likesKnown =
|
||||
creator.total_favorited !== null && creator.total_favorited !== undefined;
|
||||
const firstAt = creator.first_published_at;
|
||||
const titleParts = [];
|
||||
if (fansKnown) {
|
||||
const fans = document.createElement('span');
|
||||
fans.className = 'fans';
|
||||
fans.textContent = compact(creator.fans);
|
||||
fans.title = '粉丝数';
|
||||
th.appendChild(fans);
|
||||
titleParts.push(fmt(creator.fans) + ' 粉丝');
|
||||
}
|
||||
if (likesKnown) {
|
||||
// 主页上显示的那个「获赞总数」。
|
||||
const likes = document.createElement('span');
|
||||
likes.className = 'likes';
|
||||
likes.textContent = compact(creator.total_favorited);
|
||||
likes.title = '主页总获赞';
|
||||
th.appendChild(likes);
|
||||
titleParts.push(fmt(creator.total_favorited) + ' 总获赞');
|
||||
}
|
||||
if (firstAt) {
|
||||
const parts = dateParts(firstAt);
|
||||
const first = document.createElement('span');
|
||||
first.className = 'first';
|
||||
first.textContent = parts.date;
|
||||
first.title =
|
||||
'主页最早一条视频发布于 ' + parts.date + ' ' + parts.time;
|
||||
th.appendChild(first);
|
||||
titleParts.push('最早视频 ' + parts.date);
|
||||
}
|
||||
const nameSpan = document.createElement('span');
|
||||
nameSpan.textContent = label;
|
||||
th.appendChild(nameSpan);
|
||||
titleParts.push(label);
|
||||
th.title = titleParts.join(' · ');
|
||||
tr.appendChild(th);
|
||||
for (const day of data.dates) {
|
||||
const rowCells = data.cells[day] || {};
|
||||
tr.appendChild(cellNode(rowCells[creator.hash], day, label));
|
||||
}
|
||||
tbody.appendChild(tr);
|
||||
}
|
||||
table.appendChild(tbody);
|
||||
wrap.appendChild(table);
|
||||
}
|
||||
|
||||
async function loadTasks() {
|
||||
taskSel.innerHTML = '<option value="">全部任务</option>';
|
||||
try {
|
||||
const response = await fetch(
|
||||
'/api/monitor/tasks?platform=' + encodeURIComponent(platformSel.value),
|
||||
{ credentials: 'same-origin' },
|
||||
);
|
||||
if (!response.ok) return;
|
||||
const data = await response.json();
|
||||
for (const task of data.tasks || []) {
|
||||
const option = document.createElement('option');
|
||||
option.value = String(task.id);
|
||||
option.textContent = task.name;
|
||||
taskSel.appendChild(option);
|
||||
}
|
||||
} catch (err) {
|
||||
// 任务列表拉不到不该挡住看矩阵,保持「全部任务」即可。
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const platform = platformSel.value;
|
||||
const days = daysSel.value;
|
||||
const taskId = taskSel.value;
|
||||
|
||||
// 把当前选择写进地址栏,方便直接收藏/分享到某一组条件
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set('platform', platform);
|
||||
url.searchParams.set('days', days);
|
||||
if (taskId) url.searchParams.set('task_id', taskId);
|
||||
else url.searchParams.delete('task_id');
|
||||
history.replaceState(null, '', url);
|
||||
|
||||
setStatus('加载中…');
|
||||
wrap.innerHTML = '';
|
||||
hideTip();
|
||||
login.style.display = 'none';
|
||||
try {
|
||||
const query = new URLSearchParams({ platform: platform, days: days });
|
||||
if (taskId) query.set('task_id', taskId);
|
||||
const response = await fetch('/api/monitor/matrix?' + query.toString(), {
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (response.status === 401) {
|
||||
login.style.display = 'block';
|
||||
setStatus('未登录', true);
|
||||
return;
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error('HTTP ' + response.status);
|
||||
}
|
||||
render(await response.json());
|
||||
} catch (err) {
|
||||
setStatus('加载失败:' + err.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function init() {
|
||||
platformSel.value = params.get('platform') || 'dy';
|
||||
daysSel.value = params.get('days') || '14';
|
||||
await loadTasks();
|
||||
const wanted = params.get('task_id');
|
||||
if (wanted && Array.from(taskSel.options).some((o) => o.value === wanted)) {
|
||||
taskSel.value = wanted;
|
||||
}
|
||||
const cf = params.get('cf');
|
||||
if (cf && cf.includes(':')) {
|
||||
const parts = cf.split(':');
|
||||
const allowed = ['likes', 'comments', 'collected', 'shares', 'count'];
|
||||
if (allowed.includes(parts[0])) cfMetricSel.value = parts[0];
|
||||
cfValueInput.value = parts[1];
|
||||
}
|
||||
await load();
|
||||
}
|
||||
|
||||
document.getElementById('refresh').addEventListener('click', load);
|
||||
platformSel.addEventListener('change', async () => {
|
||||
await loadTasks();
|
||||
await load();
|
||||
});
|
||||
taskSel.addEventListener('change', load);
|
||||
daysSel.addEventListener('change', load);
|
||||
// 条件格式只重画表格,不重新请求数据。
|
||||
const rerender = () => {
|
||||
if (lastData) render(lastData);
|
||||
syncCfUrl();
|
||||
};
|
||||
cfMetricSel.addEventListener('change', rerender);
|
||||
cfValueInput.addEventListener('input', rerender);
|
||||
// 表格滚动时把提示收起来,否则它会停在原地、和格子脱节。
|
||||
wrap.addEventListener('scroll', hideTip);
|
||||
// 鼠标移进提示里(点标题)就取消收起;移出去再收。
|
||||
tip.addEventListener('mouseenter', () => clearTimeout(hideTimer));
|
||||
tip.addEventListener('mouseleave', hideTip);
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+568
-14
@@ -18,13 +18,31 @@
|
||||
|
||||
"""HTTP API for scheduled monitoring tasks."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
import json
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Response
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from ..monitor import covers, notify, qrlogin, report, service, upstream
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from ..monitor import (
|
||||
covers,
|
||||
digest,
|
||||
douyin_api,
|
||||
notify,
|
||||
qrlogin,
|
||||
report,
|
||||
service,
|
||||
superdir,
|
||||
tagrules,
|
||||
upstream,
|
||||
video_link,
|
||||
)
|
||||
from ..monitor import identities as identity_pool
|
||||
from ..monitor.db import get_session
|
||||
from ..monitor.platforms import PLATFORM_XHS
|
||||
from ..monitor.settings import (
|
||||
@@ -35,11 +53,27 @@ from ..monitor.settings import (
|
||||
set_cookie,
|
||||
set_setting,
|
||||
)
|
||||
from ..monitor.models import SETTING_WECOM_WEBHOOK, MonitorTask
|
||||
from ..monitor.models import (
|
||||
IDENTITY_SOURCE_STORED,
|
||||
IDENTITY_STATUS_OK,
|
||||
SETTING_WECOM_WEBHOOK,
|
||||
MonitorIdentity,
|
||||
MonitorTarget,
|
||||
MonitorTask,
|
||||
)
|
||||
from ..schemas.monitor import (
|
||||
CookiePayload,
|
||||
CreatorAliasPayload,
|
||||
IdentityCreate,
|
||||
IdentityUpdate,
|
||||
NoteAliasPayload,
|
||||
NoteTagsPayload,
|
||||
TagPayload,
|
||||
MonitorTaskCreate,
|
||||
MonitorTaskUpdate,
|
||||
SuperDirPreviewPayload,
|
||||
SuperDirTaskPayload,
|
||||
VideoLinksPayload,
|
||||
WebhookPayload,
|
||||
WebhookTestPayload,
|
||||
)
|
||||
@@ -128,10 +162,20 @@ async def list_notes(
|
||||
only_new: bool = False,
|
||||
limit: int = Query(default=200, ge=1, le=2000),
|
||||
platform: Optional[str] = None,
|
||||
tag_id: Optional[List[int]] = Query(
|
||||
default=None, description="可重复传,命中其中任意一个标签即算"
|
||||
),
|
||||
):
|
||||
async with get_session() as session:
|
||||
return {
|
||||
"notes": await service.list_notes(session, task_id, only_new, limit, platform)
|
||||
# windowed=True:作品栏是「正在盯的窗口」,每个博主只画最新 max_notes_count 条。
|
||||
# 库里的全量还在,趋势图/报表/导出读的都是它。
|
||||
"notes": await service.list_notes(
|
||||
session, task_id, only_new, limit, platform, windowed=True, tag_ids=tag_id
|
||||
),
|
||||
# 博主**单独给一份**,而不是让前端从作品里推。作品推不出「一条作品都没有的
|
||||
# 博主」—— 那正是最该显示的一类(还在涨粉,只是最近没发)。
|
||||
"creators": await service.list_creators(session, task_id, platform),
|
||||
}
|
||||
|
||||
|
||||
@@ -253,6 +297,59 @@ async def clear_cookie_endpoint(platform: str = Query(default=PLATFORM_XHS)):
|
||||
return {"message": "Cookie cleared"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 博主备注
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.put("/creators/{creator_hash}")
|
||||
async def set_creator_alias_endpoint(
|
||||
creator_hash: str,
|
||||
payload: CreatorAliasPayload,
|
||||
platform: str = Query(default=PLATFORM_XHS),
|
||||
):
|
||||
"""给博主起个备注(界面上的「备注」)。
|
||||
|
||||
作品栏按 creator_hash 归组,可那是个哈希、昵称又常常认不出是谁 —— 备注是人自己起的
|
||||
名字。空串表示清掉这条备注。
|
||||
"""
|
||||
async with get_session() as session:
|
||||
await service.set_creator_alias(session, platform, creator_hash, payload.alias)
|
||||
return {"creator_hash": creator_hash, "alias": payload.alias.strip()}
|
||||
|
||||
|
||||
@router.put("/notes/{note_id}")
|
||||
async def set_note_alias_endpoint(
|
||||
note_id: str,
|
||||
payload: NoteAliasPayload,
|
||||
platform: str = Query(default=PLATFORM_XHS),
|
||||
):
|
||||
"""给**作品**起个备注。
|
||||
|
||||
和上面那条博主备注是一对:博主备注回答「这个账号是谁」,这条回答「这条作品我要盯着」。
|
||||
两者不能合并 —— 一个博主底下常常只有一两件值得盯的作品。
|
||||
"""
|
||||
async with get_session() as session:
|
||||
await service.set_note_alias(session, platform, note_id, payload.alias)
|
||||
return {"note_id": note_id, "alias": payload.alias.strip()}
|
||||
|
||||
|
||||
@router.put("/notes/{note_id}/tags")
|
||||
async def set_note_tags_endpoint(
|
||||
note_id: str,
|
||||
payload: NoteTagsPayload,
|
||||
platform: str = Query(default=PLATFORM_XHS),
|
||||
):
|
||||
"""把一条作品的标签**整体替换**成这一组(空列表 = 全摘掉)。
|
||||
|
||||
传的是「这条作品现在该有哪些标签」,而不是「加上/去掉哪一个」—— 界面上是一个
|
||||
复选框对话框,点保存就是一次全量提交。
|
||||
"""
|
||||
async with get_session() as session:
|
||||
tags = await service.set_note_tags(session, platform, note_id, payload.tag_ids)
|
||||
return {"note_id": note_id, "tags": tags}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# QR login
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -370,6 +467,64 @@ async def _resolve_scope(
|
||||
return [task for task in task_ids if task in platform_ids]
|
||||
|
||||
|
||||
@router.get("/tags")
|
||||
async def list_tags():
|
||||
"""标签词表 + 各自被用在多少条作品上(删之前能看清代价)。"""
|
||||
async with get_session() as session:
|
||||
return {"tags": await service.list_tags(session)}
|
||||
|
||||
|
||||
@router.post("/tags")
|
||||
async def create_tag(payload: TagPayload):
|
||||
async with get_session() as session:
|
||||
try:
|
||||
tag = await service.create_tag(
|
||||
session, payload.name, payload.color, payload.keywords
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
# 新建的规则也立刻对已有作品生效 —— 否则「刚配好关键词,一条都没贴上」。
|
||||
tagged = await tagrules.reapply_tag_rules(session, only_tag_id=tag.id)
|
||||
return {
|
||||
"id": tag.id,
|
||||
"name": tag.name,
|
||||
"color": tag.color,
|
||||
"keywords": tag.keywords,
|
||||
"note_count": tagged,
|
||||
}
|
||||
|
||||
|
||||
@router.put("/tags/{tag_id}")
|
||||
async def update_tag(tag_id: int, payload: TagPayload):
|
||||
async with get_session() as session:
|
||||
try:
|
||||
tag = await service.update_tag(
|
||||
session, tag_id, payload.name, payload.color, payload.keywords
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
# 只重跑**这一条**规则。全都重跑的话,会把用户手动摘掉的别的标签又贴回来。
|
||||
tagged = await tagrules.reapply_tag_rules(session, only_tag_id=tag_id)
|
||||
return {
|
||||
"id": tag.id,
|
||||
"name": tag.name,
|
||||
"color": tag.color,
|
||||
"keywords": tag.keywords,
|
||||
"tagged": tagged,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/tags/{tag_id}")
|
||||
async def delete_tag(tag_id: int):
|
||||
"""删标签,连同它在所有作品上的贴纸。"""
|
||||
async with get_session() as session:
|
||||
try:
|
||||
removed = await service.delete_tag(session, tag_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
return {"removed": removed}
|
||||
|
||||
|
||||
@router.get("/export")
|
||||
async def export_data(
|
||||
kind: str = Query(..., description="notes | comments | report"),
|
||||
@@ -397,7 +552,10 @@ async def export_data(
|
||||
|
||||
if kind == "notes":
|
||||
single_task = scoped[0] if scoped and len(scoped) == 1 else None
|
||||
rows = await service.list_notes(session, single_task, False, 5000, platform)
|
||||
rows = _notes_rows(
|
||||
await service.list_creators(session, single_task, platform),
|
||||
await service.list_notes(session, single_task, False, 5000, platform),
|
||||
)
|
||||
elif kind == "comments":
|
||||
single_task = scoped[0] if scoped and len(scoped) == 1 else None
|
||||
rows = await service.list_comments(session, single_task, note_id, 5000, platform)
|
||||
@@ -440,24 +598,90 @@ async def export_data(
|
||||
)
|
||||
|
||||
|
||||
def _notes_rows(
|
||||
creators: List[Dict[str, Any]], notes: List[Dict[str, Any]]
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""博主 ∪ 作品,摊成一行行 —— **没有作品的博主也要占一行**,作品那几列留空。
|
||||
|
||||
导出是拿去比对名单的,而「这个号这段时间一条作品都没发」恰恰是名单上最该被看见的
|
||||
一行:还在涨粉、只是没动静,或者号出了问题。按作品导的话他直接消失 —— 而在表里,
|
||||
**消失和「一切正常」长得一模一样**。
|
||||
|
||||
和作品栏用的是同一个来源(`list_creators` 也是 账号快照 ∪ 作品),所以导出来的
|
||||
名单和屏幕上看到的博主是同一批。
|
||||
"""
|
||||
works_by_creator: Dict[str, List[Dict[str, Any]]] = {}
|
||||
for note in notes:
|
||||
works_by_creator.setdefault(note["creator_hash"], []).append(note)
|
||||
|
||||
rows: List[Dict[str, Any]] = []
|
||||
listed: set = set()
|
||||
for creator in creators:
|
||||
creator_hash = creator["creator_hash"]
|
||||
listed.add(creator_hash)
|
||||
works = works_by_creator.get(creator_hash, [])
|
||||
if works:
|
||||
# 作品行自己就带着博主那几列(list_notes 里已经拼好了),直接用。
|
||||
rows.extend(works)
|
||||
continue
|
||||
# 一行只填博主:作品列全是空串(`_cell` 把缺失的键变成空)。
|
||||
rows.append(
|
||||
{
|
||||
"creator_alias": creator["creator_alias"],
|
||||
"creator_name": creator["creator_name"],
|
||||
"creator_fans": creator["creator_fans"],
|
||||
"creator_total_favorited": creator["creator_total_favorited"],
|
||||
"creator_works": creator["creator_works"],
|
||||
}
|
||||
)
|
||||
|
||||
# 兜底:作品里的博主没出现在博主名单里就不该丢。正常情况下不会发生(名单是
|
||||
# 账号快照 ∪ 作品),但「悄悄少几行」是这份导出最不该犯的错。
|
||||
rows.extend(note for note in notes if note["creator_hash"] not in listed)
|
||||
|
||||
# 同一个博主的行挨在一起,按「这是谁」排 —— 表格是拿去筛和做透视的。
|
||||
rows.sort(
|
||||
key=lambda row: (
|
||||
row.get("creator_alias") or row.get("creator_name") or "",
|
||||
-(row.get("published_at") or 0),
|
||||
)
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def _export_columns(kind: str) -> List[tuple[str, str]]:
|
||||
"""(key, header) pairs per export kind."""
|
||||
if kind == "notes":
|
||||
return [
|
||||
("note_id", "作品ID"),
|
||||
# 先放「这是谁」:导出来是拿去比对和汇报的,一行只有作品 ID 没法用。
|
||||
# 备注优先 —— 昵称常常认不出是谁(见 notes 表那一层的说明)。
|
||||
("creator_alias", "博主备注"),
|
||||
("creator_name", "博主昵称"),
|
||||
# 账号级指标 —— 没有作品的博主那一行**只剩它们**,没有的话那一行等于空行。
|
||||
# 「主页作品数」是他在平台上的总数,和下面那几列(我们监控到的作品)不是
|
||||
# 一回事,所以名字要分得开。
|
||||
("creator_fans", "粉丝数"),
|
||||
("creator_total_favorited", "总获赞"),
|
||||
("creator_works", "主页作品数"),
|
||||
("note_alias", "作品备注"),
|
||||
("title", "标题"),
|
||||
("note_id", "作品ID"),
|
||||
("note_url", "链接"),
|
||||
("liked_count", "点赞"),
|
||||
("comment_count", "评论"),
|
||||
("collected_count", "收藏"),
|
||||
("share_count", "分享"),
|
||||
("liked_count_delta", "点赞增量"),
|
||||
("comment_count_delta", "评论增量"),
|
||||
("published_at", "发布时间"),
|
||||
# 指标嵌在 row["metrics"] 里,所以这里必须写成路径 —— 写成裸键名的话这几列
|
||||
# 全空(见 _lookup)。
|
||||
("metrics.liked_count", "点赞"),
|
||||
("metrics.comment_count", "评论"),
|
||||
("metrics.collected_count", "收藏"),
|
||||
("metrics.share_count", "分享"),
|
||||
("deltas.liked_count", "点赞增量"),
|
||||
("deltas.comment_count", "评论增量"),
|
||||
("first_seen_at", "首次发现"),
|
||||
("last_seen_at", "最近采集"),
|
||||
]
|
||||
if kind == "comments":
|
||||
return [
|
||||
("note_creator_name", "博主昵称"),
|
||||
("note_title", "所属作品"),
|
||||
("note_id", "作品ID"),
|
||||
("comment_id", "评论ID"),
|
||||
@@ -479,6 +703,42 @@ def _export_columns(kind: str) -> List[tuple[str, str]]:
|
||||
]
|
||||
|
||||
|
||||
# 表里存的是毫秒时间戳。直接倒进 CSV 就是一串 13 位数字 —— 打开 Excel 的人没法看,
|
||||
# 也没法排序。这几个键统一格式化成人能读的形态。
|
||||
_TIME_KEYS = {"published_at", "first_seen_at", "last_seen_at", "create_time"}
|
||||
|
||||
|
||||
def _fmt_time(value: Any) -> str:
|
||||
"""毫秒 → ``YYYY-MM-DD HH:MM``(服务器本地时区)。"""
|
||||
try:
|
||||
return datetime.fromtimestamp(int(value) / 1000).strftime("%Y-%m-%d %H:%M")
|
||||
except (TypeError, ValueError, OSError, OverflowError):
|
||||
return ""
|
||||
|
||||
|
||||
def _cell_for(row: Dict[str, Any], key: str) -> Any:
|
||||
"""一列的值:时间键格式化成人能读的,其余照原样(None 变空串)。"""
|
||||
value = _lookup(row, key)
|
||||
if key.rsplit(".", 1)[-1] in _TIME_KEYS:
|
||||
return _fmt_time(value)
|
||||
return _cell(value)
|
||||
|
||||
|
||||
def _lookup(row: Dict[str, Any], key: str) -> Any:
|
||||
"""取一列的值。键可以是 ``metrics.liked_count`` 这种路径。
|
||||
|
||||
作品行的指标是**嵌在** ``metrics`` / ``deltas`` 里的,而 ``_export_columns`` 里写的
|
||||
是 ``liked_count`` —— 照顶层键直接 ``row.get()`` 的话,点赞/评论/收藏/分享四列连带
|
||||
两个增量列**永远是空的**,导出来的表看着有这几列,其实一格都没有。
|
||||
"""
|
||||
value: Any = row
|
||||
for part in key.split("."):
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
value = value.get(part)
|
||||
return value
|
||||
|
||||
|
||||
def _cell(value: Any) -> Any:
|
||||
if value is None:
|
||||
return ""
|
||||
@@ -495,7 +755,7 @@ def _to_csv(rows: List[Dict[str, Any]], columns: List[tuple[str, str]]) -> bytes
|
||||
writer = csv.writer(buffer)
|
||||
writer.writerow([header for _, header in columns])
|
||||
for row in rows:
|
||||
writer.writerow([_cell(row.get(key)) for key, _ in columns])
|
||||
writer.writerow([_cell_for(row, key) for key, _ in columns])
|
||||
|
||||
# utf-8-sig: without the BOM Excel opens Chinese CSV as mojibake, which is
|
||||
# the single most common complaint about CSV exports here.
|
||||
@@ -512,13 +772,28 @@ def _to_xlsx(rows: List[Dict[str, Any]], columns: List[tuple[str, str]], sheet:
|
||||
worksheet.title = {"notes": "作品", "comments": "评论"}.get(sheet, "报表")
|
||||
worksheet.append([header for _, header in columns])
|
||||
for row in rows:
|
||||
worksheet.append([_cell(row.get(key)) for key, _ in columns])
|
||||
worksheet.append([_cell_for(row, key) for key, _ in columns])
|
||||
|
||||
output = io.BytesIO()
|
||||
workbook.save(output)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
@router.get("/matrix")
|
||||
async def get_tag_matrix(
|
||||
platform: str = Query(default=PLATFORM_XHS, description="dy / xhs"),
|
||||
days: int = Query(default=14, ge=1, le=90, description="回看多少天"),
|
||||
task_id: Optional[int] = Query(default=None, description="只看某一个任务;省略=整个平台"),
|
||||
):
|
||||
"""日期 × 博主 → 当天发出去的作品标签(带点赞/评论/收藏/分享的当日小计)。
|
||||
|
||||
返回**长表结构**(dates / creators / cells),转置交给前端的报表页
|
||||
(``/report/matrix``)。理由见 ``service.daily_tag_matrix`` 的说明。
|
||||
"""
|
||||
async with get_session() as session:
|
||||
return await service.daily_tag_matrix(session, platform, days, task_id=task_id)
|
||||
|
||||
|
||||
@router.get("/report")
|
||||
async def get_report(
|
||||
task_id: Optional[List[int]] = Query(
|
||||
@@ -634,3 +909,282 @@ async def run_upstream_check():
|
||||
没有推过的那批提交会留给下一次「定时检查」推 —— 推送状态记的是 tip,不是「推过没」。
|
||||
"""
|
||||
return await upstream.run_check(notify_when_new=False)
|
||||
|
||||
|
||||
@router.get("/digest/preview")
|
||||
async def preview_daily_digest(
|
||||
platform: str = Query(default=PLATFORM_XHS),
|
||||
day: Optional[str] = Query(default=None, description="YYYY-MM-DD,省略=昨天"),
|
||||
):
|
||||
"""把「昨天的视频情况」画出来直接返回图片,**不发消息**。
|
||||
|
||||
先看一眼图长什么样,再去开定时推送 —— 不必为了验证往群里发一条。省略 ``day``
|
||||
时取的就是定时推送会报的那一天,两边看到的应该是同一张。
|
||||
"""
|
||||
try:
|
||||
target = date.fromisoformat(day) if day else digest.default_day()
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="日期格式应为 YYYY-MM-DD")
|
||||
|
||||
async with get_session() as session:
|
||||
rows = await digest.daily_rows(session, platform, target)
|
||||
label = "抖音" if platform == "dy" else "小红书"
|
||||
image_bytes = digest.render_table(rows, target, label)
|
||||
return Response(content=image_bytes, media_type="image/png")
|
||||
|
||||
|
||||
@router.post("/digest/send")
|
||||
async def send_daily_digest_now(platform: str = Query(default=PLATFORM_XHS)):
|
||||
"""手动生成并发送「昨天的视频情况」图。
|
||||
|
||||
发的是**和每天早上九点那张一模一样**的内容(同样报昨天),这样点一下就能确认
|
||||
定时推送会不会如期到达,而不是收到一张口径不同的图。
|
||||
"""
|
||||
async with get_session() as session:
|
||||
ok, detail, count = await digest.send_daily_digest(session, platform)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=502, detail=detail)
|
||||
return {"ok": True, "rows": count, "detail": detail}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 视频链接 → 博主主页
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# 纯查询,不写库:拿到主页地址之后要不要建监控任务,由人决定。
|
||||
|
||||
|
||||
@router.post("/video-links")
|
||||
async def resolve_video_links(payload: VideoLinksPayload):
|
||||
"""把粘贴进来的视频链接/分享文案换成博主主页地址。
|
||||
|
||||
一次最多 20 条,逐条串行请求详情接口。单条失败只在那一条上写 ``error``,
|
||||
其余照常返回 —— 批量粘贴时最不需要的就是「一条挂全批挂」。
|
||||
"""
|
||||
return await video_link.resolve(payload.text)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 超级编导导入
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# 两段:先按「活动创建时间」区间预览作品链接(只读),再把选中/全部链接建成一个作品
|
||||
# 监控任务。分两步是因为运营要先看一眼「这一批到底有多少条、是谁发的」再决定建不建 ——
|
||||
# 一次点击就凭空多出一个几百目标的监控任务,太容易误触。
|
||||
#
|
||||
# 只有抖音:超级编导这边接的就是抖音分发,数据中心的字段也全是抖音作品。
|
||||
|
||||
|
||||
@router.post("/superdir/preview")
|
||||
async def preview_superdir(payload: SuperDirPreviewPayload):
|
||||
"""列出区间内创建的分发活动下的作品链接,**不写库**。"""
|
||||
async with get_session() as session:
|
||||
try:
|
||||
return await superdir.preview(session, payload.start, payload.end)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except superdir.SuperDirError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc))
|
||||
|
||||
|
||||
@router.post("/superdir/tasks", status_code=201)
|
||||
async def create_superdir_task(payload: SuperDirTaskPayload):
|
||||
"""把预览出来的链接建成一个作品监控任务、或追加到已有任务,默认立刻跑一轮。
|
||||
|
||||
立刻跑一轮是有意的:只有采到一次,作品栏里才有主页信息和播放数据 —— 否则用户建完
|
||||
看到一个空任务,会以为没建成功。
|
||||
|
||||
带 ``task_id`` 就是**追加**:超级编导每天都会出新作品,补进同一个任务比每周新建一个
|
||||
任务更容易盯 —— 作品、指标和变化都在一处。
|
||||
"""
|
||||
try:
|
||||
async with get_session() as session:
|
||||
if payload.task_id is not None:
|
||||
task, added, total = await superdir.append_task(
|
||||
session, payload.task_id, payload.links
|
||||
)
|
||||
else:
|
||||
task, added = await superdir.create_task(
|
||||
session,
|
||||
payload.links,
|
||||
payload.name,
|
||||
enable_comments=payload.enable_comments,
|
||||
)
|
||||
total = added
|
||||
except (ValueError, service.TargetParseError) as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
# 没有新增就别跑:一次几十分钟的采集只为确认「一条都没变」没有意义。
|
||||
if payload.run_now and added:
|
||||
service.trigger_manual_run(task.id)
|
||||
message = (
|
||||
f"已追加 {added} 条(共 {total} 条)" if payload.task_id is not None else "监控任务已创建"
|
||||
)
|
||||
return {"id": task.id, "added": added, "targets": total, "message": message}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 身份池
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# 多个登录态分片采集用。**接口永远不返回 cookie 原文**,只给 has_cookie —— 这是
|
||||
# 从运营模块那边沿用下来的约定。
|
||||
|
||||
|
||||
@router.get("/identities")
|
||||
async def list_identities(platform: str = Query(default=PLATFORM_XHS)):
|
||||
async with get_session() as session:
|
||||
rows = (
|
||||
await session.scalars(
|
||||
select(MonitorIdentity)
|
||||
.where(MonitorIdentity.platform == platform)
|
||||
.order_by(MonitorIdentity.id)
|
||||
)
|
||||
).all()
|
||||
return {"identities": [identity_pool.to_dict(row) for row in rows]}
|
||||
|
||||
|
||||
@router.post("/identities", status_code=201)
|
||||
async def create_identity(payload: IdentityCreate):
|
||||
"""新增一份登录态。
|
||||
|
||||
UA 留空时会尝试从 CDP 浏览器借一份指纹 —— cookie 仍用用户贴的这一份。再读不到
|
||||
就拒绝:评论签名要拿 UA,空 UA 的请求一定被挡。
|
||||
"""
|
||||
if payload.platform != "dy":
|
||||
raise HTTPException(status_code=400, detail="目前只有抖音支持多身份")
|
||||
|
||||
user_agent = payload.user_agent.strip()
|
||||
hints = dict(payload.client_hints)
|
||||
if not user_agent:
|
||||
user_agent, shared_hints = await douyin_api.shared_fingerprint()
|
||||
hints = hints or dict(shared_hints)
|
||||
if not user_agent:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"拿不到 UA。请手动填写 user_agent(要和 cookie 来自同一个浏览器),"
|
||||
"或先让 CDP 浏览器登录抖音。"
|
||||
),
|
||||
)
|
||||
|
||||
label = payload.label.strip()
|
||||
now = get_current_timestamp()
|
||||
async with get_session() as session:
|
||||
exists = await session.scalar(
|
||||
select(MonitorIdentity.id).where(
|
||||
MonitorIdentity.platform == payload.platform,
|
||||
MonitorIdentity.label == label,
|
||||
)
|
||||
)
|
||||
if exists:
|
||||
raise HTTPException(status_code=409, detail="同名身份已存在")
|
||||
|
||||
row = MonitorIdentity(
|
||||
platform=payload.platform,
|
||||
label=label,
|
||||
source=IDENTITY_SOURCE_STORED,
|
||||
cookie=payload.cookie.strip(),
|
||||
user_agent=user_agent,
|
||||
client_hints=json.dumps(hints, ensure_ascii=False),
|
||||
status=IDENTITY_STATUS_OK,
|
||||
enabled=True,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
session.add(row)
|
||||
await session.flush()
|
||||
return identity_pool.to_dict(row)
|
||||
|
||||
|
||||
@router.patch("/identities/{identity_id}")
|
||||
async def update_identity(identity_id: int, payload: IdentityUpdate):
|
||||
async with get_session() as session:
|
||||
row = await session.get(MonitorIdentity, identity_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="身份不存在")
|
||||
|
||||
if payload.label is not None:
|
||||
row.label = payload.label.strip()
|
||||
if payload.user_agent is not None:
|
||||
row.user_agent = payload.user_agent.strip()
|
||||
if payload.cookie is not None:
|
||||
row.cookie = payload.cookie.strip()
|
||||
# 换了 cookie,旧状态作废 —— 之前冷却/失效的原因可能已经不存在了。
|
||||
row.status = IDENTITY_STATUS_OK
|
||||
row.consecutive_failures = 0
|
||||
row.cooldown_until = None
|
||||
row.last_error = None
|
||||
if payload.enabled is not None:
|
||||
row.enabled = payload.enabled
|
||||
row.updated_at = get_current_timestamp()
|
||||
await session.flush()
|
||||
return identity_pool.to_dict(row)
|
||||
|
||||
|
||||
@router.delete("/identities/{identity_id}")
|
||||
async def delete_identity(identity_id: int):
|
||||
async with get_session() as session:
|
||||
row = await session.get(MonitorIdentity, identity_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="身份不存在")
|
||||
await session.delete(row)
|
||||
return {"deleted": identity_id}
|
||||
|
||||
|
||||
@router.post("/identities/{identity_id}/check")
|
||||
async def check_identity(identity_id: int):
|
||||
"""真去用这份身份请求一次。
|
||||
|
||||
优先拿该平台一个启用中的博主目标做探针(``author_profile``,1 个请求);没有目标
|
||||
时退化成「cookie 里有没有 sessionid」,并在 ``verified`` 里标 False —— 别把格式
|
||||
检查说成验证通过。
|
||||
"""
|
||||
async with get_session() as session:
|
||||
row = await session.get(MonitorIdentity, identity_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="身份不存在")
|
||||
platform = row.platform
|
||||
probe = await session.scalar(
|
||||
select(MonitorTarget.external_id)
|
||||
.join(MonitorTask, MonitorTask.id == MonitorTarget.task_id)
|
||||
.where(
|
||||
MonitorTask.platform == platform,
|
||||
MonitorTask.enabled.is_(True),
|
||||
MonitorTarget.kind == "creator",
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
error = ""
|
||||
verified = bool(probe)
|
||||
ok = False
|
||||
try:
|
||||
identity = await identity_pool.resolve(row)
|
||||
except ValueError as exc:
|
||||
identity = None
|
||||
error = str(exc)
|
||||
|
||||
if identity is not None:
|
||||
if probe:
|
||||
try:
|
||||
await douyin_api.author_profile(probe, identity=identity)
|
||||
ok = True
|
||||
except Exception as exc: # noqa: BLE001 - 任何失败都只是「这份身份不可用」
|
||||
error = f"{type(exc).__name__}: {exc}"[:300]
|
||||
else:
|
||||
ok = "sessionid=" in identity.cookie
|
||||
if not ok:
|
||||
error = "cookie 里没有 sessionid"
|
||||
|
||||
async with get_session() as session:
|
||||
live = await session.get(MonitorIdentity, identity_id)
|
||||
if live is not None:
|
||||
await identity_pool.record_result(session, live, ok=ok, error=error)
|
||||
return {
|
||||
"ok": ok,
|
||||
"verified": verified,
|
||||
"error": error,
|
||||
"identity": identity_pool.to_dict(live),
|
||||
}
|
||||
return {"ok": ok, "verified": verified, "error": error, "identity": None}
|
||||
|
||||
+26
-1
@@ -27,9 +27,13 @@ no gain.
|
||||
from typing import Any, Dict
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from sqlalchemy import update
|
||||
|
||||
from ..monitor import app_settings
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from ..monitor import adapters, app_settings
|
||||
from ..monitor.db import get_session
|
||||
from ..monitor.models import MODE_NOTE, MonitorTask
|
||||
from ..monitor.platforms import PLATFORM_XHS
|
||||
from ..schemas.settings import SettingsUpdatePayload
|
||||
|
||||
@@ -67,4 +71,25 @@ async def write_settings(
|
||||
except app_settings.SettingValidationError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
# 刚填好超级编导的账号密码(或换了新 token),不该让用户再等两小时才看到它生效:
|
||||
# 把自动追加的调度钟挪到「现在」,下一个 tick 就用新凭据续期/查询。
|
||||
if platform == adapters.PLATFORM_DY and any(
|
||||
key.rsplit(".", 1)[-1]
|
||||
in ("superdir_username", "superdir_password", "superdir_token")
|
||||
for key in changed
|
||||
):
|
||||
async with get_session() as session:
|
||||
await session.execute(
|
||||
update(MonitorTask)
|
||||
.where(
|
||||
MonitorTask.platform == adapters.PLATFORM_DY,
|
||||
MonitorTask.mode == MODE_NOTE,
|
||||
MonitorTask.superdir_auto_enabled.is_(True),
|
||||
)
|
||||
.values(
|
||||
superdir_auto_next_at=get_current_timestamp(),
|
||||
superdir_auto_last_error="",
|
||||
)
|
||||
)
|
||||
|
||||
return {"message": f"已保存 {len(changed)} 项设置", "changed": changed}
|
||||
|
||||
+93
-1
@@ -18,7 +18,7 @@
|
||||
|
||||
"""Request models for the monitoring API."""
|
||||
|
||||
from typing import List, Literal, Optional
|
||||
from typing import Dict, List, Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
@@ -64,6 +64,9 @@ class MonitorTaskCreate(BaseModel):
|
||||
# 异常频率低且意味着任务已经停止工作(默认开,否则你会一直不知道)。
|
||||
notify_enabled: bool = False
|
||||
notify_failures: bool = True
|
||||
# 超级编导自动追加(只有抖音的作品模式任务能用,服务层会校验)。
|
||||
superdir_auto_enabled: bool = False
|
||||
superdir_auto_interval_minutes: int = Field(default=120, ge=30, le=1440)
|
||||
# Raw pasted values: full URLs or bare ids, in either form.
|
||||
targets: List[str] = Field(min_length=1)
|
||||
|
||||
@@ -100,6 +103,10 @@ class MonitorTaskUpdate(BaseModel):
|
||||
run_timeout_seconds: Optional[int] = Field(default=None, ge=60, le=86400)
|
||||
notify_enabled: Optional[bool] = None
|
||||
notify_failures: Optional[bool] = None
|
||||
superdir_auto_enabled: Optional[bool] = None
|
||||
superdir_auto_interval_minutes: Optional[int] = Field(
|
||||
default=None, ge=30, le=1440
|
||||
)
|
||||
# When present, replaces the whole target list.
|
||||
targets: Optional[List[str]] = None
|
||||
|
||||
@@ -108,9 +115,94 @@ class CookiePayload(BaseModel):
|
||||
cookie: str = Field(min_length=1)
|
||||
|
||||
|
||||
class CreatorAliasPayload(BaseModel):
|
||||
"""给博主起的备注。空串表示清掉这条备注。"""
|
||||
|
||||
alias: str = Field(default="", max_length=128)
|
||||
|
||||
|
||||
class NoteAliasPayload(BaseModel):
|
||||
"""给作品起的备注。空串表示清掉这条备注。"""
|
||||
|
||||
alias: str = Field(default="", max_length=128)
|
||||
|
||||
|
||||
class TagPayload(BaseModel):
|
||||
"""新建/改名一个标签。`color` 是调色板里的名字,不认识的会被回落到默认色。
|
||||
|
||||
``keywords`` 是自动打标签的规则:逗号分隔,标题里出现其中任意一个就自动贴上这条标签。
|
||||
改成空就等于关掉这条规则(已经贴上去的**不会**被摘掉)。
|
||||
"""
|
||||
|
||||
name: str = Field(min_length=1, max_length=32)
|
||||
color: str = Field(default="", max_length=16)
|
||||
keywords: str = Field(default="", max_length=512)
|
||||
|
||||
|
||||
class NoteTagsPayload(BaseModel):
|
||||
"""把一条作品的标签整体替换成这一组。空列表 = 全摘掉。"""
|
||||
|
||||
tag_ids: List[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
class WebhookPayload(BaseModel):
|
||||
url: str = Field(default="", description="企业微信机器人 Webhook 地址,留空表示停用")
|
||||
|
||||
|
||||
class WebhookTestPayload(BaseModel):
|
||||
url: Optional[str] = Field(default=None, description="不传则使用已保存的地址")
|
||||
|
||||
|
||||
class VideoLinksPayload(BaseModel):
|
||||
"""一整段粘贴内容,一行一条链接(分享文案也直接粘)。
|
||||
|
||||
``max_length`` 挡的是误粘 —— 真按这个上限解析也没意义,一次最多 20 条,
|
||||
超出的部分接口会标 ``truncated`` 让前端明说。
|
||||
"""
|
||||
|
||||
text: str = Field(default="", max_length=20000)
|
||||
|
||||
|
||||
class SuperDirPreviewPayload(BaseModel):
|
||||
"""超级编导「创建时间」区间,闭区间,按东八区的自然日算。"""
|
||||
|
||||
start: str = Field(min_length=10, max_length=10, description="YYYY-MM-DD")
|
||||
end: str = Field(min_length=10, max_length=10, description="YYYY-MM-DD")
|
||||
|
||||
|
||||
class SuperDirTaskPayload(BaseModel):
|
||||
"""按预览出来的链接建一个作品监控任务。
|
||||
|
||||
链接是前端从预览结果里带回来的 —— 不在服务端重查一遍:重查会让「我看到的」和
|
||||
「建出来的」对不上(中间隔了几分钟,活动可能又发了一批发),而这种对不上比多一次
|
||||
请求难查得多。链接本身只当 id 用,建之前会再抠一次作品 id。
|
||||
"""
|
||||
|
||||
links: List[str] = Field(default_factory=list, max_length=2000)
|
||||
# 给了就追加到这个任务里,不给就新建。追加是「一个任务一直更新」的路径:
|
||||
# 每天从超级编导补一批新作品进来,而不是一周建七个任务。
|
||||
task_id: Optional[int] = None
|
||||
name: str = Field(default="", max_length=200)
|
||||
enable_comments: bool = False
|
||||
run_now: bool = True
|
||||
|
||||
|
||||
class IdentityCreate(BaseModel):
|
||||
"""新增一个采集身份(一份登录态)。
|
||||
|
||||
``user_agent`` 最好和 cookie 来自同一个浏览器。留空时后端会尝试从 CDP 浏览器
|
||||
读一份指纹兜底;再读不到就拒绝 —— 评论接口的 a_bogus 要拿 UA 去签名。
|
||||
"""
|
||||
|
||||
platform: str = Field(default="dy", max_length=16)
|
||||
label: str = Field(min_length=1, max_length=128)
|
||||
cookie: str = Field(min_length=1)
|
||||
user_agent: str = Field(default="", max_length=512)
|
||||
client_hints: Dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class IdentityUpdate(BaseModel):
|
||||
label: Optional[str] = Field(default=None, min_length=1, max_length=128)
|
||||
cookie: Optional[str] = Field(default=None)
|
||||
user_agent: Optional[str] = Field(default=None, max_length=512)
|
||||
enabled: Optional[bool] = None
|
||||
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
# API 接口清单
|
||||
|
||||
从 FastAPI 自己的 OpenAPI schema 生成的,**不是手写的** ——
|
||||
手写的接口文档从改代码那天起就开始腐烂,而且烂得无声无息。
|
||||
|
||||
重新生成:
|
||||
|
||||
```bash
|
||||
./.venv/Scripts/python.exe docs/gen_api_doc.py
|
||||
```
|
||||
|
||||
## 通用约定
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 前缀 | 所有接口都在 `/api` 下(WebSocket 是 `/api/ws/...`)|
|
||||
| 鉴权 | **Cookie 优先,Bearer 次之**:`token_from_request()` 先读会话 Cookie,读不到再读 `Authorization: Bearer <token>`。浏览器用 Cookie,脚本用 Bearer |
|
||||
| 会话怎么来 | `POST /api/auth/login`(密码),响应种下会话 Cookie;有效期由服务端 `resolve_session()` 判定 |
|
||||
| 错误形状 | FastAPI 默认的 `{"detail": "..."}`;401 是登录失效 |
|
||||
| **没有 `/docs`** | 特意关掉的:`/docs`、`/redoc`、`/openapi.json` 默认**不需要登录**,等于把整份接口地图连同「Try it out」一起送出去。要看交互式的,得挂在鉴权后面 |
|
||||
| WebSocket | `GET /api/ws/logs`(升级为 ws)—— 实时日志流。**不在这里的清单里**:OpenAPI 描述不了 WebSocket。它自己用 `require_ws_auth` 校验会话 Cookie |
|
||||
|
||||
## 目录
|
||||
|
||||
- [认证](#认证)(4 个)
|
||||
- [采集](#采集)(4 个)
|
||||
- [运营(博主账号)](#运营(博主账号))(8 个)
|
||||
- [数据](#数据)(4 个)
|
||||
- [监控](#监控)(36 个)
|
||||
- [设置](#设置)(2 个)
|
||||
|
||||
## 认证
|
||||
|
||||
这一组**没有**统一挂 `require_auth`(登录不能要求先登录),所以逐个标。
|
||||
|
||||
| 方法 | 路径 | 登录 | 说明 | 参数 | 请求体 |
|
||||
|---|---|:--:|---|---|---|
|
||||
| `POST` | `/api/auth/login` | — | Login | | LoginPayload |
|
||||
| `POST` | `/api/auth/logout` | — | Logout | | |
|
||||
| `GET` | `/api/auth/me` | ✓ | Identity probe. The SPA treats a 401 here as "show the login page". | | |
|
||||
| `POST` | `/api/auth/password` | ✓ | Change the password and log every device out. | | ChangePasswordPayload |
|
||||
|
||||
## 采集
|
||||
|
||||
| 方法 | 路径 | 登录 | 说明 | 参数 | 请求体 |
|
||||
|---|---|:--:|---|---|---|
|
||||
| `GET` | `/api/crawler/logs` | ✓ | Get recent logs | `limit`(query integer 可选=100) | |
|
||||
| `POST` | `/api/crawler/start` | ✓ | Start crawler task. | | CrawlerStartRequest |
|
||||
| `GET` | `/api/crawler/status` | ✓ | Get crawler status | | |
|
||||
| `POST` | `/api/crawler/stop` | ✓ | Stop crawler task | | |
|
||||
|
||||
## 运营(博主账号)
|
||||
|
||||
| 方法 | 路径 | 登录 | 说明 | 参数 | 请求体 |
|
||||
|---|---|:--:|---|---|---|
|
||||
| `GET` | `/api/creator/accounts` | ✓ | 账号列表。**不含 cookie**,只给 ``has_cookie``。 | | |
|
||||
| `DELETE` | `/api/creator/accounts/{account_id}` | ✓ | Delete Account | `account_id`(path integer 必填) | |
|
||||
| `GET` | `/api/creator/accounts/{account_id}` | ✓ | Get Account Detail | `account_id`(path integer 必填) | |
|
||||
| `POST` | `/api/creator/accounts/{account_id}/check` | ✓ | 重测登录态与数据权限。 | `account_id`(path integer 必填) | |
|
||||
| `POST` | `/api/creator/accounts/{account_id}/sync` | ✓ | 拉取作品数据。 | `account_id`(path integer 必填)<br>`days`(query integer 可选=90) | |
|
||||
| `DELETE` | `/api/creator/login` | ✓ | Cancel Login | | |
|
||||
| `GET` | `/api/creator/login` | ✓ | 轮询扫码结果;一旦成功就把账号落库并返回它。 | | |
|
||||
| `POST` | `/api/creator/login` | ✓ | Start Login | | |
|
||||
|
||||
## 数据
|
||||
|
||||
| 方法 | 路径 | 登录 | 说明 | 参数 | 请求体 |
|
||||
|---|---|:--:|---|---|---|
|
||||
| `GET` | `/api/data/download/{file_path}` | ✓ | Download file | `file_path`(path string 必填) | |
|
||||
| `GET` | `/api/data/files` | ✓ | Get data file list | `platform`(query string \| null 可选)<br>`file_type`(query string \| null 可选) | |
|
||||
| `GET` | `/api/data/files/{file_path}` | ✓ | Get file content or preview | `file_path`(path string 必填)<br>`preview`(query boolean 可选=True)<br>`limit`(query integer 可选=100) | |
|
||||
| `GET` | `/api/data/stats` | ✓ | Get data statistics | | |
|
||||
|
||||
## 监控
|
||||
|
||||
| 方法 | 路径 | 登录 | 说明 | 参数 | 请求体 |
|
||||
|---|---|:--:|---|---|---|
|
||||
| `GET` | `/api/monitor/comment-notes` | ✓ | Works that have comments, newest first, with counts. | `task_id`(query integer \| null 可选)<br>`platform`(query string \| null 可选) | |
|
||||
| `GET` | `/api/monitor/comments` | ✓ | Comments, each carrying the work it belongs to. | `task_id`(query integer \| null 可选)<br>`note_id`(query string \| null 可选)<br>`group_by`(query string \| null 可选)<br>`limit`(query integer 可选=200)<br>`platform`(query string \| null 可选) | |
|
||||
| `DELETE` | `/api/monitor/cookie` | ✓ | Clear Cookie Endpoint | `platform`(query string 可选='xhs') | |
|
||||
| `GET` | `/api/monitor/cookie` | ✓ | Cookie health only -- deliberately never returns the cookie value. | `platform`(query string 可选='xhs') | |
|
||||
| `POST` | `/api/monitor/cookie` | ✓ | Set Cookie Endpoint | `platform`(query string 可选='xhs') | CookiePayload |
|
||||
| `GET` | `/api/monitor/covers/{note_id}` | ✓ | 作品封面,从本地缓存读。 | `note_id`(path string 必填) | |
|
||||
| `PUT` | `/api/monitor/creators/{creator_hash}` | ✓ | 给博主起个备注(界面上的「备注」)。 | `creator_hash`(path string 必填)<br>`platform`(query string 可选='xhs') | CreatorAliasPayload |
|
||||
| `GET` | `/api/monitor/events` | ✓ | List Events | `task_id`(query integer \| null 可选)<br>`type`(query string \| null 可选)<br>`since_id`(query integer \| null 可选)<br>`limit`(query integer 可选=200)<br>`platform`(query string \| null 可选) | |
|
||||
| `POST` | `/api/monitor/events/read` | ✓ | Mark Events Read | `task_id`(query integer \| null 可选) | |
|
||||
| `GET` | `/api/monitor/export` | ✓ | Download collected data as CSV or Excel. | `kind`(query string 必填)<br>`task_id`(query integer[] \| null 可选)<br>`note_id`(query string \| null 可选)<br>`start_date`(query string \| null 可选)<br>`end_date`(query string \| null 可选)<br>`days`(query integer 可选=7)<br>`format`(query string 可选='csv')<br>`platform`(query string \| null 可选) | |
|
||||
| `DELETE` | `/api/monitor/login/qr` | ✓ | Drop our tab and stop polling. | | |
|
||||
| `GET` | `/api/monitor/login/qr` | ✓ | Poll the live session: waiting -> success / expired / error. | | |
|
||||
| `POST` | `/api/monitor/login/qr` | ✓ | Open the login page in the CDP browser and return its QR code. | `platform`(query string 可选='xhs') | |
|
||||
| `GET` | `/api/monitor/login/state` | ✓ | Ask the browser itself whether it is signed in. | `force`(query boolean 可选=False) | |
|
||||
| `GET` | `/api/monitor/notes` | ✓ | List Notes | `task_id`(query integer \| null 可选)<br>`only_new`(query boolean 可选=False)<br>`limit`(query integer 可选=200)<br>`platform`(query string \| null 可选)<br>`tag_id`(query integer[] \| null 可选) | |
|
||||
| `PUT` | `/api/monitor/notes/{note_id}` | ✓ | 给**作品**起个备注。 | `note_id`(path string 必填)<br>`platform`(query string 可选='xhs') | NoteAliasPayload |
|
||||
| `GET` | `/api/monitor/notes/{note_id}/series` | ✓ | Metric time series for a single note. | `note_id`(path string 必填)<br>`task_id`(query integer \| null 可选) | |
|
||||
| `PUT` | `/api/monitor/notes/{note_id}/tags` | ✓ | 把一条作品的标签**整体替换**成这一组(空列表 = 全摘掉)。 | `note_id`(path string 必填)<br>`platform`(query string 可选='xhs') | NoteTagsPayload |
|
||||
| `GET` | `/api/monitor/overview` | ✓ | Headline numbers for the dashboard tiles, scoped to one platform. | `platform`(query string \| null 可选) | |
|
||||
| `GET` | `/api/monitor/report` | ✓ | Daily new-content counts and interaction deltas for the selected tasks. | `task_id`(query integer[] \| null 可选)<br>`start_date`(query string \| null 可选)<br>`end_date`(query string \| null 可选)<br>`days`(query integer 可选=7)<br>`platform`(query string \| null 可选) | |
|
||||
| `GET` | `/api/monitor/tags` | ✓ | 标签词表 + 各自被用在多少条作品上(删之前能看清代价)。 | | |
|
||||
| `POST` | `/api/monitor/tags` | ✓ | Create Tag | | TagPayload |
|
||||
| `DELETE` | `/api/monitor/tags/{tag_id}` | ✓ | 删标签,连同它在所有作品上的贴纸。 | `tag_id`(path integer 必填) | |
|
||||
| `PUT` | `/api/monitor/tags/{tag_id}` | ✓ | Update Tag | `tag_id`(path integer 必填) | TagPayload |
|
||||
| `GET` | `/api/monitor/tasks` | ✓ | List Tasks | `platform`(query string \| null 可选) | |
|
||||
| `POST` | `/api/monitor/tasks` | ✓ | Create Task | | MonitorTaskCreate |
|
||||
| `DELETE` | `/api/monitor/tasks/{task_id}` | ✓ | Delete Task | `task_id`(path integer 必填) | |
|
||||
| `PATCH` | `/api/monitor/tasks/{task_id}` | ✓ | Update Task | `task_id`(path integer 必填) | MonitorTaskUpdate |
|
||||
| `POST` | `/api/monitor/tasks/{task_id}/run` | ✓ | Queue a run immediately and return; the crawl itself takes minutes. | `task_id`(path integer 必填) | |
|
||||
| `GET` | `/api/monitor/tasks/{task_id}/runs` | ✓ | List Runs | `task_id`(path integer 必填)<br>`limit`(query integer 可选=50) | |
|
||||
| `GET` | `/api/monitor/upstream` | ✓ | 最近一次上游检查的结果。 | | |
|
||||
| `POST` | `/api/monitor/upstream/check` | ✓ | 立刻检查一次上游仓库,并把结果写回缓存。 | | |
|
||||
| `DELETE` | `/api/monitor/webhook` | ✓ | Clear Webhook | | |
|
||||
| `GET` | `/api/monitor/webhook` | ✓ | Get Webhook | | |
|
||||
| `POST` | `/api/monitor/webhook` | ✓ | Set Webhook | | WebhookPayload |
|
||||
| `POST` | `/api/monitor/webhook/test` | ✓ | Send a test message so the user can verify the robot works before relying on it. | | WebhookTestPayload |
|
||||
|
||||
## 设置
|
||||
|
||||
| 方法 | 路径 | 登录 | 说明 | 参数 | 请求体 |
|
||||
|---|---|:--:|---|---|---|
|
||||
| `GET` | `/api/settings` | ✓ | Settings for one platform, plus the system-wide ones. | `platform`(query string 可选='xhs') | |
|
||||
| `PUT` | `/api/settings` | ✓ | Partial update: only the keys present in the body are written. | `platform`(query string 可选='xhs') | SettingsUpdatePayload |
|
||||
|
||||
## 请求体结构
|
||||
|
||||
### ChangePasswordPayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `current` | string | ✓ | | |
|
||||
| `new` | string | ✓ | | |
|
||||
|
||||
### CookiePayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `cookie` | string | ✓ | | |
|
||||
|
||||
### CrawlerStartRequest
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `platform` | PlatformEnum | ✓ | | |
|
||||
| `login_type` | LoginTypeEnum | | 'qrcode' | |
|
||||
| `crawler_type` | CrawlerTypeEnum | | 'search' | |
|
||||
| `keywords` | string | | '' | |
|
||||
| `specified_ids` | string | | '' | |
|
||||
| `creator_ids` | string | | '' | |
|
||||
| `start_page` | integer | | 1 | |
|
||||
| `enable_comments` | boolean | | True | |
|
||||
| `enable_sub_comments` | boolean | | False | |
|
||||
| `enable_media` | boolean | | False | |
|
||||
| `save_option` | SaveDataOptionEnum | | 'jsonl' | |
|
||||
| `cookies` | string | | '' | |
|
||||
| `headless` | boolean | | False | |
|
||||
| `max_notes_count` | integer \| null | | | |
|
||||
| `max_comments_count` | integer \| null | | | |
|
||||
| `save_data_path` | string \| null | | | |
|
||||
| `enable_cdp_mode` | boolean \| null | | | |
|
||||
| `inject_all_cookies` | boolean \| null | | | |
|
||||
| `save_login_state` | boolean \| null | | | |
|
||||
| `cookies_file` | string \| null | | | |
|
||||
| `max_concurrency_num` | integer \| null | | | |
|
||||
| `crawler_max_sleep_sec` | integer \| null | | | |
|
||||
| `enable_ip_proxy` | boolean \| null | | | |
|
||||
| `ip_proxy_pool_count` | integer \| null | | | |
|
||||
| `ip_proxy_provider_name` | string \| null | | | |
|
||||
| `static_proxy_url` | string \| null | | | |
|
||||
|
||||
### CreatorAliasPayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `alias` | string | | '' | |
|
||||
|
||||
### LoginPayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `password` | string | ✓ | | |
|
||||
|
||||
### MonitorTaskCreate
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `name` | string | ✓ | | |
|
||||
| `platform` | string | | 'xhs' | |
|
||||
| `mode` | string | ✓ | | |
|
||||
| `interval_minutes` | integer \| null | | | |
|
||||
| `schedule_mode` | string | | 'interval' | |
|
||||
| `schedule_hours` | integer[] | | | |
|
||||
| `schedule_days` | integer[] | | | |
|
||||
| `schedule_minute` | integer | | 0 | |
|
||||
| `max_notes_count` | integer \| null | | | |
|
||||
| `enable_comments` | boolean | | True | |
|
||||
| `max_comments_count` | integer \| null | | | |
|
||||
| `run_timeout_seconds` | integer | | 3600 | |
|
||||
| `enabled` | boolean | | True | |
|
||||
| `notify_enabled` | boolean | | False | |
|
||||
| `notify_failures` | boolean | | True | |
|
||||
| `targets` | string[] | ✓ | | |
|
||||
|
||||
### MonitorTaskUpdate
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `name` | string \| null | | | |
|
||||
| `enabled` | boolean \| null | | | |
|
||||
| `interval_minutes` | integer \| null | | | |
|
||||
| `schedule_mode` | string \| null | | | |
|
||||
| `schedule_hours` | integer[] \| null | | | |
|
||||
| `schedule_days` | integer[] \| null | | | |
|
||||
| `schedule_minute` | integer \| null | | | |
|
||||
| `max_notes_count` | integer \| null | | | |
|
||||
| `enable_comments` | boolean \| null | | | |
|
||||
| `max_comments_count` | integer \| null | | | |
|
||||
| `run_timeout_seconds` | integer \| null | | | |
|
||||
| `notify_enabled` | boolean \| null | | | |
|
||||
| `notify_failures` | boolean \| null | | | |
|
||||
| `targets` | string[] \| null | | | |
|
||||
|
||||
### NoteAliasPayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `alias` | string | | '' | |
|
||||
|
||||
### NoteTagsPayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `tag_ids` | integer[] | | | |
|
||||
|
||||
### SettingsUpdatePayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
|
||||
### TagPayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `name` | string | ✓ | | |
|
||||
| `color` | string | | '' | |
|
||||
|
||||
### WebhookPayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `url` | string | | '' | 企业微信机器人 Webhook 地址,留空表示停用 |
|
||||
|
||||
### WebhookTestPayload
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认 | 说明 |
|
||||
|---|---|:--:|---|---|
|
||||
| `url` | string \| null | | | 不传则使用已保存的地址 |
|
||||
|
||||
> **响应没有结构可列。** 这些接口返回的是普通 dict,没有声明 `response_model`,所以 OpenAPI 里没有响应的 shape。要看响应就调一次,或者读对应的 `service.py`。
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
# 监控层数据库表结构
|
||||
|
||||
`api/monitor/**` 这一层用到的全部表。库名 `mediacrawler_prod`(MySQL 5.7,utf8mb4)。
|
||||
|
||||
配套的原始 DDL 在 [`db-schema.sql`](./db-schema.sql) —— 那份是 `SHOW CREATE TABLE` 直接导的,
|
||||
含引擎、字符集和索引定义;本文是**带字段说明**的可读版。
|
||||
|
||||
> **这两份都不是迁移脚本。** 建表和补列是 `api/monitor/db.py::init_db()` 在每次启动时按 ORM
|
||||
> 元数据自动做的:`create_all` 建缺失的表,`_ensure_columns` 对已存在的表逐列 `ALTER TABLE
|
||||
> ADD COLUMN`(新增 NOT NULL 列会带上默认值给老行兜底)。所以加一个字段只需要改
|
||||
> `models.py`,不用手写 SQL。
|
||||
|
||||
---
|
||||
|
||||
## 读之前要知道的四条约定
|
||||
|
||||
1. **时间戳一律是毫秒**(`bigint`),由 `tools/time_util.get_current_timestamp()` 产生。
|
||||
平台给秒的(抖音是秒)在 `adapters.PlatformAdapter.time_scale` 里换算 —— 差 1000 倍,
|
||||
不换算的话 2026 年的作品会显示成 1970 年。
|
||||
2. **NULL 和 0 是两回事。** 指标、粉丝数这些「读不出来」的值一律存 **NULL,不存 0**:
|
||||
0 在趋势图上是一条砸到底的线,和「不知道」完全不同。界面上 NULL 显示成「—」。
|
||||
3. **平台 id 是 `xhs` / `dy`**(`api/monitor/adapters.py`)。注意 `dy` 是监控层的 id,
|
||||
爬虫落盘目录叫 `douyin` —— 两者不一致,靠 `adapters.artifact_dir()` 换算。
|
||||
4. **作品删除是从来不做的。** 掉出采集窗口的作品仍然留在库里(趋势图、报表、导出要用),
|
||||
只是界面不再显示。
|
||||
|
||||
---
|
||||
|
||||
## 表之间的关系
|
||||
|
||||
```
|
||||
monitor_task ─┬─< monitor_target 一个任务配若干个目标(博主 / 作品)
|
||||
├─< monitor_run 每次运行一条
|
||||
├─< monitor_note ──< monitor_note_metric
|
||||
└─< monitor_creator_stat
|
||||
|
||||
monitor_note ──┬── monitor_note_alias (按 platform + note_id 关联,不是外键)
|
||||
└── monitor_note_tag ──< monitor_tag
|
||||
|
||||
monitor_creator_alias (按 platform + creator_hash 关联)
|
||||
monitor_event 事件流,多数挂在 task / run 上
|
||||
monitor_setting 键值设置,独立
|
||||
```
|
||||
|
||||
有真正外键(`ON DELETE CASCADE`)的只有 `task_id`:`monitor_target` / `monitor_run` /
|
||||
`monitor_note` / `monitor_creator_stat` 都指向 `monitor_task`,删任务会一并带走。
|
||||
|
||||
其余关联**刻意不用外键**:它们跨的是「平台 + 业务 id」而不是主键,而且备注/标签是人为
|
||||
维护的,不该跟着采集数据被级联掉。
|
||||
|
||||
---
|
||||
|
||||
## monitor_task — 监控任务
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `name` | varchar(200) | 否 | 任务名,人起的 |
|
||||
| `platform` | varchar(32) | 否 | `xhs` / `dy` |
|
||||
| `mode` | varchar(16) | 否 | `creator` 博主模式 / `note` 作品模式 |
|
||||
| `enabled` | tinyint(1) | 否 | 是否参与定时调度 |
|
||||
| `interval_minutes` | int | 否 | 间隔模式的周期(分钟) |
|
||||
| `max_notes_count` | int | 否 | 每个博主每轮采多少条。**作品栏也按它开窗**(只画最新 N 条),但库里不删 |
|
||||
| `enable_comments` | tinyint(1) | 否 | 是否采评论 |
|
||||
| `max_comments_count` | int | 否 | 每条作品最多采多少条评论 |
|
||||
| `run_timeout_seconds` | int | 否 | 一轮的墙钟上限,超了判 `timeout` |
|
||||
| `notify_enabled` | tinyint(1) | 否 | 推送「有新作品」。默认**关**——可能每轮都有,会刷屏 |
|
||||
| `notify_failures` | tinyint(1) | 否 | 推送「出异常了」(登录失效 / 运行失败 / 没抓到数据)。默认**开** |
|
||||
| `schedule_mode` | varchar(16) | 否 | `interval` / `daily` / `weekly` |
|
||||
| `schedule_hours` | varchar(96) | 否 | `daily`/`weekly` 用:几点跑,逗号分隔,如 `9,18` |
|
||||
| `schedule_days` | varchar(32) | 否 | `weekly` 用:周几,**0 = 周一**(对齐 Python 的 `date.weekday()`) |
|
||||
| `schedule_minute` | int | 否 | 整点后的第几分钟,三个模式共用 |
|
||||
| `next_run_at` | bigint | 是 | 下次该跑的时刻。调度器就按这个字段挑任务 |
|
||||
| `last_run_at` | bigint | 是 | 上次运行的**开始**时刻(不是结束) |
|
||||
| `last_status` | varchar(32) | 否 | 上次运行状态,取值见 `monitor_run.status` |
|
||||
| `last_error` | text | 是 | 上次失败的原因,给人看的一句话 |
|
||||
| `last_notified_at` | bigint | 是 | **上次推送成功**的时刻。只在企业微信返回 `errcode=0` 之后才写 —— 所以「这个值是旧的」并不等于「没试过」,只说明没成功。目前它只是显示用的,并没有拿它做限流 |
|
||||
| `created_at` / `updated_at` | bigint | 否 | |
|
||||
|
||||
`schedule_hours` / `schedule_days` 存的是**逗号分隔的字符串**而不是关联表 —— 内容是几个
|
||||
小整数,单独建表只会让每次读取多一跳。
|
||||
|
||||
---
|
||||
|
||||
## monitor_target — 任务的目标
|
||||
|
||||
一个任务可以配多个博主(或作品)。
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `task_id` | int | 否 | → `monitor_task.id`,**级联删除** |
|
||||
| `kind` | varchar(16) | 否 | 等于任务的 `mode`:`creator` / `note` |
|
||||
| `external_id` | varchar(128) | 否 | 规范化后的 id。博主是 sec_uid(抖音)/ user_id(小红书),作品是 note_id |
|
||||
| `xsec_token` | varchar(512) | 否 | **只有小红书有**:分享链接里那个会过期的令牌。抖音恒为空串 |
|
||||
| `xsec_source` | varchar(64) | 否 | 同上,配套的 source 参数 |
|
||||
| `raw_value` | text | 否 | 用户当初粘进来的原文(URL 或裸 id),出问题时用来回溯 |
|
||||
| `label` | varchar(200) | 否 | 展示用的名字 |
|
||||
| `enabled` | tinyint(1) | 否 | 关掉的目标这一轮不采 |
|
||||
| `created_at` | bigint | 否 | |
|
||||
|
||||
**唯一键** `(task_id, kind, external_id)` —— 同一个目标粘两次不会变成两行。
|
||||
|
||||
---
|
||||
|
||||
## monitor_run — 每一次运行
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `task_id` | int | 否 | → `monitor_task.id`,级联删除 |
|
||||
| `trigger` | varchar(16) | 否 | `scheduled` 定时 / `manual` 手动 |
|
||||
| `status` | varchar(16) | 否 | `pending` 排队中、`running` 运行中、`success`、`partial` 部分成功、`failed`、`timeout`、`interrupted` 被中断 |
|
||||
| `phase` | varchar(16) | 否 | 建这条 run 时任务的 `mode`。任务中途改了模式,也还能知道当时跑的是什么 |
|
||||
| `save_data_path` | text | 否 | 这一轮产物的落盘目录 |
|
||||
| `queued_at` | bigint | 否 | 入队时刻 |
|
||||
| `not_before` | bigint | 否 | 在这之前不许开跑(错峰 / 防抖) |
|
||||
| `started_at` | bigint | 是 | 真正开跑的时刻 |
|
||||
| `finished_at` | bigint | 是 | 结束时刻 |
|
||||
| `exit_code` | bigint | 是 | 退出码。抖音走进程内 HTTP,值是 0 / 1;小红书走子进程。Windows 的进程崩溃会是大整数(NTSTATUS),`ingest.describe_exit_code()` 会翻译 |
|
||||
| `notes_fetched` | int | 否 | 这一轮**读到**多少条作品 |
|
||||
| `comments_fetched` | int | 否 | 读到多少条评论 |
|
||||
| `new_notes` | int | 否 | 其中多少条是**新的** |
|
||||
| `new_comments` | int | 否 | 同上 |
|
||||
| `is_baseline` | tinyint(1) | 否 | 是否该任务的**第一轮成功运行**。基线轮刻意不发增量事件 —— 没有「上一轮」可比,全报成新增只是噪音 |
|
||||
| `max_comments_count` | int | 否 | 跑的时候用的值快照。任务后来改了,历史记录仍然能解释得通 |
|
||||
| `error_message` | text | 是 | 失败原因 |
|
||||
|
||||
---
|
||||
|
||||
## monitor_note — 作品(笔记 / 视频)
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `task_id` | int | 否 | → `monitor_task.id`,级联删除 |
|
||||
| `note_id` | varchar(128) | 否 | 平台上的作品 id(抖音叫 `aweme_id`) |
|
||||
| `title` | text | 否 | 标题 / 文案 |
|
||||
| `note_url` | text | 否 | 作品页地址 |
|
||||
| `cover` | text | 否 | 封面。**优先是本地缓存地址** `/api/monitor/covers/{note_id}`——远程图床地址带签名、会过期(实测隔天 403),本地那份不会 |
|
||||
| `creator_hash` | varchar(64) | 否 | 创作者 id 的**单向哈希**。爬虫刻意不落原始 user_id,所以这是唯一稳定的创作者标识,作品栏按它分组 |
|
||||
| `creator_name` | varchar(200) | 否 | 创作者昵称(本仓库关掉了脱敏,是原文) |
|
||||
| `source_kind` | varchar(16) | 否 | 平台自己的作品类型:小红书取 `type`,抖音取 `aweme_type` |
|
||||
| `published_at` | bigint | 是 | **作者发布**的时间。和 `first_seen_at` 完全不是一回事——把早就发过的作品加进监控时,两者能差好几个月 |
|
||||
| `first_seen_run_id` | int | 是 | 第一次看到它是在哪一轮 |
|
||||
| `first_seen_at` | bigint | 否 | **我们第一次看到它**的时刻 |
|
||||
| `last_seen_run_id` | int | 是 | 最后一次采到它的轮次 |
|
||||
| `last_seen_at` | bigint | 否 | 最后一次采到它的时刻 |
|
||||
|
||||
**唯一键** `(task_id, note_id)` —— 同一件作品被两个任务同时监控就是两行,各算各的增量。
|
||||
|
||||
> 掉出采集窗口的作品**不会被删**。界面按 `max_notes_count` 开窗只画最新 N 条,而库里保留
|
||||
> 全部:趋势图、报表、导出读的都是这份全量。
|
||||
|
||||
---
|
||||
|
||||
## monitor_note_metric — 作品指标快照(趋势的来源)
|
||||
|
||||
一轮一条,作品的四项互动指标。
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `task_id` | int | 否 | 属于哪个任务 |
|
||||
| `note_id` | varchar(128) | 否 | 哪条作品 |
|
||||
| `run_id` | int | 否 | 哪一轮采的 |
|
||||
| `captured_at` | bigint | 否 | 采集时刻 |
|
||||
| `liked_count` | int | **是** | 点赞。**解析不出来就是 NULL,不是 0** |
|
||||
| `comment_count` | int | **是** | 评论 |
|
||||
| `collected_count` | int | **是** | 收藏 |
|
||||
| `share_count` | int | **是** | 分享 |
|
||||
| `raw_liked_count` | varchar(64) | 否 | 平台返回的**原文**(可能是 `1.2万`) |
|
||||
| `raw_comment_count` | varchar(64) | 否 | 同上 |
|
||||
| `raw_collected_count` | varchar(64) | 否 | 同上 |
|
||||
| `raw_share_count` | varchar(64) | 否 | 同上 |
|
||||
|
||||
**唯一键** `(task_id, note_id, run_id)`。
|
||||
|
||||
留 `raw_*` 四列是为了**事后可审计**:解析规则出问题时,原文还在,能重新算一遍。
|
||||
|
||||
---
|
||||
|
||||
## monitor_comment — 评论
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `task_id` | int | 否 | 属于哪个任务 |
|
||||
| `note_id` | varchar(128) | 否 | 评论挂在哪条作品下 |
|
||||
| `comment_id` | varchar(128) | 否 | 平台上的评论 id |
|
||||
| `content` | text | 否 | 评论正文 |
|
||||
| `nickname` | varchar(200) | 否 | 评论人昵称 |
|
||||
| `creator_hash` | varchar(64) | 否 | 评论人 id 的哈希 |
|
||||
| `create_time` | bigint | 是 | 评论发布时间 |
|
||||
| `like_count` | int | 是 | 这条评论的点赞 |
|
||||
| `sub_comment_count` | int | 否 | 子评论数。平台没给就是不填,**不猜** |
|
||||
| `parent_comment_id` | varchar(128) | 否 | 父评论 id。**顶层评论两边写法不同**:小红书是空串,抖音是 `"0"`——`adapters.parent_comment_id()` 会把 `"0"` 归一成空串 |
|
||||
| `first_seen_run_id` | int | 是 | 第一次见到是在哪一轮 |
|
||||
| `first_seen_at` | bigint | 否 | 第一次见到的时刻 |
|
||||
|
||||
**唯一键** `(task_id, note_id, comment_id)`。
|
||||
|
||||
> 评论接口**没有时间排序**,只能看到平台默认顺序下的前 N 条。所以第一次见到的评论分成
|
||||
> 「上一轮之后发的」和「第一次见到的」两类事件,而不是一口咬定都是新发的。
|
||||
|
||||
---
|
||||
|
||||
## monitor_creator_stat — 博主账号级快照
|
||||
|
||||
一门一个人:粉丝数 / 总获赞 / 作品数。这是**作品列表给不了**的东西 —— 作品说的是「这条涨了
|
||||
多少赞」,这里说的是「这个人整个账号在涨还是在掉」。
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `task_id` | int | 否 | → `monitor_task.id`,级联删除 |
|
||||
| `run_id` | int | 否 | 哪一轮采的 |
|
||||
| `creator_hash` | varchar(64) | 否 | 博主哈希(和 `monitor_note.creator_hash` 同一个口径) |
|
||||
| `nickname` | varchar(128) | 否 | 昵称 |
|
||||
| `creator_id` | varchar(128) | 否 | **平台上的主页 id**(抖音是 sec_uid)。用来拼「跳到他主页」的链接——哈希是单向的,拼不出地址 |
|
||||
| `fans` | bigint | **是** | 粉丝数 |
|
||||
| `total_favorited` | bigint | **是** | 总获赞 |
|
||||
| `works_count` | bigint | **是** | 主页作品总数(和我们监控到的条数不是一回事) |
|
||||
| `following` | bigint | **是** | 关注数 |
|
||||
| `captured_at` | bigint | 否 | 采集时刻 |
|
||||
|
||||
**唯一键** `(task_id, creator_hash, run_id)`。
|
||||
|
||||
> **目前只有抖音会写这张表。** 小红书走的是爬虫子进程,而它的 `save_creator()` 在教学版里
|
||||
> 是空函数,从来没落过创作者资料。所以小红书的博主没有粉丝数,也没有主页链接。
|
||||
|
||||
---
|
||||
|
||||
## monitor_creator_alias — 博主备注
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `platform` | varchar(16) | 否 | `xhs` / `dy` |
|
||||
| `creator_hash` | varchar(64) | 否 | 哪个博主 |
|
||||
| `alias` | varchar(128) | 否 | 人自己起的名字(「竞品A」)。空串表示没起过 |
|
||||
| `updated_at` | bigint | 否 | |
|
||||
|
||||
**唯一键** `(platform, creator_hash)` —— 同一个博主出现在多个任务里,备注只填一次。
|
||||
|
||||
作品栏按 `creator_hash` 分组,可那是个哈希、昵称又常常认不出是谁;备注是唯一能把账号对上
|
||||
人的东西。
|
||||
|
||||
---
|
||||
|
||||
## monitor_note_alias — 作品备注
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `platform` | varchar(16) | 否 | `xhs` / `dy` |
|
||||
| `note_id` | varchar(128) | 否 | 哪条作品 |
|
||||
| `alias` | varchar(128) | 否 | 一句话的备注 |
|
||||
| `updated_at` | bigint | 否 | |
|
||||
|
||||
**唯一键** `(platform, note_id)`。
|
||||
|
||||
和博主备注是一对,但回答的不是同一个问题:博主备注回答「这个账号是谁」,作品备注回答
|
||||
「这条我要盯着」。一个博主底下常常只有一两件值得盯的,所以不能合并。
|
||||
|
||||
---
|
||||
|
||||
## monitor_tag — 标签词表
|
||||
|
||||
在「设置 → 作品标签」里维护。**全局一套,不按平台分**——「重点」是给人自己用的心智,不该在
|
||||
小红书和抖音各定义一遍。
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `name` | varchar(32) | 否 | 标签名 |
|
||||
| `color` | varchar(16) | 否 | **调色板里的名字**:`cyan`/`pink`/`green`/`orange`/`muted`。不是色值——Tailwind 的类名是构建时静态提取的,拼出来的动态类名它看不见,线上会静默变无色 |
|
||||
| `sort_order` | int | 否 | 展示顺序。新建时取 `max+1` 而不是 `count`:删过标签之后 count 会撞上已有的值 |
|
||||
| `created_at` | bigint | 否 | |
|
||||
|
||||
**唯一键** `(name)` —— 两个「重点」在筛选列表里是灾难,选哪个都像对的。
|
||||
|
||||
---
|
||||
|
||||
## monitor_note_tag — 作品 ↔ 标签
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `platform` | varchar(16) | 否 | `xhs` / `dy` |
|
||||
| `note_id` | varchar(128) | 否 | 哪条作品 |
|
||||
| `tag_id` | int | 否 | → 逻辑上指向 `monitor_tag.id`,**但没有外键**(见下) |
|
||||
| `created_at` | bigint | 否 | |
|
||||
|
||||
**唯一键** `(platform, note_id, tag_id)` —— **多对多**:一条作品可以既是「重点」又是「竞品」。
|
||||
|
||||
> 删标签时**显式删关联**,不依赖外键级联:测试跑的是 SQLite,而它默认不启用外键约束。
|
||||
> 靠级联的话会出现「测试全绿、线上才对」或者反过来的情况。
|
||||
|
||||
标签和备注并存、不是一回事:备注是一句话的**自由文字**,标签是**封闭词表里的分类**。分类
|
||||
必须封闭,否则「重点/重要/优先」各写各的,筛选就没法用了。
|
||||
|
||||
---
|
||||
|
||||
## monitor_event — 变化事件
|
||||
|
||||
界面上的「变化」列表和企业微信推送读的都是它。
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `id` | int | 否 | 主键 |
|
||||
| `task_id` | int | 否 | 属于哪个任务 |
|
||||
| `run_id` | int | 是 | 由哪一轮产生 |
|
||||
| `type` | varchar(32) | 否 | 见下表 |
|
||||
| `severity` | varchar(16) | 否 | `info` / `warning` / `error` |
|
||||
| `target_kind` | varchar(16) | 否 | 目前只有两种值:作品级的事件写 `note`,任务级的事件(运行失败 / 疑似登录失效 / 没抓到数据)留**空串** |
|
||||
| `target_id` | varchar(128) | 否 | 对象 id —— 作品级的是作品 id(note_id / aweme_id),任务级的是空串 |
|
||||
| `title` | text | 否 | 一句话。推送和列表里显示的就是它 |
|
||||
| `payload_json` | text | 否 | 结构化细节(增量数值、退出码、失败原因…) |
|
||||
| `created_at` | bigint | 否 | |
|
||||
| `is_read` | tinyint(1) | 否 | 未读数就是按它统计的 |
|
||||
|
||||
`type` 的取值:
|
||||
|
||||
| 值 | 含义 |
|
||||
|---|---|
|
||||
| `new_note` | 发现新作品 |
|
||||
| `new_comment_posted` | 上一轮之后**发布**的评论 |
|
||||
| `new_comment_seen` | 第一次见到的评论(未必是刚发的,见评论那节的说明) |
|
||||
| `metric_delta` | 指标有明显变化 |
|
||||
| `run_failed` | 运行失败 |
|
||||
| `suspected_auth_failure` | 疑似登录失效(一条都没抓到,且没有别的解释) |
|
||||
| `no_data_found` | 没抓到数据,但原因不是登录(比如产物写在别的目录) |
|
||||
|
||||
---
|
||||
|
||||
## monitor_setting — 键值设置
|
||||
|
||||
| 字段 | 类型 | 空 | 说明 |
|
||||
|---|---|:--:|---|
|
||||
| `key` | varchar(64) | 否 | 主键。两种形状:`platform.<平台>.<名字>` / `system.<名字>` |
|
||||
| `value` | text | 否 | **一律存字符串**,读的时候按注册表里的类型转 |
|
||||
| `updated_at` | bigint | 否 | |
|
||||
|
||||
哪些 key 合法、各是什么类型/默认值,由 `api/monitor/app_settings.py` 的注册表决定 —— 设置页
|
||||
的表单就是照它自动生成的。密钥类的设置(webhook 地址、cookie)存进来但**从不原样返回**给
|
||||
前端,只回「有没有设置」和长度。
|
||||
@@ -0,0 +1,242 @@
|
||||
-- MediaCrawler 监控层 —— 生产库表结构快照
|
||||
--
|
||||
-- 从 192.168.20.220 上的 mediacrawler_prod 里 SHOW CREATE TABLE 导出来的,
|
||||
-- 2026-10-11。**这是一份快照**,不是迁移脚本 —— 真正的建表/改列由
|
||||
-- api/monitor/db.py::init_db() 在启动时按 ORM 元数据自动完成(create_all 建缺失的
|
||||
-- 表,_ensure_columns 补缺失的列)。
|
||||
--
|
||||
-- 要看最新的,重新导一遍就行:
|
||||
-- docker compose exec -T mediacrawler python -c \
|
||||
-- 'import asyncio;from sqlalchemy import text;from api.monitor.db import get_session;
|
||||
-- ...' # 见 docs/db-schema.sql 的生成方式,或问 Claude
|
||||
--
|
||||
|
||||
|
||||
CREATE TABLE `monitor_comment` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`task_id` int(11) NOT NULL,
|
||||
`note_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`comment_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`content` text COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`nickname` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`creator_hash` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`create_time` bigint(20) DEFAULT NULL,
|
||||
`like_count` int(11) DEFAULT NULL,
|
||||
`sub_comment_count` int(11) NOT NULL,
|
||||
`parent_comment_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`first_seen_run_id` int(11) DEFAULT NULL,
|
||||
`first_seen_at` bigint(20) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uq_monitor_comment` (`task_id`,`note_id`,`comment_id`),
|
||||
KEY `ix_monitor_comment_task_id` (`task_id`),
|
||||
KEY `ix_monitor_comment_note_id` (`note_id`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=287 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_creator_alias` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`platform` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`creator_hash` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`alias` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`updated_at` bigint(20) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uq_creator_alias` (`platform`,`creator_hash`),
|
||||
KEY `ix_monitor_creator_alias_platform` (`platform`),
|
||||
KEY `ix_monitor_creator_alias_creator_hash` (`creator_hash`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_creator_stat` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`task_id` int(11) NOT NULL,
|
||||
`run_id` int(11) NOT NULL,
|
||||
`creator_hash` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`nickname` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`fans` bigint(20) DEFAULT NULL,
|
||||
`total_favorited` bigint(20) DEFAULT NULL,
|
||||
`works_count` bigint(20) DEFAULT NULL,
|
||||
`following` bigint(20) DEFAULT NULL,
|
||||
`captured_at` bigint(20) NOT NULL,
|
||||
`creator_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uq_creator_stat` (`task_id`,`creator_hash`,`run_id`),
|
||||
KEY `ix_monitor_creator_stat_task_id` (`task_id`),
|
||||
KEY `ix_monitor_creator_stat_captured_at` (`captured_at`),
|
||||
KEY `ix_monitor_creator_stat_creator_hash` (`creator_hash`),
|
||||
KEY `ix_monitor_creator_stat_run_id` (`run_id`),
|
||||
CONSTRAINT `monitor_creator_stat_ibfk_1` FOREIGN KEY (`task_id`) REFERENCES `monitor_task` (`id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=90 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_event` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`task_id` int(11) NOT NULL,
|
||||
`run_id` int(11) DEFAULT NULL,
|
||||
`type` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`severity` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`target_kind` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`target_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`title` text COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`payload_json` text COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`created_at` bigint(20) NOT NULL,
|
||||
`is_read` tinyint(1) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `ix_monitor_event_type` (`type`),
|
||||
KEY `ix_monitor_event_task_id` (`task_id`),
|
||||
KEY `ix_monitor_event_run_id` (`run_id`),
|
||||
KEY `ix_monitor_event_created_at` (`created_at`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=380 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_note` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`task_id` int(11) NOT NULL,
|
||||
`note_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`title` text COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`note_url` text COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`cover` text COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`creator_hash` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`source_kind` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`published_at` bigint(20) DEFAULT NULL,
|
||||
`first_seen_run_id` int(11) DEFAULT NULL,
|
||||
`first_seen_at` bigint(20) NOT NULL,
|
||||
`last_seen_run_id` int(11) DEFAULT NULL,
|
||||
`last_seen_at` bigint(20) NOT NULL,
|
||||
`creator_name` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uq_monitor_note` (`task_id`,`note_id`),
|
||||
KEY `ix_monitor_note_task_id` (`task_id`),
|
||||
KEY `ix_monitor_note_note_id` (`note_id`),
|
||||
CONSTRAINT `monitor_note_ibfk_1` FOREIGN KEY (`task_id`) REFERENCES `monitor_task` (`id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=192 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_note_alias` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`platform` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`note_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`alias` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`updated_at` bigint(20) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uq_note_alias` (`platform`,`note_id`),
|
||||
KEY `ix_monitor_note_alias_note_id` (`note_id`),
|
||||
KEY `ix_monitor_note_alias_platform` (`platform`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_note_metric` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`task_id` int(11) NOT NULL,
|
||||
`note_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`run_id` int(11) NOT NULL,
|
||||
`captured_at` bigint(20) NOT NULL,
|
||||
`liked_count` int(11) DEFAULT NULL,
|
||||
`comment_count` int(11) DEFAULT NULL,
|
||||
`collected_count` int(11) DEFAULT NULL,
|
||||
`share_count` int(11) DEFAULT NULL,
|
||||
`raw_liked_count` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`raw_comment_count` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`raw_collected_count` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`raw_share_count` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uq_note_metric` (`task_id`,`note_id`,`run_id`),
|
||||
KEY `ix_monitor_note_metric_task_id` (`task_id`),
|
||||
KEY `ix_monitor_note_metric_note_id` (`note_id`),
|
||||
KEY `ix_monitor_note_metric_run_id` (`run_id`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=404 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_note_tag` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`platform` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`note_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`tag_id` int(11) NOT NULL,
|
||||
`created_at` bigint(20) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uq_note_tag` (`platform`,`note_id`,`tag_id`),
|
||||
KEY `ix_monitor_note_tag_note_id` (`note_id`),
|
||||
KEY `ix_monitor_note_tag_tag_id` (`tag_id`),
|
||||
KEY `ix_monitor_note_tag_platform` (`platform`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_run` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`task_id` int(11) NOT NULL,
|
||||
`trigger` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`status` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`phase` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`save_data_path` text COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`queued_at` bigint(20) NOT NULL,
|
||||
`not_before` bigint(20) NOT NULL,
|
||||
`started_at` bigint(20) DEFAULT NULL,
|
||||
`finished_at` bigint(20) DEFAULT NULL,
|
||||
`exit_code` bigint(20) DEFAULT NULL,
|
||||
`notes_fetched` int(11) NOT NULL,
|
||||
`comments_fetched` int(11) NOT NULL,
|
||||
`new_notes` int(11) NOT NULL,
|
||||
`new_comments` int(11) NOT NULL,
|
||||
`is_baseline` tinyint(1) NOT NULL,
|
||||
`max_comments_count` int(11) NOT NULL,
|
||||
`error_message` text COLLATE utf8mb4_unicode_ci,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `ix_monitor_run_status` (`status`),
|
||||
KEY `ix_monitor_run_task_id` (`task_id`),
|
||||
CONSTRAINT `monitor_run_ibfk_1` FOREIGN KEY (`task_id`) REFERENCES `monitor_task` (`id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_setting` (
|
||||
`key` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`value` text COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`updated_at` bigint(20) NOT NULL,
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_tag` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`color` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`sort_order` int(11) NOT NULL,
|
||||
`created_at` bigint(20) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uq_tag_name` (`name`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_target` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`task_id` int(11) NOT NULL,
|
||||
`kind` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`external_id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`xsec_token` varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`xsec_source` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`raw_value` text COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`label` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`enabled` tinyint(1) NOT NULL,
|
||||
`created_at` bigint(20) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uq_monitor_target` (`task_id`,`kind`,`external_id`),
|
||||
KEY `ix_monitor_target_task_id` (`task_id`),
|
||||
CONSTRAINT `monitor_target_ibfk_1` FOREIGN KEY (`task_id`) REFERENCES `monitor_task` (`id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `monitor_task` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`platform` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`mode` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`enabled` tinyint(1) NOT NULL,
|
||||
`interval_minutes` int(11) NOT NULL,
|
||||
`max_notes_count` int(11) NOT NULL,
|
||||
`enable_comments` tinyint(1) NOT NULL,
|
||||
`max_comments_count` int(11) NOT NULL,
|
||||
`run_timeout_seconds` int(11) NOT NULL,
|
||||
`notify_enabled` tinyint(1) NOT NULL,
|
||||
`next_run_at` bigint(20) DEFAULT NULL,
|
||||
`last_run_at` bigint(20) DEFAULT NULL,
|
||||
`last_status` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`last_error` text COLLATE utf8mb4_unicode_ci,
|
||||
`last_notified_at` bigint(20) DEFAULT NULL,
|
||||
`created_at` bigint(20) NOT NULL,
|
||||
`updated_at` bigint(20) NOT NULL,
|
||||
`schedule_mode` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'interval',
|
||||
`schedule_hours` varchar(96) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
|
||||
`schedule_days` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
|
||||
`schedule_minute` int(11) NOT NULL DEFAULT '0',
|
||||
`notify_failures` tinyint(1) NOT NULL DEFAULT '1',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `ix_monitor_task_next_run_at` (`next_run_at`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
--- stderr ---
|
||||
@@ -0,0 +1,275 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""从 FastAPI 自己的 OpenAPI schema 生成 docs/api.md。
|
||||
|
||||
**为什么是生成的而不是手写的**:手写的接口文档,从改代码的那天起就开始腐烂,而且烂得
|
||||
无声无息 —— 读者还会以为它是对的。这份每次跑一遍就是最新的。
|
||||
|
||||
./.venv/Scripts/python.exe docs/gen_api_doc.py # Windows
|
||||
python docs/gen_api_doc.py # 服务器/容器里
|
||||
|
||||
注意这个脚本**只读** app 对象,不连数据库、不起服务。
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
# 让脚本能从仓库根目录跑起来(它自己不在根目录)。
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
||||
|
||||
from api.main import app # noqa: E402
|
||||
|
||||
OUTPUT = pathlib.Path(__file__).resolve().parent / "api.md"
|
||||
|
||||
# **不能从 schema 里读出鉴权** —— `require_auth` 是个普通依赖,不是 security scheme,
|
||||
# 所以它不会出现在 OpenAPI 的 security 字段里。这份名单是照 api/routers/ 里实际写的
|
||||
# `dependencies=[Depends(require_auth)]` 核出来的:
|
||||
#
|
||||
# * auth 那一组整体**不加** require_auth(登录本身就不能要求先登录),但组里
|
||||
# /me 和 /password 各自另有保护 —— 所以不能按「组」一刀切。
|
||||
# * 其它五个 router 都在 include_router 上统一挂了 require_auth。
|
||||
PUBLIC_PATHS = {
|
||||
"/api/auth/login", # 登录本身
|
||||
"/api/auth/logout", # 清了 cookie 就完事,没有会话也能调
|
||||
}
|
||||
|
||||
TAG_TITLES = {
|
||||
"auth": "认证",
|
||||
"crawler": "采集",
|
||||
"creator": "运营(博主账号)",
|
||||
"data": "数据",
|
||||
"monitor": "监控",
|
||||
"settings": "设置",
|
||||
}
|
||||
|
||||
TAG_ORDER = ["auth", "crawler", "creator", "data", "monitor", "settings"]
|
||||
|
||||
JSON_METHODS = {"post", "put", "patch"}
|
||||
|
||||
BACKSLASH = chr(92)
|
||||
PIPE = "|"
|
||||
|
||||
|
||||
def first_paragraph(text: str) -> str:
|
||||
"""文档字符串的第一段 —— 整篇塞进去会把接口清单淹掉。"""
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
return text.split("\n\n")[0].strip()
|
||||
|
||||
|
||||
def describe_schema(schema: dict, spec: dict) -> str:
|
||||
"""把一个 schema 说成人话:引用就展开名字,数组说成「数组」。"""
|
||||
if not schema:
|
||||
return ""
|
||||
if "$ref" in schema:
|
||||
return schema["$ref"].rsplit("/", 1)[-1]
|
||||
kind = schema.get("type", "")
|
||||
if kind == "array":
|
||||
inner = describe_schema(schema.get("items", {}), spec)
|
||||
return f"{inner}[]"
|
||||
if kind == "object":
|
||||
props = schema.get("properties") or {}
|
||||
return "{" + ", ".join(props.keys()) + "}" if props else "object"
|
||||
if schema.get("anyOf") or schema.get("allOf"):
|
||||
variants = schema.get("anyOf") or schema.get("allOf")
|
||||
return " | ".join(filter(None, (describe_schema(v, spec) for v in variants)))
|
||||
return kind or "?"
|
||||
|
||||
|
||||
def param_cell(params: list, spec: dict) -> str:
|
||||
if not params:
|
||||
return ""
|
||||
parts = []
|
||||
for param in params:
|
||||
name = param["name"]
|
||||
where = param["in"]
|
||||
kind = describe_schema(param.get("schema", {}), spec)
|
||||
required = "必填" if param.get("required") else "可选"
|
||||
default = param.get("schema", {}).get("default")
|
||||
suffix = f"={default!r}" if default is not None else ""
|
||||
# 查询参数是前端最常搞错的地方,标出来。
|
||||
parts.append(f"`{name}`({where} {kind} {required}{suffix})")
|
||||
return "<br>".join(parts).replace("|", "\\|")
|
||||
|
||||
|
||||
def body_cell(op: dict, spec: dict) -> str:
|
||||
body = op.get("requestBody")
|
||||
if not body:
|
||||
return ""
|
||||
content = body.get("content", {})
|
||||
schema = content.get("application/json", {}).get("schema", {})
|
||||
# anyOf 会拼出 `integer | null` 这种,竖线不转义就会把这行切成两格。
|
||||
return describe_schema(schema, spec).replace("|", "\\|")
|
||||
|
||||
|
||||
def render() -> str:
|
||||
spec = app.openapi()
|
||||
paths = spec["paths"]
|
||||
|
||||
by_tag: dict[str, list] = {}
|
||||
for path, operations in paths.items():
|
||||
for method, op in operations.items():
|
||||
if method not in ("get", "post", "put", "patch", "delete"):
|
||||
continue
|
||||
tag = (op.get("tags") or ["其他"])[0]
|
||||
by_tag.setdefault(tag, []).append((path, method, op))
|
||||
|
||||
lines: list[str] = []
|
||||
lines.append("# API 接口清单")
|
||||
lines.append("")
|
||||
lines.append("从 FastAPI 自己的 OpenAPI schema 生成的,**不是手写的** ——")
|
||||
lines.append("手写的接口文档从改代码那天起就开始腐烂,而且烂得无声无息。")
|
||||
lines.append("")
|
||||
lines.append("重新生成:")
|
||||
lines.append("")
|
||||
lines.append("```bash")
|
||||
lines.append("./.venv/Scripts/python.exe docs/gen_api_doc.py")
|
||||
lines.append("```")
|
||||
lines.append("")
|
||||
lines.append("## 通用约定")
|
||||
lines.append("")
|
||||
lines.append("| | |")
|
||||
lines.append("|---|---|")
|
||||
lines.append("| 前缀 | 所有接口都在 `/api` 下(WebSocket 是 `/api/ws/...`)|")
|
||||
lines.append(
|
||||
"| 鉴权 | **Cookie 优先,Bearer 次之**:`token_from_request()` 先读会话 Cookie,"
|
||||
"读不到再读 `Authorization: Bearer <token>`。浏览器用 Cookie,脚本用 Bearer |"
|
||||
)
|
||||
lines.append(
|
||||
"| 会话怎么来 | `POST /api/auth/login`(密码),响应种下会话 Cookie;"
|
||||
"有效期由服务端 `resolve_session()` 判定 |"
|
||||
)
|
||||
lines.append("| 错误形状 | FastAPI 默认的 `{\"detail\": \"...\"}`;401 是登录失效 |")
|
||||
lines.append(
|
||||
"| **没有 `/docs`** | 特意关掉的:`/docs`、`/redoc`、`/openapi.json` 默认"
|
||||
"**不需要登录**,等于把整份接口地图连同「Try it out」一起送出去。要看交互式的,"
|
||||
"得挂在鉴权后面 |"
|
||||
)
|
||||
lines.append(
|
||||
"| WebSocket | `GET /api/ws/logs`(升级为 ws)—— 实时日志流。**不在这里的清单里**:"
|
||||
"OpenAPI 描述不了 WebSocket。它自己用 `require_ws_auth` 校验会话 Cookie |"
|
||||
)
|
||||
lines.append("")
|
||||
lines.append("## 目录")
|
||||
lines.append("")
|
||||
for tag in TAG_ORDER:
|
||||
if tag in by_tag:
|
||||
title = TAG_TITLES.get(tag, tag)
|
||||
lines.append(f"- [{title}](#{title})({len(by_tag[tag])} 个)")
|
||||
lines.append("")
|
||||
|
||||
for tag in TAG_ORDER:
|
||||
if tag not in by_tag:
|
||||
continue
|
||||
title = TAG_TITLES.get(tag, tag)
|
||||
lines.append(f"## {title}")
|
||||
lines.append("")
|
||||
if tag == "auth":
|
||||
lines.append(
|
||||
"这一组**没有**统一挂 `require_auth`(登录不能要求先登录),所以逐个标。"
|
||||
)
|
||||
lines.append("")
|
||||
lines.append("| 方法 | 路径 | 登录 | 说明 | 参数 | 请求体 |")
|
||||
lines.append("|---|---|:--:|---|---|---|")
|
||||
for path, method, op in sorted(by_tag[tag], key=lambda item: (item[0], item[1])):
|
||||
summary = first_paragraph(op.get("description") or op.get("summary") or "")
|
||||
# 表格单元格里的换行/竖线会把表格撑破。
|
||||
summary = summary.replace("\n", " ").replace("|", "\\|")
|
||||
params = [p for p in op.get("parameters", []) if p["in"] != "header"]
|
||||
lines.append(
|
||||
"| `{}` | `{}` | {} | {} | {} | {} |".format(
|
||||
method.upper(),
|
||||
path,
|
||||
"—" if path in PUBLIC_PATHS else "✓",
|
||||
summary,
|
||||
param_cell(params, spec),
|
||||
body_cell(op, spec),
|
||||
)
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
# ---- 附录:请求体长什么样 ------------------------------------------------
|
||||
#
|
||||
# 上面那些接口的「请求体」列只写了 schema 的名字,不写字段的话等于没说。
|
||||
used = set()
|
||||
for operations in paths.values():
|
||||
for method, op in operations.items():
|
||||
if method in JSON_METHODS:
|
||||
body = op.get("requestBody")
|
||||
if body:
|
||||
name = describe_schema(
|
||||
body.get("content", {}).get("application/json", {}).get("schema", {}),
|
||||
spec,
|
||||
)
|
||||
if name:
|
||||
used.add(name)
|
||||
|
||||
schemas = spec.get("components", {}).get("schemas", {})
|
||||
if used:
|
||||
lines.append("## 请求体结构")
|
||||
lines.append("")
|
||||
for name in sorted(used):
|
||||
schema = schemas.get(name)
|
||||
if not schema:
|
||||
continue
|
||||
lines.append(f"### {name}")
|
||||
lines.append("")
|
||||
lines.append("| 字段 | 类型 | 必填 | 默认 | 说明 |")
|
||||
lines.append("|---|---|:--:|---|---|")
|
||||
required = set(schema.get("required") or [])
|
||||
for field, prop in (schema.get("properties") or {}).items():
|
||||
kind = describe_schema(prop, spec).replace("|", "\\|")
|
||||
default = prop.get("default")
|
||||
desc = (prop.get("description") or "").replace("\n", " ").replace("|", "\\|")
|
||||
lines.append(
|
||||
"| `{}` | {} | {} | {} | {} |".format(
|
||||
field,
|
||||
kind,
|
||||
"✓" if field in required else "",
|
||||
"" if default is None else repr(default),
|
||||
desc,
|
||||
)
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
lines.append(
|
||||
"> **响应没有结构可列。** 这些接口返回的是普通 dict,没有声明 "
|
||||
"`response_model`,所以 OpenAPI 里没有响应的 shape。要看响应就调一次,"
|
||||
"或者读对应的 `service.py`。"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def check_tables(text: str) -> None:
|
||||
"""生成完顺手验一遍表格。
|
||||
|
||||
一个没转义的竖线就能把整张表切歪 —— 而 markdown 不会报错,它只是安静地多出一格。
|
||||
参数类型里的 `integer | null` 到处都是,所以这不是假想的风险。
|
||||
"""
|
||||
escaped = BACKSLASH + PIPE
|
||||
sentinel = "\x00"
|
||||
expected = {2, 5, 6} # 约定表 2、请求体表 5、接口表 6
|
||||
bad = []
|
||||
|
||||
for number, line in enumerate(text.splitlines(), 1):
|
||||
if not line.lstrip().startswith(PIPE):
|
||||
continue
|
||||
cells = line.strip().replace(escaped, sentinel).split(PIPE)[1:-1]
|
||||
if len(cells) not in expected:
|
||||
bad.append((number, len(cells), line[:70]))
|
||||
|
||||
if bad:
|
||||
for number, count, snippet in bad[:5]:
|
||||
print(f" 第 {number} 行有 {count} 格(预期 {sorted(expected)}): {snippet}")
|
||||
raise SystemExit("生成的表格结构不对,先修转义")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
text = render()
|
||||
check_tables(text)
|
||||
OUTPUT.write_text(text, encoding="utf-8")
|
||||
print(f"写出 {OUTPUT}({len(text.splitlines())} 行)")
|
||||
@@ -0,0 +1,122 @@
|
||||
-- 抖音账号日报:今天的账号情况 + 与昨天比对 + 推送有没有发出去
|
||||
--
|
||||
-- 分两段,因为它们是**两个维度**,硬塞进一张表会难看:
|
||||
--
|
||||
-- 【一】账号维度:每个博主一行,今天的账号指标、相对昨天的增减、今天的作品情况。
|
||||
-- 【二】任务维度:推送到底有没有发出去,以及从上次成功之后漏了几次。
|
||||
--
|
||||
-- 口径说明:
|
||||
-- * 「今天」= 该博主**最新一条**账号快照;「昨天」= 最新一条**日期早于今天**的快照。
|
||||
-- 快照是一轮一条(任务一天跑好几轮),所以按日期取,不按轮次。
|
||||
-- * 差值为 NULL 表示**没有可比的昨天**(昨天没跑或没采到这个号),不是 0。
|
||||
-- * 时间戳是毫秒,日期换算统一走 FROM_UNIXTIME(x/1000)。
|
||||
-- * MySQL 5.7 没有窗口函数,所以「最新一条」还是相关子查询。
|
||||
|
||||
-- ===========================================================================
|
||||
-- 【一】账号日报
|
||||
-- ===========================================================================
|
||||
SELECT
|
||||
al.alias AS 博主备注,
|
||||
COALESCE(cur.nickname, yest.nickname, '') AS 博主昵称,
|
||||
cur.fans AS 粉丝数,
|
||||
cur.fans - yest.fans AS 粉丝增减,
|
||||
cur.total_favorited AS 总获赞,
|
||||
cur.total_favorited - yest.total_favorited AS 获赞增减,
|
||||
cur.works_count AS 主页作品数,
|
||||
cur.works_count - yest.works_count AS 作品数增减,
|
||||
(SELECT COUNT(*) FROM monitor_note n
|
||||
JOIN monitor_task tn ON tn.id = n.task_id
|
||||
WHERE tn.platform = 'dy' AND n.creator_hash = base.creator_hash) AS 监控中作品,
|
||||
(SELECT COUNT(*) FROM monitor_note n
|
||||
JOIN monitor_task tn ON tn.id = n.task_id
|
||||
WHERE tn.platform = 'dy' AND n.creator_hash = base.creator_hash
|
||||
AND n.first_seen_at >= UNIX_TIMESTAMP(CURDATE()) * 1000) AS 今日新采到,
|
||||
FROM_UNIXTIME((SELECT MAX(n.published_at) FROM monitor_note n
|
||||
JOIN monitor_task tn ON tn.id = n.task_id
|
||||
WHERE tn.platform = 'dy'
|
||||
AND n.creator_hash = base.creator_hash) / 1000) AS 最近作品发布,
|
||||
FROM_UNIXTIME(cur.captured_at / 1000) AS 最近快照,
|
||||
CASE WHEN yest.id IS NULL THEN '昨天无快照' ELSE '有' END AS 昨日可比
|
||||
FROM (
|
||||
-- 账号清单:作品里出现过的 ∪ 有账号资料的(含一条作品都没有的号)
|
||||
SELECT n1.creator_hash FROM monitor_note n1
|
||||
JOIN monitor_task t1 ON t1.id = n1.task_id WHERE t1.platform = 'dy'
|
||||
UNION
|
||||
SELECT s1.creator_hash FROM monitor_creator_stat s1
|
||||
JOIN monitor_task t2 ON t2.id = s1.task_id WHERE t2.platform = 'dy'
|
||||
) base
|
||||
-- 今天(最新一条快照)
|
||||
LEFT JOIN monitor_creator_stat cur
|
||||
ON cur.id = (SELECT s.id FROM monitor_creator_stat s
|
||||
JOIN monitor_task t3 ON t3.id = s.task_id
|
||||
WHERE t3.platform = 'dy' AND s.creator_hash = base.creator_hash
|
||||
ORDER BY s.captured_at DESC, s.id DESC LIMIT 1)
|
||||
-- 昨天(最新一条日期早于今天的快照)
|
||||
LEFT JOIN monitor_creator_stat yest
|
||||
ON yest.id = (SELECT s.id FROM monitor_creator_stat s
|
||||
JOIN monitor_task t4 ON t4.id = s.task_id
|
||||
WHERE t4.platform = 'dy' AND s.creator_hash = base.creator_hash
|
||||
AND DATE(FROM_UNIXTIME(s.captured_at / 1000)) < CURDATE()
|
||||
ORDER BY s.captured_at DESC, s.id DESC LIMIT 1)
|
||||
LEFT JOIN monitor_creator_alias al
|
||||
ON al.platform = 'dy' AND al.creator_hash = base.creator_hash
|
||||
ORDER BY (cur.fans - yest.fans) IS NULL, cur.fans - yest.fans DESC, cur.fans DESC;
|
||||
|
||||
|
||||
-- ===========================================================================
|
||||
-- 【二】推送有没有发出去(任务维度)
|
||||
-- ===========================================================================
|
||||
--
|
||||
-- 判定办法,两步:
|
||||
--
|
||||
-- 1. `last_notified_at` **只在企业微信返回 errcode=0 之后才写**,所以它是「最近一次
|
||||
-- 推送成功的时刻」。推送就发生在那一轮跑完之后几秒内 —— 拿它去和一串 run 的结束
|
||||
-- 时间比,落在两分钟内的那一轮,就是**最后一次真正发出去的那轮**。
|
||||
-- 2. 那一轮**之后**、本该推送却没有的轮次,就是漏掉的。`漏掉几次` 就是这么数的。
|
||||
--
|
||||
-- 为什么不能更精确:失败的推送没有留下任何记录(原因只打到容器 stdout),`last_notified_at`
|
||||
-- 也只有一个值,会被后来的成功覆盖。要逐轮可查得让它落一条事件或一列原因 —— 那是改代码,
|
||||
-- 不是这条 SQL 能补的。
|
||||
--
|
||||
-- 「本该推送」= 那轮 new_notes > 0,或者出了失败类事件(和 notify.build_run_message 的
|
||||
-- 判断一致:它按任务上的两个开关过滤事件,没有可推的就返回 None、压根不发)。
|
||||
SELECT
|
||||
t.id AS 任务,
|
||||
t.name AS 名称,
|
||||
t.notify_enabled AS 推新作品,
|
||||
t.notify_failures AS 推异常,
|
||||
FROM_UNIXTIME(t.last_notified_at / 1000) AS 上次推送成功于,
|
||||
hit.run_id AS 成功的是这轮,
|
||||
-- 没有匹配行(= 一次没漏)时 LEFT JOIN 给的是 NULL,直接显示会是一片空白,
|
||||
-- 分不清「零」和「查不到」。这里补成 0。
|
||||
COALESCE(leaks.漏掉几次, 0) AS 那之后漏掉,
|
||||
leaks.最近漏掉的那轮 AS 最近漏掉的轮次,
|
||||
FROM_UNIXTIME(leaks.最近漏掉的时间) AS 它结束于
|
||||
FROM monitor_task t
|
||||
-- 找「推送成功时刻」对应的那一轮:结束时间落在它之前两分钟内、且最近的那一轮。
|
||||
LEFT JOIN (
|
||||
SELECT r.task_id, MAX(r.id) AS run_id
|
||||
FROM monitor_run r
|
||||
JOIN monitor_task t5 ON t5.id = r.task_id
|
||||
WHERE t5.last_notified_at IS NOT NULL
|
||||
AND r.finished_at <= t5.last_notified_at
|
||||
AND t5.last_notified_at - r.finished_at <= 120000
|
||||
GROUP BY r.task_id
|
||||
) hit ON hit.task_id = t.id
|
||||
-- 上次成功之后,本该推送却没推的轮次。
|
||||
LEFT JOIN (
|
||||
SELECT r.task_id,
|
||||
COUNT(*) AS 漏掉几次,
|
||||
MAX(r.id) AS 最近漏掉的那轮,
|
||||
MAX(r.finished_at) AS 最近漏掉的时间
|
||||
FROM monitor_run r
|
||||
JOIN monitor_task t6 ON t6.id = r.task_id
|
||||
WHERE r.finished_at > COALESCE(t6.last_notified_at, 0)
|
||||
AND (r.new_notes > 0
|
||||
OR EXISTS (SELECT 1 FROM monitor_event e
|
||||
WHERE e.run_id = r.id
|
||||
AND e.type IN ('suspected_auth_failure', 'run_failed', 'no_data_found')))
|
||||
GROUP BY r.task_id
|
||||
) leaks ON leaks.task_id = t.id
|
||||
WHERE t.platform = 'dy'
|
||||
ORDER BY t.id;
|
||||
@@ -0,0 +1,104 @@
|
||||
-- 抖音所有账号:最近七天有没有带「广告」标签的视频
|
||||
--
|
||||
-- **每个账号一行,一个都不少** —— 包括这几天没发广告的、以及一条作品都没有的号。
|
||||
-- 有广告的:那一行带上「最新那条广告视频」的详情;没有的:只剩博主信息,作品列是空的。
|
||||
--
|
||||
-- 判定口径:
|
||||
-- * 「最近七天」看的是作品的 **published_at(作者发布时间)**,不是我们什么时候采到的。
|
||||
-- 想改成「最近七天新发现的」,把两处 `n.published_at >= ...` 换成
|
||||
-- `n3.first_seen_at >= ...` / `n2.first_seen_at >= ...`。
|
||||
-- * 广告标签按**名字**匹配(`tg.name = '广告'`)。改了标签名的话这里也要跟着改。
|
||||
-- 标签是全局的(不按平台分),而这里只查抖音。
|
||||
-- * 窗口下界只在**一个地方**定义(下面那个 `w` 子查询),改天数只改那一处。
|
||||
-- 写成 `(UNIX_TIMESTAMP() - 7 * 86400) * 1000` 算的,**不经过时区** —— 库里存的是
|
||||
-- 毫秒时间戳,和 MySQL 的 time_zone 设置无关,这样最不容易出错。
|
||||
-- * MySQL 5.7 没有窗口函数,挑「最新那条」还是用相关子查询。
|
||||
--
|
||||
-- 只想看某一个任务:把四处 `t.platform = 'dy'` 换成 `t1.id = 7` 这类条件
|
||||
-- (账号清单两处、最新广告视频子查询一处、账号快照子查询一处)。
|
||||
|
||||
SELECT
|
||||
acct.creator_hash AS 博主哈希,
|
||||
ca.alias AS 博主备注,
|
||||
COALESCE(st.nickname, n.creator_name, '') AS 博主昵称,
|
||||
st.fans AS 粉丝数,
|
||||
st.total_favorited AS 总获赞,
|
||||
st.works_count AS 主页作品数,
|
||||
-- 这七天里带「广告」标签的视频有几条。0 就是没有 —— 这一行的作品列会是空的。
|
||||
(SELECT COUNT(*)
|
||||
FROM monitor_note n3
|
||||
JOIN monitor_task t5 ON t5.id = n3.task_id
|
||||
WHERE t5.platform = 'dy'
|
||||
AND n3.creator_hash = acct.creator_hash
|
||||
AND n3.published_at >= w.since
|
||||
AND EXISTS (SELECT 1 FROM monitor_note_tag nt
|
||||
JOIN monitor_tag tg ON tg.id = nt.tag_id
|
||||
WHERE nt.platform = 'dy'
|
||||
AND nt.note_id = n3.note_id
|
||||
AND tg.name = '广告')) AS 近七天广告视频数,
|
||||
n.note_id AS 作品ID,
|
||||
n.title AS 作品标题,
|
||||
n.note_url AS 作品链接,
|
||||
FROM_UNIXTIME(n.published_at / 1000) AS 发布时间,
|
||||
m.liked_count AS 点赞,
|
||||
m.comment_count AS 评论,
|
||||
m.collected_count AS 收藏,
|
||||
m.share_count AS 分享,
|
||||
(SELECT GROUP_CONCAT(t.name ORDER BY t.sort_order SEPARATOR ' / ')
|
||||
FROM monitor_note_tag nt
|
||||
JOIN monitor_tag t ON t.id = nt.tag_id
|
||||
WHERE nt.platform = 'dy' AND nt.note_id = n.note_id) AS 标签,
|
||||
(SELECT na.alias FROM monitor_note_alias na
|
||||
WHERE na.platform = 'dy' AND na.note_id = n.note_id LIMIT 1) AS 作品备注
|
||||
FROM
|
||||
-- 七天窗口的下界(毫秒)。**改天数只改这一行。**
|
||||
(SELECT (UNIX_TIMESTAMP() - 7 * 86400) * 1000 AS since) w
|
||||
CROSS JOIN (
|
||||
-- 账号清单:作品里出现过的
|
||||
SELECT n1.creator_hash
|
||||
FROM monitor_note n1
|
||||
JOIN monitor_task t1 ON t1.id = n1.task_id
|
||||
WHERE t1.platform = 'dy'
|
||||
UNION
|
||||
-- ∪ 有账号资料的(包含一条作品都没有的博主)
|
||||
SELECT s1.creator_hash
|
||||
FROM monitor_creator_stat s1
|
||||
JOIN monitor_task t2 ON t2.id = s1.task_id
|
||||
WHERE t2.platform = 'dy'
|
||||
) acct
|
||||
-- 这七天里最新的一条**带广告标签的**作品。没有就整块为空 —— 但博主那几列照常显示。
|
||||
LEFT JOIN monitor_note n
|
||||
ON n.id = (SELECT n2.id
|
||||
FROM monitor_note n2
|
||||
JOIN monitor_task t3 ON t3.id = n2.task_id
|
||||
WHERE t3.platform = 'dy'
|
||||
AND n2.creator_hash = acct.creator_hash
|
||||
AND n2.published_at >= w.since
|
||||
AND EXISTS (SELECT 1 FROM monitor_note_tag nt2
|
||||
JOIN monitor_tag tg2 ON tg2.id = nt2.tag_id
|
||||
WHERE nt2.platform = 'dy'
|
||||
AND nt2.note_id = n2.note_id
|
||||
AND tg2.name = '广告')
|
||||
ORDER BY n2.published_at DESC, n2.id DESC
|
||||
LIMIT 1)
|
||||
-- 那条作品最近一轮的指标
|
||||
LEFT JOIN monitor_note_metric m
|
||||
ON m.id = (SELECT m2.id
|
||||
FROM monitor_note_metric m2
|
||||
WHERE m2.task_id = n.task_id
|
||||
AND m2.note_id = n.note_id
|
||||
ORDER BY m2.run_id DESC
|
||||
LIMIT 1)
|
||||
LEFT JOIN monitor_creator_alias ca
|
||||
ON ca.platform = 'dy' AND ca.creator_hash = acct.creator_hash
|
||||
-- 博主最近一轮的账号级指标
|
||||
LEFT JOIN monitor_creator_stat st
|
||||
ON st.id = (SELECT s2.id
|
||||
FROM monitor_creator_stat s2
|
||||
JOIN monitor_task t4 ON t4.id = s2.task_id
|
||||
WHERE t4.platform = 'dy'
|
||||
AND s2.creator_hash = acct.creator_hash
|
||||
ORDER BY s2.run_id DESC
|
||||
LIMIT 1)
|
||||
-- 有广告的排前面(数量降序),其余按粉丝数
|
||||
ORDER BY 近七天广告视频数 DESC, st.fans DESC, acct.creator_hash
|
||||
@@ -0,0 +1,125 @@
|
||||
-- 抖音博主 × 发布日 矩阵表
|
||||
--
|
||||
-- 博主昵称 | 2026-10-12 | 2026-10-13 | ...
|
||||
-- 锋哥苏州同城人脉汇 | 1 条 / 大字报 | 1 条 / 大字报·养号 | ...
|
||||
--
|
||||
-- 格子里是「这一天发了几条 / 这些作品的标签」。没有标签就只显示「N 条」。
|
||||
-- 左边列出**所有**抖音博主,一条作品都没有的博主也会占一行(格子为空);
|
||||
-- 不想要这些空行,就把下面 `c` 里 `UNION` 后面那段 `monitor_creator_stat` 删掉。
|
||||
--
|
||||
-- 旁边那列 `博主哈希` 是为了区分**昵称相同的两个账号**(库里确实有同名小号),
|
||||
-- 平时可以忽略。
|
||||
--
|
||||
-- 为什么这么绕:**MySQL 5.7 既没有 PIVOT 也没有 CTE**,而日期是数据、不是固定列,
|
||||
-- 所以只能先从数据里查出有哪些日期,用 GROUP_CONCAT 拼出 `MAX(CASE WHEN ...)` 的
|
||||
-- 列定义,再 PREPARE 执行。
|
||||
--
|
||||
-- 用法:**整段一次性执行**(这是一段脚本,不是一条 SELECT)。Navicat / DBeaver /
|
||||
-- DataEase 的 SQL 窗口里全选运行即可。最后那条 SELECT 就是结果。
|
||||
--
|
||||
-- 想换时间范围:只改 @days 这一个数字。
|
||||
-- (不加限制的话,库里回填的早年作品会让列数涨到一百多列,没法看。)
|
||||
|
||||
SET SESSION group_concat_max_len = 1000000;
|
||||
|
||||
SET @days := 14;
|
||||
SET @since := (UNIX_TIMESTAMP() - @days * 86400) * 1000;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 1) 窗口内出现过哪些发布日 → 拼成列定义(升序)
|
||||
-- ---------------------------------------------------------------------------
|
||||
SET @cols := (
|
||||
SELECT GROUP_CONCAT(
|
||||
CONCAT('MAX(CASE WHEN d.日期 = ''', d.日期, ''' THEN d.单元格 END) AS `', d.日期, '`')
|
||||
ORDER BY d.日期 SEPARATOR ', '
|
||||
)
|
||||
FROM (
|
||||
SELECT DATE(FROM_UNIXTIME(n.published_at / 1000)) AS 日期
|
||||
FROM monitor_note n
|
||||
JOIN monitor_task t ON t.id = n.task_id
|
||||
WHERE t.platform = 'dy'
|
||||
AND n.published_at IS NOT NULL
|
||||
AND n.published_at >= @since
|
||||
GROUP BY 1
|
||||
) d
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 2) 拼出并执行整条 SQL
|
||||
-- ---------------------------------------------------------------------------
|
||||
SET @sql := CONCAT(
|
||||
'SELECT
|
||||
c.博主昵称,
|
||||
-- 库里确实存在**昵称相同、哈希不同**的两个账号(同名小号),只靠昵称分不出来,
|
||||
-- 所以补一列短哈希。一眼看不出重复时可以忽略这一列。
|
||||
LEFT(c.creator_hash, 8) AS 博主哈希, ',
|
||||
@cols, '
|
||||
FROM (
|
||||
-- 所有抖音博主:作品里出现过的 ∪ 有账号快照的
|
||||
SELECT x.creator_hash,
|
||||
COALESCE(NULLIF(cs.nickname, ''''),
|
||||
(SELECT n9.creator_name
|
||||
FROM monitor_note n9
|
||||
JOIN monitor_task t9 ON t9.id = n9.task_id
|
||||
WHERE t9.platform = ''dy''
|
||||
AND n9.creator_hash = x.creator_hash
|
||||
AND n9.creator_name <> ''''
|
||||
ORDER BY n9.last_seen_at DESC
|
||||
LIMIT 1),
|
||||
-- 昵称一个字都没有时至少给出哈希,别在报表里留一行空白
|
||||
CONCAT(''未知('', x.creator_hash, '')'')) AS 博主昵称
|
||||
FROM (
|
||||
SELECT DISTINCT n1.creator_hash
|
||||
FROM monitor_note n1
|
||||
JOIN monitor_task t1 ON t1.id = n1.task_id
|
||||
WHERE t1.platform = ''dy'' AND n1.creator_hash <> ''''
|
||||
UNION
|
||||
SELECT DISTINCT s1.creator_hash
|
||||
FROM monitor_creator_stat s1
|
||||
JOIN monitor_task t5 ON t5.id = s1.task_id
|
||||
WHERE t5.platform = ''dy'' AND s1.creator_hash <> ''''
|
||||
) x
|
||||
LEFT JOIN (
|
||||
-- 每个博主最新一条账号快照的昵称
|
||||
SELECT s.creator_hash, s.nickname
|
||||
FROM monitor_creator_stat s
|
||||
JOIN monitor_task t2 ON t2.id = s.task_id
|
||||
WHERE t2.platform = ''dy''
|
||||
AND s.id = (SELECT s2.id
|
||||
FROM monitor_creator_stat s2
|
||||
JOIN monitor_task t3 ON t3.id = s2.task_id
|
||||
WHERE t3.platform = ''dy''
|
||||
AND s2.creator_hash = s.creator_hash
|
||||
ORDER BY s2.captured_at DESC, s2.id DESC
|
||||
LIMIT 1)
|
||||
) cs ON cs.creator_hash = x.creator_hash
|
||||
) c
|
||||
LEFT JOIN (
|
||||
-- 长表:每个博主、每一天 → 「N 条 / 标签」
|
||||
SELECT n.creator_hash,
|
||||
DATE(FROM_UNIXTIME(n.published_at / 1000)) AS 日期,
|
||||
CONCAT(
|
||||
COUNT(DISTINCT n.note_id), '' 条'',
|
||||
CASE WHEN COUNT(DISTINCT tg.name) = 0 THEN ''''
|
||||
ELSE CONCAT('' / '',
|
||||
GROUP_CONCAT(DISTINCT tg.name
|
||||
ORDER BY tg.sort_order SEPARATOR ''·''))
|
||||
END
|
||||
) AS 单元格
|
||||
FROM monitor_note n
|
||||
JOIN monitor_task t ON t.id = n.task_id
|
||||
LEFT JOIN monitor_note_tag nt
|
||||
ON nt.platform = ''dy'' AND nt.note_id = n.note_id
|
||||
LEFT JOIN monitor_tag tg ON tg.id = nt.tag_id
|
||||
WHERE t.platform = ''dy''
|
||||
AND n.published_at IS NOT NULL
|
||||
AND n.published_at >= @since
|
||||
GROUP BY n.creator_hash, DATE(FROM_UNIXTIME(n.published_at / 1000))
|
||||
) d ON d.creator_hash = c.creator_hash
|
||||
GROUP BY c.creator_hash, c.博主昵称
|
||||
ORDER BY c.博主昵称'
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
@@ -0,0 +1,81 @@
|
||||
-- 抖音:日期 × 博主 的标签矩阵(转置版)
|
||||
--
|
||||
-- 日期 | 锋哥苏州同城人脉汇 | 周周苏州探店日记 | ...
|
||||
-- 2026-10-21 | 大字报·养号 | 无标签 | ...
|
||||
--
|
||||
-- 行 = 日期(新到旧),列 = 博主昵称,格子里是**这一天这个号发出去的视频标签**:
|
||||
-- · 当天没发作品 → 空
|
||||
-- · 发了但没打标签 → 「无标签」(和「没发」区分开)
|
||||
-- · 一天发多条、标签不同 → 用「·」连起来
|
||||
--
|
||||
-- **为什么是一大串写死的 CASE**:报表工具的 SQL 数据集只接受**单条 SELECT**,
|
||||
-- 而 MySQL 5.7 没有 PIVOT、动态列只能靠 PREPARE —— 那条路在数据集里走不通。
|
||||
-- 所以博主列只能写死。**新增博主后需要重新生成这一段**(40 多列手工加很痛苦,
|
||||
-- 可以让 Claude 重新生成)。
|
||||
--
|
||||
-- 列按昵称去重:库里有同名不同号(「锋哥苏州市井烟火」「锋哥苏州民生好服务商」
|
||||
-- 各两个),它们的标签会并到同一列。只影响展示,不影响数据。
|
||||
--
|
||||
-- 时间范围:改下面 `14` 这个数字即可。
|
||||
|
||||
SELECT
|
||||
d.日期,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州休闲打卡' THEN d.单元格 END) AS `周周苏州休闲打卡`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州吃喝玩乐' THEN d.单元格 END) AS `周周苏州吃喝玩乐`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州周末去哪' THEN d.单元格 END) AS `周周苏州周末去哪`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州家庭服务见闻' THEN d.单元格 END) AS `周周苏州家庭服务见闻`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州寻宝藏小店' THEN d.单元格 END) AS `周周苏州寻宝藏小店`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州平价美食' THEN d.单元格 END) AS `周周苏州平价美食`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州康养养生探店' THEN d.单元格 END) AS `周周苏州康养养生探店`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州探店日记' THEN d.单元格 END) AS `周周苏州探店日记`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州约会好去处' THEN d.单元格 END) AS `周周苏州约会好去处`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州街边烟火' THEN d.单元格 END) AS `周周苏州街边烟火`,
|
||||
MAX(CASE WHEN d.博主 = '周周苏州遛娃攻略' THEN d.单元格 END) AS `周周苏州遛娃攻略`,
|
||||
MAX(CASE WHEN d.博主 = '周周逛苏州' THEN d.单元格 END) AS `周周逛苏州`,
|
||||
MAX(CASE WHEN d.博主 = '姑苏周周养生寻迹' THEN d.单元格 END) AS `姑苏周周养生寻迹`,
|
||||
MAX(CASE WHEN d.博主 = '姑苏周周话康养' THEN d.单元格 END) AS `姑苏周周话康养`,
|
||||
MAX(CASE WHEN d.博主 = '姑苏阿周慢病养护' THEN d.单元格 END) AS `姑苏阿周慢病养护`,
|
||||
MAX(CASE WHEN d.博主 = '老周姑苏健康闲谈' THEN d.单元格 END) AS `老周姑苏健康闲谈`,
|
||||
MAX(CASE WHEN d.博主 = '老周苏州健康说' THEN d.单元格 END) AS `老周苏州健康说`,
|
||||
MAX(CASE WHEN d.博主 = '苏州阿周中老年指南' THEN d.单元格 END) AS `苏州阿周中老年指南`,
|
||||
MAX(CASE WHEN d.博主 = '苏州阿周寻养生好去处' THEN d.单元格 END) AS `苏州阿周寻养生好去处`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州创业实录' THEN d.单元格 END) AS `锋哥苏州创业实录`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州吃喝玩乐' THEN d.单元格 END) AS `锋哥苏州吃喝玩乐`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州同城人脉汇' THEN d.单元格 END) AS `锋哥苏州同城人脉汇`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州周末去哪玩' THEN d.单元格 END) AS `锋哥苏州周末去哪玩`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州商圈走访' THEN d.单元格 END) AS `锋哥苏州商圈走访`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州地道美食' THEN d.单元格 END) AS `锋哥苏州地道美食`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州实体老板聊' THEN d.单元格 END) AS `锋哥苏州实体老板聊`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州寻宝藏小店' THEN d.单元格 END) AS `锋哥苏州寻宝藏小店`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州居家服务实录' THEN d.单元格 END) AS `锋哥苏州居家服务实录`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州居家生活探' THEN d.单元格 END) AS `锋哥苏州居家生活探`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州市井烟火' THEN d.单元格 END) AS `锋哥苏州市井烟火`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州康养探店' THEN d.单元格 END) AS `锋哥苏州康养探店`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州探店实录' THEN d.单元格 END) AS `锋哥苏州探店实录`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州民生好服务商' THEN d.单元格 END) AS `锋哥苏州民生好服务商`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州百业探访' THEN d.单元格 END) AS `锋哥苏州百业探访`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州私董会纪实' THEN d.单元格 END) AS `锋哥苏州私董会纪实`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州访老总' THEN d.单元格 END) AS `锋哥苏州访老总`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州遛娃好去处' THEN d.单元格 END) AS `锋哥苏州遛娃好去处`,
|
||||
MAX(CASE WHEN d.博主 = '锋哥苏州邻里好店探访' THEN d.单元格 END) AS `锋哥苏州邻里好店探访`,
|
||||
MAX(CASE WHEN d.博主 = '阿周苏州健康好物' THEN d.单元格 END) AS `阿周苏州健康好物`
|
||||
FROM (
|
||||
SELECT
|
||||
DATE(FROM_UNIXTIME(n.published_at / 1000)) AS 日期,
|
||||
COALESCE(MAX(NULLIF(n.creator_name, '')),
|
||||
CONCAT('未知(', LEFT(n.creator_hash, 6), ')')) AS 博主,
|
||||
CASE WHEN COUNT(DISTINCT tg.name) = 0 THEN '无标签'
|
||||
ELSE GROUP_CONCAT(DISTINCT tg.name ORDER BY tg.sort_order SEPARATOR '·')
|
||||
END AS 单元格
|
||||
FROM monitor_note n
|
||||
JOIN monitor_task t ON t.id = n.task_id
|
||||
LEFT JOIN monitor_note_tag nt
|
||||
ON nt.platform = 'dy' AND nt.note_id = n.note_id
|
||||
LEFT JOIN monitor_tag tg ON tg.id = nt.tag_id
|
||||
WHERE t.platform = 'dy'
|
||||
AND n.published_at IS NOT NULL
|
||||
AND n.published_at >= (UNIX_TIMESTAMP() - 14 * 86400) * 1000
|
||||
GROUP BY DATE(FROM_UNIXTIME(n.published_at / 1000)), n.creator_hash
|
||||
) d
|
||||
GROUP BY d.日期
|
||||
ORDER BY d.日期 DESC
|
||||
@@ -0,0 +1,85 @@
|
||||
-- 抖音所有账号,各自最近一条视频 + 标签 + 详细数据
|
||||
--
|
||||
-- 直接在 MySQL 5.7 里跑(生产库 mediacrawler_prod)。已实测:42 个账号,包含
|
||||
-- **一条作品都没有的**(那些行的作品列是空的)—— 它们出现在列表里是有意的,
|
||||
-- 和界面上的作品栏一致。
|
||||
--
|
||||
-- 为什么写成这个形状:
|
||||
--
|
||||
-- * **5.7 没有窗口函数**,ROW_NUMBER() 用不了。所以「每个博主最新那条」是用
|
||||
-- 相关子查询 `ORDER BY published_at DESC LIMIT 1` 挑的,而不是 rank 之后取 1。
|
||||
-- * 账号清单取的是 **作品里出现过的 ∪ 有账号资料的**(`UNION` 去重)。只从作品里取
|
||||
-- 的话,那些「加了目标、也采到了粉丝数、但一条作品都没有」的号会整行消失。
|
||||
-- * 「最新」按 **published_at**(作者发布时间)排,不是 last_seen_at。降级路径
|
||||
-- (作品列表被风控挡住)会把所有已知作品都刷一遍,那时 last_seen_at 全都一样,
|
||||
-- 按它排等于没排。
|
||||
-- * 指标取**最近一轮**(run_id 最大)的快照。注意抖音作品目前没有 published_at
|
||||
-- 为空的,所以不存在「没有日期的作品排哪儿」的问题。
|
||||
--
|
||||
-- 只想看某一个任务的话,把四处 `t.platform = 'dy'` 换成对应的 task_id,例如:
|
||||
-- WHERE t1.id = 7
|
||||
-- (四处指的是:账号清单里两处、最新作品子查询一处、账号快照子查询一处。)
|
||||
|
||||
SELECT
|
||||
acct.creator_hash AS 博主哈希,
|
||||
ca.alias AS 博主备注,
|
||||
COALESCE(st.nickname, n.creator_name, '') AS 博主昵称,
|
||||
st.fans AS 粉丝数,
|
||||
st.total_favorited AS 总获赞,
|
||||
st.works_count AS 主页作品数,
|
||||
n.note_id AS 作品ID,
|
||||
n.title AS 作品标题,
|
||||
n.note_url AS 作品链接,
|
||||
FROM_UNIXTIME(n.published_at / 1000) AS 发布时间,
|
||||
m.liked_count AS 点赞,
|
||||
m.comment_count AS 评论,
|
||||
m.collected_count AS 收藏,
|
||||
m.share_count AS 分享,
|
||||
(SELECT GROUP_CONCAT(t.name ORDER BY t.sort_order SEPARATOR ' / ')
|
||||
FROM monitor_note_tag nt
|
||||
JOIN monitor_tag t ON t.id = nt.tag_id
|
||||
WHERE nt.platform = 'dy' AND nt.note_id = n.note_id) AS 标签,
|
||||
(SELECT na.alias FROM monitor_note_alias na
|
||||
WHERE na.platform = 'dy' AND na.note_id = n.note_id LIMIT 1) AS 作品备注
|
||||
FROM (
|
||||
-- 账号清单:作品里出现过的
|
||||
SELECT n1.creator_hash
|
||||
FROM monitor_note n1
|
||||
JOIN monitor_task t1 ON t1.id = n1.task_id
|
||||
WHERE t1.platform = 'dy'
|
||||
UNION
|
||||
-- ∪ 有账号资料的(包含一条作品都没有的博主)
|
||||
SELECT s1.creator_hash
|
||||
FROM monitor_creator_stat s1
|
||||
JOIN monitor_task t2 ON t2.id = s1.task_id
|
||||
WHERE t2.platform = 'dy'
|
||||
) acct
|
||||
-- 这个博主最新的一条作品
|
||||
LEFT JOIN monitor_note n
|
||||
ON n.id = (SELECT n2.id
|
||||
FROM monitor_note n2
|
||||
JOIN monitor_task t3 ON t3.id = n2.task_id
|
||||
WHERE t3.platform = 'dy'
|
||||
AND n2.creator_hash = acct.creator_hash
|
||||
ORDER BY n2.published_at DESC, n2.id DESC
|
||||
LIMIT 1)
|
||||
-- 那条作品最近一轮的指标
|
||||
LEFT JOIN monitor_note_metric m
|
||||
ON m.id = (SELECT m2.id
|
||||
FROM monitor_note_metric m2
|
||||
WHERE m2.task_id = n.task_id
|
||||
AND m2.note_id = n.note_id
|
||||
ORDER BY m2.run_id DESC
|
||||
LIMIT 1)
|
||||
LEFT JOIN monitor_creator_alias ca
|
||||
ON ca.platform = 'dy' AND ca.creator_hash = acct.creator_hash
|
||||
-- 博主最近一轮的账号级指标
|
||||
LEFT JOIN monitor_creator_stat st
|
||||
ON st.id = (SELECT s2.id
|
||||
FROM monitor_creator_stat s2
|
||||
JOIN monitor_task t4 ON t4.id = s2.task_id
|
||||
WHERE t4.platform = 'dy'
|
||||
AND s2.creator_hash = acct.creator_hash
|
||||
ORDER BY s2.run_id DESC
|
||||
LIMIT 1)
|
||||
ORDER BY st.fans DESC, acct.creator_hash
|
||||
@@ -0,0 +1,78 @@
|
||||
-- 抖音作品列表 + 标签数值指标
|
||||
--
|
||||
-- 在原查询的基础上,把「标签」这个文本列展开成**每个标签一列,命中记 1、没命中记 0**,
|
||||
-- 这样就能直接 SUM / 算占比 / 做透视:
|
||||
--
|
||||
-- 博主昵称 | 标签 | 大字报 | 养号 | 人设 | 广告 | 标题
|
||||
-- 锋哥苏州同城人脉汇 | 大字报 / 养号 | 1 | 1 | 0 | 0 | ...
|
||||
--
|
||||
-- 列是按 `monitor_tag` 词表**动态生成**的 —— 以后加标签不用改这段 SQL。
|
||||
-- (MySQL 5.7 没有 PIVOT,所以用 GROUP_CONCAT 拼列定义再 PREPARE。)
|
||||
--
|
||||
-- 一张作品命中多个标签时,每一列都会是 1 —— 和界面上「多个话题命中就打多个标签」
|
||||
-- 的语义一致,这些列之间不是互斥的。
|
||||
--
|
||||
-- 用法:**整段一次性执行**,不是单条 SELECT。最后那条 EXECUTE 才是结果。
|
||||
|
||||
SET SESSION group_concat_max_len = 1000000;
|
||||
|
||||
-- 1) 每个标签一列:EXISTS(...) 在 MySQL 里直接返回 1 / 0,不需要 GROUP BY
|
||||
SET @tag_cols := IFNULL((
|
||||
SELECT GROUP_CONCAT(
|
||||
CONCAT(
|
||||
'EXISTS(SELECT 1 FROM monitor_note_tag nt2',
|
||||
' JOIN monitor_tag tg2 ON tg2.id = nt2.tag_id',
|
||||
' WHERE nt2.platform = ''dy'' AND nt2.note_id = n.note_id',
|
||||
' AND tg2.name = ', QUOTE(tg.name), ') AS `',
|
||||
REPLACE(tg.name, '`', ''), '`'
|
||||
)
|
||||
ORDER BY tg.sort_order, tg.id SEPARATOR ', '
|
||||
)
|
||||
FROM monitor_tag tg
|
||||
), '0 AS `无标签`');
|
||||
|
||||
-- 2) 把列定义拼进原查询
|
||||
SET @sql := CONCAT('
|
||||
SELECT
|
||||
COALESCE(st.nickname, n.creator_name, '''') AS 博主昵称,
|
||||
(SELECT COUNT(*)
|
||||
FROM monitor_note n2
|
||||
JOIN monitor_task t5 ON t5.id = n2.task_id
|
||||
WHERE t5.platform = ''dy''
|
||||
AND n2.creator_hash <> ''''
|
||||
AND n2.creator_hash = n.creator_hash) AS 账号作品数,
|
||||
ca.alias AS 博主备注,
|
||||
FROM_UNIXTIME(n.published_at / 1000) AS 发布时间,
|
||||
n.title AS 标题,
|
||||
n.note_url AS 链接,
|
||||
m.liked_count AS 点赞,
|
||||
m.comment_count AS 评论,
|
||||
m.collected_count AS 收藏,
|
||||
m.share_count AS 分享,
|
||||
(SELECT GROUP_CONCAT(t.name ORDER BY t.sort_order SEPARATOR '' / '')
|
||||
FROM monitor_note_tag nt
|
||||
JOIN monitor_tag t ON t.id = nt.tag_id
|
||||
WHERE nt.platform = ''dy'' AND nt.note_id = n.note_id) AS 标签,
|
||||
', @tag_cols, ',
|
||||
(SELECT na.alias FROM monitor_note_alias na
|
||||
WHERE na.platform = ''dy'' AND na.note_id = n.note_id LIMIT 1) AS 作品备注,
|
||||
FROM_UNIXTIME(n.first_seen_at / 1000) AS 首次采到
|
||||
FROM monitor_note n
|
||||
JOIN monitor_task t ON t.id = n.task_id
|
||||
LEFT JOIN monitor_note_metric m
|
||||
ON m.id = (SELECT m2.id FROM monitor_note_metric m2
|
||||
WHERE m2.task_id = n.task_id AND m2.note_id = n.note_id
|
||||
ORDER BY m2.run_id DESC LIMIT 1)
|
||||
LEFT JOIN monitor_creator_stat st
|
||||
ON st.id = (SELECT s.id FROM monitor_creator_stat s
|
||||
JOIN monitor_task t2 ON t2.id = s.task_id
|
||||
WHERE t2.platform = ''dy'' AND s.creator_hash = n.creator_hash
|
||||
ORDER BY s.captured_at DESC, s.id DESC LIMIT 1)
|
||||
LEFT JOIN monitor_creator_alias ca
|
||||
ON ca.platform = ''dy'' AND ca.creator_hash = n.creator_hash
|
||||
WHERE t.platform = ''dy''
|
||||
ORDER BY n.published_at DESC');
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
@@ -0,0 +1,61 @@
|
||||
-- 最近七天发布的视频(抖音)。换平台把两处 platform='dy' 改成 'xhs'。
|
||||
--
|
||||
-- 窗口按 **published_at(作者发布时间)** 算,不经过时区:库里存的是毫秒时间戳,
|
||||
-- 用 UNIX_TIMESTAMP() 拿当前 epoch 相减,和 MySQL 的 time_zone 设置无关。
|
||||
--
|
||||
-- 改成「最近七天我们采到的」就把 n.published_at 换成 n.first_seen_at(两处)。
|
||||
--
|
||||
-- **`账号作品数` 取的是界面上「N 篇」那个数**,也就是 `list_creators` 的口径:
|
||||
-- 按「任务 × 博主」`count(*)`,再把同一博主跨任务相加 —— 所以它只数**我们采到的**,
|
||||
-- 不等于平台主页写的作品总数。两者别混:
|
||||
--
|
||||
-- * 界面/这一列 = 库里该账号的作品条数(可信,随时可查)。
|
||||
-- * `monitor_creator_stat.works_count` = 平台主页报的总数。**它现在不可信**:
|
||||
-- `锋哥苏州同城人脉汇` 库里存着 10-12 / 10-13 / 10-14 / 10-15 四条(一天一条),
|
||||
-- 平台却在连续 8 次快照、横跨 22 小时里一直报「2」。全局 dy 的 1559 行快照里
|
||||
-- 49% 作品数为 0、58% 粉丝数为 0,NULL 一行都没有 —— `douyin_api._as_int` 的
|
||||
-- 失败分支 `return 0` 把「读不到」伪装成了 0,而 models.py 要求的正相反。
|
||||
--
|
||||
-- `creator_hash <> ''` 这个条件别省:service 里也有,否则空哈希的作品会被算到每一
|
||||
-- 个查不出哈希的博主头上。
|
||||
SELECT
|
||||
COALESCE(st.nickname, n.creator_name, '') AS 博主昵称,
|
||||
(SELECT COUNT(*)
|
||||
FROM monitor_note n2
|
||||
JOIN monitor_task t5 ON t5.id = n2.task_id
|
||||
WHERE t5.platform = 'dy'
|
||||
AND n2.creator_hash <> ''
|
||||
AND n2.creator_hash = n.creator_hash) AS 账号作品数,
|
||||
ca.alias AS 博主备注,
|
||||
FROM_UNIXTIME(n.published_at / 1000) AS 发布时间,
|
||||
n.title AS 标题,
|
||||
n.note_url AS 链接,
|
||||
m.liked_count AS 点赞,
|
||||
m.comment_count AS 评论,
|
||||
m.collected_count AS 收藏,
|
||||
m.share_count AS 分享,
|
||||
(SELECT GROUP_CONCAT(t.name ORDER BY t.sort_order SEPARATOR ' / ')
|
||||
FROM monitor_note_tag nt
|
||||
JOIN monitor_tag t ON t.id = nt.tag_id
|
||||
WHERE nt.platform = 'dy' AND nt.note_id = n.note_id) AS 标签,
|
||||
(SELECT na.alias FROM monitor_note_alias na
|
||||
WHERE na.platform = 'dy' AND na.note_id = n.note_id LIMIT 1) AS 作品备注,
|
||||
FROM_UNIXTIME(n.first_seen_at / 1000) AS 首次采到
|
||||
FROM monitor_note n
|
||||
JOIN monitor_task t ON t.id = n.task_id
|
||||
-- 这条作品最近一轮的指标
|
||||
LEFT JOIN monitor_note_metric m
|
||||
ON m.id = (SELECT m2.id FROM monitor_note_metric m2
|
||||
WHERE m2.task_id = n.task_id AND m2.note_id = n.note_id
|
||||
ORDER BY m2.run_id DESC LIMIT 1)
|
||||
-- 博主最近一轮的账号级指标(昵称优先取这个,它每轮都从资料接口重写)
|
||||
LEFT JOIN monitor_creator_stat st
|
||||
ON st.id = (SELECT s.id FROM monitor_creator_stat s
|
||||
JOIN monitor_task t2 ON t2.id = s.task_id
|
||||
WHERE t2.platform = 'dy' AND s.creator_hash = n.creator_hash
|
||||
ORDER BY s.captured_at DESC, s.id DESC LIMIT 1)
|
||||
LEFT JOIN monitor_creator_alias ca
|
||||
ON ca.platform = 'dy' AND ca.creator_hash = n.creator_hash
|
||||
WHERE t.platform = 'dy'
|
||||
AND n.published_at >= (UNIX_TIMESTAMP() - 7 * 86400) * 1000
|
||||
ORDER BY n.published_at DESC;
|
||||
@@ -0,0 +1,46 @@
|
||||
-- 抖音:日期 × 博主 → 标签(长表视图)
|
||||
--
|
||||
-- 已经在生产库创建:`v_dy_daily_tags`。重装/换库时把这段跑一遍即可。
|
||||
--
|
||||
-- 日期 | 博主哈希 | 博主昵称 | 标签
|
||||
-- 2026-10-21 | ba460c1d... | 周周苏州休闲打卡 | 无标签
|
||||
-- 2026-10-20 | ea66570b... | 周周苏州寻宝藏小店 | 大字报·养号
|
||||
--
|
||||
-- **为什么是长表,不是「博主做列」的矩阵。** MySQL 视图的列在创建时就固定了,
|
||||
-- 没法按数据动态生成列。用昵称写死矩阵列的写法一改名字就对不上(CASE 命中不了,
|
||||
-- 列头还是旧名),加博主更要整段重写。
|
||||
--
|
||||
-- 这个视图把昵称放在**行**里,所以:
|
||||
-- * 博主改名 → 下次采集 `creator_name` 一更新,视图里自动是新名字;
|
||||
-- * 新增博主 → 自动多出行,不用改任何 SQL;
|
||||
-- * 日期范围 → 由调用方 `WHERE` 过滤,视图本身不写死窗口。
|
||||
--
|
||||
-- 报表工具里怎么用:
|
||||
-- * 支持「透视表且允许维度做单元格」的 → 行=日期、列=博主昵称、值=标签;
|
||||
-- * 不支持(DataEase 的透视表指标要求是数值)→ 当明细表展示,或让工具按
|
||||
-- 日期分组、博主昵称做列(能转就转,转不了就竖着看,信息一样全)。
|
||||
--
|
||||
-- 想直接看最近 14 天:
|
||||
-- SELECT * FROM v_dy_daily_tags
|
||||
-- WHERE 日期 >= CURDATE() - INTERVAL 14 DAY
|
||||
-- ORDER BY 日期 DESC, 博主昵称;
|
||||
--
|
||||
-- 删除:DROP VIEW IF EXISTS v_dy_daily_tags;
|
||||
|
||||
CREATE OR REPLACE VIEW v_dy_daily_tags AS
|
||||
SELECT
|
||||
DATE(FROM_UNIXTIME(n.published_at / 1000)) AS 日期,
|
||||
n.creator_hash AS 博主哈希,
|
||||
COALESCE(MAX(NULLIF(n.creator_name, '')),
|
||||
CONCAT('未知(', LEFT(n.creator_hash, 6), ')')) AS 博主昵称,
|
||||
CASE WHEN COUNT(DISTINCT tg.name) = 0 THEN '无标签'
|
||||
ELSE GROUP_CONCAT(DISTINCT tg.name ORDER BY tg.sort_order SEPARATOR '·')
|
||||
END AS 标签
|
||||
FROM monitor_note n
|
||||
JOIN monitor_task t ON t.id = n.task_id
|
||||
LEFT JOIN monitor_note_tag nt
|
||||
ON nt.platform = 'dy' AND nt.note_id = n.note_id
|
||||
LEFT JOIN monitor_tag tg ON tg.id = nt.tag_id
|
||||
WHERE t.platform = 'dy'
|
||||
AND n.published_at IS NOT NULL
|
||||
GROUP BY DATE(FROM_UNIXTIME(n.published_at / 1000)), n.creator_hash;
|
||||
@@ -44,7 +44,11 @@ from . import media as douyin_media
|
||||
from .client import DouYinClient
|
||||
from .exception import DataFetchError
|
||||
from .field import PublishTimeType
|
||||
from .help import parse_video_info_from_url, parse_creator_info_from_url
|
||||
from .help import (
|
||||
client_hint_headers,
|
||||
parse_creator_info_from_url,
|
||||
parse_video_info_from_url,
|
||||
)
|
||||
from .login import DouYinLogin
|
||||
|
||||
|
||||
@@ -320,10 +324,17 @@ class DouYinCrawler(AbstractCrawler):
|
||||
self.browser_context,
|
||||
urls=self.cookie_urls,
|
||||
) # type: ignore
|
||||
# 声称自己是 Chrome,就得带上 sec-ch-ua 系列头 —— 浏览器一定会带,而缺了它们
|
||||
# 的请求在抖音网关看来就是机器人:回一个 **200 + 空 body**,不报错、不给原因,
|
||||
# 表现为采集抓到 0 条。见 help.client_hint_headers 的实测记录。
|
||||
client_hints = client_hint_headers(
|
||||
await self.context_page.evaluate("() => navigator.userAgentData || null")
|
||||
)
|
||||
douyin_client = DouYinClient(
|
||||
proxy=httpx_proxy,
|
||||
headers={
|
||||
"User-Agent": await self.context_page.evaluate("() => navigator.userAgent"),
|
||||
**client_hints,
|
||||
"Cookie": cookie_str,
|
||||
"Host": "www.douyin.com",
|
||||
"Origin": "https://www.douyin.com/",
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
import random
|
||||
import re
|
||||
from typing import Optional
|
||||
from typing import Dict, Optional
|
||||
|
||||
import execjs
|
||||
from playwright.async_api import Page
|
||||
@@ -98,6 +98,38 @@ async def get_a_bogus_from_playwright(params: str, post_data: dict, user_agent:
|
||||
return a_bogus
|
||||
|
||||
|
||||
def client_hint_headers(user_agent_data) -> Dict[str, str]:
|
||||
"""由 ``navigator.userAgentData`` 还原 ``sec-ch-ua`` 系列请求头。
|
||||
|
||||
浏览器只要声称自己是 Chrome,就**一定会**带这三个头。缺了它们,「Chrome 的 UA +
|
||||
没有 sec-ch-ua」就是最典型的机器人特征 —— 抖音网关会因此返回 **200 + 空 body**:
|
||||
不报错、不给原因、HTTP 状态还是成功的,表现为采集拿到 0 条。
|
||||
|
||||
实测(同一 URL、同一 cookie、同一参数):不带头 → 0 字节;补上这三个头 → 7077 字节。
|
||||
|
||||
从 ``userAgentData`` 现算而不是写死,是为了 Chrome 升级后不会悄悄失配 —— 写死的
|
||||
版本号和 UA 里的版本号一旦对不上,就又是一个可疑特征。
|
||||
"""
|
||||
if not isinstance(user_agent_data, dict):
|
||||
return {}
|
||||
|
||||
brands = user_agent_data.get("brands") or []
|
||||
sec_ch_ua = ", ".join(
|
||||
f'"{brand.get("brand", "")}";v="{brand.get("version", "")}"' for brand in brands
|
||||
)
|
||||
if not sec_ch_ua:
|
||||
return {}
|
||||
|
||||
headers = {
|
||||
"sec-ch-ua": sec_ch_ua,
|
||||
"sec-ch-ua-mobile": "?1" if user_agent_data.get("mobile") else "?0",
|
||||
}
|
||||
platform = user_agent_data.get("platform")
|
||||
if platform:
|
||||
headers["sec-ch-ua-platform"] = f'"{platform}"'
|
||||
return headers
|
||||
|
||||
|
||||
def parse_video_info_from_url(url: str) -> VideoUrlInfo:
|
||||
"""
|
||||
Parse video ID from Douyin video URL
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""无限动画只能动可合成的属性。
|
||||
|
||||
**这条规则是真金白银换来的。** `.status-dot-online` 的呼吸光晕原先动画的是
|
||||
`box-shadow` —— 那是个**不可合成**的属性,每一帧都要整块重新光栅化。配上
|
||||
`infinite`,页面从打开那一刻起就永不空闲;而这些圆点背后又全是
|
||||
`backdrop-filter` 玻璃面板,每次重绘都连带把模糊整块重算。
|
||||
|
||||
CDP trace 实测(静置 6 秒,监控页上有 4 个这样的圆点):
|
||||
|
||||
动画动 box-shadow:光栅任务 2115 次 / 689ms,GPU 2115 次 / 699ms,主帧 790
|
||||
动画只动 opacity :光栅任务 4 次 / 1ms,GPU 5 次 / 1ms,主帧 0
|
||||
|
||||
差三个数量级。在开发机上完全感觉不到,在慢机器上就是「点什么都卡、整台电脑发僵」,
|
||||
而且**在浏览器 Network 面板里会伪装成「每个接口都下载 20 秒」** —— 主线程被占死,
|
||||
响应体读不进来,那个阶段就一直挂着。
|
||||
|
||||
所以这里把规则钉住:凡是 `infinite` 的动画,它引用的 @keyframes 里只能出现
|
||||
opacity / transform 这类由合成器处理的属性。
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
CSS = pathlib.Path("webui/src/index.css")
|
||||
TAILWIND = pathlib.Path("webui/tailwind.config.ts")
|
||||
|
||||
# 由合成器处理、改它们不触发重绘的属性。照抄 Chrome 的可合成动画白名单。
|
||||
COMPOSITABLE = {"opacity", "transform", "translate", "rotate", "scale"}
|
||||
|
||||
# Tailwind 自带的那几个关键帧(pulse / spin / ping / bounce)全是可合成的,
|
||||
# 定义在它的内部源码里,这里读不到 —— 遇到不认识的动画名就跳过。
|
||||
_ANIMATION_DECL = re.compile(
|
||||
r"animation(?:-name)?\s*:\s*['\"]?([A-Za-z][\w-]*)", re.IGNORECASE
|
||||
)
|
||||
_PROPERTY = re.compile(r"([A-Za-z][A-Za-z-]*)\s*:")
|
||||
|
||||
|
||||
def _blocks(text: str, opener: str) -> str:
|
||||
"""取出 text 里从 ``opener`` 开始的那个花括号区块(含嵌套)。"""
|
||||
start = text.find(opener)
|
||||
if start < 0:
|
||||
return ""
|
||||
start = text.find("{", start)
|
||||
depth = 0
|
||||
for index in range(start, len(text)):
|
||||
if text[index] == "{":
|
||||
depth += 1
|
||||
elif text[index] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return text[start + 1 : index]
|
||||
return ""
|
||||
|
||||
|
||||
def _keyframes(source: str, is_css: bool) -> dict[str, str]:
|
||||
"""把 ``名字 -> 关键帧正文`` 收集出来。
|
||||
|
||||
CSS 用 ``@keyframes name { ... }``;Tailwind 配置里是 ``name: { ... }``
|
||||
的对象字面量 —— 后者靠 camelCase 属性名(boxShadow 等)也能认出来。
|
||||
"""
|
||||
region = source if is_css else _blocks(source, "keyframes")
|
||||
found: dict[str, str] = {}
|
||||
pattern = (
|
||||
re.compile(r"@keyframes\s+([\w-]+)\s*\{")
|
||||
if is_css
|
||||
else re.compile(r"([A-Za-z][\w-]*)\s*:\s*\{")
|
||||
)
|
||||
for match in pattern.finditer(region):
|
||||
name = match.group(1)
|
||||
brace = region.find("{", match.start())
|
||||
depth = 0
|
||||
for index in range(brace, len(region)):
|
||||
if region[index] == "{":
|
||||
depth += 1
|
||||
elif region[index] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
found[name] = region[brace + 1 : index]
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def _properties(body: str) -> set[str]:
|
||||
"""关键帧正文里出现的 CSS 属性名,camelCase 归一成 kebab-case。"""
|
||||
names = set()
|
||||
for raw in _PROPERTY.findall(body):
|
||||
# boxShadow -> box-shadow;顺带丢掉百分比选择器残渣(100% 之类)
|
||||
kebab = re.sub(r"(?<!^)(?=[A-Z])", "-", raw).lower()
|
||||
names.add(kebab)
|
||||
return {name for name in names if name not in {"from", "to"}}
|
||||
|
||||
|
||||
def _infinite_animations(css: str, tailwind: str) -> list[tuple[str, str]]:
|
||||
"""所有写了 infinite 的动画,返回 (动画名, 出处)。"""
|
||||
found = []
|
||||
for match in re.finditer(r"animation[^;{}]*infinite[^;{}]*", css, re.IGNORECASE):
|
||||
names = _ANIMATION_DECL.findall(match.group(0))
|
||||
for name in names:
|
||||
found.append((name, "index.css"))
|
||||
anim_block = _blocks(tailwind, "animation")
|
||||
for match in re.finditer(r"'([\w-]+)'\s*:\s*'([^']*infinite[^']*)'", anim_block):
|
||||
names = _ANIMATION_DECL.findall(match.group(2))
|
||||
for name in names:
|
||||
found.append((name, f"tailwind.config.ts ({match.group(1)})"))
|
||||
return found
|
||||
|
||||
|
||||
@pytest.mark.skipif(not CSS.exists(), reason="没有前端源码")
|
||||
def test_infinite_animations_only_touch_compositable_properties():
|
||||
css = CSS.read_text(encoding="utf-8")
|
||||
tailwind = TAILWIND.read_text(encoding="utf-8") if TAILWIND.exists() else ""
|
||||
|
||||
known = {**_keyframes(css, True), **_keyframes(tailwind, False)}
|
||||
assert known, "一个 @keyframes 都没解析出来 —— 解析器坏了,这条测试也就失去意义了"
|
||||
|
||||
offenders = []
|
||||
for name, origin in _infinite_animations(css, tailwind):
|
||||
body = known.get(name)
|
||||
if body is None:
|
||||
# Tailwind 自带的关键帧(pulse / spin / ping / bounce)都是可合成的。
|
||||
continue
|
||||
bad = _properties(body) - COMPOSITABLE
|
||||
if bad:
|
||||
offenders.append(f"{name}({origin})动画了 {sorted(bad)}")
|
||||
|
||||
assert not offenders, (
|
||||
"无限动画动了不可合成的属性,会让页面永远重绘(慢机器上表现为整台电脑卡、"
|
||||
"且接口在 Network 面板里显示成「下载 20 秒」)。\n"
|
||||
"要发光就把光晕画在伪元素上、动画只改 opacity —— 见 index.css 的 "
|
||||
".status-dot-online。\n " + "\n ".join(offenders)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not CSS.exists(), reason="没有前端源码")
|
||||
def test_the_online_dot_glow_is_pseudo_element_opacity():
|
||||
"""把修好的写法钉住:光晕在 ::after 上,动画只动 opacity。"""
|
||||
css = CSS.read_text(encoding="utf-8")
|
||||
|
||||
assert ".status-dot-online::after" in css
|
||||
assert "statusDotGlow" in css
|
||||
|
||||
rule = css.split(".status-dot-online::after", 1)[1].split("}", 1)[0]
|
||||
assert "box-shadow" in rule, "光晕本身还得在伪元素上画出来"
|
||||
assert "animation" in rule
|
||||
|
||||
glow = _keyframes(css, True)["statusDotGlow"]
|
||||
assert _properties(glow) == {"opacity"}, (
|
||||
"呼吸光晕只能动画 opacity;换回 box-shadow 就是那个把整台电脑拖死的写法"
|
||||
)
|
||||
@@ -0,0 +1,475 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""抖音 Web 接口客户端 —— 纯逻辑部分(不发网络请求、不连浏览器)。
|
||||
|
||||
发请求那半边只能在真环境里验(要 CDP 浏览器 + 登录态),所以这里钉住的是那些
|
||||
「错了会一路错到入库」的地方:请求头的成套性、cookie 解析、以及产物键名。
|
||||
"""
|
||||
|
||||
from tools.user_hash import anonymize_user_id
|
||||
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api.monitor import adapters, douyin_api
|
||||
|
||||
|
||||
class TestCookieParsing:
|
||||
def test_cookie_header_is_normalised(self):
|
||||
assert douyin_api._cookie_header(" a=1 ; b = 2 ;; c=3 ") == "a=1; b=2; c=3"
|
||||
|
||||
def test_cookie_value_lookup(self):
|
||||
assert douyin_api._cookie_value("a=1; UIFID=xyz; b=2", "UIFID") == "xyz"
|
||||
assert douyin_api._cookie_value("a=1", "UIFID") == ""
|
||||
assert douyin_api._cookie_value("", "UIFID") == ""
|
||||
|
||||
def test_session_detection(self):
|
||||
assert douyin_api._has_session("a=1; sessionid=abc") is True
|
||||
assert douyin_api._has_session("a=1; sessionid_ss=abc") is False
|
||||
assert douyin_api._has_session("") is False
|
||||
|
||||
|
||||
class TestRequestHeaders:
|
||||
"""请求头必须**成套**,而且成套地来自同一个浏览器。
|
||||
|
||||
实测:只有 UA + client hints + Cookie 时,主页接口回 200 但只有 121 字节(空壳);
|
||||
补上 Accept / Accept-Language / Referer 才变成 7074 字节的真数据。
|
||||
"""
|
||||
|
||||
def test_the_full_set_is_sent(self):
|
||||
identity = douyin_api.BrowserIdentity(
|
||||
cookie="sessionid=s; UIFID=u1",
|
||||
user_agent="UA-of-this-browser",
|
||||
client_hints={"sec-ch-ua": '"Chrome";v="155"'},
|
||||
)
|
||||
|
||||
headers = identity.headers()
|
||||
|
||||
assert headers["User-Agent"] == "UA-of-this-browser"
|
||||
assert headers["sec-ch-ua"] == '"Chrome";v="155"'
|
||||
assert headers["Accept"], "Accept 系列是主页接口能不能返回真数据的必要条件"
|
||||
assert headers["Accept-Language"]
|
||||
assert headers["Referer"] == "https://www.douyin.com/"
|
||||
assert headers["x-tt-argus"] == douyin_api.ARGUS_HEADER_VALUE
|
||||
assert headers["uifid"] == "u1"
|
||||
assert headers["Cookie"] == "sessionid=s; UIFID=u1"
|
||||
|
||||
def test_uifid_is_omitted_when_absent(self):
|
||||
"""cookie 里没有 uifid 就别带 —— 送个空值反而更像异常请求。"""
|
||||
identity = douyin_api.BrowserIdentity(
|
||||
cookie="sessionid=s", user_agent="UA", client_hints={}
|
||||
)
|
||||
|
||||
assert "uifid" not in identity.headers()
|
||||
|
||||
def test_uifid_temp_is_used_as_a_fallback(self):
|
||||
identity = douyin_api.BrowserIdentity(
|
||||
cookie="sessionid=s; UIFID_TEMP=temp-1", user_agent="UA", client_hints={}
|
||||
)
|
||||
|
||||
assert identity.headers()["uifid"] == "temp-1"
|
||||
|
||||
|
||||
class TestNormalizeAweme:
|
||||
def test_keys_match_what_the_store_writes(self):
|
||||
"""键名必须和 store/douyin 一模一样,否则 ingest 一条都读不到。"""
|
||||
record = douyin_api.normalize_aweme(
|
||||
{
|
||||
"aweme_id": 7690458980574358513,
|
||||
"desc": "中秋哪儿都堵",
|
||||
"create_time": 1790574515,
|
||||
"author": {"uid": "776719710825195", "nickname": "AA建材王总"},
|
||||
"statistics": {
|
||||
"digg_count": 3,
|
||||
"comment_count": 1,
|
||||
"collect_count": 2,
|
||||
"share_count": 0,
|
||||
},
|
||||
"video": {"cover": {"url_list": ["https://img/cover.jpg"]}},
|
||||
}
|
||||
)
|
||||
|
||||
assert record["aweme_id"] == "7690458980574358513"
|
||||
assert record["title"] == "中秋哪儿都堵"
|
||||
assert record["nickname"] == "AA建材王总"
|
||||
assert record["cover_url"] == "https://img/cover.jpg"
|
||||
assert (
|
||||
record["aweme_url"]
|
||||
== "https://www.douyin.com/video/7690458980574358513"
|
||||
)
|
||||
# 与 store 一致:creator_hash 是 uid 的匿名哈希。
|
||||
assert record["creator_hash"] == anonymize_user_id("776719710825195")
|
||||
# **秒**。adapters 的 time_scale=1000 会把它换成毫秒 —— 这一层不算毫秒。
|
||||
assert record["create_time"] == 1790574515
|
||||
# 指标按 store 的形态落成字符串,交给 ingest 的 parse_count 解析。
|
||||
assert record["liked_count"] == "3"
|
||||
assert record["collected_count"] == "2"
|
||||
# 这条 payload 里没有 sec_uid:主页 id 就空着,不许拿 uid 冒充。
|
||||
assert record["creator_id"] == ""
|
||||
|
||||
def test_creator_id_is_the_sec_uid_not_the_uid(self):
|
||||
"""主页链接只能由 sec_uid 拼出来 —— uid 是数字、creator_hash 是单向哈希。"""
|
||||
record = douyin_api.normalize_aweme(
|
||||
{
|
||||
"aweme_id": "1",
|
||||
"author": {
|
||||
"uid": "776719710825195",
|
||||
"sec_uid": "MS4wLjABAAAAcmv4-Oaxe7FN4bdQECz1knSBzKb50uhnykbLIArdkk7",
|
||||
"nickname": "AA建材王总",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert record["creator_id"] == "MS4wLjABAAAAcmv4-Oaxe7FN4bdQECz1knSBzKb50uhnykbLIArdkk7"
|
||||
assert adapters.creator_url("dy", record["creator_id"]).startswith(
|
||||
"https://www.douyin.com/user/"
|
||||
)
|
||||
|
||||
def test_the_authors_account_stats_ride_along(self):
|
||||
"""作品详情里的 author 带着粉丝数 —— 作品模式靠它填博主的账号指标。"""
|
||||
record = douyin_api.normalize_aweme(
|
||||
{
|
||||
"aweme_id": "1",
|
||||
"author": {
|
||||
"uid": "776719710825195",
|
||||
"follower_count": 1444,
|
||||
"total_favorited": 9751,
|
||||
# 实测详情里 aweme_count 是 null
|
||||
"aweme_count": None,
|
||||
"following_count": 0,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert record["creator_fans"] == 1444
|
||||
assert record["creator_total_favorited"] == 9751
|
||||
assert record["creator_works"] is None
|
||||
assert record["creator_following"] == 0
|
||||
|
||||
def test_missing_author_counts_stay_none_not_zero(self):
|
||||
"""0 会被界面显示成「粉丝 0」;事实是没采到,必须留 None。"""
|
||||
record = douyin_api.normalize_aweme(
|
||||
{"aweme_id": "1", "author": {"uid": "1", "nickname": "x"}}
|
||||
)
|
||||
|
||||
assert record["creator_fans"] is None
|
||||
assert record["creator_total_favorited"] is None
|
||||
assert record["creator_works"] is None
|
||||
assert record["creator_following"] is None
|
||||
|
||||
def test_hashtags_come_from_text_extra_not_the_truncated_desc(self):
|
||||
"""`desc` 会在话题列表中途被截断,后半段话题只在 `text_extra` 里。
|
||||
|
||||
实测那条:desc 断在「#噶痔疮 #……版本过低,升级后可展示全部信息」,而完整
|
||||
话题列表里还有 #szgtgg —— 只看 desc 的话,后面的标签规则永远命中不了。
|
||||
"""
|
||||
record = douyin_api.normalize_aweme(
|
||||
{
|
||||
"aweme_id": "1",
|
||||
"desc": "经历过痔疮术后才懂…… #痔疮 #痔疮术后 #噶痔疮 "
|
||||
"#……版本过低,升级后可展示全部信息",
|
||||
"text_extra": [
|
||||
{"hashtag_name": "痔疮", "type": 1},
|
||||
{"hashtag_name": "噶痔疮", "type": 1},
|
||||
{"hashtag_name": "szgtgg", "type": 1},
|
||||
{"type": 0},
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
assert record["hashtags"] == "#痔疮 #噶痔疮 #szgtgg"
|
||||
|
||||
def test_missing_fields_do_not_crash(self):
|
||||
record = douyin_api.normalize_aweme({"aweme_id": "1"})
|
||||
|
||||
assert record["aweme_id"] == "1"
|
||||
assert record["title"] == ""
|
||||
assert record["cover_url"] == ""
|
||||
assert record["liked_count"] == "0"
|
||||
assert record["create_time"] == 0
|
||||
|
||||
|
||||
class TestIdentityFromPages:
|
||||
"""身份得从浏览器里问,但**不能被一个卡死的标签页拖住**。
|
||||
|
||||
实测过:标签页 URL 为空、渲染进程卡死,``page.evaluate`` 永远不返回;而问身份是采集的
|
||||
第一步 —— 没超时的话整轮就挂在那儿,run 永远停在「运行中」。
|
||||
"""
|
||||
|
||||
class _Page:
|
||||
def __init__(self, url, *, user_agent=None, hang=False):
|
||||
self.url = url
|
||||
self._user_agent = user_agent
|
||||
self._hang = hang
|
||||
self.closed = False
|
||||
|
||||
async def evaluate(self, expression):
|
||||
if self._hang:
|
||||
await asyncio.sleep(30) # 模拟渲染进程卡死
|
||||
if expression.startswith("() => navigator.userAgentData"):
|
||||
return {
|
||||
"brands": [{"brand": "Chrome", "version": "155"}],
|
||||
"mobile": False,
|
||||
"platform": "Linux",
|
||||
}
|
||||
return self._user_agent
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
|
||||
class _Context:
|
||||
def __init__(self, pages, temp=None):
|
||||
self.pages = pages
|
||||
self._temp = temp
|
||||
self.made_temp = False
|
||||
|
||||
async def new_page(self):
|
||||
self.made_temp = True
|
||||
if self._temp is None:
|
||||
raise AssertionError("这个用例不该走到临时页")
|
||||
return self._temp
|
||||
|
||||
def _fast_timeout(self, monkeypatch):
|
||||
monkeypatch.setattr(douyin_api, "EVALUATE_TIMEOUT_SECONDS", 0.05)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_hanging_page_is_skipped(self, monkeypatch):
|
||||
self._fast_timeout(monkeypatch)
|
||||
stuck = self._Page("", hang=True)
|
||||
good = self._Page("https://example.com/", user_agent="UA-of-good-page")
|
||||
|
||||
user_agent, hints = await douyin_api._identity_from_pages(
|
||||
self._Context([stuck, good])
|
||||
)
|
||||
|
||||
assert user_agent == "UA-of-good-page"
|
||||
assert hints["sec-ch-ua"] == '"Chrome";v="155"'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_page_without_a_user_agent_is_skipped(self, monkeypatch):
|
||||
self._fast_timeout(monkeypatch)
|
||||
blank = self._Page("", user_agent=None)
|
||||
good = self._Page("https://example.com/", user_agent="UA-of-good-page")
|
||||
|
||||
user_agent, _ = await douyin_api._identity_from_pages(
|
||||
self._Context([blank, good])
|
||||
)
|
||||
|
||||
assert user_agent == "UA-of-good-page"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_it_opens_a_temporary_page_when_nothing_else_works(self, monkeypatch):
|
||||
self._fast_timeout(monkeypatch)
|
||||
stuck = self._Page("", hang=True)
|
||||
temp = self._Page("about:blank", user_agent="UA-of-temp-page")
|
||||
context = self._Context([stuck], temp=temp)
|
||||
|
||||
user_agent, _ = await douyin_api._identity_from_pages(context)
|
||||
|
||||
assert context.made_temp is True
|
||||
assert user_agent == "UA-of-temp-page"
|
||||
assert temp.closed is True, "临时页问完要关掉,别在操作者的浏览器里留垃圾"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_douyin_page_is_preferred(self, monkeypatch):
|
||||
"""有抖音页面就先问它 —— 它才是我们要模仿的那个身份。"""
|
||||
self._fast_timeout(monkeypatch)
|
||||
other = self._Page("https://example.com/", user_agent="UA-of-other")
|
||||
douyin = self._Page("https://www.douyin.com/explore", user_agent="UA-of-douyin")
|
||||
|
||||
user_agent, _ = await douyin_api._identity_from_pages(
|
||||
self._Context([other, douyin])
|
||||
)
|
||||
|
||||
assert user_agent == "UA-of-douyin"
|
||||
|
||||
|
||||
class TestGet:
|
||||
"""`_get` 的失败路径 —— 它们决定了失败会不会被伪装成「这个博主没作品」。"""
|
||||
|
||||
@staticmethod
|
||||
def _client_returning(monkeypatch, status_code: int, text: str):
|
||||
class _Response:
|
||||
def json(self):
|
||||
import json as _json
|
||||
|
||||
return _json.loads(self.text)
|
||||
|
||||
response = _Response()
|
||||
response.status_code = status_code
|
||||
response.text = text
|
||||
|
||||
class _Client:
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def get(self, *args, **kwargs):
|
||||
return response
|
||||
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: _Client())
|
||||
|
||||
def _identity(self):
|
||||
return douyin_api.BrowserIdentity(
|
||||
cookie="sessionid=s", user_agent="UA", client_hints={}
|
||||
)
|
||||
|
||||
def test_an_empty_body_is_an_error_not_an_empty_result(self, monkeypatch):
|
||||
"""「200 + 空 body」是网关拒绝请求的典型回应。
|
||||
|
||||
必须当场报错 —— 放过去的话,它会在下游变成「这个博主没作品」,把一次失败伪装成
|
||||
一条正常的空结果。爬虫那条路就是这么栽的,还被翻译成「账号被封」。
|
||||
"""
|
||||
self._client_returning(monkeypatch, 200, "")
|
||||
|
||||
with pytest.raises(douyin_api.DouyinApiError) as excinfo:
|
||||
asyncio.run(douyin_api._get("/x", {}, self._identity()))
|
||||
|
||||
assert "空内容" in str(excinfo.value)
|
||||
|
||||
def test_a_403_carries_the_gateways_own_message(self, monkeypatch):
|
||||
"""抖音难得会说原因,把它带出来,别丢。"""
|
||||
self._client_returning(
|
||||
monkeypatch, 403, "Blocked by ArgusSecurityPlugin Uifid Not Found"
|
||||
)
|
||||
|
||||
with pytest.raises(douyin_api.DouyinApiError) as excinfo:
|
||||
asyncio.run(douyin_api._get("/x", {}, self._identity()))
|
||||
|
||||
assert "403" in str(excinfo.value)
|
||||
assert "Uifid Not Found" in str(excinfo.value)
|
||||
|
||||
def test_a_200_with_data_is_returned_as_is(self, monkeypatch):
|
||||
self._client_returning(monkeypatch, 200, '{"user": {"nickname": "x"}}')
|
||||
|
||||
assert asyncio.run(douyin_api._get("/x", {}, self._identity())) == {
|
||||
"user": {"nickname": "x"}
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_signer(monkeypatch):
|
||||
"""把真正的 ``a_bogus`` 签名换成假的。
|
||||
|
||||
真的那个在 import 的瞬间就要把 ``libs/douyin.js`` 喂给 execjs(还得有 node 和正确的
|
||||
相对路径),单元测试不该依赖这些。**签名本身是实测过的**:带上它是 200 + 真评论,
|
||||
不带是 200 + 空 body。这里只负责钉住「有没有带上、传对了没有」。
|
||||
"""
|
||||
import sys
|
||||
import types
|
||||
|
||||
module = types.ModuleType("media_platform.douyin.help")
|
||||
calls: list = []
|
||||
|
||||
def get_a_bogus_from_js(url: str, params: str, user_agent: str) -> str:
|
||||
calls.append({"url": url, "params": params, "user_agent": user_agent})
|
||||
return "FAKE-BOGUS"
|
||||
|
||||
module.get_a_bogus_from_js = get_a_bogus_from_js
|
||||
monkeypatch.setitem(sys.modules, "media_platform.douyin.help", module)
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def recording_client(monkeypatch):
|
||||
"""记下实际发出去的那次请求。"""
|
||||
sent: dict = {}
|
||||
|
||||
class _Response:
|
||||
status_code = 200
|
||||
text = '{"comments": []}'
|
||||
|
||||
def json(self):
|
||||
return {"comments": []}
|
||||
|
||||
class _Client:
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def get(self, url, **kwargs):
|
||||
sent["url"] = url
|
||||
sent.update(kwargs)
|
||||
return _Response()
|
||||
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: _Client())
|
||||
return sent
|
||||
|
||||
|
||||
class TestCommentSigning:
|
||||
"""评论接口**必须**带 a_bogus。
|
||||
|
||||
不带的话网关回 200 + 空 body —— 那在下游会变成「这条作品没有评论」,把一次被挡住的
|
||||
请求伪装成一条正常的空结果。和登录失效长得一模一样,查起来能查半天。
|
||||
"""
|
||||
|
||||
def _identity(self):
|
||||
return douyin_api.BrowserIdentity(
|
||||
cookie="sessionid=s", user_agent="UA", client_hints={}
|
||||
)
|
||||
|
||||
def test_the_signature_is_computed_over_the_unsigned_params(
|
||||
self, fake_signer, recording_client
|
||||
):
|
||||
asyncio.run(
|
||||
douyin_api._get(
|
||||
douyin_api.COMMENT_PATH,
|
||||
{"aweme_id": "123", "count": 20},
|
||||
self._identity(),
|
||||
signed=True,
|
||||
)
|
||||
)
|
||||
|
||||
assert len(fake_signer) == 1
|
||||
# 签名算在**不含 a_bogus** 的那串上 —— 把它自己也算进去是循环的。
|
||||
assert fake_signer[0]["params"] == "aweme_id=123&count=20"
|
||||
assert fake_signer[0]["url"] == douyin_api.COMMENT_PATH
|
||||
assert fake_signer[0]["user_agent"] == "UA"
|
||||
|
||||
def test_the_signature_goes_out_with_the_request(self, fake_signer, recording_client):
|
||||
asyncio.run(
|
||||
douyin_api._get(
|
||||
douyin_api.COMMENT_PATH, {"aweme_id": "123"}, self._identity(), signed=True
|
||||
)
|
||||
)
|
||||
|
||||
assert recording_client["params"]["a_bogus"] == "FAKE-BOGUS"
|
||||
assert recording_client["params"]["aweme_id"] == "123"
|
||||
|
||||
def test_unsigned_calls_never_touch_the_signer(self, fake_signer, recording_client):
|
||||
"""作品 / 详情 / 博主资料三个接口不带签名也照常返回。
|
||||
|
||||
给它们加签名是**没验证过的改动** —— 所以这里钉住「不签」,防止有人图省事把
|
||||
signed=True 改成全局默认。
|
||||
"""
|
||||
asyncio.run(
|
||||
douyin_api._get(douyin_api.POSTS_PATH, {"sec_user_id": "x"}, self._identity())
|
||||
)
|
||||
|
||||
assert fake_signer == []
|
||||
assert "a_bogus" not in recording_client["params"]
|
||||
|
||||
def test_a_broken_signer_is_reported_as_such(self, monkeypatch, recording_client):
|
||||
"""execjs 起不来时要说出是签名失败,而不是让它变成「没评论」。"""
|
||||
import sys
|
||||
import types
|
||||
|
||||
module = types.ModuleType("media_platform.douyin.help")
|
||||
|
||||
def boom(url, params, user_agent):
|
||||
raise RuntimeError("node 没装")
|
||||
|
||||
module.get_a_bogus_from_js = boom
|
||||
monkeypatch.setitem(sys.modules, "media_platform.douyin.help", module)
|
||||
|
||||
with pytest.raises(douyin_api.DouyinApiError, match="a_bogus"):
|
||||
asyncio.run(
|
||||
douyin_api._get(
|
||||
douyin_api.COMMENT_PATH, {"aweme_id": "1"}, self._identity(), signed=True
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,55 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""sec-ch-ua 系列请求头:为什么必须带、怎么还原。
|
||||
|
||||
抖音网关对「声称自己是 Chrome、却没带 sec-ch-ua」的请求会回 **200 + 空 body** ——
|
||||
不报错、不给原因、HTTP 状态还是成功的,采集侧只看到 0 条。实测同一 URL、同一 cookie、
|
||||
同一参数:不带头 0 字节,补上这三个头 7077 字节。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from media_platform.douyin.help import client_hint_headers
|
||||
|
||||
# 实测从真实浏览器抓到的 navigator.userAgentData
|
||||
REAL_UA_DATA = {
|
||||
"brands": [
|
||||
{"brand": "Google Chrome", "version": "155"},
|
||||
{"brand": "Chromium", "version": "155"},
|
||||
{"brand": "Not(A:Brand", "version": "24"},
|
||||
],
|
||||
"mobile": False,
|
||||
"platform": "Linux",
|
||||
}
|
||||
|
||||
|
||||
def test_headers_are_derived_from_user_agent_data():
|
||||
hints = client_hint_headers(REAL_UA_DATA)
|
||||
|
||||
assert hints["sec-ch-ua"] == (
|
||||
'"Google Chrome";v="155", "Chromium";v="155", "Not(A:Brand";v="24"'
|
||||
)
|
||||
assert hints["sec-ch-ua-mobile"] == "?0"
|
||||
assert hints["sec-ch-ua-platform"] == '"Linux"'
|
||||
|
||||
|
||||
def test_mobile_is_reflected():
|
||||
hints = client_hint_headers({**REAL_UA_DATA, "mobile": True})
|
||||
|
||||
assert hints["sec-ch-ua-mobile"] == "?1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [None, [], "not-a-dict", {}, {"brands": []}])
|
||||
def test_nothing_is_invented_when_user_agent_data_is_unavailable(value):
|
||||
"""拿不到就返回空。
|
||||
|
||||
凭空造一组和 UA 对不上的头,只会变成**另一个**可疑特征 —— 那比不带头更糟。
|
||||
"""
|
||||
assert client_hint_headers(value) == {}
|
||||
|
||||
|
||||
def test_missing_platform_still_sends_the_other_two():
|
||||
hints = client_hint_headers({"brands": REAL_UA_DATA["brands"], "mobile": False})
|
||||
|
||||
assert "sec-ch-ua" in hints
|
||||
assert "sec-ch-ua-mobile" in hints
|
||||
assert "sec-ch-ua-platform" not in hints
|
||||
@@ -0,0 +1,474 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""抖音采集编排 —— 不碰网络,把 douyin_api 整个换掉。
|
||||
|
||||
验的是编排本身:产物落在正确的目录、文件名是 store 那套、以及**作品列表被挡时的退化**
|
||||
(用已知 aweme_id 逐条刷新)—— 那条退化路径决定了今天这个功能是「完全没用」还是
|
||||
「已知作品还能看」。
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from api.monitor import douyin_api, douyin_fetch
|
||||
|
||||
|
||||
def _profile(**overrides) -> dict:
|
||||
profile = {
|
||||
"creator_hash": "hash",
|
||||
"nickname": "博主",
|
||||
"unique_id": "abc",
|
||||
"fans": 12000,
|
||||
"total_favorited": 83000,
|
||||
"works": 42,
|
||||
"following": 7,
|
||||
}
|
||||
profile.update(overrides)
|
||||
return profile
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fake_profile(monkeypatch):
|
||||
"""每个用例都挡住「问博主资料」这一跳。
|
||||
|
||||
它是附加信息,不在任何一条编排路径上,但真发出去就会去连 9222 那个浏览器 ——
|
||||
于是所有 creator 用例都会多出一次连接失败、并把 ``errors`` 弄脏。想验它自己的
|
||||
用例再单独覆盖这个 fixture。
|
||||
"""
|
||||
|
||||
async def _profile_call(sec_user_id, *, cookie="", identity=None):
|
||||
return _profile()
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_profile", _profile_call)
|
||||
|
||||
# 作品模式会为了「主页最新视频的时间」问一次作品列表;不挡住就会真连抖音。
|
||||
async def _videos_call(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", _videos_call)
|
||||
|
||||
|
||||
def _video(aweme_id: str, likes: str = "1") -> dict:
|
||||
return {
|
||||
"aweme_id": aweme_id,
|
||||
"title": f"title-{aweme_id}",
|
||||
"aweme_url": f"https://www.douyin.com/video/{aweme_id}",
|
||||
"cover_url": "",
|
||||
"aweme_type": "0",
|
||||
"create_time": 1790574515,
|
||||
"creator_hash": "hash",
|
||||
"nickname": "博主",
|
||||
"liked_count": likes,
|
||||
"comment_count": "0",
|
||||
"collected_count": "0",
|
||||
"share_count": "0",
|
||||
}
|
||||
|
||||
|
||||
def _comment(aweme_id: str, index: int) -> dict:
|
||||
return {
|
||||
"comment_id": f"c{index}",
|
||||
"aweme_id": aweme_id,
|
||||
"content": f"评论{index}",
|
||||
"nickname": "路人",
|
||||
"creator_hash": "h2",
|
||||
"create_time": 1790574600,
|
||||
"like_count": "0",
|
||||
"sub_comment_count": "0",
|
||||
"parent_comment_id": "0",
|
||||
}
|
||||
|
||||
|
||||
class _Target:
|
||||
def __init__(self, external_id: str) -> None:
|
||||
self.external_id = external_id
|
||||
|
||||
|
||||
def _read(path):
|
||||
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]
|
||||
|
||||
|
||||
async def _collect(tmp_path, **overrides):
|
||||
kwargs = dict(
|
||||
platform="dy",
|
||||
mode="creator",
|
||||
limit=20,
|
||||
want_comments=True,
|
||||
comment_limit=20,
|
||||
targets=[_Target("MS4w-sec")],
|
||||
cookie="sessionid=x",
|
||||
)
|
||||
kwargs.update(overrides)
|
||||
return await douyin_fetch.collect(tmp_path, **kwargs)
|
||||
|
||||
|
||||
class TestHappyPath:
|
||||
@pytest.mark.asyncio
|
||||
async def test_writes_the_layout_ingest_expects(self, monkeypatch, tmp_path):
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
return [_video("111"), _video("222")]
|
||||
|
||||
async def fake_comments(aweme_id, count=20, *, cookie="", identity=None):
|
||||
return [_comment(aweme_id, 1)]
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
monkeypatch.setattr(douyin_api, "video_comments", fake_comments)
|
||||
|
||||
result = await _collect(tmp_path)
|
||||
|
||||
assert result["notes"] == 2
|
||||
assert result["comments"] == 2
|
||||
assert result["errors"] == []
|
||||
|
||||
# 目录名必须是 douyin(不是平台 id dy)—— ingest 找文件用的是同一个来源。
|
||||
jsonl_dir = tmp_path / "douyin" / "jsonl"
|
||||
assert jsonl_dir.is_dir()
|
||||
|
||||
contents = list(jsonl_dir.glob("*_contents_*.jsonl"))
|
||||
comments = list(jsonl_dir.glob("*_comments_*.jsonl"))
|
||||
assert len(contents) == 1
|
||||
assert len(comments) == 1
|
||||
|
||||
notes = _read(contents[0])
|
||||
assert [n["aweme_id"] for n in notes] == ["111", "222"]
|
||||
# 键名照抄 store/douyin —— ingest 靠这个读出来。
|
||||
assert notes[0]["aweme_url"] == "https://www.douyin.com/video/111"
|
||||
# 秒,不是毫秒;换算交给 adapters。
|
||||
assert notes[0]["create_time"] == 1790574515
|
||||
|
||||
assert _read(comments[0])[0]["aweme_id"] == "111"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_comment_file_exists_even_without_comments(self, monkeypatch, tmp_path):
|
||||
"""评论文件必须建出来。
|
||||
|
||||
ingest 靠「文件在不在」区分「这一轮没评论」和「这一轮什么都没抓到」——
|
||||
两种情况的含义完全不同。
|
||||
"""
|
||||
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
return [_video("111")]
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
|
||||
await _collect(tmp_path, want_comments=False)
|
||||
|
||||
assert len(list((tmp_path / "douyin" / "jsonl").glob("*_comments_*.jsonl"))) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_duplicate_works_are_written_once(self, monkeypatch, tmp_path):
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
return [_video("111"), _video("111")]
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
|
||||
result = await _collect(tmp_path, want_comments=False)
|
||||
|
||||
assert result["notes"] == 1
|
||||
|
||||
|
||||
class TestNoteMode:
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_work_target_is_fetched_by_detail_not_by_creator_list(
|
||||
self, monkeypatch, tmp_path
|
||||
):
|
||||
"""作品模式的目标**本身就是作品 id**,不能拿它当博主的 sec_uid 去查列表。
|
||||
|
||||
走错了会必然失败,而且失败原因很难看懂(接口说你没登录/不是浏览器)——
|
||||
「粘贴作品链接的监控」今天本来是能用的,别让它因为这一处走错而废掉。
|
||||
"""
|
||||
|
||||
async def must_not_be_called(*args, **kwargs):
|
||||
raise AssertionError("作品模式不该去拉博主的作品列表")
|
||||
|
||||
async def fake_detail(aweme_id, *, cookie="", identity=None):
|
||||
return _video(aweme_id)
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", must_not_be_called)
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await _collect(
|
||||
tmp_path,
|
||||
mode="note",
|
||||
want_comments=False,
|
||||
targets=[_Target("111"), _Target("222")],
|
||||
)
|
||||
|
||||
assert result["notes"] == 2
|
||||
assert result["errors"] == []
|
||||
|
||||
notes = _read(list((tmp_path / "douyin" / "jsonl").glob("*_contents_*.jsonl"))[0])
|
||||
assert [n["aweme_id"] for n in notes] == ["111", "222"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_broken_work_does_not_lose_the_others(self, monkeypatch, tmp_path):
|
||||
async def flaky(aweme_id, *, cookie="", identity=None):
|
||||
if aweme_id == "222":
|
||||
raise douyin_api.DouyinApiError("作品已被删除")
|
||||
return _video(aweme_id)
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", flaky)
|
||||
|
||||
result = await _collect(
|
||||
tmp_path,
|
||||
mode="note",
|
||||
want_comments=False,
|
||||
targets=[_Target("111"), _Target("222")],
|
||||
)
|
||||
|
||||
assert result["notes"] == 1
|
||||
assert any("222" in error for error in result["errors"])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_creator_stats_come_from_the_detail_itself(self, monkeypatch, tmp_path):
|
||||
"""作品模式不拉博主资料,粉丝数只能从详情返回的 author 里拿。
|
||||
|
||||
不带出来的话,超级编导导入的任务里每个博主都没有粉丝数 —— 而运营要看的就是
|
||||
「这批号多大」。详情里作者那段是白拿的,不需要多发一次请求。
|
||||
"""
|
||||
|
||||
async def fake_detail(aweme_id, *, cookie="", identity=None):
|
||||
record = _video(aweme_id)
|
||||
record.update(
|
||||
{
|
||||
"creator_id": "MS4wLjABAAAAsecuid",
|
||||
"creator_fans": 1444,
|
||||
"creator_total_favorited": 9751,
|
||||
"creator_works": None,
|
||||
"creator_following": 0,
|
||||
}
|
||||
)
|
||||
return record
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await _collect(
|
||||
tmp_path, mode="note", want_comments=False, targets=[_Target("111")]
|
||||
)
|
||||
|
||||
profiles = _read(
|
||||
list((tmp_path / "douyin" / "jsonl").glob("*_profile_*.jsonl"))[0]
|
||||
)
|
||||
assert result["notes"] == 1
|
||||
assert len(profiles) == 1
|
||||
assert profiles[0]["fans"] == 1444
|
||||
assert profiles[0]["total_favorited"] == 9751
|
||||
assert profiles[0]["creator_id"] == "MS4wLjABAAAAsecuid"
|
||||
# 详情里没有作品总数,留 None 而不是 0。
|
||||
assert profiles[0]["works"] is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_stats_means_no_profile_row(self, monkeypatch, tmp_path):
|
||||
"""精简版 author(字段全缺)不该写一条全 NULL 的快照。"""
|
||||
|
||||
async def fake_detail(aweme_id, *, cookie="", identity=None):
|
||||
return _video(aweme_id)
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
await _collect(
|
||||
tmp_path, mode="note", want_comments=False, targets=[_Target("111")]
|
||||
)
|
||||
|
||||
profiles = _read(
|
||||
list((tmp_path / "douyin" / "jsonl").glob("*_profile_*.jsonl"))[0]
|
||||
)
|
||||
assert profiles == []
|
||||
|
||||
|
||||
class TestDegradation:
|
||||
"""作品列表被挡时的行为 —— 决定了这个功能今天有没有用。"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_falls_back_to_refreshing_known_works(self, monkeypatch, tmp_path):
|
||||
async def blocked(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
raise douyin_api.DouyinApiError("接口返回了空内容")
|
||||
|
||||
refreshed = []
|
||||
|
||||
async def fake_detail(aweme_id, *, cookie="", identity=None):
|
||||
refreshed.append(aweme_id)
|
||||
return _video(aweme_id, likes="9")
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", blocked)
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await _collect(
|
||||
tmp_path, want_comments=False, known_aweme_ids=["999", "888"]
|
||||
)
|
||||
|
||||
assert refreshed == ["999", "888"]
|
||||
assert result["notes"] == 2
|
||||
# 但错误照样报出来 —— 这一轮是「部分可用」,不是「一切正常」,别粉饰。
|
||||
assert any("作品列表失败" in error for error in result["errors"])
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_known_works_are_not_refetched_for_every_target(self, monkeypatch, tmp_path):
|
||||
"""退化路径不能每个目标都把同一批已知作品再刷一遍。
|
||||
|
||||
任务有多个目标时那会让同一件作品在一轮里出现两次,而指标快照的唯一键是
|
||||
(task_id, note_id, run_id) —— 第二次插入直接撞键,整个 run 崩掉(踩过:
|
||||
Duplicate entry for key 'uq_note_metric')。
|
||||
"""
|
||||
|
||||
async def blocked(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
raise douyin_api.DouyinApiError("接口返回了空内容")
|
||||
|
||||
calls = []
|
||||
|
||||
async def fake_detail(aweme_id, *, cookie="", identity=None):
|
||||
calls.append(aweme_id)
|
||||
return _video(aweme_id)
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", blocked)
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await _collect(
|
||||
tmp_path,
|
||||
want_comments=False,
|
||||
targets=[_Target("sec-a"), _Target("sec-b")],
|
||||
known_aweme_ids=["999"],
|
||||
)
|
||||
|
||||
assert calls == ["999"], "同一件已知作品只该刷一次,而不是每个目标一次"
|
||||
assert result["notes"] == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nothing_at_all_still_reports_the_reason(self, monkeypatch, tmp_path):
|
||||
async def blocked(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
raise douyin_api.DouyinApiError("接口返回了空内容")
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", blocked)
|
||||
|
||||
result = await _collect(tmp_path, want_comments=False)
|
||||
|
||||
assert result["notes"] == 0
|
||||
assert result["errors"]
|
||||
# 产物仍然写出来(空的),让调用方去判断这是失败而不是「这个博主没作品」。
|
||||
assert (tmp_path / "douyin" / "jsonl").is_dir()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_failing_comment_fetch_does_not_lose_the_work(self, monkeypatch, tmp_path):
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
return [_video("111")]
|
||||
|
||||
async def broken_comments(aweme_id, count=20, *, cookie="", identity=None):
|
||||
raise douyin_api.DouyinApiError("评论接口抽风")
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
monkeypatch.setattr(douyin_api, "video_comments", broken_comments)
|
||||
|
||||
result = await _collect(tmp_path)
|
||||
|
||||
# 评论拿不到是小事,作品不能跟着丢。
|
||||
assert result["notes"] == 1
|
||||
assert any("评论失败" in error for error in result["errors"])
|
||||
|
||||
|
||||
class TestCreatorProfile:
|
||||
"""博主的**账号级**指标 —— 粉丝 / 总获赞 / 作品数。
|
||||
|
||||
作品列表给不了这个东西:它说的是一件作品涨了多少赞,不是这个人整个账号的粉丝
|
||||
在涨还是在掉。单独问一次资料接口。
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _profiles(tmp_path):
|
||||
files = list((tmp_path / "douyin" / "jsonl").glob("*_profile_*.jsonl"))
|
||||
assert len(files) == 1
|
||||
return _read(files[0])
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_profile_lands_in_the_run_dir(self, monkeypatch, tmp_path):
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
return [_video("111")]
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
|
||||
await _collect(tmp_path, want_comments=False)
|
||||
|
||||
assert self._profiles(tmp_path) == [_profile()]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_profile_is_keyed_by_the_same_hash_as_the_works(
|
||||
self, monkeypatch, tmp_path
|
||||
):
|
||||
"""**这条是关键。** 快照表的唯一键是 (任务, creator_hash, 轮次),而界面上是按
|
||||
作品的 creator_hash 归组去查它的。两边只要差一个字符,粉丝数就永远查不出来 ——
|
||||
而且是静默的:表里有数据,界面上什么都没有。
|
||||
"""
|
||||
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
return [_video("111")] # 作品带的哈希是 "hash"
|
||||
|
||||
# 资料接口自己算出来的是另一个值(比如它那边 uid 缺字段、只能拿 sec_uid 算)。
|
||||
async def off_hash_profile(sec_user_id, *, cookie="", identity=None):
|
||||
return _profile(creator_hash="另一个哈希")
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
monkeypatch.setattr(douyin_api, "author_profile", off_hash_profile)
|
||||
|
||||
await _collect(tmp_path, want_comments=False)
|
||||
|
||||
# 以作品为准:作品才是界面上的行,快照必须挂在能查到它的那个键上。
|
||||
assert self._profiles(tmp_path)[0]["creator_hash"] == "hash"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_profile_without_an_identity_is_dropped(self, monkeypatch, tmp_path):
|
||||
"""哈希都算不出来的快照,落下去只会是一条谁也查不到的垃圾。"""
|
||||
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
return []
|
||||
|
||||
async def anonymous_profile(sec_user_id, *, cookie="", identity=None):
|
||||
return _profile(creator_hash="")
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
monkeypatch.setattr(douyin_api, "author_profile", anonymous_profile)
|
||||
|
||||
result = await _collect(tmp_path, want_comments=False)
|
||||
|
||||
assert self._profiles(tmp_path) == []
|
||||
assert any("身份标识" in error for error in result["errors"])
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_failing_profile_does_not_lose_the_works(self, monkeypatch, tmp_path):
|
||||
"""附加信息拿不到,这一轮采到的作品不能跟着判成失败。"""
|
||||
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
return [_video("111")]
|
||||
|
||||
async def broken_profile(sec_user_id, *, cookie="", identity=None):
|
||||
raise douyin_api.DouyinApiError("资料接口抽风")
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
monkeypatch.setattr(douyin_api, "author_profile", broken_profile)
|
||||
|
||||
result = await _collect(tmp_path, want_comments=False)
|
||||
|
||||
assert result["notes"] == 1
|
||||
assert self._profiles(tmp_path) == []
|
||||
assert any("资料失败" in error for error in result["errors"])
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_work_target_never_asks_for_a_profile(self, monkeypatch, tmp_path):
|
||||
"""作品模式的目标是一件作品,没有「这个博主是谁」可问 —— 不该白发一个请求。"""
|
||||
|
||||
asked = []
|
||||
|
||||
async def fake_detail(aweme_id, *, cookie="", identity=None):
|
||||
return _video(aweme_id)
|
||||
|
||||
async def recording_profile(sec_user_id, *, cookie="", identity=None):
|
||||
asked.append(sec_user_id)
|
||||
return _profile()
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
monkeypatch.setattr(douyin_api, "author_profile", recording_profile)
|
||||
|
||||
await _collect(tmp_path, mode="note", want_comments=False)
|
||||
|
||||
assert asked == []
|
||||
# 文件仍然建出来(空的):事后翻 run 目录能看出「这次根本没问过」。
|
||||
assert self._profiles(tmp_path) == []
|
||||
+130
-27
@@ -70,13 +70,33 @@ class TestParseTargetInput:
|
||||
assert parsed["external_id"] == "6aa3d827000000002802c5c8"
|
||||
assert parsed["xsec_token"] == ""
|
||||
|
||||
def test_creator_url_rejected_in_note_mode(self):
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input(CREATOR_URL, "note")
|
||||
def test_a_creator_url_in_note_mode_falls_through_to_the_raw_value(self):
|
||||
"""粘错类型的链接**不再被拦**(2026-10-12 关掉了校验)。
|
||||
|
||||
def test_garbage_is_rejected(self):
|
||||
代价是明摆着的:以前它会告诉你「这是博主链接,但任务要的是笔记」,现在它照单
|
||||
全收,存进去的是一个抓不到东西的 id。那个代价落在采集那一轮 —— ingest 会发现
|
||||
「一条都没抓到」并报出来,而不是静默通过。
|
||||
"""
|
||||
parsed = parse_target_input(CREATOR_URL, "note")
|
||||
assert parsed["external_id"] == CREATOR_URL[:128]
|
||||
|
||||
def test_garbage_is_stored_as_is(self):
|
||||
parsed = parse_target_input("not a url at all !!", "creator")
|
||||
assert parsed["external_id"] == "not a url at all !!"
|
||||
|
||||
def test_empty_input_is_still_rejected(self):
|
||||
"""「关掉校验」放的是**认不出来的链接**,不是「什么都没粘」。空目标连库都写不进去。"""
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input("not a url at all !!", "creator")
|
||||
parse_target_input(" ", "creator")
|
||||
|
||||
def test_a_too_long_value_is_truncated_to_fit_the_column(self):
|
||||
"""`external_id` 是 varchar(128),而带参数的完整链接常常就 130+ 字符
|
||||
(抖音的 sec_uid 本身 66 位)。不截断的话这一条会直接写库失败。"""
|
||||
long_url = "https://www.douyin.com/root/search/python?aid=b733a3b0&" + "x" * 200
|
||||
|
||||
parsed = parse_target_input(long_url, "note", "dy")
|
||||
|
||||
assert len(parsed["external_id"]) == 128
|
||||
|
||||
# --- 抖音 -------------------------------------------------------------
|
||||
# 链接形态由平台决定,所以每一个都要显式带上 "dy"。
|
||||
@@ -116,21 +136,16 @@ class TestParseTargetInput:
|
||||
assert parsed["external_id"] == sec_uid
|
||||
|
||||
def test_douyin_bare_sec_uid_beyond_the_xhs_length_cap(self):
|
||||
"""裸 id 的长度上限必须按平台分开。
|
||||
"""长 sec_uid 两个平台都收得下 —— 身份校验已经关掉了。
|
||||
|
||||
小红书那条规则封顶 64 字符,而 sec_user_id 长过 64 是常态(实测样本 55,
|
||||
但字段本身是变长的)。共用一条规则的话,长一点的 sec_uid 会被直接拒掉 ——
|
||||
对用户来说就是「粘贴了一个完全正确的链接却报无法识别」。
|
||||
以前小红书那条规则封顶 64 字符,而 sec_user_id 长过 64 是常态,于是「粘贴了一个
|
||||
完全正确的链接却报无法识别」。现在两个平台都原样收下。
|
||||
"""
|
||||
sec_uid = "MS4wLjABAAAA" + "aB3dEf6hIj9lMn2pQr5tUv8xYz1" * 3
|
||||
assert len(sec_uid) > 64
|
||||
|
||||
parsed = parse_target_input(sec_uid, "creator", "dy")
|
||||
assert parsed["external_id"] == sec_uid
|
||||
|
||||
# 同一条 id 拿小红书规则来解析会被拒 —— 这正是两条规则必须分开的原因。
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input(sec_uid, "creator", "xhs")
|
||||
assert parse_target_input(sec_uid, "creator", "dy")["external_id"] == sec_uid
|
||||
assert parse_target_input(sec_uid, "creator", "xhs")["external_id"] == sec_uid
|
||||
|
||||
def test_douyin_bare_video_id(self):
|
||||
parsed = parse_target_input("7525082444551310602", "note", "dy")
|
||||
@@ -138,21 +153,27 @@ class TestParseTargetInput:
|
||||
# 抖音不需要 xsec_token —— 和小红书不同,裸链接就能用。
|
||||
assert parsed["xsec_token"] == ""
|
||||
|
||||
def test_douyin_short_link_is_rejected_with_a_reason(self):
|
||||
"""短链要联网跳一次才知道指向谁。明确拒绝好过存一个永远抓不到东西的目标。"""
|
||||
with pytest.raises(TargetParseError) as excinfo:
|
||||
parse_target_input("https://v.douyin.com/drIPtQ_WPWY/", "note", "dy")
|
||||
assert "短链" in str(excinfo.value)
|
||||
def test_douyin_short_link_is_accepted_but_will_not_fetch(self):
|
||||
"""分享短链现在放行,但存进去的是短码本身 —— 那个目标抓不到东西。
|
||||
|
||||
以前这里是明确拒绝的(「短链要联网跳一次才知道指向谁」)。关掉校验之后不拦了,
|
||||
代价转移到了采集那一轮。要真正支持短链得联网跟一次跳转解出 sec_uid,那是另一件事。
|
||||
"""
|
||||
parsed = parse_target_input("https://v.douyin.com/drIPtQ_WPWY/", "note", "dy")
|
||||
|
||||
assert parsed["external_id"] == "https://v.douyin.com/drIPtQ_WPWY/"
|
||||
|
||||
def test_a_douyin_link_is_not_parsed_with_xhs_rules(self):
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input(
|
||||
"https://www.douyin.com/video/7525082444551310602", "note", "xhs"
|
||||
)
|
||||
"""**这条仍然重要**:关掉的是「拦截」,不是「辨别」。
|
||||
|
||||
小红书的正则不该从抖音链接里抠出一个 id 来 —— 那会是一个**看起来正常但完全
|
||||
错误**的目标,比原样存下来糟得多。
|
||||
"""
|
||||
url = "https://www.douyin.com/video/7525082444551310602"
|
||||
assert parse_target_input(url, "note", "xhs")["external_id"] == url
|
||||
|
||||
def test_an_xhs_link_is_not_parsed_for_douyin(self):
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input(NOTE_URL, "note", "dy")
|
||||
assert parse_target_input(NOTE_URL, "note", "dy")["external_id"] == NOTE_URL
|
||||
|
||||
def test_a_platform_without_an_adapter_is_rejected(self):
|
||||
with pytest.raises(TargetParseError):
|
||||
@@ -230,11 +251,27 @@ class TestTaskCrud:
|
||||
assert listing.json()["tasks"][0]["target_count"] == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_target_returns_400(self, client):
|
||||
async def test_an_unrecognised_target_is_accepted_as_is(self, client):
|
||||
"""认不出来的目标不再被拒(2026-10-12 关掉了链接校验)。
|
||||
|
||||
存的是原值 —— 采集那一轮会抓不到东西并报出来,而不是静默通过。
|
||||
"""
|
||||
response = await client.post(
|
||||
"/api/monitor/tasks",
|
||||
json={"name": "bad", "mode": "creator", "targets": ["!!! nonsense !!!"]},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
tasks = (await client.get("/api/monitor/tasks")).json()["tasks"]
|
||||
assert tasks[0]["targets"][0]["external_id"] == "!!! nonsense !!!"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_empty_target_is_still_rejected(self, client):
|
||||
"""空目标连库都写不进去,这个仍然要拦。"""
|
||||
response = await client.post(
|
||||
"/api/monitor/tasks",
|
||||
json={"name": "bad", "mode": "creator", "targets": [" "]},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -317,3 +354,69 @@ class TestDashboardQueries:
|
||||
overview = (await client.get("/api/monitor/overview")).json()
|
||||
assert overview["tasks"] == 0
|
||||
assert overview["notes"] == 0
|
||||
|
||||
|
||||
class TestShortLinksAreResolvedOnCreate:
|
||||
"""建任务时短链要**先解开再存** —— 存的是短码本身的话,采集永远抓不到东西。
|
||||
|
||||
这一条测的是**接线**(create_task / update_task 有没有走 prepare_target)。
|
||||
解短链本身的逻辑在 test_monitor_short_link.py 里测。
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_share_link_is_stored_expanded(self, client, monkeypatch):
|
||||
from api.monitor import service
|
||||
|
||||
real = "https://www.xiaohongshu.com/user/profile/69d388f00000000032024a75"
|
||||
|
||||
async def fake_expand(value, platform):
|
||||
return real
|
||||
|
||||
monkeypatch.setattr(service, "expand_short_link", fake_expand)
|
||||
|
||||
response = await client.post(
|
||||
"/api/monitor/tasks",
|
||||
json={
|
||||
"name": "短链",
|
||||
"mode": "creator",
|
||||
"platform": "xhs",
|
||||
"targets": ["https://xhslink.cn/o/AhQpHsqcme5"],
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
tasks = (await client.get("/api/monitor/tasks")).json()["tasks"]
|
||||
target = tasks[0]["targets"][0]
|
||||
assert target["external_id"] == "69d388f00000000032024a75"
|
||||
# 原文留着 —— 解错目标时靠它回溯用户当初粘的是什么。
|
||||
assert target["raw_value"] == "https://xhslink.cn/o/AhQpHsqcme5"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_updating_targets_resolves_them_too(self, client, monkeypatch):
|
||||
"""改目标走的是另一条路,同样不能漏。"""
|
||||
from api.monitor import service
|
||||
|
||||
async def fake_expand(value, platform):
|
||||
return "https://www.xiaohongshu.com/user/profile/aaaabbbbccccddddeeeeffff"
|
||||
|
||||
created = await client.post(
|
||||
"/api/monitor/tasks",
|
||||
json={
|
||||
"name": "改目标",
|
||||
"mode": "creator",
|
||||
"platform": "xhs",
|
||||
"targets": ["5f58bd990000000001003753"],
|
||||
},
|
||||
)
|
||||
assert created.status_code == 201
|
||||
task_id = (await client.get("/api/monitor/tasks")).json()["tasks"][0]["id"]
|
||||
monkeypatch.setattr(service, "expand_short_link", fake_expand)
|
||||
|
||||
response = await client.patch(
|
||||
f"/api/monitor/tasks/{task_id}",
|
||||
json={"targets": ["https://xhslink.cn/o/whatever"]},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
|
||||
tasks = (await client.get("/api/monitor/tasks")).json()["tasks"]
|
||||
assert tasks[0]["targets"][0]["external_id"] == "aaaabbbbccccddddeeeeffff"
|
||||
|
||||
@@ -10,7 +10,7 @@ work from the model metadata.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import Boolean, Column, Integer, MetaData, String, Table
|
||||
from sqlalchemy import Boolean, Column, Integer, LargeBinary, MetaData, String, Table, Text
|
||||
|
||||
from api.monitor import db
|
||||
from api.monitor.models import MonitorBase
|
||||
@@ -54,6 +54,10 @@ def test_not_null_columns_carry_a_default(column):
|
||||
"""
|
||||
if column.nullable:
|
||||
pytest.skip("nullable column needs no seed value")
|
||||
# TEXT/BLOB 例外:MySQL 5.7 直接拒绝 DEFAULT(报 1101)。这类列靠 MySQL 给已有行
|
||||
# 填隐式默认值 —— 真踩过,启动时的 ALTER 失败会让整个服务反复重启。
|
||||
if isinstance(column.type, (Text, LargeBinary)):
|
||||
pytest.skip("TEXT/BLOB 不能带 DEFAULT(MySQL 5.7)")
|
||||
|
||||
assert "DEFAULT" in db._column_ddl(column)
|
||||
|
||||
@@ -81,3 +85,21 @@ def test_a_not_null_column_without_a_model_default_falls_back_to_zero():
|
||||
ddl = _ddl(Column("n", Integer, nullable=False))
|
||||
|
||||
assert "DEFAULT 0" in ddl
|
||||
|
||||
|
||||
def test_text_columns_never_get_a_default():
|
||||
"""MySQL 5.7 不允许 TEXT/BLOB 列带 DEFAULT。
|
||||
|
||||
补列在**启动阶段**跑:一旦拼出 `TEXT NOT NULL DEFAULT ''`,ALTER 直接报 1101,
|
||||
应用起不来、容器反复重启。真的踩过(hashtags 列)。
|
||||
"""
|
||||
ddl = db._column_ddl(Column("hashtags", Text, nullable=False))
|
||||
|
||||
assert "DEFAULT" not in ddl.upper()
|
||||
|
||||
|
||||
def test_varchar_columns_still_get_a_default():
|
||||
"""VARCHAR 可以带 DEFAULT,而且带了对已有行更友好 —— 别一刀切。"""
|
||||
ddl = db._column_ddl(Column("hashtags", String(2000), nullable=False))
|
||||
|
||||
assert "DEFAULT ''" in ddl
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
|
||||
import csv
|
||||
import io
|
||||
import re
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
@@ -264,7 +265,8 @@ class TestExport:
|
||||
workbook = load_workbook(io.BytesIO(response.content))
|
||||
sheet = workbook.active
|
||||
assert sheet.max_row == 5 # header + four comments
|
||||
assert sheet.cell(row=1, column=1).value == "所属作品"
|
||||
assert sheet.cell(row=1, column=1).value == "博主昵称"
|
||||
assert sheet.cell(row=1, column=2).value == "所属作品"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_report_export(self, client):
|
||||
@@ -292,3 +294,158 @@ class TestExport:
|
||||
"/api/monitor/export", params={"kind": "comments", "note_id": "no-such-note"}
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestNotesExportColumns:
|
||||
"""作品导出的列 —— 「有列名」和「列里有数」是两回事。
|
||||
|
||||
原先这几列写的是裸键名 `liked_count`,而作品行的指标是嵌在 `metrics` 里的,
|
||||
于是导出来的表有「点赞/评论/收藏/分享」四列,**每一格都是空的**,还没人发现 ——
|
||||
因为原来的测试只断言了 `作品ID`。
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_metric_columns_actually_contain_numbers(self, client):
|
||||
from api.monitor.models import MonitorNoteMetric
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
from sqlalchemy import select
|
||||
|
||||
task_id = (await session.scalar(select(MonitorTask.id))).__int__()
|
||||
session.add(
|
||||
MonitorNoteMetric(
|
||||
task_id=task_id, note_id="note-a", run_id=1,
|
||||
captured_at=1_700_000_000_000,
|
||||
liked_count=123, comment_count=45,
|
||||
collected_count=6, share_count=7,
|
||||
)
|
||||
)
|
||||
|
||||
response = await client.get(
|
||||
"/api/monitor/export", params={"kind": "notes", "format": "csv"}
|
||||
)
|
||||
rows = list(csv.DictReader(io.StringIO(response.content.decode("utf-8-sig"))))
|
||||
by_id = {row["作品ID"]: row for row in rows}
|
||||
|
||||
assert by_id["note-a"]["点赞"] == "123"
|
||||
assert by_id["note-a"]["评论"] == "45"
|
||||
assert by_id["note-a"]["收藏"] == "6"
|
||||
assert by_id["note-a"]["分享"] == "7"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_missing_metric_is_left_empty_not_zero(self, client):
|
||||
"""没采到的指标留空。写 0 的话,导出来的表会声称这条作品零互动。"""
|
||||
response = await client.get(
|
||||
"/api/monitor/export", params={"kind": "notes", "format": "csv"}
|
||||
)
|
||||
rows = list(csv.DictReader(io.StringIO(response.content.decode("utf-8-sig"))))
|
||||
|
||||
assert rows[0]["点赞"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_export_says_who_the_creator_is(self, client):
|
||||
"""一行只有作品 ID 没法用 —— 导出来是拿去比对和汇报的。
|
||||
|
||||
备注优先:昵称常常认不出是谁,而备注是人自己起的名字。
|
||||
"""
|
||||
response = await client.get(
|
||||
"/api/monitor/export", params={"kind": "notes", "format": "csv"}
|
||||
)
|
||||
rows = list(csv.DictReader(io.StringIO(response.content.decode("utf-8-sig"))))
|
||||
|
||||
assert {row["博主昵称"] for row in rows} == {"博主甲", "博主乙"}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_times_are_readable_not_raw_milliseconds(self, client):
|
||||
"""毫秒时间戳倒进 CSV 就是 13 位数字,打开 Excel 的人没法看、也没法排序。"""
|
||||
response = await client.get(
|
||||
"/api/monitor/export", params={"kind": "notes", "format": "csv"}
|
||||
)
|
||||
rows = list(csv.DictReader(io.StringIO(response.content.decode("utf-8-sig"))))
|
||||
by_id = {row["作品ID"]: row for row in rows}
|
||||
|
||||
# 断言**形状**而不是具体时刻:格式化用的是服务器本地时区,写死一个字符串的话
|
||||
# 换个时区的机器上就会红。
|
||||
assert re.fullmatch(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}", by_id["note-a"]["发布时间"])
|
||||
assert re.fullmatch(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}", by_id["note-a"]["首次发现"])
|
||||
# 而且不能是原始毫秒。
|
||||
assert by_id["note-a"]["发布时间"] != str(PUBLISHED_A)
|
||||
|
||||
|
||||
class TestNotesExportWithoutWorks:
|
||||
"""**一条作品都没有的博主,也要在导出里占一行**,作品那几列留空。
|
||||
|
||||
导出是拿去比对名单的,「这个号这段时间一条作品都没发」恰恰是名单上最该被看见的
|
||||
一行 —— 还在涨粉、只是没动静,或者号出了问题。按作品导的话他直接消失,而在表里,
|
||||
**消失和「一切正常」长得一模一样**。
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
async def _add_creator_without_works(**overrides) -> None:
|
||||
from sqlalchemy import select
|
||||
|
||||
from api.monitor.models import MonitorCreatorStat
|
||||
|
||||
fields = dict(
|
||||
run_id=1, creator_hash="hash-c", nickname="博主丙", fans=8800,
|
||||
total_favorited=4321, works_count=7, following=2,
|
||||
captured_at=1_700_000_000_000,
|
||||
)
|
||||
fields.update(overrides)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
task_id = await session.scalar(select(MonitorTask.id))
|
||||
session.add(MonitorCreatorStat(task_id=task_id, **fields))
|
||||
|
||||
@staticmethod
|
||||
async def _rows(client):
|
||||
response = await client.get(
|
||||
"/api/monitor/export", params={"kind": "notes", "format": "csv"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
return list(csv.DictReader(io.StringIO(response.content.decode("utf-8-sig"))))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_without_works_gets_a_row(self, client):
|
||||
await self._add_creator_without_works()
|
||||
|
||||
rows = await self._rows(client)
|
||||
only = [row for row in rows if row["博主昵称"] == "博主丙"]
|
||||
|
||||
assert len(only) == 1, "没有作品的博主从导出里消失了"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_that_row_keeps_the_creator_info_and_leaves_works_empty(self, client):
|
||||
await self._add_creator_without_works()
|
||||
|
||||
row = next(r for r in await self._rows(client) if r["博主昵称"] == "博主丙")
|
||||
|
||||
# 博主那几列要有 —— 否则这一行就是个空行。
|
||||
assert row["粉丝数"] == "8800"
|
||||
assert row["总获赞"] == "4321"
|
||||
assert row["主页作品数"] == "7"
|
||||
# 作品那几列留空。**空,不是 0** —— 0 会读成「这条作品零互动」。
|
||||
for column in ("作品ID", "标题", "链接", "发布时间", "点赞", "评论", "收藏", "分享"):
|
||||
assert row[column] == "", f"{column} 应该是空的"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_works_are_still_all_there(self, client):
|
||||
"""加了这一类行之后,原来那些作品一行都不能少。"""
|
||||
await self._add_creator_without_works()
|
||||
|
||||
rows = await self._rows(client)
|
||||
|
||||
assert {row["作品ID"] for row in rows if row["作品ID"]} == {"note-a", "note-b"}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_whose_metrics_are_unknown_leaves_them_empty(self, client):
|
||||
"""采不到账号指标时留空,不写 0 —— 和界面一个口径。"""
|
||||
await self._add_creator_without_works(
|
||||
fans=None, total_favorited=None, works_count=None
|
||||
)
|
||||
|
||||
row = next(r for r in await self._rows(client) if r["博主昵称"] == "博主丙")
|
||||
|
||||
assert row["粉丝数"] == ""
|
||||
assert row["总获赞"] == ""
|
||||
assert row["主页作品数"] == ""
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""主页「最早一条视频」的扫描:翻页、取最小值、缓存与失败重试。"""
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import select
|
||||
|
||||
from api.monitor import creator_scan, db as monitor_db, douyin_api
|
||||
from api.monitor.models import MonitorCreatorFirstVideo
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def session(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "scan.db")
|
||||
await monitor_db.init_db()
|
||||
async with monitor_db.get_session() as db_session:
|
||||
yield db_session
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fast(monkeypatch):
|
||||
monkeypatch.setattr(creator_scan, "REQUEST_GAP_SECONDS", 0)
|
||||
|
||||
async def fake_identity(cookie="", force=False):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(douyin_api, "browser_identity", fake_identity)
|
||||
|
||||
|
||||
class TestScan:
|
||||
@pytest.mark.asyncio
|
||||
async def test_pages_to_the_end_and_takes_the_oldest(self, monkeypatch):
|
||||
pages = {
|
||||
0: ([{"create_time": 1793000000}, {"create_time": 1792000000}], 100, True),
|
||||
100: ([{"create_time": 1700000000}], 50, True),
|
||||
50: ([{"create_time": 1600000000}], 0, False),
|
||||
}
|
||||
|
||||
async def fake_page(sec_user_id, max_cursor=0, count=20, *, cookie="", identity=None):
|
||||
return pages[max_cursor]
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos_page", fake_page)
|
||||
|
||||
oldest, page_count, complete = await creator_scan._scan("MS4w-sec")
|
||||
|
||||
assert oldest == 1600000000 * 1000
|
||||
assert page_count == 3
|
||||
assert complete is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_unchanging_cursor_does_not_loop_forever(self, monkeypatch):
|
||||
async def fake_page(sec_user_id, max_cursor=0, count=20, *, cookie="", identity=None):
|
||||
return [{"create_time": 1600000000}], 7, True
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos_page", fake_page)
|
||||
|
||||
_oldest, page_count, complete = await creator_scan._scan("MS4w-sec")
|
||||
|
||||
assert page_count == 2
|
||||
assert complete is False
|
||||
|
||||
|
||||
class TestCache:
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_successful_scan_is_written_to_the_cache(self, session, monkeypatch):
|
||||
async def fake_scan(creator_id):
|
||||
return 1700000000000, 4, True
|
||||
|
||||
monkeypatch.setattr(creator_scan, "_scan", fake_scan)
|
||||
|
||||
ok = await creator_scan.scan_one(session, "dy", "hash-a", "MS4w-sec")
|
||||
|
||||
assert ok is True
|
||||
row = await session.scalar(
|
||||
select(MonitorCreatorFirstVideo).where(
|
||||
MonitorCreatorFirstVideo.creator_id == "MS4w-sec"
|
||||
)
|
||||
)
|
||||
assert row.first_published_at == 1700000000000
|
||||
assert row.scanned_pages == 4
|
||||
assert row.complete is True
|
||||
assert row.error == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_failure_is_recorded_and_retried_after_a_while(
|
||||
self, session, monkeypatch
|
||||
):
|
||||
async def boom(creator_id):
|
||||
raise douyin_api.DouyinApiError("接口超时")
|
||||
|
||||
monkeypatch.setattr(creator_scan, "_scan", boom)
|
||||
now = get_current_timestamp()
|
||||
|
||||
ok = await creator_scan.scan_one(
|
||||
session, "dy", "hash-a", "MS4w-sec", now=now
|
||||
)
|
||||
|
||||
assert ok is False
|
||||
row = await session.scalar(
|
||||
select(MonitorCreatorFirstVideo).where(
|
||||
MonitorCreatorFirstVideo.creator_id == "MS4w-sec"
|
||||
)
|
||||
)
|
||||
assert "接口超时" in row.error
|
||||
assert row.first_published_at is None
|
||||
# checked_at 往前拨:大约 6 小时后就重新到期,而不是锁 30 天。
|
||||
assert row.checked_at == now - creator_scan.TTL_MS + creator_scan.RETRY_MS
|
||||
@@ -0,0 +1,418 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""作品栏里的**博主**:备注(他到底是谁)与账号级指标(他现在多大)。
|
||||
|
||||
按 creator_hash 分组、显示 creator_name,两样都认不出人:一个是哈希,一个是平台昵称。
|
||||
备注是人自己起的名字。账号级指标则是作品列表给不了的东西 —— 作品说的是"这条涨了多少赞",
|
||||
粉丝数说的是"这个人整个账号在涨还是在掉"。
|
||||
"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from api.main import app
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor.models import (
|
||||
MODE_CREATOR,
|
||||
MonitorCreatorStat,
|
||||
MonitorNote,
|
||||
MonitorTask,
|
||||
)
|
||||
|
||||
CREATOR_HASH = "hash-a"
|
||||
NICKNAME = "张三"
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
|
||||
await monitor_db.init_db()
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http_client:
|
||||
yield http_client
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
async def _seed(
|
||||
platform: str = "xhs", task_name: str = "任务", creator_id: str = ""
|
||||
) -> int:
|
||||
"""一个任务 + 一条作品,博主固定用 CREATOR_HASH / NICKNAME。"""
|
||||
async with monitor_db.get_session() as session:
|
||||
task = MonitorTask(
|
||||
name=task_name, platform=platform, mode=MODE_CREATOR, enabled=True,
|
||||
interval_minutes=60, max_notes_count=20, enable_comments=False,
|
||||
max_comments_count=50, run_timeout_seconds=3600,
|
||||
notify_enabled=False, created_at=0, updated_at=0,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
session.add(
|
||||
MonitorNote(
|
||||
task_id=task.id, note_id=f"{platform}-n1", title="作品",
|
||||
note_url="", cover="", creator_hash=CREATOR_HASH,
|
||||
creator_name=NICKNAME, creator_id=creator_id, source_kind="",
|
||||
published_at=None,
|
||||
first_seen_run_id=1, first_seen_at=0,
|
||||
last_seen_run_id=1, last_seen_at=0,
|
||||
)
|
||||
)
|
||||
return task.id
|
||||
|
||||
|
||||
async def _notes(client, platform: str = "xhs"):
|
||||
return (await client.get("/api/monitor/notes", params={"platform": platform})).json()["notes"]
|
||||
|
||||
|
||||
async def _set_alias(client, alias: str, platform: str = "xhs", creator_hash=CREATOR_HASH):
|
||||
return await client.put(
|
||||
f"/api/monitor/creators/{creator_hash}",
|
||||
params={"platform": platform},
|
||||
json={"alias": alias},
|
||||
)
|
||||
|
||||
|
||||
class TestCreatorAlias:
|
||||
@pytest.mark.asyncio
|
||||
async def test_notes_start_without_an_alias(self, client):
|
||||
await _seed()
|
||||
|
||||
assert (await _notes(client))[0]["creator_alias"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_alias_comes_back_with_the_notes(self, client):
|
||||
await _seed()
|
||||
|
||||
response = await _set_alias(client, "竞品A")
|
||||
|
||||
assert response.status_code == 200
|
||||
note = (await _notes(client))[0]
|
||||
assert note["creator_alias"] == "竞品A"
|
||||
# 备注是**叠加**在昵称之上的,不是替换 —— 昵称仍然是有用的对照。
|
||||
assert note["creator_name"] == NICKNAME
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_alias_is_shared_across_tasks(self, client):
|
||||
"""同一个博主出现在两个任务里,备注只该填一次。
|
||||
|
||||
creator_hash 对同一个 uid 是稳定的,所以键取 (platform, creator_hash) 而不是
|
||||
按任务存 —— 否则每加一个任务都要重新认一遍人。
|
||||
"""
|
||||
await _seed(task_name="任务甲")
|
||||
await _seed(task_name="任务乙")
|
||||
await _set_alias(client, "竞品A")
|
||||
|
||||
for note in await _notes(client):
|
||||
assert note["creator_alias"] == "竞品A"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_alias_does_not_leak_to_another_platform(self, client):
|
||||
"""同一个哈希在另一个平台上是另一个(或同一个)人 —— 别串味。"""
|
||||
await _seed(platform="xhs")
|
||||
await _seed(platform="dy")
|
||||
|
||||
await _set_alias(client, "小红书那边的", platform="xhs")
|
||||
|
||||
assert (await _notes(client, "xhs"))[0]["creator_alias"] == "小红书那边的"
|
||||
assert (await _notes(client, "dy"))[0]["creator_alias"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_empty_alias_clears_it(self, client):
|
||||
await _seed()
|
||||
await _set_alias(client, "竞品A")
|
||||
|
||||
await _set_alias(client, "")
|
||||
|
||||
assert (await _notes(client))[0]["creator_alias"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_alias_is_trimmed(self, client):
|
||||
await _seed()
|
||||
|
||||
await _set_alias(client, " 竞品A ")
|
||||
|
||||
assert (await _notes(client))[0]["creator_alias"] == "竞品A"
|
||||
|
||||
|
||||
async def _add_stat(
|
||||
task_id: int,
|
||||
run_id: int,
|
||||
fans: int | None,
|
||||
*,
|
||||
total_favorited: int | None = 83000,
|
||||
works: int | None = 42,
|
||||
creator_hash: str = CREATOR_HASH,
|
||||
captured_at: int = 1,
|
||||
creator_id: str = "",
|
||||
nickname: str = NICKNAME,
|
||||
) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorCreatorStat(
|
||||
task_id=task_id,
|
||||
run_id=run_id,
|
||||
creator_hash=creator_hash,
|
||||
nickname=nickname,
|
||||
creator_id=creator_id,
|
||||
fans=fans,
|
||||
total_favorited=total_favorited,
|
||||
works_count=works,
|
||||
following=7,
|
||||
captured_at=captured_at,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class TestCreatorStats:
|
||||
"""账号级指标跟着作品一起返回 —— 界面上是按博主归组的,为了一个组头再发一轮请求
|
||||
没道理。"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_without_snapshots_the_fields_are_null(self, client):
|
||||
"""null 而不是 0:0 会显示成「粉丝 0」,而事实是"还没采到"。"""
|
||||
await _seed()
|
||||
|
||||
note = (await _notes(client))[0]
|
||||
|
||||
assert note["creator_fans"] is None
|
||||
assert note["creator_total_favorited"] is None
|
||||
assert note["creator_works"] is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_snapshot_shows_up_on_every_work_of_that_creator(self, client):
|
||||
task_id = await _seed()
|
||||
await _add_stat(task_id, run_id=1, fans=12000)
|
||||
|
||||
for note in await _notes(client):
|
||||
assert note["creator_fans"] == 12000
|
||||
assert note["creator_total_favorited"] == 83000
|
||||
assert note["creator_works"] == 42
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_latest_run_wins(self, client):
|
||||
"""一轮一条,所以总会有好几条 —— 给界面的必须是最近那条。"""
|
||||
task_id = await _seed()
|
||||
await _add_stat(task_id, run_id=1, fans=12000)
|
||||
await _add_stat(task_id, run_id=2, fans=12300)
|
||||
|
||||
assert (await _notes(client))[0]["creator_fans"] == 12300
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_another_platforms_snapshot_does_not_leak(self, client):
|
||||
"""两个平台上恰好同名同哈希的博主是两个人 —— 快照挂在任务上,不该串。"""
|
||||
await _seed(platform="xhs")
|
||||
dy_task_id = await _seed(platform="dy")
|
||||
await _add_stat(dy_task_id, run_id=1, fans=999)
|
||||
|
||||
assert (await _notes(client, "xhs"))[0]["creator_fans"] is None
|
||||
assert (await _notes(client, "dy"))[0]["creator_fans"] == 999
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_unparsed_count_stays_null(self, client):
|
||||
"""快照在,但某一项没解析出来 —— 那一项必须是 null,不能变成 0。
|
||||
|
||||
和上一条的区别:那条是"根本没有快照",这条是"有快照、其中一项平台没给"。
|
||||
界面上两种都该是「—」。
|
||||
"""
|
||||
task_id = await _seed()
|
||||
await _add_stat(
|
||||
task_id, run_id=1, fans=None, total_favorited=None, works=None
|
||||
)
|
||||
|
||||
note = (await _notes(client))[0]
|
||||
|
||||
assert note["creator_fans"] is None
|
||||
assert note["creator_works"] is None
|
||||
# 快照本身是有的(有采集时间),只是值不知道 —— 前端要能分开这两件事。
|
||||
assert note["creator_stats_at"] is not None
|
||||
|
||||
|
||||
async def _seed_task(platform: str = "xhs", task_name: str = "空任务") -> int:
|
||||
"""只有任务,**一条作品都没有**。"""
|
||||
async with monitor_db.get_session() as session:
|
||||
task = MonitorTask(
|
||||
name=task_name, platform=platform, mode=MODE_CREATOR, enabled=True,
|
||||
interval_minutes=60, max_notes_count=20, enable_comments=False,
|
||||
max_comments_count=50, run_timeout_seconds=3600,
|
||||
notify_enabled=False, created_at=0, updated_at=0,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
return task.id
|
||||
|
||||
|
||||
async def _creators(client, platform: str = "xhs"):
|
||||
return (await client.get("/api/monitor/notes", params={"platform": platform})).json()["creators"]
|
||||
|
||||
|
||||
class TestCreatorList:
|
||||
"""作品栏要显示谁 —— **包括一条作品都没有的博主**。
|
||||
|
||||
组原先是从作品推出来的,于是「目标加了、资料采到了、粉丝数在库里,界面上什么都
|
||||
没有」。而这类博主恰恰最该看见:还在涨粉,只是最近没发东西。
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_with_no_works_still_shows_up(self, client):
|
||||
"""**这条就是这个改动的全部理由。**"""
|
||||
task_id = await _seed_task()
|
||||
await _add_stat(task_id, run_id=1, fans=12000)
|
||||
|
||||
creators = await _creators(client)
|
||||
|
||||
assert len(creators) == 1
|
||||
assert creators[0]["creator_hash"] == CREATOR_HASH
|
||||
assert creators[0]["creator_name"] == NICKNAME # 只剩快照这一个来源
|
||||
assert creators[0]["note_count"] == 0
|
||||
assert creators[0]["creator_fans"] == 12000
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_with_works_carries_their_count(self, client):
|
||||
task_id = await _seed()
|
||||
await _add_stat(task_id, run_id=1, fans=12000)
|
||||
|
||||
creators = await _creators(client)
|
||||
|
||||
assert len(creators) == 1
|
||||
assert creators[0]["note_count"] == 1
|
||||
assert creators[0]["creator_name"] == NICKNAME
|
||||
assert creators[0]["creator_fans"] == 12000
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_with_neither_works_nor_a_snapshot_is_absent(self, client):
|
||||
"""两个来源都没有 = 我们对他一无所知,不该凭空造一个组出来。"""
|
||||
await _seed_task()
|
||||
|
||||
assert await _creators(client) == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_work_without_a_snapshot_still_lists_its_creator(self, client):
|
||||
"""小红书那条路不产生账号快照 —— 那边只能靠作品认出人来。"""
|
||||
await _seed()
|
||||
|
||||
creators = await _creators(client)
|
||||
|
||||
assert len(creators) == 1
|
||||
assert creators[0]["note_count"] == 1
|
||||
assert creators[0]["creator_fans"] is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_creator_remark_comes_along(self, client):
|
||||
"""没有作品的博主也要能起备注 —— 否则「这是谁」在最需要的时候认不出来。"""
|
||||
task_id = await _seed_task()
|
||||
await _add_stat(task_id, run_id=1, fans=12000)
|
||||
|
||||
await _set_alias(client, "竞品A")
|
||||
|
||||
assert (await _creators(client))[0]["creator_alias"] == "竞品A"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_platforms_stay_apart(self, client):
|
||||
dy_task = await _seed_task(platform="dy")
|
||||
await _add_stat(dy_task, run_id=1, fans=999)
|
||||
|
||||
assert await _creators(client, "xhs") == []
|
||||
assert (await _creators(client, "dy"))[0]["creator_fans"] == 999
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_same_creator_under_two_tasks_is_two_rows_the_ui_merges(self, client):
|
||||
"""服务端按 任务×博主 给(快照就是那么存的),合并交给界面 —— 因为备注跨任务
|
||||
是同一条,合并之后的组才是人眼里的「一个博主」。"""
|
||||
first = await _seed(task_name="任务甲")
|
||||
second = await _seed(task_name="任务乙")
|
||||
await _add_stat(first, run_id=1, fans=12000)
|
||||
|
||||
creators = await _creators(client)
|
||||
|
||||
assert len(creators) == 2
|
||||
assert {row["creator_hash"] for row in creators} == {CREATOR_HASH}
|
||||
assert sum(row["note_count"] for row in creators) == 2
|
||||
|
||||
|
||||
class TestCreatorProfileLink:
|
||||
"""组头上那个「跳到他主页」的按钮。
|
||||
|
||||
它要的是**平台上的主页 id**,不是 ``creator_hash``(哈希单向,拼不出地址)。所以
|
||||
这个 id 是采集资料时单独存下来的;拿不到就返回空串让界面不画按钮。
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_link_is_built_from_the_stored_id(self, client):
|
||||
task_id = await _seed_task(platform="dy")
|
||||
await _add_stat(task_id, run_id=1, fans=1, creator_id="MS4wLjABAAAAsomebody")
|
||||
|
||||
creators = await _creators(client, "dy")
|
||||
|
||||
assert creators[0]["creator_url"] == (
|
||||
"https://www.douyin.com/user/MS4wLjABAAAAsomebody"
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_id_means_no_link(self, client):
|
||||
"""没采到主页 id 就不给链接 —— 画一个点开 404 的按钮比不画糟。"""
|
||||
task_id = await _seed_task(platform="dy")
|
||||
await _add_stat(task_id, run_id=1, fans=1, creator_id="")
|
||||
|
||||
assert (await _creators(client, "dy"))[0]["creator_url"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_with_only_works_has_no_link_either(self, client):
|
||||
"""小红书那条路根本不落创作者资料,所以那边永远是空的 —— 这是已知的、可接受的。"""
|
||||
await _seed(platform="xhs")
|
||||
|
||||
assert (await _creators(client, "xhs"))[0]["creator_url"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_work_id_is_enough_without_a_snapshot(self, client):
|
||||
"""作品模式 / 超级编导导入不拉创作者资料,快照一行都没有。
|
||||
|
||||
这种任务里主页 id 只能从作品上取 —— 作品详情里的 ``author.sec_uid`` 已经落库了。
|
||||
没有这层兜底的话,整类任务里没有博主能点进主页。
|
||||
"""
|
||||
await _seed(platform="dy", creator_id="MS4wLjABAAAAfromwork")
|
||||
|
||||
creators = await _creators(client, "dy")
|
||||
|
||||
assert creators[0]["creator_url"].endswith("/user/MS4wLjABAAAAfromwork")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_snapshot_id_wins_over_the_work_id(self, client):
|
||||
task_id = await _seed(platform="dy", creator_id="MS4wLjABAAAAfromwork")
|
||||
await _add_stat(task_id, run_id=1, fans=1, creator_id="MS4wLjABAAAAfresh")
|
||||
|
||||
assert (await _creators(client, "dy"))[0]["creator_url"].endswith(
|
||||
"/user/MS4wLjABAAAAfresh"
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_with_no_works_still_gets_the_link(self, client):
|
||||
"""**没有作品的博主照样能跳过去** —— 他恰恰是你想点进去看看发的什么的那个人。"""
|
||||
task_id = await _seed_task(platform="dy")
|
||||
await _add_stat(task_id, run_id=1, fans=1, creator_id="MS4wLjABAAAAquiet")
|
||||
|
||||
creators = await _creators(client, "dy")
|
||||
|
||||
assert creators[0]["note_count"] == 0
|
||||
assert creators[0]["creator_url"].endswith("/user/MS4wLjABAAAAquiet")
|
||||
|
||||
|
||||
class TestNicknameSource:
|
||||
"""博主改名之后,组头显示哪个名字。
|
||||
|
||||
**账号快照里的昵称优先**:那一行每次采集都从资料接口重写一遍,是这一行最新的一份。
|
||||
作品上的名字只会跟着「这一轮采到的那几条」更新 —— 掉出采集窗口的老作品可能还留着
|
||||
旧名字,而作品栏取的是该博主名下作品的 max(name),恰好可能取到旧的。
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_snapshot_name_wins_over_a_stale_work_name(self, client):
|
||||
task_id = await _seed(platform="dy") # 作品上的名字还是 NICKNAME
|
||||
await _add_stat(task_id, run_id=1, fans=1, nickname="改过的名字")
|
||||
|
||||
assert (await _creators(client, "dy"))[0]["creator_name"] == "改过的名字"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_without_a_snapshot_it_falls_back_to_the_work_name(self, client):
|
||||
"""小红书那条路不产生账号快照 —— 只能靠作品上的名字。"""
|
||||
await _seed(platform="xhs")
|
||||
|
||||
assert (await _creators(client, "xhs"))[0]["creator_name"] == NICKNAME
|
||||
@@ -0,0 +1,202 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""每日「视频情况」图:取数、版式、发送前的大小闸门。"""
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor import digest
|
||||
from api.monitor.models import (
|
||||
MODE_CREATOR,
|
||||
MonitorNote,
|
||||
MonitorNoteMetric,
|
||||
MonitorTask,
|
||||
)
|
||||
def _at(day_offset: int, hour: int = 12) -> int:
|
||||
"""某天某个整点的毫秒时间戳(``day_offset`` 相对今天,-1 就是昨天)。
|
||||
|
||||
不用 ``now - 24h``:凌晨跑测试时它会掉到前天,让本来正确的断言莫名其妙地挂。
|
||||
"""
|
||||
day = date.today() + timedelta(days=day_offset)
|
||||
return int(datetime.combine(day, datetime.min.time()).timestamp() * 1000) + hour * 3_600_000
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def db(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "digest.db")
|
||||
await monitor_db.init_db()
|
||||
yield monitor_db
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
async def _task(platform: str = "dy", name: str = "图") -> int:
|
||||
async with monitor_db.get_session() as session:
|
||||
task = MonitorTask(
|
||||
name=name,
|
||||
platform=platform,
|
||||
mode=MODE_CREATOR,
|
||||
enabled=True,
|
||||
interval_minutes=60,
|
||||
max_notes_count=20,
|
||||
enable_comments=False,
|
||||
max_comments_count=10,
|
||||
run_timeout_seconds=3600,
|
||||
created_at=0,
|
||||
updated_at=0,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
return task.id
|
||||
|
||||
|
||||
async def _note(task_id: int, note_id: str, name: str, published_at: int) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorNote(
|
||||
task_id=task_id,
|
||||
note_id=note_id,
|
||||
title=f"标题-{note_id}",
|
||||
hashtags="",
|
||||
note_url="",
|
||||
cover="",
|
||||
creator_hash="hash-a",
|
||||
creator_name=name,
|
||||
source_kind="video",
|
||||
published_at=published_at,
|
||||
first_seen_at=published_at,
|
||||
last_seen_at=published_at,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _metric(task_id: int, note_id: str, run_id: int, liked: int | None) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorNoteMetric(
|
||||
task_id=task_id,
|
||||
note_id=note_id,
|
||||
run_id=run_id,
|
||||
captured_at=run_id,
|
||||
liked_count=liked,
|
||||
comment_count=liked,
|
||||
collected_count=liked,
|
||||
share_count=liked,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_the_digest_reports_yesterday():
|
||||
"""早上九点推的是前一天的账 —— 补发、预览、定时三处都从这里取日子。"""
|
||||
assert digest.default_day() == date.today() - timedelta(days=1)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_by_default_only_yesterdays_notes_are_listed(db):
|
||||
task_id = await _task()
|
||||
await _note(task_id, "today", "今天", _at(0))
|
||||
await _note(task_id, "yesterday", "昨天", _at(-1))
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
rows = await digest.daily_rows(session, "dy")
|
||||
|
||||
assert [row["note_id"] for row in rows] == ["yesterday"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_explicit_day_wins_over_the_default(db):
|
||||
task_id = await _task()
|
||||
await _note(task_id, "today", "今天", _at(0))
|
||||
await _note(task_id, "yesterday", "昨天", _at(-1))
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
rows = await digest.daily_rows(session, "dy", date.today())
|
||||
|
||||
assert [row["note_id"] for row in rows] == ["today"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_latest_metric_wins_and_rows_sort_by_likes(db):
|
||||
task_id = await _task()
|
||||
await _note(task_id, "a", "博主A", _at(-1, 11))
|
||||
await _note(task_id, "b", "博主B", _at(-1, 10))
|
||||
await _metric(task_id, "a", run_id=1, liked=5)
|
||||
await _metric(task_id, "a", run_id=2, liked=99)
|
||||
await _metric(task_id, "b", run_id=1, liked=500)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
rows = await digest.daily_rows(session, "dy")
|
||||
|
||||
assert [row["note_id"] for row in rows] == ["b", "a"] # 点赞降序
|
||||
assert rows[1]["likes"] == 99 # 取最近一轮,不是先写进去的那轮
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_same_note_under_two_tasks_is_listed_once(db):
|
||||
first = await _task(name="一")
|
||||
second = await _task(name="二")
|
||||
await _note(first, "same", "博主A", _at(-1))
|
||||
await _note(second, "same", "博主A", _at(-1))
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
rows = await digest.daily_rows(session, "dy")
|
||||
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
def _time_reached(send_at: str, now: datetime) -> bool:
|
||||
from api.monitor.scheduler import _time_reached as reached
|
||||
|
||||
return reached(now, send_at)
|
||||
|
||||
|
||||
def test_time_reached_handles_bad_config():
|
||||
now = datetime(2026, 10, 23, 8, 30)
|
||||
assert _time_reached("08:00", now) is True
|
||||
assert _time_reached("09:00", now) is False
|
||||
assert _time_reached("09:00", datetime(2026, 10, 23, 9, 0)) is True
|
||||
# 写错就按 09:00 算,而不是永远不发
|
||||
assert _time_reached("九点半", datetime(2026, 10, 23, 9, 1)) is True
|
||||
assert _time_reached("", datetime(2026, 10, 23, 8, 59)) is False
|
||||
|
||||
|
||||
@pytest.mark.skipif(digest._font_path() is None, reason="本机没有中文字体")
|
||||
def test_render_table_returns_a_png():
|
||||
rows = [
|
||||
{
|
||||
"note_id": "1",
|
||||
"creator": "博主A",
|
||||
"title": "一条标题",
|
||||
"hashtags": "",
|
||||
"likes": 12,
|
||||
"comments": 3,
|
||||
"collected": 4,
|
||||
"shares": 5,
|
||||
}
|
||||
]
|
||||
|
||||
image = digest.render_table(rows, date.today(), "抖音")
|
||||
|
||||
assert image.startswith(b"\x89PNG")
|
||||
assert len(image) > 1000
|
||||
|
||||
|
||||
@pytest.mark.skipif(digest._font_path() is None, reason="本机没有中文字体")
|
||||
def test_render_table_handles_an_empty_day():
|
||||
image = digest.render_table([], date.today(), "抖音")
|
||||
|
||||
assert image.startswith(b"\x89PNG")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_image_sender_guards_missing_webhook_and_oversize():
|
||||
from api.monitor import notify
|
||||
|
||||
ok, detail = await notify.send_wecom_image("", b"x")
|
||||
assert ok is False and "未配置" in detail
|
||||
|
||||
ok, detail = await notify.send_wecom_image(
|
||||
"http://example.invalid", b"x" * (notify.WECOM_IMAGE_MAX_BYTES + 1)
|
||||
)
|
||||
assert ok is False and "太大" in detail
|
||||
@@ -0,0 +1,236 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""身份池:分片、解析、健康状态。
|
||||
|
||||
这里钉住的是「多个账号怎么分活」和「一个号什么时候该被停用」。真去请求抖音的那层
|
||||
另有测试(test_douyin_api / test_douyin_fetch),这里全部用假函数。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor import douyin_api, douyin_fetch, identities
|
||||
from api.monitor.models import (
|
||||
IDENTITY_SOURCE_STORED,
|
||||
IDENTITY_STATUS_COOLDOWN,
|
||||
IDENTITY_STATUS_OK,
|
||||
MODE_CREATOR,
|
||||
MonitorIdentity,
|
||||
)
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def db(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "identities.db")
|
||||
await monitor_db.init_db()
|
||||
yield monitor_db
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
async def _identity(
|
||||
label: str = "主号",
|
||||
cookie: str = "sessionid=abc",
|
||||
user_agent: str = "UA/1.0",
|
||||
) -> MonitorIdentity:
|
||||
now = get_current_timestamp()
|
||||
async with monitor_db.get_session() as session:
|
||||
row = MonitorIdentity(
|
||||
platform="dy",
|
||||
label=label,
|
||||
source=IDENTITY_SOURCE_STORED,
|
||||
cookie=cookie,
|
||||
user_agent=user_agent,
|
||||
client_hints="{}",
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
session.add(row)
|
||||
await session.flush()
|
||||
return row
|
||||
|
||||
|
||||
# --- 分片 -------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_assignment_is_deterministic_and_covers_every_target():
|
||||
targets = [SimpleNamespace(external_id=f"t{index}") for index in range(30)]
|
||||
first = identities.assign(targets, ["id:1", "id:2"])
|
||||
second = identities.assign(targets, ["id:1", "id:2"])
|
||||
|
||||
assert [t.external_id for t in first["id:1"]] == [t.external_id for t in second["id:1"]]
|
||||
assert sum(len(bucket) for bucket in first.values()) == 30
|
||||
# 两个身份都应该分到活,否则分片没意义
|
||||
assert first["id:1"] and first["id:2"]
|
||||
|
||||
|
||||
def test_adding_an_identity_moves_only_a_fraction_of_targets():
|
||||
"""Rendezvous Hashing 的意义:加一个身份,只迁移约 1/(n+1) 的目标。"""
|
||||
targets = [SimpleNamespace(external_id=f"t{index}") for index in range(300)]
|
||||
before = {
|
||||
target.external_id: key
|
||||
for key, bucket in identities.assign(targets, ["id:1", "id:2"]).items()
|
||||
for target in bucket
|
||||
}
|
||||
after = {
|
||||
target.external_id: key
|
||||
for key, bucket in identities.assign(targets, ["id:1", "id:2", "id:3"]).items()
|
||||
for target in bucket
|
||||
}
|
||||
moved = sum(1 for external, key in before.items() if after[external] != key)
|
||||
|
||||
assert 0 < moved < len(targets) * 0.6
|
||||
|
||||
|
||||
# --- 解析 -------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_builds_the_identity_from_the_row(db):
|
||||
row = await _identity()
|
||||
|
||||
identity = await identities.resolve(row)
|
||||
|
||||
assert identity.cookie == "sessionid=abc"
|
||||
assert identity.user_agent == "UA/1.0"
|
||||
assert identity.identity_key == f"id:{row.id}"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_rejects_a_stored_identity_without_user_agent(db):
|
||||
"""没有 UA 就不能用 —— a_bogus 签名要拿它,空 UA 签出来的请求一定被挡。"""
|
||||
row = await _identity(user_agent="")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
await identities.resolve(row)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_rejects_a_stored_identity_without_cookie(db):
|
||||
row = await _identity(cookie="")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
await identities.resolve(row)
|
||||
|
||||
|
||||
# --- 健康状态 ---------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_two_failures_trigger_a_cooldown(db):
|
||||
row = await _identity()
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
live = await session.get(MonitorIdentity, row.id)
|
||||
await identities.record_result(session, live, ok=False, error="空 body")
|
||||
# 一次失败可能只是抖动,不停用
|
||||
assert live.status == IDENTITY_STATUS_OK
|
||||
|
||||
await identities.record_result(session, live, ok=False, error="空 body")
|
||||
assert live.status == IDENTITY_STATUS_COOLDOWN
|
||||
assert live.cooldown_until > get_current_timestamp()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_success_clears_the_cooldown(db):
|
||||
row = await _identity()
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
live = await session.get(MonitorIdentity, row.id)
|
||||
await identities.record_result(session, live, ok=False, error="x")
|
||||
await identities.record_result(session, live, ok=False, error="x")
|
||||
assert live.status == IDENTITY_STATUS_COOLDOWN
|
||||
|
||||
await identities.record_result(session, live, ok=True)
|
||||
assert live.status == IDENTITY_STATUS_OK
|
||||
assert live.cooldown_until is None
|
||||
assert live.consecutive_failures == 0
|
||||
assert live.last_ok_at is not None
|
||||
|
||||
|
||||
def test_a_cooling_identity_is_not_available():
|
||||
row = MonitorIdentity(
|
||||
platform="dy",
|
||||
label="x",
|
||||
source=IDENTITY_SOURCE_STORED,
|
||||
cookie="sessionid=a",
|
||||
user_agent="UA",
|
||||
client_hints="{}",
|
||||
status=IDENTITY_STATUS_OK,
|
||||
enabled=True,
|
||||
consecutive_failures=2,
|
||||
cooldown_until=get_current_timestamp() + 60_000,
|
||||
created_at=0,
|
||||
updated_at=0,
|
||||
)
|
||||
assert identities.is_available(row) is False
|
||||
|
||||
row.cooldown_until = get_current_timestamp() - 1
|
||||
assert identities.is_available(row) is True
|
||||
|
||||
|
||||
# --- 采集分片 ---------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collect_shards_targets_across_identities(tmp_path, monkeypatch):
|
||||
used = []
|
||||
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
used.append((identity.identity_key, sec_user_id))
|
||||
return [
|
||||
{
|
||||
"aweme_id": f"a-{sec_user_id}",
|
||||
"creator_hash": "hash-a",
|
||||
"creator_name": "博主",
|
||||
"title": "",
|
||||
"aweme_url": "",
|
||||
"cover_url": "",
|
||||
"aweme_type": "video",
|
||||
"create_time": 0,
|
||||
}
|
||||
]
|
||||
|
||||
async def fake_profile(sec_user_id, *, cookie="", identity=None):
|
||||
return {
|
||||
"creator_hash": "hash-a",
|
||||
"nickname": "博主",
|
||||
"creator_id": sec_user_id,
|
||||
"unique_id": "",
|
||||
"fans": 0,
|
||||
"total_favorited": 0,
|
||||
"works": 0,
|
||||
"following": 0,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
monkeypatch.setattr(douyin_api, "author_profile", fake_profile)
|
||||
|
||||
targets = [SimpleNamespace(external_id=f"t{index}") for index in range(20)]
|
||||
pool = [
|
||||
douyin_api.BrowserIdentity(
|
||||
cookie="sessionid=a", user_agent="UA", client_hints={}, identity_key="id:1"
|
||||
),
|
||||
douyin_api.BrowserIdentity(
|
||||
cookie="sessionid=b", user_agent="UA", client_hints={}, identity_key="id:2"
|
||||
),
|
||||
]
|
||||
|
||||
result = await douyin_fetch.collect(
|
||||
tmp_path,
|
||||
platform="dy",
|
||||
mode=MODE_CREATOR,
|
||||
limit=20,
|
||||
want_comments=False,
|
||||
comment_limit=0,
|
||||
targets=targets,
|
||||
identities=pool,
|
||||
)
|
||||
|
||||
assert len(used) == 20
|
||||
assert {key for key, _ in used} == {"id:1", "id:2"}
|
||||
assert result["notes"] == 20
|
||||
assert len(result["shards"]) == 2
|
||||
assert sum(shard["targets"] for shard in result["shards"]) == 20
|
||||
@@ -30,7 +30,7 @@ from typing import Any, Dict, List, Optional
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
@@ -54,10 +54,14 @@ from api.monitor.models import (
|
||||
MODE_CREATOR,
|
||||
MonitorBase,
|
||||
MonitorComment,
|
||||
MonitorCreatorStat,
|
||||
MonitorEvent,
|
||||
MonitorNote,
|
||||
MonitorNoteMetric,
|
||||
MonitorNoteTag,
|
||||
MonitorRun,
|
||||
MonitorTag,
|
||||
MonitorTarget,
|
||||
MonitorTask,
|
||||
RUN_FAILED,
|
||||
RUN_PARTIAL,
|
||||
@@ -127,11 +131,15 @@ def _write_run_dir(
|
||||
notes: List[Dict[str, Any]],
|
||||
comments: Optional[List[Dict[str, Any]]] = None,
|
||||
subdir: str = "xhs",
|
||||
profiles: Optional[List[Dict[str, Any]]] = None,
|
||||
) -> Path:
|
||||
"""Write a run's jsonl output in the crawler's own layout.
|
||||
|
||||
``subdir`` 是**爬虫**落盘的目录名,不是监控层的平台 id —— 抖音那边这两者不同
|
||||
(平台 id 是 ``dy``、目录是 ``douyin``),所以必须能分开指定,否则测不出那个差异。
|
||||
|
||||
``profiles`` 为 None 时**不写**这个文件(小红书那条路根本不产生它),给列表时写
|
||||
——包括空列表,那是「问了但没问到」。
|
||||
"""
|
||||
jsonl_dir = root / subdir / "jsonl"
|
||||
jsonl_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -147,6 +155,12 @@ def _write_run_dir(
|
||||
"\n".join(json.dumps(c, ensure_ascii=False) for c in comments),
|
||||
encoding="utf-8",
|
||||
)
|
||||
if profiles is not None:
|
||||
profile_file = jsonl_dir / "creator_profile_2026-01-01.jsonl"
|
||||
profile_file.write_text(
|
||||
"\n".join(json.dumps(p, ensure_ascii=False) for p in profiles),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return root
|
||||
|
||||
|
||||
@@ -623,6 +637,53 @@ class TestDouyinIngest:
|
||||
assert note.published_at == 1790574515 * 1000
|
||||
assert result.notes_fetched == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_sec_uid_lands_on_the_note(self, db, tmp_path):
|
||||
"""作品详情里的 ``author.sec_uid`` 要落到作品上。
|
||||
|
||||
作品模式(以及超级编导导入)**不拉创作者资料**,没有账号快照;博主主页链接
|
||||
只能从这条作品记录里拼出来。丢了它,这类任务里一个主页都点不进去。
|
||||
"""
|
||||
aweme_id = "7525082444551310602"
|
||||
await self._ingest(
|
||||
db, tmp_path, [_dy_note(aweme_id, creator_id="MS4wLjABAAAAtestsuid")]
|
||||
)
|
||||
|
||||
note = await db.scalar(select(MonitorNote))
|
||||
|
||||
assert note.creator_id == "MS4wLjABAAAAtestsuid"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_later_run_backfills_a_missing_sec_uid(self, db, tmp_path):
|
||||
"""这条字段是后加的:加之前入库的作品都空着,重采一次就该补上。"""
|
||||
aweme_id = "7525082444551310602"
|
||||
task = await _make_task(db, platform="dy")
|
||||
|
||||
run1 = await _make_run(db, task, started_at=1000)
|
||||
await ingest_run(
|
||||
db,
|
||||
run1,
|
||||
task,
|
||||
_write_run_dir(
|
||||
tmp_path / "run1", [_dy_note(aweme_id)], subdir="douyin"
|
||||
),
|
||||
)
|
||||
|
||||
run2 = await _make_run(db, task, started_at=2000)
|
||||
await ingest_run(
|
||||
db,
|
||||
run2,
|
||||
task,
|
||||
_write_run_dir(
|
||||
tmp_path / "run2",
|
||||
[_dy_note(aweme_id, creator_id="MS4wLjABAAAAtestsuid")],
|
||||
subdir="douyin",
|
||||
),
|
||||
)
|
||||
|
||||
note = await db.scalar(select(MonitorNote))
|
||||
assert note.creator_id == "MS4wLjABAAAAtestsuid"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_timestamps_are_normalised_to_milliseconds(self, db, tmp_path):
|
||||
"""抖音的时间戳是**秒**,小红书是毫秒 —— 差 1000 倍,必须换算。
|
||||
@@ -725,6 +786,28 @@ class TestDouyinIngest:
|
||||
assert len(await _events(db, EVENT_METRIC_DELTA)) == 1
|
||||
|
||||
|
||||
class TestDuplicateRecordsInOneRun:
|
||||
"""一轮产物里重复出现的作品只该算一次。
|
||||
|
||||
指标快照的唯一键是 ``(task_id, note_id, run_id)``:同一条作品在一轮里进来两次,
|
||||
第二次插入会撞键并让整个 run 崩掉 —— 产物里重复并不罕见(多个目标指向同一个人、
|
||||
或退化路径重复刷新)。
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_duplicated_note_is_processed_once(self, db, tmp_path):
|
||||
task = await _make_task(db)
|
||||
_write_run_dir(tmp_path, [_note("n1"), _note("n1")])
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
|
||||
result = await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
assert result.new_notes == 1
|
||||
assert len(list((await db.scalars(select(MonitorNote))).all())) == 1
|
||||
# 崩就崩在这一句上:一条作品只能有一份本轮快照。
|
||||
assert len(list((await db.scalars(select(MonitorNoteMetric))).all())) == 1
|
||||
|
||||
|
||||
class TestNicknameRefresh:
|
||||
"""已入库的评论,昵称要跟着重新采集的值走。
|
||||
|
||||
@@ -807,3 +890,423 @@ class TestFailureDiagnosis:
|
||||
|
||||
events = await _events(db, EVENT_RUN_FAILED)
|
||||
assert "account blocked" in events[0].title
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 博主账号级指标(粉丝 / 总获赞 / 作品数)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _profile(creator_hash: str = "hash", **extra) -> Dict[str, Any]:
|
||||
"""``creator_profile_*.jsonl`` 里的一行 —— 形状由 douyin_api.author_profile 决定。"""
|
||||
record: Dict[str, Any] = {
|
||||
"creator_hash": creator_hash,
|
||||
"nickname": "博主",
|
||||
"creator_id": "MS4wLjABAAAAtestsuid",
|
||||
"unique_id": "abc",
|
||||
"fans": 12000,
|
||||
"total_favorited": 83000,
|
||||
"works": 42,
|
||||
"following": 7,
|
||||
}
|
||||
record.update(extra)
|
||||
return record
|
||||
|
||||
|
||||
class TestCreatorStatSnapshots:
|
||||
"""**账号级**指标和作品级指标是两回事:后者说"这条视频涨了多少赞",前者说
|
||||
"这个人整个账号的粉丝在涨还是在掉"。作品列表给不了后者,所以单独存一张表。
|
||||
"""
|
||||
|
||||
async def _ingest(self, db, tmp_path, notes, profiles, platform="dy", subdir="douyin"):
|
||||
task = await _make_task(db, platform=platform)
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, notes, comments=[], subdir=subdir, profiles=profiles)
|
||||
result = await ingest_run(db, run, task, tmp_path)
|
||||
return task, run, result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_profile_becomes_a_snapshot(self, db, tmp_path):
|
||||
task, run, _result = await self._ingest(db, tmp_path, [_dy_note("1")], [_profile()])
|
||||
|
||||
stat = await db.scalar(select(MonitorCreatorStat))
|
||||
|
||||
assert stat is not None
|
||||
assert (stat.task_id, stat.run_id) == (task.id, run.id)
|
||||
assert stat.creator_hash == "hash"
|
||||
assert stat.nickname == "博主"
|
||||
assert (stat.fans, stat.total_favorited, stat.works_count) == (12000, 83000, 42)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_missing_count_stays_null_not_zero(self, db, tmp_path):
|
||||
"""0 是真实值(掉到零),null 是不知道。混起来趋势图就是在撒谎。"""
|
||||
await self._ingest(db, tmp_path, [_dy_note("1")], [_profile(fans=None)])
|
||||
|
||||
stat = await db.scalar(select(MonitorCreatorStat))
|
||||
|
||||
assert stat.fans is None
|
||||
# 同一个博主其它字段照常。
|
||||
assert stat.works_count == 42
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_abbreviated_counts_are_parsed(self, db, tmp_path):
|
||||
"""走的是和作品指标同一个 parse_count —— 平台给你「1.2万」也得认。"""
|
||||
await self._ingest(db, tmp_path, [_dy_note("1")], [_profile(fans="1.2万")])
|
||||
|
||||
assert (await db.scalar(select(MonitorCreatorStat))).fans == 12000
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_same_creator_twice_in_one_run_yields_one_snapshot(self, db, tmp_path):
|
||||
"""一个任务可以配多个目标,退化路径下它们可能落在同一个博主身上。
|
||||
|
||||
唯一键是 (task_id, creator_hash, run_id) —— 重复插入会撞键,把整轮炸掉。
|
||||
(和作品重复那次是同一类事故。)
|
||||
"""
|
||||
await self._ingest(
|
||||
db, tmp_path, [_dy_note("1")], [_profile(), _profile(nickname="另一条")]
|
||||
)
|
||||
|
||||
stats = list((await db.scalars(select(MonitorCreatorStat))).all())
|
||||
|
||||
assert len(stats) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_profile_without_a_hash_is_skipped(self, db, tmp_path):
|
||||
"""哈希都算不出来,这条快照谁也查不到,落下去只是垃圾。"""
|
||||
await self._ingest(db, tmp_path, [_dy_note("1")], [_profile(creator_hash="")])
|
||||
|
||||
assert (await db.scalars(select(MonitorCreatorStat))).all() == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_profile_file_is_fine(self, db, tmp_path):
|
||||
"""小红书那条路(爬虫进程)根本不产生这个文件 —— 不能因此报错。"""
|
||||
task = await _make_task(db) # xhs
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, [_note("n1")], comments=[]) # 没有 profiles 参数
|
||||
|
||||
result = await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
assert result.status == RUN_SUCCESS
|
||||
assert (await db.scalars(select(MonitorCreatorStat))).all() == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_stats_are_kept_even_when_no_works_were_fetched(self, db, tmp_path):
|
||||
"""**这条是这里最值得留的一个。**
|
||||
|
||||
作品列表被风控挡住时,这一轮一条作品都拿不到、run 会被判成失败。但博主的粉丝数
|
||||
并不因为这件事就不存在 —— 「粉丝还在涨,但新作品没在发现」恰恰是最该看见的时刻。
|
||||
快照要是挂在「作品采到了」后面,就正好在最需要它的那一轮丢掉。
|
||||
"""
|
||||
_task, run, result = await self._ingest(db, tmp_path, [], [_profile()])
|
||||
|
||||
assert result.status == RUN_PARTIAL # 一条作品都没有,这轮确实不算成功
|
||||
assert run.status == RUN_PARTIAL
|
||||
stat = await db.scalar(select(MonitorCreatorStat))
|
||||
assert stat is not None and stat.fans == 12000
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_each_run_adds_its_own_snapshot(self, db, tmp_path):
|
||||
"""趋势靠的就是这个:一条一轮,不要覆盖。"""
|
||||
task = await _make_task(db, platform="dy")
|
||||
first = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, [_dy_note("1")], comments=[], subdir="douyin",
|
||||
profiles=[_profile(fans=12000)])
|
||||
await ingest_run(db, first, task, tmp_path)
|
||||
|
||||
second = await _make_run(db, task, started_at=2000)
|
||||
_write_run_dir(tmp_path, [_dy_note("1")], comments=[], subdir="douyin",
|
||||
profiles=[_profile(fans=12300)])
|
||||
await ingest_run(db, second, task, tmp_path)
|
||||
|
||||
stats = list(
|
||||
(
|
||||
await db.scalars(
|
||||
select(MonitorCreatorStat).order_by(MonitorCreatorStat.run_id)
|
||||
)
|
||||
).all()
|
||||
)
|
||||
|
||||
assert [s.fans for s in stats] == [12000, 12300]
|
||||
|
||||
|
||||
class TestCreatorIdIsStored:
|
||||
"""主页 id 要单独存下来 —— ``creator_hash`` 是单向的,拼不出主页地址。"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_profile_id_lands_on_the_snapshot(self, db, tmp_path):
|
||||
task = await _make_task(db, platform="dy")
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(
|
||||
tmp_path, [_dy_note("1")], comments=[], subdir="douyin", profiles=[_profile()]
|
||||
)
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
stat = await db.scalar(select(MonitorCreatorStat))
|
||||
|
||||
assert stat.creator_id == "MS4wLjABAAAAtestsuid"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_missing_id_is_empty_not_a_crash(self, db, tmp_path):
|
||||
"""老数据/别的平台没有这个字段 —— 空串,界面据此不画按钮。"""
|
||||
task = await _make_task(db, platform="dy")
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(
|
||||
tmp_path,
|
||||
[_dy_note("1")],
|
||||
comments=[],
|
||||
subdir="douyin",
|
||||
profiles=[_profile(creator_id="")],
|
||||
)
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
assert (await db.scalar(select(MonitorCreatorStat))).creator_id == ""
|
||||
|
||||
|
||||
class TestNicknameRefresh:
|
||||
"""博主改名之后,库里不能一半是新名字、一半是旧名字。
|
||||
|
||||
昵称是**博主级**的属性,而作品是逐条刷的 —— 一个博主只有落在采集窗口里的那几条会被
|
||||
重刷,掉出窗口的老作品会一直留着旧名字。界面按作品名分组时取的是其中任意一个,
|
||||
导出和 SQL 更是直接看到旧名字。
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_rename_reaches_the_works_outside_this_runs_window(self, db, tmp_path):
|
||||
task = await _make_task(db, platform="dy")
|
||||
|
||||
# 第一轮:两条作品,都叫「旧名字」。
|
||||
first = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(
|
||||
tmp_path,
|
||||
[_dy_note("111", nickname="旧名字"), _dy_note("222", nickname="旧名字")],
|
||||
comments=[],
|
||||
subdir="douyin",
|
||||
)
|
||||
await ingest_run(db, first, task, tmp_path)
|
||||
|
||||
# 第二轮:只采到 111(222 掉出了采集窗口),而博主已经改名。
|
||||
second = await _make_run(db, task, started_at=2000)
|
||||
_write_run_dir(
|
||||
tmp_path,
|
||||
[_dy_note("111", nickname="新名字")],
|
||||
comments=[],
|
||||
subdir="douyin",
|
||||
)
|
||||
await ingest_run(db, second, task, tmp_path)
|
||||
|
||||
names = {
|
||||
row.note_id: row.creator_name
|
||||
for row in (await db.scalars(select(MonitorNote))).all()
|
||||
}
|
||||
assert names == {"111": "新名字", "222": "新名字"}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_rename_does_not_leak_into_another_task(self, db, tmp_path):
|
||||
"""博主级不等于全局 —— 另一个任务里的同一个人是另一条跟踪线,别顺手改它。"""
|
||||
mine = await _make_task(db, name="我的", platform="dy")
|
||||
other = await _make_task(db, name="别人的", platform="dy")
|
||||
|
||||
run = await _make_run(db, other, started_at=1)
|
||||
_write_run_dir(tmp_path, [_dy_note("999", nickname="别人的名字")], comments=[], subdir="douyin")
|
||||
await ingest_run(db, run, other, tmp_path)
|
||||
|
||||
run = await _make_run(db, mine, started_at=1)
|
||||
_write_run_dir(tmp_path, [_dy_note("111", nickname="旧名字")], comments=[], subdir="douyin")
|
||||
await ingest_run(db, run, mine, tmp_path)
|
||||
|
||||
run = await _make_run(db, mine, started_at=2000)
|
||||
_write_run_dir(tmp_path, [_dy_note("111", nickname="新名字")], comments=[], subdir="douyin")
|
||||
await ingest_run(db, run, mine, tmp_path)
|
||||
|
||||
by_task = {
|
||||
row.note_id: row.creator_name
|
||||
for row in (await db.scalars(select(MonitorNote))).all()
|
||||
}
|
||||
assert by_task["999"] == "别人的名字"
|
||||
assert by_task["111"] == "新名字"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_empty_name_does_not_wipe_the_stored_one(self, db, tmp_path):
|
||||
"""平台这一轮没给昵称时,不要把已有的抹掉。"""
|
||||
task = await _make_task(db, platform="dy")
|
||||
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, [_dy_note("111", nickname="有名字")], comments=[], subdir="douyin")
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
run = await _make_run(db, task, started_at=2000)
|
||||
_write_run_dir(tmp_path, [_dy_note("111", nickname="")], comments=[], subdir="douyin")
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
assert (await db.scalar(select(MonitorNote))).creator_name == "有名字"
|
||||
|
||||
|
||||
class TestABrokenTargetIsNotBlamedOnTheCookie:
|
||||
"""目标是一串没解析开的链接时,**不许报「登录态失效」**。
|
||||
|
||||
真事(2026-10-14):任务 22 的目标被存成了 `https://xhslink.cn/o/AhQpHsqcme5`(短链,
|
||||
链接校验关掉之后原样存下来的),于是永远抓不到东西。而报出来的是「疑似登录态失效」,
|
||||
因为那一刻往前 6 小时正好没有别的任务成功过 —— 隔壁任务 1 的成功**比它晚 6 秒**,
|
||||
就是撞不上。同一份 cookie,任务 1 采集正常。
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
async def _seed_target(db, task, external_id: str) -> None:
|
||||
db.add(
|
||||
MonitorTarget(
|
||||
task_id=task.id,
|
||||
kind=task.mode,
|
||||
external_id=external_id,
|
||||
xsec_token="",
|
||||
xsec_source="",
|
||||
raw_value=external_id,
|
||||
label=external_id,
|
||||
enabled=True,
|
||||
created_at=0,
|
||||
)
|
||||
)
|
||||
await db.flush()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_unparsed_url_target_is_reported_as_such(self, db, tmp_path):
|
||||
task = await _make_task(db)
|
||||
await self._seed_target(db, task, "https://xhslink.cn/o/AhQpHsqcme5")
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, [], comments=[])
|
||||
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
# 不许出现「登录失效」那条 —— 那会把人的注意力引到 cookie 上,而 cookie 是好的。
|
||||
assert await _events(db, EVENT_AUTH_FAILURE) == []
|
||||
no_data = await _events(db, EVENT_NO_DATA)
|
||||
assert no_data
|
||||
assert "没解析开" in no_data[0].title
|
||||
assert "xhslink.cn" in no_data[0].title
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_normal_target_still_gets_the_usual_diagnosis(self, db, tmp_path):
|
||||
"""不能因为加了这条就把原有的判断顶掉 —— 正常的目标还是走原来那套。"""
|
||||
task = await _make_task(db)
|
||||
await self._seed_target(db, task, "5f58bd990000000001003753")
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, [], comments=[])
|
||||
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
assert await _events(db, EVENT_AUTH_FAILURE)
|
||||
assert await _events(db, EVENT_NO_DATA) == []
|
||||
|
||||
|
||||
class TestAutoTaggingOnIngest:
|
||||
"""新作品按关键词规则自动打标签 —— 而且**只在第一次入库时**跑。
|
||||
|
||||
每轮都跑的话,自动打标签「只贴不摘」这件事就变得毫无意义:用户手动摘掉的标签,
|
||||
下一轮采集又会长回来。
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
async def _seed_rule(db, keywords: str) -> int:
|
||||
tag = MonitorTag(
|
||||
name="大字报", color="cyan", keywords=keywords, sort_order=1, created_at=0
|
||||
)
|
||||
db.add(tag)
|
||||
await db.flush()
|
||||
return tag.id
|
||||
|
||||
@staticmethod
|
||||
async def _note_tags(db) -> list:
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(MonitorNote.note_id, MonitorTag.name)
|
||||
.join(MonitorNoteTag, MonitorNoteTag.note_id == MonitorNote.note_id)
|
||||
.join(MonitorTag, MonitorTag.id == MonitorNoteTag.tag_id)
|
||||
.order_by(MonitorNote.note_id)
|
||||
)
|
||||
).all()
|
||||
return [(row[0], row[1]) for row in rows]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_new_work_matching_a_keyword_gets_the_tag(self, db, tmp_path):
|
||||
await self._seed_rule(db, "szgtdzb")
|
||||
task = await _make_task(db)
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, [_note("n1", title="苏州探店 #szgtdzb")], comments=[])
|
||||
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
assert await self._note_tags(db) == [("n1", "大字报")]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_tag_only_present_in_hashtags_is_matched(self, db, tmp_path):
|
||||
"""标题被截断、话题在后半段 —— 只在 hashtags 里,也得贴上。
|
||||
|
||||
抖音的 desc 断在「……版本过低,升级后可展示全部信息」,后面的话题不在标题里。
|
||||
"""
|
||||
await self._seed_rule(db, "szgtgg")
|
||||
task = await _make_task(db)
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(
|
||||
tmp_path,
|
||||
[
|
||||
_note(
|
||||
"n1",
|
||||
title="经历过痔疮术后才懂 #痔疮 #痔疮术后 #……版本过低,升级后可展示全部信息",
|
||||
hashtags="#痔疮 #痔疮术后 #szgtgg",
|
||||
)
|
||||
],
|
||||
comments=[],
|
||||
)
|
||||
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
assert await self._note_tags(db) == [("n1", "大字报")]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_work_that_does_not_match_is_left_alone(self, db, tmp_path):
|
||||
await self._seed_rule(db, "szgtdzb")
|
||||
task = await _make_task(db)
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, [_note("n1", title="随便一条")], comments=[])
|
||||
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
assert await self._note_tags(db) == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_one_work_can_pick_up_several_tags(self, db, tmp_path):
|
||||
"""命中几个话题就打几个标签。"""
|
||||
await self._seed_rule(db, "szgtdzb")
|
||||
db.add(MonitorTag(name="旅游号", color="cyan", keywords="苏州旅游", sort_order=2, created_at=0))
|
||||
await db.flush()
|
||||
task = await _make_task(db)
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(
|
||||
tmp_path, [_note("n1", title="探店 #szgtdzb #苏州旅游")], comments=[]
|
||||
)
|
||||
|
||||
await ingest_run(db, run, task, tmp_path)
|
||||
|
||||
assert await self._note_tags(db) == [("n1", "大字报"), ("n1", "旅游号")]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_tag_removed_by_hand_does_not_come_back_next_run(self, db, tmp_path):
|
||||
"""**这条是这个设计的全部理由。**"""
|
||||
await self._seed_rule(db, "szgtdzb")
|
||||
task = await _make_task(db)
|
||||
first = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, [_note("n1", title="苏州探店 #szgtdzb")], comments=[])
|
||||
await ingest_run(db, first, task, tmp_path)
|
||||
assert await self._note_tags(db) == [("n1", "大字报")]
|
||||
|
||||
# 用户手动摘掉
|
||||
await db.execute(
|
||||
delete(MonitorNoteTag).where(MonitorNoteTag.note_id == "n1")
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
# 下一轮又把同一条作品采回来了
|
||||
second = await _make_run(db, task, started_at=2000)
|
||||
_write_run_dir(tmp_path, [_note("n1", title="苏州探店 #szgtdzb")], comments=[])
|
||||
await ingest_run(db, second, task, tmp_path)
|
||||
|
||||
assert await self._note_tags(db) == []
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""标签矩阵:日期 × 博主 → 当天发出去的标签。
|
||||
|
||||
这个接口的形状(长表 + 前端转置)是被 MySQL 5.7 逼出来的 —— 没有 PIVOT,列数又随
|
||||
博主变化。所以这里重点测**分组与去重**,那才是容易出错的地方:
|
||||
|
||||
* 同一天同一个号的几条作品要合成一格,计数相加、标签取并集且保序;
|
||||
* 同一个作品挂在两个任务下(``monitor_note`` 的唯一键是 ``(task_id, note_id)``)
|
||||
只能算一次,否则计数翻倍;
|
||||
* 窗口外的老作品不出现。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from api.main import app
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor import service
|
||||
from api.monitor.models import (
|
||||
MODE_CREATOR,
|
||||
MonitorCreatorFirstVideo,
|
||||
MonitorCreatorStat,
|
||||
MonitorNote,
|
||||
MonitorNoteMetric,
|
||||
MonitorNoteTag,
|
||||
MonitorTag,
|
||||
MonitorTask,
|
||||
)
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
DAY_MS = 86_400_000
|
||||
|
||||
|
||||
def _day(ms: int) -> str:
|
||||
return datetime.fromtimestamp(ms / 1000).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def db(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "matrix.db")
|
||||
await monitor_db.init_db()
|
||||
yield monitor_db
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "matrix_api.db")
|
||||
await monitor_db.init_db()
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
|
||||
yield http
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
async def _task(platform: str = "dy", name: str = "矩阵测试") -> int:
|
||||
async with monitor_db.get_session() as session:
|
||||
task = MonitorTask(
|
||||
name=name,
|
||||
platform=platform,
|
||||
mode=MODE_CREATOR,
|
||||
enabled=True,
|
||||
interval_minutes=60,
|
||||
max_notes_count=20,
|
||||
enable_comments=False,
|
||||
max_comments_count=10,
|
||||
run_timeout_seconds=3600,
|
||||
created_at=0,
|
||||
updated_at=0,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
return task.id
|
||||
|
||||
|
||||
async def _note(
|
||||
task_id: int,
|
||||
note_id: str,
|
||||
name: str,
|
||||
published_at: int,
|
||||
creator_hash: str = "hash-a",
|
||||
title: str = "t",
|
||||
) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorNote(
|
||||
task_id=task_id,
|
||||
note_id=note_id,
|
||||
title=title,
|
||||
note_url=f"https://www.douyin.com/video/{note_id}",
|
||||
cover="",
|
||||
creator_hash=creator_hash,
|
||||
creator_name=name,
|
||||
source_kind="video",
|
||||
published_at=published_at,
|
||||
first_seen_at=published_at,
|
||||
last_seen_at=published_at,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _tag(name: str, sort_order: int) -> int:
|
||||
async with monitor_db.get_session() as session:
|
||||
tag = MonitorTag(name=name, color="cyan", keywords="", sort_order=sort_order, created_at=0)
|
||||
session.add(tag)
|
||||
await session.flush()
|
||||
return tag.id
|
||||
|
||||
|
||||
async def _attach(platform: str, note_id: str, tag_id: int) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorNoteTag(platform=platform, note_id=note_id, tag_id=tag_id, created_at=0)
|
||||
)
|
||||
|
||||
|
||||
async def _metric(
|
||||
task_id: int,
|
||||
note_id: str,
|
||||
run_id: int,
|
||||
liked: int | None = None,
|
||||
comment: int | None = None,
|
||||
collected: int | None = None,
|
||||
share: int | None = None,
|
||||
) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorNoteMetric(
|
||||
task_id=task_id,
|
||||
note_id=note_id,
|
||||
run_id=run_id,
|
||||
captured_at=run_id,
|
||||
liked_count=liked,
|
||||
comment_count=comment,
|
||||
collected_count=collected,
|
||||
share_count=share,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_same_day_notes_collapse_with_tags_union(db):
|
||||
task_id = await _task()
|
||||
today = get_current_timestamp() - 1000
|
||||
await _note(task_id, "n1", "博主A", today)
|
||||
await _note(task_id, "n2", "博主A", today)
|
||||
|
||||
dazibao = await _tag("大字报", 1)
|
||||
yanghao = await _tag("养号", 2)
|
||||
await _attach("dy", "n1", dazibao)
|
||||
await _attach("dy", "n2", yanghao)
|
||||
await _attach("dy", "n2", dazibao)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
# 日期列是**完整区间**(7 天),不是只有有作品的那天
|
||||
assert len(data["dates"]) == 7
|
||||
assert data["dates"][0] == _day(today)
|
||||
assert [c["name"] for c in data["creators"]] == ["博主A"]
|
||||
|
||||
cell = data["cells"][_day(today)]["hash-a"]
|
||||
assert cell["count"] == 2
|
||||
# 按词表 order 排序,不是按出现顺序
|
||||
assert cell["tags"] == ["大字报", "养号"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_two_notes_with_different_tags_merge_into_one_cell(db):
|
||||
"""同一天两条不同标签:合成一格,计数相加,标签取并集。
|
||||
|
||||
注意并集**按词表顺序**排,不是按作品先后 —— 否则同样的数据换个遍历顺序就会
|
||||
看起来不一样。代价是「哪个标签属于哪条视频」这个信息在这一格里没有了。
|
||||
"""
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp()
|
||||
await _note(task_id, "older", "博主A", now - 2000)
|
||||
await _note(task_id, "newer", "博主A", now - 1000)
|
||||
|
||||
dazibao = await _tag("大字报", 1)
|
||||
yanghao = await _tag("养号", 2)
|
||||
await _attach("dy", "older", dazibao)
|
||||
await _attach("dy", "newer", yanghao)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
cell = data["cells"][_day(now)]["hash-a"]
|
||||
assert cell["count"] == 2
|
||||
assert cell["tags"] == ["大字报", "养号"]
|
||||
# 逐条明细按发布时间正序:先发的在前,各自带自己的标签
|
||||
assert [item["tags"] for item in cell["details"]] == [["大字报"], ["养号"]]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dates_newest_first_and_creators_sorted(db):
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp()
|
||||
await _note(task_id, "n1", "B博主", now - 2 * DAY_MS, creator_hash="hash-b")
|
||||
await _note(task_id, "n2", "A博主", now - 1000, creator_hash="hash-a")
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data["dates"] == sorted(data["dates"], reverse=True)
|
||||
assert [c["name"] for c in data["creators"]] == ["A博主", "B博主"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_notes_outside_the_window_are_excluded(db):
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp()
|
||||
await _note(task_id, "fresh", "博主A", now - 1000)
|
||||
await _note(task_id, "old", "博主A", now - 40 * DAY_MS)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert len(data["dates"]) == 7
|
||||
assert data["dates"][0] == _day(now)
|
||||
assert data["cells"][_day(now)]["hash-a"]["count"] == 1
|
||||
# 40 天前那天不该出现在 cells 里
|
||||
assert _day(now - 40 * DAY_MS) not in data["cells"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_same_note_under_two_tasks_counts_once(db):
|
||||
first = await _task(name="任务一")
|
||||
second = await _task(name="任务二")
|
||||
now = get_current_timestamp() - 1000
|
||||
# 同一个作品被两个任务各记了一行
|
||||
await _note(first, "same", "博主A", now)
|
||||
await _note(second, "same", "博主A", now)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data["cells"][_day(now)]["hash-a"]["count"] == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_tasks_returns_an_empty_shape(db):
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data == {
|
||||
"platform": "dy",
|
||||
"days": 7,
|
||||
"task_id": None,
|
||||
"dates": [],
|
||||
"creators": [],
|
||||
"cells": {},
|
||||
}
|
||||
|
||||
|
||||
async def _stat(
|
||||
task_id: int,
|
||||
creator_hash: str,
|
||||
nickname: str,
|
||||
captured_at: int | None = None,
|
||||
run_id: int = 1,
|
||||
fans: int | None = None,
|
||||
total_favorited: int | None = None,
|
||||
creator_id: str = "",
|
||||
) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorCreatorStat(
|
||||
task_id=task_id,
|
||||
run_id=run_id,
|
||||
creator_hash=creator_hash,
|
||||
nickname=nickname,
|
||||
creator_id=creator_id,
|
||||
works_count=0,
|
||||
fans=fans,
|
||||
total_favorited=total_favorited,
|
||||
captured_at=captured_at or get_current_timestamp(),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _first_video(
|
||||
platform: str,
|
||||
creator_id: str,
|
||||
first_at: int | None,
|
||||
creator_hash: str = "hash-a",
|
||||
) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorCreatorFirstVideo(
|
||||
platform=platform,
|
||||
creator_id=creator_id,
|
||||
creator_hash=creator_hash,
|
||||
first_published_at=first_at,
|
||||
scanned_pages=3,
|
||||
complete=True,
|
||||
checked_at=get_current_timestamp(),
|
||||
error="",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_creators_without_notes_still_get_a_row(db):
|
||||
"""只在账号快照里出现的号不能消失。
|
||||
|
||||
典型是资料读成纯数字昵称、作品数为 0 的那几个 —— 它们一条作品都没有,如果博主
|
||||
名单只从作品里取,整行就不见了。日期列也一样:一行数据都没有时,7 个日期还在。
|
||||
"""
|
||||
task_id = await _task()
|
||||
await _stat(task_id, "hash-num", "26828346705")
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert [c["name"] for c in data["creators"]] == ["26828346705"]
|
||||
assert data["cells"] == {}
|
||||
assert len(data["dates"]) == 7
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_creator_row_carries_the_latest_fan_count(db):
|
||||
"""博主列左边要显示的粉丝数 —— 取最近一次**读到了数字**的快照。
|
||||
|
||||
最新一轮如果是 None(没解析出来),不能让几千粉丝变成一个空白 ——
|
||||
「这一轮没读到」不等于「这个号没有粉丝」。
|
||||
"""
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp()
|
||||
await _stat(task_id, "hash-a", "博主A", captured_at=now - 120_000, fans=1000, run_id=1)
|
||||
await _stat(task_id, "hash-a", "博主A", captured_at=now - 60_000, fans=1200, run_id=2)
|
||||
await _stat(task_id, "hash-a", "博主A", captured_at=now, fans=None, run_id=3)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert len(data["creators"]) == 1
|
||||
assert data["creators"][0]["name"] == "博主A"
|
||||
assert data["creators"][0]["fans"] == 1200
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_creator_row_carries_the_total_likes_from_the_profile(db):
|
||||
"""名字左边还要显示主页上的「获赞总数」,同样取最近一次读到的值。"""
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp()
|
||||
await _stat(
|
||||
task_id, "hash-a", "博主A",
|
||||
captured_at=now - 60_000, total_favorited=80000, run_id=1,
|
||||
)
|
||||
await _stat(
|
||||
task_id, "hash-a", "博主A",
|
||||
captured_at=now, total_favorited=83000, run_id=2,
|
||||
)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data["creators"][0]["total_favorited"] == 83000
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_first_video_date_comes_from_the_scan_cache(db):
|
||||
"""后台扫过主页就把最早那条的日期存下来 —— 它可能根本不在监控目标里。"""
|
||||
task_id = await _task()
|
||||
sec = "MS4wLjABAAAAsecuid"
|
||||
scanned_first = get_current_timestamp() - 300 * DAY_MS
|
||||
await _stat(task_id, "hash-a", "博主A", creator_id=sec)
|
||||
await _first_video("dy", sec, scanned_first)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data["creators"][0]["first_published_at"] == scanned_first
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_it_falls_back_to_the_earliest_tracked_note(db):
|
||||
"""还没扫到主页时,退到库里**最早**的一条作品。"""
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp() - 1000
|
||||
first = now - 400 * DAY_MS
|
||||
await _note(task_id, "old", "博主A", first)
|
||||
await _note(task_id, "new", "博主A", now)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data["creators"][0]["first_published_at"] == first
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_without_works_has_no_first_video_date(db):
|
||||
task_id = await _task()
|
||||
await _stat(task_id, "hash-a", "博主A", fans=10)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data["creators"][0]["first_published_at"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_without_a_snapshot_has_no_fan_count(db):
|
||||
"""作品模式刚导入、还没跑过一轮:粉丝数留 None,界面不画那个数字(不是 0)。"""
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp()
|
||||
await _note(task_id, "n1", "只有作品", now - 1000)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data["creators"][0]["fans"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_degraded_stat_snapshot_does_not_hide_the_name(db):
|
||||
"""资料接口偶尔回空对象(昵称/粉丝/作品数全空)。
|
||||
|
||||
那一轮不能算「最新的名字」—— 否则一个空字符串会把之前的好名字盖掉,界面上
|
||||
变成「未知(hash)」。线上真有两个号这么丢过名字。
|
||||
"""
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp()
|
||||
await _stat(task_id, "hash-a", "好名字", captured_at=now - 60_000, run_id=1)
|
||||
await _stat(task_id, "hash-a", "", captured_at=now, run_id=2) # 更新,但是坏的
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert [c["name"] for c in data["creators"]] == ["好名字"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_stat_falls_back_to_the_note_name(db):
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp()
|
||||
await _note(task_id, "n1", "作品里的名字", now - 1000)
|
||||
await _stat(task_id, "hash-a", "")
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert [c["name"] for c in data["creators"]] == ["作品里的名字"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cell_sums_the_latest_metric_of_each_note(db):
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp() - 1000
|
||||
await _note(task_id, "n1", "博主A", now, title="作品一")
|
||||
await _note(task_id, "n2", "博主A", now, title="作品二")
|
||||
|
||||
# 同一篇有两轮快照,只取 run_id 最大的那一轮
|
||||
await _metric(task_id, "n1", run_id=1, liked=10, comment=1, collected=2, share=3)
|
||||
await _metric(task_id, "n1", run_id=2, liked=20, comment=2, collected=4, share=5)
|
||||
await _metric(task_id, "n2", run_id=1, liked=5, comment=None, collected=1, share=0)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
cell = data["cells"][_day(now)]["hash-a"]
|
||||
assert cell["count"] == 2
|
||||
assert cell["likes"] == 25
|
||||
assert cell["comments"] == 2 # None 不参与求和
|
||||
assert cell["collected"] == 5
|
||||
assert cell["shares"] == 5
|
||||
|
||||
# 逐条明细带**各自的**指标,不是格子的合计 —— 悬停时看的就是这个。
|
||||
by_title = {item["title"]: item for item in cell["details"]}
|
||||
assert by_title["作品一"]["likes"] == 20 # 取最近一轮
|
||||
assert by_title["作品一"]["comments"] == 2
|
||||
assert by_title["作品一"]["collected"] == 4
|
||||
assert by_title["作品一"]["shares"] == 5
|
||||
assert by_title["作品二"]["likes"] == 5
|
||||
assert by_title["作品二"]["comments"] is None # 未知不是 0
|
||||
assert by_title["作品二"]["shares"] == 0
|
||||
# 提示里的标题要能点过去 —— 地址按平台在入库时拼好,原样带出。
|
||||
assert by_title["作品一"]["url"] == "https://www.douyin.com/video/n1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_metrics_are_none_not_zero(db):
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp() - 1000
|
||||
await _note(task_id, "n1", "博主A", now)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
cell = data["cells"][_day(now)]["hash-a"]
|
||||
# 「不知道」和「是 0」要分开 —— 前者在提示里显示成「—」
|
||||
assert cell["likes"] is None
|
||||
assert cell["comments"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_task_filter_scopes_the_matrix(db):
|
||||
first = await _task(name="任务一")
|
||||
second = await _task(name="任务二")
|
||||
now = get_current_timestamp() - 1000
|
||||
await _note(first, "a", "博主A", now, creator_hash="hash-a")
|
||||
await _note(second, "b", "博主B", now, creator_hash="hash-b")
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7, task_id=second)
|
||||
|
||||
assert data["task_id"] == second
|
||||
assert [c["name"] for c in data["creators"]] == ["博主B"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_task_from_another_platform_is_rejected(db):
|
||||
xhs_task = await _task(platform="xhs")
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7, task_id=xhs_task)
|
||||
|
||||
assert data["dates"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_account_pool_status_is_attached_by_nickname(db, monkeypatch):
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp() - 1000
|
||||
await _note(task_id, "n1", "博主A", now)
|
||||
|
||||
async def fake_pool():
|
||||
return [
|
||||
{"nickname": "博主A", "account_status": "账号异常"},
|
||||
{"nickname": "别人", "account_status": "账号正常"},
|
||||
]
|
||||
|
||||
monkeypatch.setenv("MC_ACCOUNT_POOL_URL", "http://pool/api")
|
||||
monkeypatch.setattr(service, "_fetch_account_pool", fake_pool)
|
||||
service._reset_account_status_cache()
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data["creators"][0]["account_status"] == "账号异常"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_account_pool_failure_does_not_break_the_report(db, monkeypatch):
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp() - 1000
|
||||
await _note(task_id, "n1", "博主A", now)
|
||||
|
||||
async def down():
|
||||
raise RuntimeError("pool is down")
|
||||
|
||||
monkeypatch.setenv("MC_ACCOUNT_POOL_URL", "http://pool/api")
|
||||
monkeypatch.setattr(service, "_fetch_account_pool", down)
|
||||
service._reset_account_status_cache()
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
# 外部服务挂了,报表照出,只是没有状态
|
||||
assert data["dates"]
|
||||
assert data["creators"][0]["account_status"] == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_endpoint_returns_the_long_shape(client):
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp() - 1000
|
||||
await _note(task_id, "n1", "博主A", now)
|
||||
tag_id = await _tag("大字报", 1)
|
||||
await _attach("dy", "n1", tag_id)
|
||||
|
||||
response = await client.get("/api/monitor/matrix", params={"platform": "dy", "days": 7})
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert _day(now) in body["dates"]
|
||||
assert body["creators"][0]["name"] == "博主A"
|
||||
cell = body["cells"][_day(now)]["hash-a"]
|
||||
assert cell["count"] == 1
|
||||
assert cell["tags"] == ["大字报"]
|
||||
assert "likes" in cell
|
||||
@@ -0,0 +1,146 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""作品备注 —— 一个博主底下,哪几条是真正要盯的。
|
||||
|
||||
和博主备注(test_monitor_creators.py)是一对,但回答的不是同一个问题:博主备注回答
|
||||
「这个账号是谁」,作品备注回答「这条作品我要盯着」。一个博主底下常常只有一两件值得
|
||||
盯的作品,所以不能合成一条。
|
||||
"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from api.main import app
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor.models import MODE_CREATOR, MonitorNote, MonitorTask
|
||||
|
||||
NOTE_ID = "note-a"
|
||||
TITLE = "中秋哪儿都堵"
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
|
||||
await monitor_db.init_db()
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http_client:
|
||||
yield http_client
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
async def _seed(platform: str = "xhs", task_name: str = "任务", note_id: str = NOTE_ID) -> int:
|
||||
async with monitor_db.get_session() as session:
|
||||
task = MonitorTask(
|
||||
name=task_name, platform=platform, mode=MODE_CREATOR, enabled=True,
|
||||
interval_minutes=60, max_notes_count=20, enable_comments=False,
|
||||
max_comments_count=50, run_timeout_seconds=3600,
|
||||
notify_enabled=False, created_at=0, updated_at=0,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
session.add(
|
||||
MonitorNote(
|
||||
task_id=task.id, note_id=note_id, title=TITLE,
|
||||
note_url="", cover="", creator_hash="hash-a",
|
||||
creator_name="张三", source_kind="", published_at=None,
|
||||
first_seen_run_id=1, first_seen_at=0,
|
||||
last_seen_run_id=1, last_seen_at=0,
|
||||
)
|
||||
)
|
||||
return task.id
|
||||
|
||||
|
||||
async def _notes(client, platform: str = "xhs"):
|
||||
return (await client.get("/api/monitor/notes", params={"platform": platform})).json()["notes"]
|
||||
|
||||
|
||||
async def _set_alias(client, alias: str, platform: str = "xhs", note_id: str = NOTE_ID):
|
||||
return await client.put(
|
||||
f"/api/monitor/notes/{note_id}",
|
||||
params={"platform": platform},
|
||||
json={"alias": alias},
|
||||
)
|
||||
|
||||
|
||||
class TestNoteAlias:
|
||||
@pytest.mark.asyncio
|
||||
async def test_notes_start_without_a_remark(self, client):
|
||||
await _seed()
|
||||
|
||||
assert (await _notes(client))[0]["note_alias"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_remark_comes_back_with_the_notes(self, client):
|
||||
await _seed()
|
||||
|
||||
response = await _set_alias(client, "重点")
|
||||
|
||||
assert response.status_code == 200
|
||||
note = (await _notes(client))[0]
|
||||
assert note["note_alias"] == "重点"
|
||||
# 备注是**叠加**在标题之上的,不是替换 —— 标题仍然是这条作品本身。
|
||||
assert note["title"] == TITLE
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_remark_is_shared_across_tasks(self, client):
|
||||
"""同一件作品被两个任务都监控时,备注只该填一次。"""
|
||||
await _seed(task_name="任务甲")
|
||||
await _seed(task_name="任务乙")
|
||||
await _set_alias(client, "重点")
|
||||
|
||||
for note in await _notes(client):
|
||||
assert note["note_alias"] == "重点"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_remark_does_not_leak_to_another_platform(self, client):
|
||||
"""作品的 id 是平台各自的编号体系 —— 抖音的 123 和小红书的 123 是两条作品。"""
|
||||
await _seed(platform="xhs")
|
||||
await _seed(platform="dy")
|
||||
|
||||
await _set_alias(client, "小红书那边的", platform="xhs")
|
||||
|
||||
assert (await _notes(client, "xhs"))[0]["note_alias"] == "小红书那边的"
|
||||
assert (await _notes(client, "dy"))[0]["note_alias"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_remark_does_not_leak_to_another_work(self, client):
|
||||
"""钉住这里的**作用域**:键是 note_id。写错成按任务存的话,给一条起了备注,
|
||||
同一个博主底下的其它作品会跟着一起变 —— 那这个功能就没用了。"""
|
||||
await _seed(note_id="note-a")
|
||||
await _seed(task_name="另一个任务", note_id="note-b")
|
||||
|
||||
await _set_alias(client, "重点", note_id="note-a")
|
||||
|
||||
by_id = {note["note_id"]: note["note_alias"] for note in await _notes(client)}
|
||||
assert by_id == {"note-a": "重点", "note-b": ""}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_empty_remark_clears_it(self, client):
|
||||
await _seed()
|
||||
await _set_alias(client, "重点")
|
||||
|
||||
await _set_alias(client, "")
|
||||
|
||||
assert (await _notes(client))[0]["note_alias"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_remark_is_trimmed(self, client):
|
||||
await _seed()
|
||||
|
||||
await _set_alias(client, " 重点 ")
|
||||
|
||||
assert (await _notes(client))[0]["note_alias"] == "重点"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_two_kinds_of_remark_stay_apart(self, client):
|
||||
"""博主备注和作品备注是两张表、两个键 —— 一个不该把另一个盖掉。"""
|
||||
await _seed()
|
||||
|
||||
await _set_alias(client, "重点")
|
||||
await client.put(
|
||||
"/api/monitor/creators/hash-a", params={"platform": "xhs"}, json={"alias": "竞品A"}
|
||||
)
|
||||
|
||||
note = (await _notes(client))[0]
|
||||
assert note["note_alias"] == "重点"
|
||||
assert note["creator_alias"] == "竞品A"
|
||||
@@ -0,0 +1,190 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""作品栏的**窗口** —— 每个博主只显示最新 N 条。
|
||||
|
||||
采集端 ``aweme/post`` 拿的就是最新 N 条,掉出这个窗口的作品**再也采不到**,指标会冻在
|
||||
最后一次。而它看上去和正在跟踪的作品一模一样 —— 那才是会骗人的地方。所以界面按同一个
|
||||
窗口显示,库里则一条不删(趋势图、报表、导出读的是全量)。
|
||||
"""
|
||||
|
||||
import csv
|
||||
import io
|
||||
from datetime import datetime
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from api.main import app
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor.models import MODE_CREATOR, MODE_NOTE, MonitorNote, MonitorTask
|
||||
|
||||
CREATOR = "hash-a"
|
||||
|
||||
# 固定的基准时刻,避免用例依赖「今天是几号」。
|
||||
BASE = int(datetime(2026, 1, 1, 12, 0).timestamp() * 1000)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
|
||||
await monitor_db.init_db()
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http_client:
|
||||
yield http_client
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
async def _seed_task(mode: str = MODE_CREATOR, cap: int = 2) -> int:
|
||||
async with monitor_db.get_session() as session:
|
||||
task = MonitorTask(
|
||||
name="窗口测试", platform="xhs", mode=mode, enabled=True,
|
||||
interval_minutes=60, max_notes_count=cap, enable_comments=False,
|
||||
max_comments_count=50, run_timeout_seconds=3600,
|
||||
notify_enabled=False, created_at=0, updated_at=0,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
return task.id
|
||||
|
||||
|
||||
async def _add_note(
|
||||
task_id: int,
|
||||
note_id: str,
|
||||
published_at,
|
||||
last_seen_at: int,
|
||||
creator_hash: str = CREATOR,
|
||||
) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorNote(
|
||||
task_id=task_id, note_id=note_id, title=f"作品{note_id}",
|
||||
note_url="", cover="", creator_hash=creator_hash,
|
||||
creator_name="博主", source_kind="", published_at=published_at,
|
||||
first_seen_run_id=1, first_seen_at=BASE,
|
||||
last_seen_run_id=1, last_seen_at=last_seen_at,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _notes(client, **params):
|
||||
return (await client.get("/api/monitor/notes", params=params)).json()["notes"]
|
||||
|
||||
|
||||
def _ids(notes):
|
||||
return sorted(note["note_id"] for note in notes)
|
||||
|
||||
|
||||
class TestCreatorWindow:
|
||||
@pytest.mark.asyncio
|
||||
async def test_only_the_newest_n_survive(self, client):
|
||||
"""三条作品、上限两条 —— 最早的 `a` 掉出窗口。"""
|
||||
task_id = await _seed_task(cap=2)
|
||||
await _add_note(task_id, "a", BASE, BASE)
|
||||
await _add_note(task_id, "b", BASE + 1000, BASE + 1000)
|
||||
await _add_note(task_id, "c", BASE + 2000, BASE + 2000)
|
||||
|
||||
assert _ids(await _notes(client)) == ["b", "c"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_window_is_by_publish_time_not_by_last_seen(self, client):
|
||||
"""**这条是这个功能的关键。**
|
||||
|
||||
「最后一次见到」和「最新发布」是两回事:降级路径(作品列表被风控挡住)会把**所有**
|
||||
已知作品都刷一遍,于是每条作品的 last_seen_at 都变成最新 —— 按它开窗等于没开。
|
||||
窗口必须按发布时间,那才是采集端 `aweme/post` 返回的排序。
|
||||
"""
|
||||
task_id = await _seed_task(cap=2)
|
||||
# a 发布最早,但「最后一次见到」最新。
|
||||
await _add_note(task_id, "a", BASE, BASE + 9000)
|
||||
await _add_note(task_id, "b", BASE + 1000, BASE + 1000)
|
||||
await _add_note(task_id, "c", BASE + 2000, BASE + 2000)
|
||||
|
||||
assert _ids(await _notes(client)) == ["b", "c"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_work_with_no_publish_time_is_never_hidden(self, client):
|
||||
"""**解析不出日期不该让一条作品消失** —— 多显示一条远好过悄悄少一条。"""
|
||||
task_id = await _seed_task(cap=2)
|
||||
await _add_note(task_id, "undated", None, BASE)
|
||||
await _add_note(task_id, "b", BASE + 1000, BASE + 1000)
|
||||
await _add_note(task_id, "c", BASE + 2000, BASE + 2000)
|
||||
|
||||
assert "undated" in _ids(await _notes(client))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_each_creator_gets_its_own_window(self, client):
|
||||
"""上限是「每个博主 N 条」,不是「整个任务 N 条」。"""
|
||||
task_id = await _seed_task(cap=1)
|
||||
await _add_note(task_id, "a1", BASE, BASE, creator_hash="hash-a")
|
||||
await _add_note(task_id, "a2", BASE + 1000, BASE + 1000, creator_hash="hash-a")
|
||||
await _add_note(task_id, "b1", BASE, BASE, creator_hash="hash-b")
|
||||
|
||||
assert _ids(await _notes(client)) == ["a2", "b1"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_note_mode_task_is_not_windowed(self, client):
|
||||
"""笔记模式的 max_notes_count 管的是「每条目标拉多少」,它的目标本身就是一件作品。"""
|
||||
task_id = await _seed_task(mode=MODE_NOTE, cap=1)
|
||||
await _add_note(task_id, "a", BASE, BASE)
|
||||
await _add_note(task_id, "b", BASE + 1000, BASE + 1000)
|
||||
await _add_note(task_id, "c", BASE + 2000, BASE + 2000)
|
||||
|
||||
assert _ids(await _notes(client)) == ["a", "b", "c"]
|
||||
|
||||
|
||||
class TestTheDatabaseKeepsEverything:
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_window_hides_it_but_does_not_delete_it(self, client):
|
||||
"""界面是窗口,库是账本 —— 掉出窗口那条必须还在,否则趋势图和报表会缺历史。"""
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from api.monitor.db import get_engine
|
||||
|
||||
task_id = await _seed_task(cap=1)
|
||||
await _add_note(task_id, "a", BASE, BASE)
|
||||
await _add_note(task_id, "b", BASE + 1000, BASE + 1000)
|
||||
|
||||
assert _ids(await _notes(client)) == ["b"]
|
||||
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
factory = async_sessionmaker(
|
||||
get_engine(), class_=AsyncSession, expire_on_commit=False
|
||||
)
|
||||
async with factory() as session:
|
||||
stored = list((await session.scalars(select(MonitorNote.note_id))).all())
|
||||
|
||||
assert sorted(stored) == ["a", "b"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_export_still_gets_everything(self, client):
|
||||
"""导出是**全量账本**,不是屏幕上那一屏 —— 界面上少显示几条是故意的,
|
||||
但导出的数据少几条就是在丢东西了。"""
|
||||
task_id = await _seed_task(cap=1)
|
||||
await _add_note(task_id, "a", BASE, BASE)
|
||||
await _add_note(task_id, "b", BASE + 1000, BASE + 1000)
|
||||
|
||||
response = await client.get(
|
||||
"/api/monitor/export", params={"kind": "notes", "format": "csv"}
|
||||
)
|
||||
rows = list(csv.DictReader(io.StringIO(response.content.decode("utf-8-sig"))))
|
||||
|
||||
assert sorted(row["作品ID"] for row in rows) == ["a", "b"]
|
||||
|
||||
|
||||
class TestTheGroupHeaderCounts:
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_creator_list_reports_the_full_count(self, client):
|
||||
"""组头显示「显示了几篇 / 库里一共几篇」,两个数不一样是**对的**。
|
||||
|
||||
屏幕上是开过窗的(这个博主最新 N 条),而 ``note_count`` 是库里这个博主的全部
|
||||
作品数 —— 组头那行提示说的正是这件事。
|
||||
"""
|
||||
task_id = await _seed_task(cap=1)
|
||||
await _add_note(task_id, "a", BASE, BASE)
|
||||
await _add_note(task_id, "b", BASE + 1000, BASE + 1000)
|
||||
|
||||
creators = (await client.get("/api/monitor/notes", params={})).json()["creators"]
|
||||
|
||||
assert creators[0]["note_count"] == 2
|
||||
@@ -0,0 +1,110 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""monitor runner —— 尤其是抖音那条(不走子进程的)路的运行状态流转。
|
||||
|
||||
这条路的地位特殊:它不经过 ``crawler_manager``,所以爬虫那套「退出码 / 日志尾巴」的
|
||||
约定它一个都不沾。凡是写在那里面的东西,这条路都得单独有一份。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import select
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor import runner as runner_module
|
||||
from api.monitor.models import (
|
||||
MODE_CREATOR,
|
||||
RUN_RUNNING,
|
||||
MonitorRun,
|
||||
MonitorTarget,
|
||||
MonitorTask,
|
||||
)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def db(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
|
||||
await monitor_db.init_db()
|
||||
yield monitor_db
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
async def _make_douyin_task() -> int:
|
||||
async with monitor_db.get_session() as session:
|
||||
now = get_current_timestamp()
|
||||
task = MonitorTask(
|
||||
name="dy", platform="dy", mode=MODE_CREATOR, enabled=True,
|
||||
interval_minutes=360, max_notes_count=20, enable_comments=False,
|
||||
max_comments_count=20, run_timeout_seconds=3600,
|
||||
notify_enabled=False, notify_failures=False,
|
||||
created_at=now, updated_at=now,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
session.add(
|
||||
MonitorTarget(
|
||||
task_id=task.id, kind=MODE_CREATOR, external_id="MS4w-sec",
|
||||
xsec_token="", xsec_source="", raw_value="MS4w-sec",
|
||||
label="x", enabled=True, created_at=now,
|
||||
)
|
||||
)
|
||||
return task.id
|
||||
|
||||
|
||||
class TestDouyinRunStatus:
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_run_is_marked_running_before_collecting(self, db, monkeypatch):
|
||||
"""**采集开始之前**,run 就必须已经是 running。
|
||||
|
||||
这一行原先只写在爬虫那条分支里,于是抖音路上 run 一直停在 pending —— 一旦中途
|
||||
出事(异常、或进程被重启),界面上就是一个永远「排队中」的幽灵,而且 recover()
|
||||
当时也只收 running、够不着它。
|
||||
"""
|
||||
task_id = await _make_douyin_task()
|
||||
seen = {}
|
||||
|
||||
async def fake_collect(out_dir, **kwargs):
|
||||
async with monitor_db.get_session() as session:
|
||||
run = await session.scalar(select(MonitorRun).order_by(MonitorRun.id))
|
||||
seen["status"] = run.status
|
||||
return {
|
||||
"notes": 0,
|
||||
"comments": 0,
|
||||
"errors": ["故意失败"],
|
||||
"jsonl_dir": str(out_dir),
|
||||
}
|
||||
|
||||
monkeypatch.setattr(runner_module.douyin_fetch, "collect", fake_collect)
|
||||
|
||||
await runner_module.execute_task(task_id, trigger="manual")
|
||||
|
||||
assert seen["status"] == RUN_RUNNING
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_hanging_collect_does_not_leave_the_run_running(self, db, monkeypatch):
|
||||
"""进程内那条路也要有超时。
|
||||
|
||||
爬虫那条靠 ``run_and_wait(timeout=...)`` 兜底,这条路没有子进程、没人管 ——
|
||||
里面任何一次卡住(实测过 ``page.evaluate`` 打在一个卡死的标签页上不返回)都会让
|
||||
run 永远停在「运行中」,界面上看起来就是任务卡死了。
|
||||
"""
|
||||
task_id = await _make_douyin_task()
|
||||
async with monitor_db.get_session() as session:
|
||||
task = await session.get(MonitorTask, task_id)
|
||||
task.run_timeout_seconds = 1 # 把超时压到 1 秒,别让测试真等
|
||||
|
||||
async def hanging_collect(out_dir, **kwargs):
|
||||
await asyncio.sleep(60)
|
||||
raise AssertionError("不该走到这里")
|
||||
|
||||
monkeypatch.setattr(runner_module.douyin_fetch, "collect", hanging_collect)
|
||||
|
||||
await runner_module.execute_task(task_id, trigger="manual")
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
run = await session.scalar(select(MonitorRun).order_by(MonitorRun.id))
|
||||
assert run.status != RUN_RUNNING
|
||||
assert "超时" in (run.error_message or "") or "超过" in (run.error_message or "")
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
"""Tests for the monitor scheduler's firing, deferral and recovery rules."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import select
|
||||
@@ -30,6 +32,7 @@ from api.monitor.models import (
|
||||
MonitorTarget,
|
||||
MonitorTask,
|
||||
RUN_INTERRUPTED,
|
||||
RUN_PENDING,
|
||||
RUN_RUNNING,
|
||||
RUN_SUCCESS,
|
||||
)
|
||||
@@ -72,6 +75,16 @@ async def executed(monkeypatch):
|
||||
return calls
|
||||
|
||||
|
||||
async def _tick(scheduler: MonitorScheduler) -> None:
|
||||
"""tick + 等后台采集结束。
|
||||
|
||||
采集现在跑在后台任务里(卡死的一轮不能堵住整个调度循环),断言调用记录之前
|
||||
得先把它等回来。
|
||||
"""
|
||||
await scheduler.tick()
|
||||
await scheduler.drain()
|
||||
|
||||
|
||||
async def _make_task(
|
||||
next_run_at, enabled: bool = True, interval: int = 60, platform: str = "xhs"
|
||||
) -> int:
|
||||
@@ -122,7 +135,7 @@ class TestFiring:
|
||||
past = get_current_timestamp() - MS_PER_MINUTE
|
||||
task_id = await _make_task(past)
|
||||
|
||||
await MonitorScheduler().tick()
|
||||
await _tick(MonitorScheduler())
|
||||
|
||||
assert executed == [(task_id, "scheduled")]
|
||||
task = await _get_task(task_id)
|
||||
@@ -134,7 +147,7 @@ class TestFiring:
|
||||
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
||||
await _make_task(get_current_timestamp() + 10 * MS_PER_MINUTE)
|
||||
|
||||
await MonitorScheduler().tick()
|
||||
await _tick(MonitorScheduler())
|
||||
|
||||
assert executed == []
|
||||
|
||||
@@ -143,7 +156,7 @@ class TestFiring:
|
||||
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
||||
await _make_task(get_current_timestamp() - MS_PER_MINUTE, enabled=False)
|
||||
|
||||
await MonitorScheduler().tick()
|
||||
await _tick(MonitorScheduler())
|
||||
|
||||
assert executed == []
|
||||
|
||||
@@ -162,7 +175,7 @@ class TestFiring:
|
||||
|
||||
task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy")
|
||||
|
||||
await MonitorScheduler().tick()
|
||||
await _tick(MonitorScheduler())
|
||||
|
||||
assert executed == [(task_id, "scheduled")]
|
||||
|
||||
@@ -181,7 +194,7 @@ class TestFiring:
|
||||
|
||||
task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy")
|
||||
|
||||
await MonitorScheduler().tick()
|
||||
await _tick(MonitorScheduler())
|
||||
|
||||
assert executed == [(task_id, "scheduled")]
|
||||
|
||||
@@ -194,11 +207,36 @@ class TestFiring:
|
||||
|
||||
scheduler = MonitorScheduler()
|
||||
await scheduler.tick()
|
||||
await scheduler.drain()
|
||||
await scheduler.tick()
|
||||
await scheduler.drain()
|
||||
|
||||
assert len(executed) == 1
|
||||
|
||||
|
||||
class TestNonBlocking:
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_hanging_run_does_not_block_the_scheduler(self, monkeypatch, db):
|
||||
"""卡死的一轮不能钉住整个循环 —— 其他任务和自动追加都靠这个 tick。
|
||||
|
||||
实测:抖音采集协程偶尔不响应取消,内联 await 会让循环停 65 分钟。
|
||||
"""
|
||||
|
||||
async def never(task_id, trigger="scheduled"):
|
||||
await asyncio.Event().wait()
|
||||
|
||||
monkeypatch.setattr(scheduler_module, "execute_task", never)
|
||||
await _make_task(get_current_timestamp() - MS_PER_MINUTE)
|
||||
scheduler = MonitorScheduler()
|
||||
|
||||
# 必须在很短时间内返回,而不是等采集结束。
|
||||
await asyncio.wait_for(scheduler.tick(), timeout=2)
|
||||
|
||||
assert len(scheduler._running_tasks) == 1
|
||||
for task in list(scheduler._running_tasks.values()):
|
||||
task.cancel()
|
||||
|
||||
|
||||
class TestDeferral:
|
||||
@pytest.mark.asyncio
|
||||
async def test_busy_crawler_defers_without_advancing(self, monkeypatch, db, executed):
|
||||
@@ -207,7 +245,7 @@ class TestDeferral:
|
||||
due_at = get_current_timestamp() - MS_PER_MINUTE
|
||||
task_id = await _make_task(due_at)
|
||||
|
||||
await MonitorScheduler().tick()
|
||||
await _tick(MonitorScheduler())
|
||||
|
||||
assert executed == []
|
||||
task = await _get_task(task_id)
|
||||
@@ -222,10 +260,12 @@ class TestDeferral:
|
||||
|
||||
scheduler = MonitorScheduler()
|
||||
await scheduler.tick()
|
||||
await scheduler.drain()
|
||||
assert executed == []
|
||||
|
||||
fake.busy = False
|
||||
await scheduler.tick()
|
||||
await scheduler.drain()
|
||||
assert executed == [(task_id, "scheduled")]
|
||||
|
||||
|
||||
@@ -242,7 +282,7 @@ class TestCookieGuard:
|
||||
due_at = get_current_timestamp() - MS_PER_MINUTE
|
||||
task_id = await _make_task(due_at)
|
||||
|
||||
await MonitorScheduler().tick()
|
||||
await _tick(MonitorScheduler())
|
||||
|
||||
assert executed == []
|
||||
task = await _get_task(task_id)
|
||||
@@ -279,6 +319,39 @@ class TestRecovery:
|
||||
assert run.status == RUN_INTERRUPTED
|
||||
assert run.finished_at is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pending_runs_are_also_cleaned_up(self, db):
|
||||
"""挂在 ``pending`` 的 run 同样是残留,必须一起收。
|
||||
|
||||
那一行是上一轮建的,可它后面的采集根本没机会开始(进程被重启,或采集那条路抛了
|
||||
异常)。只清 ``running`` 的话,它会永远挂在界面上显示「排队中」——
|
||||
用户看到的就是任务卡死了。
|
||||
"""
|
||||
async with monitor_db.get_session() as session:
|
||||
now = get_current_timestamp()
|
||||
task = MonitorTask(
|
||||
name="t", platform="dy", mode=MODE_CREATOR, enabled=True,
|
||||
interval_minutes=60, max_notes_count=20, enable_comments=False,
|
||||
max_comments_count=50, run_timeout_seconds=3600,
|
||||
next_run_at=now, last_status="pending", created_at=now, updated_at=now,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
session.add(
|
||||
MonitorRun(
|
||||
task_id=task.id, trigger="manual", status=RUN_PENDING,
|
||||
phase=MODE_CREATOR, save_data_path="", queued_at=now, not_before=0,
|
||||
max_comments_count=50,
|
||||
)
|
||||
)
|
||||
|
||||
await MonitorScheduler().recover()
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
run = await session.scalar(select(MonitorRun))
|
||||
assert run.status == RUN_INTERRUPTED
|
||||
assert run.finished_at is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_completed_runs_are_left_alone(self, db):
|
||||
async with monitor_db.get_session() as session:
|
||||
@@ -304,3 +377,77 @@ class TestRecovery:
|
||||
async with monitor_db.get_session() as session:
|
||||
run = await session.scalar(select(MonitorRun))
|
||||
assert run.status == RUN_SUCCESS
|
||||
|
||||
|
||||
async def _make_run(
|
||||
task_id: int, *, started_minutes_ago: int, status: str = RUN_RUNNING
|
||||
) -> int:
|
||||
now = get_current_timestamp()
|
||||
async with monitor_db.get_session() as session:
|
||||
run = MonitorRun(
|
||||
task_id=task_id,
|
||||
trigger="scheduled",
|
||||
status=status,
|
||||
phase=MODE_CREATOR,
|
||||
save_data_path="",
|
||||
queued_at=now,
|
||||
not_before=0,
|
||||
started_at=now - started_minutes_ago * MS_PER_MINUTE,
|
||||
max_comments_count=50,
|
||||
)
|
||||
session.add(run)
|
||||
await session.flush()
|
||||
return run.id
|
||||
|
||||
|
||||
async def _get_run(run_id: int) -> MonitorRun:
|
||||
async with monitor_db.get_session() as session:
|
||||
return await session.get(MonitorRun, run_id)
|
||||
|
||||
|
||||
class TestReapStaleRuns:
|
||||
"""卡在「运行中」的 run 必须能被周期性地收掉,而不是只能靠重启。
|
||||
|
||||
``runner`` 那边用 ``asyncio.wait_for(collect(...), timeout=...)`` 兜底,但超时后
|
||||
它会去**取消**采集协程、并且**等取消完成**。抖音那条路卡在 Playwright 调用上时
|
||||
协程不响应取消,于是 ``except asyncio.TimeoutError`` 根本轮不到 —— 线上真的因此
|
||||
挂过 7 条幽灵 run,最久的 48 小时,产物目录全空,只有重启才清掉。
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_past_its_own_timeout_is_reaped(self, db):
|
||||
task_id = await _make_task(get_current_timestamp()) # run_timeout_seconds=3600
|
||||
run_id = await _make_run(task_id, started_minutes_ago=120)
|
||||
|
||||
assert await scheduler_module.reap_stale_runs() == 1
|
||||
|
||||
run = await _get_run(run_id)
|
||||
assert run.status == RUN_INTERRUPTED
|
||||
assert run.finished_at is not None
|
||||
# 留下来的必须是**说得清**的原因,不能是空字符串
|
||||
assert "卡死" in (run.error_message or "")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_still_inside_its_timeout_is_untouched(self, db):
|
||||
task_id = await _make_task(get_current_timestamp())
|
||||
run_id = await _make_run(task_id, started_minutes_ago=30)
|
||||
|
||||
assert await scheduler_module.reap_stale_runs() == 0
|
||||
assert (await _get_run(run_id)).status == RUN_RUNNING
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_grace_period_leaves_the_runner_time_to_finish(self, db):
|
||||
"""刚过超时那一小段不动手 —— 采集那边到点后还要收尾写库。"""
|
||||
task_id = await _make_task(get_current_timestamp())
|
||||
run_id = await _make_run(task_id, started_minutes_ago=61) # 3600s 刚过
|
||||
|
||||
assert await scheduler_module.reap_stale_runs() == 0
|
||||
assert (await _get_run(run_id)).status == RUN_RUNNING
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_finished_runs_are_left_alone(self, db):
|
||||
task_id = await _make_task(get_current_timestamp())
|
||||
run_id = await _make_run(task_id, started_minutes_ago=1000, status=RUN_SUCCESS)
|
||||
|
||||
assert await scheduler_module.reap_stale_runs() == 0
|
||||
assert (await _get_run(run_id)).status == RUN_SUCCESS
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""分享短链 —— 保存目标时联网跟一次跳转,解出真实地址。
|
||||
|
||||
不这么做的话,粘进去的是一串短码,被当成 user_id 存下来,采集时拿它去请求什么都抓不到
|
||||
(真事:任务 22,`https://xhslink.cn/o/AhQpHsqcme5`,报出来却是「疑似登录态失效」)。
|
||||
"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api.monitor.service import expand_short_link, parse_target_input, prepare_target
|
||||
|
||||
# **真实的跳转**(实测 xhslink.cn/o/AhQpHsqcme5 的第一个 302),不是编的 ——
|
||||
# 这个地址的形状决定了能不能抠出 id 和 xsec_token。
|
||||
REAL_XHS_REDIRECT = (
|
||||
"https://www.xiaohongshu.com/user/profile/69d388f00000000032024a75"
|
||||
"?xsec_token=YBpTJH9kYbkTkgL-F4POKqd_kEM5A05smIjgbcyMSI2k4%3D"
|
||||
"&xsec_source=app_share&xhsshare=CopyLink&track_code=4s40v6M3mwa"
|
||||
)
|
||||
|
||||
|
||||
def _client_returning(monkeypatch, status_code: int, location: str):
|
||||
"""假装是那个短链服务器:只看 Location,不跟跳转。"""
|
||||
seen: dict = {}
|
||||
|
||||
class _Response:
|
||||
headers = {"location": location} if location else {}
|
||||
|
||||
_Response.status_code = status_code
|
||||
|
||||
class _Client:
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def get(self, url, **kwargs):
|
||||
seen["url"] = url
|
||||
seen.update(kwargs)
|
||||
return _Response()
|
||||
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: _Client())
|
||||
return seen
|
||||
|
||||
|
||||
class TestExpandShortLink:
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_share_link_is_expanded(self, monkeypatch):
|
||||
_client_returning(monkeypatch, 302, REAL_XHS_REDIRECT)
|
||||
|
||||
expanded = await expand_short_link("https://xhslink.cn/o/AhQpHsqcme5", "xhs")
|
||||
|
||||
assert expanded == REAL_XHS_REDIRECT
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_it_asks_for_the_first_hop_only(self, monkeypatch):
|
||||
"""**不跟随跳转**:跟到底会落到登录页,反而把要的东西丢了。"""
|
||||
seen = _client_returning(monkeypatch, 302, REAL_XHS_REDIRECT)
|
||||
|
||||
await expand_short_link("https://xhslink.cn/o/AhQpHsqcme5", "xhs")
|
||||
|
||||
assert seen["follow_redirects"] is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_normal_link_is_not_even_requested(self, monkeypatch):
|
||||
"""普通链接不联网 —— 多发一个请求既慢又没有意义,还可能把 token 弄丢。"""
|
||||
seen = _client_returning(monkeypatch, 302, REAL_XHS_REDIRECT)
|
||||
|
||||
value = "https://www.xiaohongshu.com/user/profile/69d388f00000000032024a75"
|
||||
|
||||
assert await expand_short_link(value, "xhs") == value
|
||||
assert seen == {}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_bare_id_is_not_requested(self, monkeypatch):
|
||||
seen = _client_returning(monkeypatch, 302, REAL_XHS_REDIRECT)
|
||||
|
||||
assert await expand_short_link("69d388f00000000032024a75", "xhs") == (
|
||||
"69d388f00000000032024a75"
|
||||
)
|
||||
assert seen == {}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_dead_short_link_keeps_the_original_value(self, monkeypatch):
|
||||
"""码不存在时抖音会跳到首页 —— 那就解不出来。**保持原值,不报错**:
|
||||
链接校验已经关掉了,再造一个拒绝点自相矛盾。"""
|
||||
_client_returning(monkeypatch, 302, "https://www.douyin.com/")
|
||||
|
||||
assert await expand_short_link("https://v.douyin.com/zzz/", "dy") != ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_network_error_keeps_the_original_value(self, monkeypatch):
|
||||
"""短链服务不通时不能把「新建任务」这个动作也带崩。"""
|
||||
|
||||
class _Boom:
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def get(self, *args, **kwargs):
|
||||
raise httpx.ConnectTimeout("boom")
|
||||
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: _Boom())
|
||||
value = "https://xhslink.cn/o/AhQpHsqcme5"
|
||||
|
||||
assert await expand_short_link(value, "xhs") == value
|
||||
|
||||
|
||||
class TestPrepareTarget:
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_real_short_link_yields_a_usable_target(self, monkeypatch):
|
||||
"""**这就是任务 22 该有的结果** —— 而不是把短链本身存成 external_id。"""
|
||||
_client_returning(monkeypatch, 302, REAL_XHS_REDIRECT)
|
||||
|
||||
parsed = await prepare_target("https://xhslink.cn/o/AhQpHsqcme5", "creator", "xhs")
|
||||
|
||||
assert parsed["external_id"] == "69d388f00000000032024a75"
|
||||
assert parsed["xsec_token"] == "YBpTJH9kYbkTkgL-F4POKqd_kEM5A05smIjgbcyMSI2k4="
|
||||
assert parsed["xsec_source"] == "app_share"
|
||||
# 原文留着,出问题时能回溯用户当初粘的是什么。
|
||||
assert parsed["raw_value"] == "https://xhslink.cn/o/AhQpHsqcme5"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_unexpandable_link_still_gets_stored(self, monkeypatch):
|
||||
"""解不开也照存 —— 这是「完全不校验」的既定行为,不能在这里偷偷加一个拒绝点。"""
|
||||
_client_returning(monkeypatch, 302, "")
|
||||
|
||||
parsed = await prepare_target("https://xhslink.cn/o/dead", "creator", "xhs")
|
||||
|
||||
assert parsed["external_id"] == "https://xhslink.cn/o/dead"
|
||||
|
||||
|
||||
class TestParseIsStillPure:
|
||||
"""纯函数那层没变 —— 短链解不开时它仍然只能原样存,网络那一步在外面。"""
|
||||
|
||||
def test_parse_alone_does_not_expand(self):
|
||||
parsed = parse_target_input("https://xhslink.cn/o/AhQpHsqcme5", "creator", "xhs")
|
||||
assert parsed["external_id"] == "https://xhslink.cn/o/AhQpHsqcme5"
|
||||
@@ -0,0 +1,736 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""超级编导导入:区间筛选、去重、建任务时的作品 id,以及那些「看起来像没数据」的坑。"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import select
|
||||
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor import superdir
|
||||
from api.monitor.models import MODE_NOTE, MonitorTarget
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
AWEME_A = "7699073324462902970"
|
||||
AWEME_B = "7580311223398286720"
|
||||
AWEME_C = "7638788935163048838"
|
||||
|
||||
|
||||
def _video(aweme_id: str, **overrides):
|
||||
record = {
|
||||
"share_url": f"https://www.douyin.com/video//{aweme_id}",
|
||||
"nickname": "帆",
|
||||
"title": "美女请多营业",
|
||||
"published_at": 1792748542,
|
||||
"play_count": 243,
|
||||
"digg_count": 9,
|
||||
"comment_count": 0,
|
||||
"share_count": 0,
|
||||
"video_status": 5,
|
||||
}
|
||||
record.update(overrides)
|
||||
return record
|
||||
|
||||
|
||||
def _activity(activity_id: int, day: date, title: str = "活动"):
|
||||
return {
|
||||
"id": activity_id,
|
||||
"title": title,
|
||||
"created_at": superdir._day_start(day) + 3600,
|
||||
}
|
||||
|
||||
|
||||
class TestDayBounds:
|
||||
def test_days_are_east_eight_not_the_containers_timezone(self):
|
||||
"""created_at 是「本地时区」的 Unix 秒,而容器通常跑在 UTC。
|
||||
|
||||
按容器 localtime 算边界,整段查询会错开 8 小时:早上的「今天」会算进昨晚的活动。
|
||||
"""
|
||||
assert superdir._day_start(date(2026, 10, 21)) == int(
|
||||
datetime(2026, 10, 20, 16, 0, 0, tzinfo=timezone.utc).timestamp()
|
||||
)
|
||||
|
||||
def test_the_whole_day_is_included(self):
|
||||
start = superdir._day_start(date(2026, 10, 21))
|
||||
end = superdir._day_end(date(2026, 10, 21))
|
||||
|
||||
assert end - start == 86399
|
||||
|
||||
|
||||
class TestPreview:
|
||||
@pytest.mark.asyncio
|
||||
async def test_only_activities_created_in_the_range_are_fetched(self, monkeypatch):
|
||||
fetched: list = []
|
||||
|
||||
async def fake_activities(token, client):
|
||||
return [
|
||||
_activity(1, date(2026, 10, 19), "区间外"),
|
||||
_activity(2, date(2026, 10, 21), "目标活动"),
|
||||
]
|
||||
|
||||
async def fake_videos(token, activity_id, client):
|
||||
fetched.append(activity_id)
|
||||
return [_video(AWEME_A)]
|
||||
|
||||
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
|
||||
return "token"
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
|
||||
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
|
||||
monkeypatch.setattr(superdir, "get_token", fake_token)
|
||||
|
||||
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
|
||||
|
||||
assert fetched == [2]
|
||||
assert result["activities"] == 1
|
||||
assert result["videos"] == 1
|
||||
assert result["rows"][0]["aweme_id"] == AWEME_A
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_matched_activities_explain_a_zero_video_result(self, monkeypatch):
|
||||
"""活动建了但还没人发布 —— 0 条作品是真的,界面上得说得出是哪几个活动。
|
||||
|
||||
实测踩到过:运营按「10-22 ~ 10-24」查,返回 4 个活动、0 条作品,以为链接没取到。
|
||||
那 4 个活动全是排期在未来的(10.26/10.27/10.28/10.29),当然还没有作品。
|
||||
"""
|
||||
|
||||
async def fake_activities(token, client):
|
||||
return [
|
||||
{
|
||||
"id": 9,
|
||||
"title": "10.26 漫展",
|
||||
"created_at": superdir._day_start(date(2026, 10, 22)) + 3600,
|
||||
"total_count": 0,
|
||||
"published_count": 0,
|
||||
}
|
||||
]
|
||||
|
||||
async def fake_videos(token, activity_id, client):
|
||||
return []
|
||||
|
||||
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
|
||||
return "token"
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
|
||||
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
|
||||
monkeypatch.setattr(superdir, "get_token", fake_token)
|
||||
|
||||
result = await superdir.preview(None, "2026-10-22", "2026-10-24")
|
||||
|
||||
assert result["videos"] == 0
|
||||
assert result["rows"] == []
|
||||
assert result["matched_activities"] == [
|
||||
{
|
||||
"id": 9,
|
||||
"title": "10.26 漫展",
|
||||
"created_at": superdir._day_start(date(2026, 10, 22)) + 3600,
|
||||
"total_count": 0,
|
||||
"published_count": 0,
|
||||
}
|
||||
]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unpublished_and_private_videos_are_skipped(self, monkeypatch):
|
||||
async def fake_activities(token, client):
|
||||
return [_activity(2, date(2026, 10, 21))]
|
||||
|
||||
async def fake_videos(token, activity_id, client):
|
||||
return [
|
||||
_video(AWEME_A),
|
||||
# 还没发布:没有 share_url
|
||||
_video(AWEME_B, share_url=""),
|
||||
# 私密:链接点不开,拉进监控每轮都会失败一次
|
||||
_video(AWEME_C, video_status=2),
|
||||
]
|
||||
|
||||
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
|
||||
return "token"
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
|
||||
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
|
||||
monkeypatch.setattr(superdir, "get_token", fake_token)
|
||||
|
||||
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
|
||||
|
||||
assert [row["aweme_id"] for row in result["rows"]] == [AWEME_A]
|
||||
assert result["skipped"] == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_same_video_under_two_activities_is_one_row(self, monkeypatch):
|
||||
"""分发活动被复制过,同一件作品会挂在两个活动下面 —— 建任务时不能重复。"""
|
||||
|
||||
async def fake_activities(token, client):
|
||||
return [
|
||||
_activity(2, date(2026, 10, 21)),
|
||||
_activity(3, date(2026, 10, 21)),
|
||||
]
|
||||
|
||||
async def fake_videos(token, activity_id, client):
|
||||
return [_video(AWEME_A)]
|
||||
|
||||
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
|
||||
return "token"
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
|
||||
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
|
||||
monkeypatch.setattr(superdir, "get_token", fake_token)
|
||||
|
||||
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
|
||||
|
||||
assert len(result["rows"]) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_one_broken_activity_does_not_sink_the_preview(self, monkeypatch):
|
||||
async def fake_activities(token, client):
|
||||
return [
|
||||
_activity(2, date(2026, 10, 21), "坏的"),
|
||||
_activity(3, date(2026, 10, 21), "好的"),
|
||||
]
|
||||
|
||||
async def fake_videos(token, activity_id, client):
|
||||
if activity_id == 2:
|
||||
raise superdir.SuperDirError(500, "取作品失败")
|
||||
return [_video(AWEME_A)]
|
||||
|
||||
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
|
||||
return "token"
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
|
||||
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
|
||||
monkeypatch.setattr(superdir, "get_token", fake_token)
|
||||
|
||||
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
|
||||
|
||||
assert len(result["rows"]) == 1
|
||||
assert [item["activity_id"] for item in result["failed_activities"]] == [2]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_more_than_the_limit_is_truncated_not_silently_dropped(self, monkeypatch):
|
||||
async def fake_activities(token, client):
|
||||
return [_activity(2, date(2026, 10, 21))]
|
||||
|
||||
async def fake_videos(token, activity_id, client):
|
||||
return [_video(str(7000000000000000000 + i)) for i in range(3)]
|
||||
|
||||
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
|
||||
return "token"
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
|
||||
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
|
||||
monkeypatch.setattr(superdir, "get_token", fake_token)
|
||||
monkeypatch.setattr(superdir, "MAX_TARGETS", 2)
|
||||
|
||||
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
|
||||
|
||||
assert result["truncated"] is True
|
||||
assert result["videos"] == 3
|
||||
assert len(result["rows"]) == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_without_a_token_the_message_says_where_to_put_it(
|
||||
self, session, monkeypatch
|
||||
):
|
||||
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
|
||||
return ""
|
||||
|
||||
monkeypatch.setattr(superdir, "get_token", fake_token)
|
||||
|
||||
with pytest.raises(superdir.SuperDirError) as excinfo:
|
||||
await superdir.preview(session, "2026-10-21", "2026-10-21")
|
||||
|
||||
assert "设置" in str(excinfo.value)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_backwards_range_is_rejected(self):
|
||||
with pytest.raises(ValueError):
|
||||
await superdir.preview(None, "2026-10-21", "2026-10-20")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_too_wide_range_is_rejected(self):
|
||||
with pytest.raises(ValueError):
|
||||
await superdir.preview(None, "2026-01-01", "2026-03-01")
|
||||
|
||||
|
||||
class TestPagination:
|
||||
@pytest.mark.asyncio
|
||||
async def test_pages_stop_at_total(self, monkeypatch):
|
||||
calls: list = []
|
||||
|
||||
async def fake_request(path, params, token, client):
|
||||
calls.append(params["page"])
|
||||
if params["page"] == 1:
|
||||
return {"items": [{"id": 1}, {"id": 2}], "total": 3}
|
||||
return {"items": [{"id": 3}], "total": 3}
|
||||
|
||||
monkeypatch.setattr(superdir, "_request", fake_request)
|
||||
|
||||
items = await superdir._paginate(
|
||||
"/x", {}, "token", None, page_size=2, max_pages=10
|
||||
)
|
||||
|
||||
assert [item["id"] for item in items] == [1, 2, 3]
|
||||
assert calls == [1, 2]
|
||||
|
||||
|
||||
class TestActivityPaging:
|
||||
@pytest.mark.asyncio
|
||||
async def test_every_activity_page_is_fetched(self, monkeypatch):
|
||||
"""活动列表没有日期过滤,每次查询都要把整个历史翻完 —— 一页都不能少。"""
|
||||
calls: list = []
|
||||
|
||||
async def fake_request(path, params, token, client):
|
||||
calls.append(params["page"])
|
||||
pages = {
|
||||
1: [{"id": 1}, {"id": 2}],
|
||||
2: [{"id": 3}, {"id": 4}],
|
||||
3: [{"id": 5}],
|
||||
}
|
||||
return {"items": pages[params["page"]], "total": 5}
|
||||
|
||||
monkeypatch.setattr(superdir, "_request", fake_request)
|
||||
monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2)
|
||||
|
||||
items = await superdir._fetch_activities("token", None)
|
||||
|
||||
assert sorted(calls) == [1, 2, 3]
|
||||
assert [item["id"] for item in items] == [1, 2, 3, 4, 5]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_failed_page_fails_the_whole_list_not_a_partial_one(self, monkeypatch):
|
||||
"""少一页 = 少一批活动,看上去却像「这段时间就这些」—— 必须报错。"""
|
||||
|
||||
async def fake_request(path, params, token, client):
|
||||
if params["page"] == 2:
|
||||
raise superdir.SuperDirError(500, "这一页没取到")
|
||||
return {"items": [{"id": 1}, {"id": 2}], "total": 5}
|
||||
|
||||
monkeypatch.setattr(superdir, "_request", fake_request)
|
||||
monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2)
|
||||
|
||||
with pytest.raises(superdir.SuperDirError):
|
||||
await superdir._fetch_activities("token", None)
|
||||
|
||||
|
||||
class TestRetryBackoff:
|
||||
def test_a_wrong_password_stops_the_auto_retry_loop(self):
|
||||
"""密码错一次就退到「等人来修」——账号有尝试次数限制,自动重试会把号锁掉。"""
|
||||
error = superdir._error({"code": 1002, "message": "登录密码错误"})
|
||||
|
||||
assert superdir.retry_delay_ms(error) == superdir.CREDENTIAL_RETRY_DISABLED_MS
|
||||
|
||||
def test_an_ordinary_failure_retries_soon(self):
|
||||
error = superdir.SuperDirError(500, "服务端错误")
|
||||
|
||||
assert superdir.retry_delay_ms(error) == superdir.SYNC_FAILURE_RETRY_MS
|
||||
|
||||
def test_a_missing_token_is_not_a_credential_error(self):
|
||||
"""没配凭据不会去登录,所以不算「密码错」,按普通间隔重试即可。"""
|
||||
error = superdir.SuperDirError("", "没有配置账号密码")
|
||||
|
||||
assert superdir.retry_delay_ms(error) == superdir.SYNC_FAILURE_RETRY_MS
|
||||
|
||||
|
||||
class TestErrorHints:
|
||||
def test_a_relogin_error_explains_itself(self):
|
||||
error = superdir._error({"code": 4017, "message": "账号已在别处登录"})
|
||||
|
||||
assert "4017" in str(error)
|
||||
assert "自动用账号密码续期" in str(error)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def session(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
|
||||
await monitor_db.init_db()
|
||||
async with monitor_db.get_session() as db_session:
|
||||
yield db_session
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
class TestCreateTask:
|
||||
@pytest.mark.asyncio
|
||||
async def test_targets_are_bare_aweme_ids_not_share_urls(self, session):
|
||||
"""``share_url`` 是双斜杠形态,``prepare_target`` 认不出来。
|
||||
|
||||
原样存进去的话,采集时会把一整条链接当作品 id 去请求,每轮都抓不到东西 ——
|
||||
而且不会报错,只会安静地什么也没有。
|
||||
"""
|
||||
task, count = await superdir.create_task(
|
||||
session,
|
||||
[
|
||||
f"https://www.douyin.com/video//{AWEME_A}",
|
||||
f"https://www.douyin.com/video//{AWEME_A}",
|
||||
f"https://www.douyin.com/video/{AWEME_B}",
|
||||
],
|
||||
"测试导入",
|
||||
)
|
||||
|
||||
targets = list(
|
||||
await session.scalars(
|
||||
select(MonitorTarget).where(MonitorTarget.task_id == task.id)
|
||||
)
|
||||
)
|
||||
assert count == 2
|
||||
assert task.mode == MODE_NOTE
|
||||
assert sorted(target.external_id for target in targets) == sorted(
|
||||
[AWEME_A, AWEME_B]
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_comments_are_off_by_default(self, session):
|
||||
"""批量导入动辄上百条,评论默认抓的话请求量直接翻倍。"""
|
||||
task, _ = await superdir.create_task(session, [AWEME_A], "")
|
||||
|
||||
assert task.enable_comments is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_name_is_generated_when_blank(self, session):
|
||||
task, _ = await superdir.create_task(session, [AWEME_A], " ")
|
||||
|
||||
assert task.name.startswith("超级编导导入")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_links_without_an_aweme_id_are_rejected(self, session):
|
||||
with pytest.raises(ValueError):
|
||||
await superdir.create_task(session, ["https://example.com/nothing"], "")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_append_adds_only_the_new_links(self, session):
|
||||
"""「一个任务一直更新」:每天补一批,已有的不重复、也不丢掉。"""
|
||||
task, _ = await superdir.create_task(session, [AWEME_A], "同一批")
|
||||
|
||||
task, added, total = await superdir.append_task(
|
||||
session, task.id, [AWEME_A, AWEME_B, f"https://www.douyin.com/video//{AWEME_B}"]
|
||||
)
|
||||
|
||||
assert (added, total) == (1, 2)
|
||||
targets = list(
|
||||
await session.scalars(
|
||||
select(MonitorTarget).where(MonitorTarget.task_id == task.id)
|
||||
)
|
||||
)
|
||||
assert sorted(target.external_id for target in targets) == sorted(
|
||||
[AWEME_A, AWEME_B]
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_appending_nothing_new_is_a_noop(self, session):
|
||||
task, _ = await superdir.create_task(session, [AWEME_A], "")
|
||||
|
||||
_task, added, total = await superdir.append_task(session, task.id, [AWEME_A])
|
||||
|
||||
assert (added, total) == (0, 1)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_append_refuses_a_creator_task(self, session):
|
||||
"""博主模式的目标是主页,往里面塞作品 id 只会让那个目标永远抓不到东西。"""
|
||||
task = await superdir.service.create_task(
|
||||
session,
|
||||
{
|
||||
"name": "博主任务",
|
||||
"platform": "dy",
|
||||
"mode": "creator",
|
||||
"targets": ["MS4wLjABAAAAsomebody"],
|
||||
},
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
await superdir.append_task(session, task.id, [AWEME_A])
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_append_to_a_missing_task_is_rejected(self, session):
|
||||
with pytest.raises(ValueError):
|
||||
await superdir.append_task(session, 99999, [AWEME_A])
|
||||
|
||||
|
||||
class TestTokenRenewal:
|
||||
"""Token 过期(4017/5006)时用设置里的账号密码自动续期,并重试整段。"""
|
||||
|
||||
async def _set_token(
|
||||
self,
|
||||
session,
|
||||
value: str = "old-token",
|
||||
username: str = "15655035256",
|
||||
password: str = "pw",
|
||||
):
|
||||
await superdir.app_settings.update(
|
||||
session,
|
||||
{
|
||||
"platform.dy.superdir_token": value,
|
||||
"platform.dy.superdir_username": username,
|
||||
"platform.dy.superdir_password": password,
|
||||
},
|
||||
"dy",
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_expired_token_is_renewed_and_the_operation_retried(
|
||||
self, session, monkeypatch
|
||||
):
|
||||
await self._set_token(session)
|
||||
seen = []
|
||||
|
||||
async def fake_login(username, password):
|
||||
seen.append((username, password))
|
||||
return {"token": "new-token"}
|
||||
|
||||
monkeypatch.setattr(superdir, "_login", fake_login)
|
||||
|
||||
calls = []
|
||||
|
||||
async def operation(token):
|
||||
calls.append(token)
|
||||
if token == "old-token":
|
||||
raise superdir.SuperDirError(4017, "登录已过期")
|
||||
return "ok"
|
||||
|
||||
result = await superdir._run_with_token(session, "dy", operation)
|
||||
|
||||
assert result == "ok"
|
||||
assert calls == ["old-token", "new-token"]
|
||||
assert seen == [("15655035256", "pw")]
|
||||
# 新 token 写回设置,后面的查询就不会再撞一次墙。
|
||||
assert await superdir.get_token(session) == "new-token"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_non_auth_error_is_not_retried(self, session, monkeypatch):
|
||||
await self._set_token(session)
|
||||
|
||||
async def must_not_login(*args, **kwargs):
|
||||
raise AssertionError("非登录类错误不该去登录")
|
||||
|
||||
monkeypatch.setattr(superdir, "_login", must_not_login)
|
||||
|
||||
calls = []
|
||||
|
||||
async def operation(token):
|
||||
calls.append(token)
|
||||
raise superdir.SuperDirError(500, "服务端错误")
|
||||
|
||||
with pytest.raises(superdir.SuperDirError):
|
||||
await superdir._run_with_token(session, "dy", operation)
|
||||
|
||||
assert calls == ["old-token"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_without_credentials_the_message_says_where_to_configure(
|
||||
self, session
|
||||
):
|
||||
await self._set_token(session, username="", password="")
|
||||
|
||||
async def operation(token):
|
||||
raise superdir.SuperDirError(4017, "登录已过期")
|
||||
|
||||
with pytest.raises(superdir.SuperDirError) as excinfo:
|
||||
await superdir._run_with_token(session, "dy", operation)
|
||||
|
||||
assert "设置" in str(excinfo.value)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_wrong_password_surfaces_1002(self, session, monkeypatch):
|
||||
"""登录失败不能吞成「token 失效」,要把平台的原话(含剩余次数)报出来。"""
|
||||
await self._set_token(session)
|
||||
|
||||
async def fake_login(*args, **kwargs):
|
||||
raise superdir._error(
|
||||
{"code": 1002, "message": "登录密码错误,今日剩余尝试次数 4 次"}
|
||||
)
|
||||
|
||||
monkeypatch.setattr(superdir, "_login", fake_login)
|
||||
|
||||
async def operation(token):
|
||||
raise superdir.SuperDirError(4017, "登录已过期")
|
||||
|
||||
with pytest.raises(superdir.SuperDirError) as excinfo:
|
||||
await superdir._run_with_token(session, "dy", operation)
|
||||
|
||||
assert "1002" in str(excinfo.value)
|
||||
assert "密码" in str(excinfo.value)
|
||||
|
||||
|
||||
class TestAutoAppend:
|
||||
"""每隔 N 分钟自动把新发布的作品补进同一个任务。"""
|
||||
|
||||
async def _task(self, session):
|
||||
task, _ = await superdir.create_task(session, [AWEME_A], "自动追加")
|
||||
return task
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _token(self, monkeypatch):
|
||||
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
|
||||
return "token"
|
||||
|
||||
monkeypatch.setattr(superdir, "get_token", fake_token)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sync_appends_only_new_public_videos(self, session, monkeypatch):
|
||||
task = await self._task(session)
|
||||
task.superdir_auto_interval_minutes = 120
|
||||
|
||||
async def fake_fetch(token, client, start_ts, end_ts):
|
||||
return [
|
||||
_video(AWEME_A), # 已经在任务里
|
||||
_video(AWEME_B), # 新的
|
||||
_video(AWEME_C, video_status=2), # 私密,不收
|
||||
]
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
|
||||
|
||||
result = await superdir.sync_task(session, task)
|
||||
|
||||
assert result == {"fetched": 2, "added": 1, "total": 2}
|
||||
assert task.superdir_auto_last_added == 1
|
||||
assert task.superdir_auto_last_error == ""
|
||||
assert task.superdir_auto_last_at is not None
|
||||
assert task.superdir_auto_next_at is not None
|
||||
|
||||
targets = list(
|
||||
await session.scalars(
|
||||
select(MonitorTarget).where(MonitorTarget.task_id == task.id)
|
||||
)
|
||||
)
|
||||
assert sorted(t.external_id for t in targets) == sorted([AWEME_A, AWEME_B])
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_same_window_twice_adds_nothing_the_second_time(
|
||||
self, session, monkeypatch
|
||||
):
|
||||
task = await self._task(session)
|
||||
|
||||
async def fake_fetch(token, client, start_ts, end_ts):
|
||||
return [_video(AWEME_A), _video(AWEME_B)]
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
|
||||
|
||||
await superdir.sync_task(session, task)
|
||||
# 窗口重叠一小时是故意的(接口有索引延迟),重复的靠去重消化。
|
||||
result = await superdir.sync_task(session, task)
|
||||
|
||||
assert result["added"] == 0
|
||||
assert result["total"] == 2
|
||||
assert task.superdir_auto_last_added == 0
|
||||
assert task.superdir_auto_last_error == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nothing_new_still_advances_the_clock(self, session, monkeypatch):
|
||||
task = await self._task(session)
|
||||
|
||||
async def fake_fetch(token, client, start_ts, end_ts):
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
|
||||
result = await superdir.sync_task(session, task)
|
||||
|
||||
assert result["added"] == 0
|
||||
assert result["total"] == 1
|
||||
assert task.superdir_auto_last_error == ""
|
||||
assert task.superdir_auto_last_at is not None
|
||||
# 下一次在「这次成功」之后一个间隔,而不是更早。
|
||||
assert (
|
||||
task.superdir_auto_next_at
|
||||
== task.superdir_auto_last_at + 120 * 60_000
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_first_check_covers_all_of_today(self, session, monkeypatch):
|
||||
"""窗口起点是**今天 00:00**,不是「任务创建时刻」也不是「一个间隔之前」。
|
||||
|
||||
活动可以提前几天建好(今天把后面几天的活动都建了),视频却是之后才发 ——
|
||||
按任务/活动创建时间筛,这些晚发的作品整批都看不到。
|
||||
"""
|
||||
task = await self._task(session)
|
||||
captured = {}
|
||||
|
||||
async def fake_fetch(token, client, start_ts, end_ts):
|
||||
captured["start"] = start_ts
|
||||
captured["end"] = end_ts
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
|
||||
|
||||
today = superdir._day_start(datetime.now(superdir.CN_TZ).date())
|
||||
await superdir.sync_task(session, task)
|
||||
tomorrow = superdir._day_start(datetime.now(superdir.CN_TZ).date())
|
||||
|
||||
# 允许恰好跨过午夜:两次取日期之间可能已经换天了。
|
||||
assert captured["start"] in (today, tomorrow)
|
||||
assert captured["end"] >= captured["start"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_downtime_gap_is_still_covered(self, session, monkeypatch):
|
||||
"""进程停过几天时不能只看今天 —— 那几天的新作品会永远漏掉。"""
|
||||
task = await self._task(session)
|
||||
last = get_current_timestamp() - 3 * 86400 * 1000
|
||||
task.superdir_auto_last_at = last
|
||||
captured = {}
|
||||
|
||||
async def fake_fetch(token, client, start_ts, end_ts):
|
||||
captured["start"] = start_ts
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
|
||||
|
||||
await superdir.sync_task(session, task)
|
||||
|
||||
assert captured["start"] <= last // 1000 - superdir.SYNC_OVERLAP_SECONDS
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_failure_does_not_advance_the_watermark(self, session, monkeypatch):
|
||||
"""接口挂了的时候 last_at 必须停住,否则恢复后那段时间的作品就漏了。"""
|
||||
task = await self._task(session)
|
||||
|
||||
async def boom(token, client, start_ts, end_ts):
|
||||
raise superdir.SuperDirError(500, "接口挂了")
|
||||
|
||||
monkeypatch.setattr(superdir, "_fetch_published", boom)
|
||||
|
||||
with pytest.raises(superdir.SuperDirError):
|
||||
await superdir.sync_task(session, task)
|
||||
|
||||
assert task.superdir_auto_last_at is None
|
||||
assert task.superdir_auto_last_added is None
|
||||
|
||||
|
||||
class TestAutoAppendScheduling:
|
||||
@pytest.mark.asyncio
|
||||
async def test_enabling_schedules_the_first_check_immediately(self, session):
|
||||
task, _ = await superdir.create_task(session, [AWEME_A], "自动")
|
||||
|
||||
await superdir.service.update_task(
|
||||
session, task.id, {"superdir_auto_enabled": True}
|
||||
)
|
||||
|
||||
assert task.superdir_auto_enabled is True
|
||||
assert task.superdir_auto_next_at is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabling_clears_the_clock(self, session):
|
||||
task, _ = await superdir.create_task(session, [AWEME_A], "自动")
|
||||
await superdir.service.update_task(
|
||||
session, task.id, {"superdir_auto_enabled": True}
|
||||
)
|
||||
|
||||
await superdir.service.update_task(
|
||||
session, task.id, {"superdir_auto_enabled": False}
|
||||
)
|
||||
|
||||
assert task.superdir_auto_enabled is False
|
||||
assert task.superdir_auto_next_at is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_task_cannot_enable_it(self, session):
|
||||
task = await superdir.service.create_task(
|
||||
session,
|
||||
{
|
||||
"name": "博主任务",
|
||||
"platform": "dy",
|
||||
"mode": "creator",
|
||||
"targets": ["MS4wLjABAAAAsomebody"],
|
||||
},
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
await superdir.service.update_task(
|
||||
session, task.id, {"superdir_auto_enabled": True}
|
||||
)
|
||||
@@ -0,0 +1,183 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""自动打标签 —— 标题里出现关键词就贴上,命中几个贴几个。
|
||||
|
||||
规则长在标签自己身上(标签叫「大字报」,关键词可能是 `szgtdzb`),因为话题词和给人看的
|
||||
分类名不是一回事。
|
||||
"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from api.main import app
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor.models import MODE_CREATOR, MonitorNote, MonitorTag, MonitorTask
|
||||
from api.monitor.tagrules import split_keywords, tags_matching
|
||||
|
||||
TITLE = "苏州探店 #szgtdzb #苏州旅游 今天真热闹"
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
|
||||
await monitor_db.init_db()
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http_client:
|
||||
yield http_client
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
async def _seed_notes(titles=("第一条",)) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
task = MonitorTask(
|
||||
name="任务", platform="xhs", mode=MODE_CREATOR, enabled=True,
|
||||
interval_minutes=60, max_notes_count=20, enable_comments=False,
|
||||
max_comments_count=50, run_timeout_seconds=3600,
|
||||
notify_enabled=False, created_at=0, updated_at=0,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
for index, title in enumerate(titles):
|
||||
session.add(
|
||||
MonitorNote(
|
||||
task_id=task.id, note_id=f"note-{index}", title=title,
|
||||
note_url="", cover="", creator_hash="hash-a",
|
||||
creator_name="博主", source_kind="", published_at=1,
|
||||
first_seen_run_id=1, first_seen_at=1,
|
||||
last_seen_run_id=1, last_seen_at=1,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _make_tag(client, name, keywords="", color=""):
|
||||
response = await client.post(
|
||||
"/api/monitor/tags", json={"name": name, "color": color, "keywords": keywords}
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()["id"]
|
||||
|
||||
|
||||
async def _notes(client, platform="xhs"):
|
||||
return (await client.get("/api/monitor/notes", params={"platform": platform})).json()["notes"]
|
||||
|
||||
|
||||
def _tags_by_note(notes):
|
||||
return {
|
||||
note["note_id"]: sorted(tag["name"] for tag in note["tags"]) for note in notes
|
||||
}
|
||||
|
||||
|
||||
class TestSplitKeywords:
|
||||
def test_both_comma_styles_are_accepted(self):
|
||||
"""中文逗号是最常见的输入法产物 —— 只认英文逗号的话人会以为规则没生效。"""
|
||||
assert split_keywords("广告, 合作,推广") == ["广告", "合作", "推广"]
|
||||
|
||||
def test_blanks_and_duplicates_are_dropped(self):
|
||||
assert split_keywords("广告,, 广告 , ") == ["广告"]
|
||||
|
||||
def test_empty_stays_empty(self):
|
||||
assert split_keywords("") == []
|
||||
|
||||
|
||||
class TestTagsMatching:
|
||||
@staticmethod
|
||||
def _tag(keywords: str, tag_id: int = 1) -> MonitorTag:
|
||||
return MonitorTag(id=tag_id, name="t", color="", keywords=keywords, sort_order=0, created_at=0)
|
||||
|
||||
def test_a_keyword_matches_the_title(self):
|
||||
assert tags_matching(TITLE, [self._tag("szgtdzb")]) == [1]
|
||||
|
||||
def test_matching_ignores_case(self):
|
||||
"""代号大小写混着写的很常见,用户不该为了这个配两遍。"""
|
||||
assert tags_matching("今天 #SZGTDZB", [self._tag("szgtdzb")]) == [1]
|
||||
|
||||
def test_several_rules_can_hit_at_once(self):
|
||||
"""**这是这个功能的核心**:一条作品命中几个话题,就贴几个标签。"""
|
||||
rules = [self._tag("szgtdzb", 1), self._tag("苏州旅游", 2), self._tag("不存在的词", 3)]
|
||||
|
||||
assert tags_matching(TITLE, rules) == [1, 2]
|
||||
|
||||
def test_a_tag_without_keywords_never_matches(self):
|
||||
assert tags_matching(TITLE, [self._tag("")]) == []
|
||||
|
||||
def test_an_empty_title_matches_nothing(self):
|
||||
assert tags_matching("", [self._tag("szgtdzb")]) == []
|
||||
|
||||
|
||||
class TestRulesApplyToExistingWorks:
|
||||
@pytest.mark.asyncio
|
||||
async def test_creating_a_tag_with_keywords_tags_matching_works(self, client):
|
||||
"""配好关键词却一条都没贴上,正是这个功能最容易被当成坏掉的样子。"""
|
||||
await _seed_notes(titles=[TITLE, "无关的一条"])
|
||||
|
||||
await _make_tag(client, "大字报", keywords="szgtdzb")
|
||||
|
||||
assert _tags_by_note(await _notes(client)) == {
|
||||
"note-0": ["大字报"],
|
||||
"note-1": [],
|
||||
}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_one_work_can_get_several_tags_at_once(self, client):
|
||||
await _seed_notes(titles=[TITLE])
|
||||
|
||||
await _make_tag(client, "大字报", keywords="szgtdzb")
|
||||
await _make_tag(client, "旅游号", keywords="苏州旅游")
|
||||
|
||||
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报", "旅游号"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_editing_keywords_retags_existing_works(self, client):
|
||||
await _seed_notes(titles=[TITLE])
|
||||
tag_id = await _make_tag(client, "大字报", keywords="别的词")
|
||||
assert _tags_by_note(await _notes(client))["note-0"] == []
|
||||
|
||||
response = await client.put(
|
||||
f"/api/monitor/tags/{tag_id}",
|
||||
json={"name": "大字报", "keywords": "szgtdzb"},
|
||||
)
|
||||
|
||||
assert response.json()["tagged"] == 1
|
||||
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_editing_one_rule_does_not_rerun_the_others(self, client):
|
||||
"""**只贴不摘的一种具体后果**:改 A 的关键词,不该把用户从 B 上摘掉的标签贴回来。
|
||||
|
||||
两条规则都命中这条作品 → 两条都自动贴上 → 用户手动全摘掉 → 只改 A 的关键词。
|
||||
结果应该只有 A 回来,B 保持被摘掉的状态。
|
||||
"""
|
||||
await _seed_notes(titles=[TITLE])
|
||||
a = await _make_tag(client, "大字报", keywords="szgtdzb")
|
||||
await _make_tag(client, "旅游号", keywords="苏州旅游")
|
||||
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报", "旅游号"]
|
||||
|
||||
await client.put(
|
||||
"/api/monitor/notes/note-0/tags",
|
||||
params={"platform": "xhs"},
|
||||
json={"tag_ids": []},
|
||||
)
|
||||
assert _tags_by_note(await _notes(client))["note-0"] == []
|
||||
|
||||
await client.put(f"/api/monitor/tags/{a}", json={"name": "大字报", "keywords": "szgtdzb"})
|
||||
|
||||
# 只有 A 回来了 —— B 没被顺手重跑,「旅游号」不该出现。
|
||||
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turning_keywords_off_does_not_remove_existing_tags(self, client):
|
||||
"""**只贴不摘** —— 关掉规则不等于把已经贴上的撕下来。"""
|
||||
await _seed_notes(titles=[TITLE])
|
||||
tag_id = await _make_tag(client, "大字报", keywords="szgtdzb")
|
||||
|
||||
await client.put(f"/api/monitor/tags/{tag_id}", json={"name": "大字报", "keywords": ""})
|
||||
|
||||
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keywords_come_back_with_the_tag_list(self, client):
|
||||
await _make_tag(client, "大字报", keywords="szgtdzb, 探店")
|
||||
|
||||
tags = (await client.get("/api/monitor/tags")).json()["tags"]
|
||||
|
||||
assert tags[0]["keywords"] == "szgtdzb,探店"
|
||||
@@ -0,0 +1,237 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""作品标签 —— 词表在设置里维护,作品上贴。
|
||||
|
||||
和「作品备注」是两件事,刻意并存:备注是一句话说明(自由文字),标签是从**一份固定
|
||||
词表**里选的分类。分类得是一套封闭的词,否则「重点 / 重要 / 优先」会各写各的,筛选
|
||||
就没法用了。
|
||||
"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from api.main import app
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor.models import MODE_CREATOR, MonitorNote, MonitorTask
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
|
||||
await monitor_db.init_db()
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http_client:
|
||||
yield http_client
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
async def _seed(platform: str = "xhs", task_name: str = "任务", note_ids=("note-a",)) -> int:
|
||||
async with monitor_db.get_session() as session:
|
||||
task = MonitorTask(
|
||||
name=task_name, platform=platform, mode=MODE_CREATOR, enabled=True,
|
||||
interval_minutes=60, max_notes_count=20, enable_comments=False,
|
||||
max_comments_count=50, run_timeout_seconds=3600,
|
||||
notify_enabled=False, created_at=0, updated_at=0,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
for note_id in note_ids:
|
||||
session.add(
|
||||
MonitorNote(
|
||||
task_id=task.id, note_id=note_id, title=f"作品{note_id}",
|
||||
note_url="", cover="", creator_hash="hash-a",
|
||||
creator_name="博主", source_kind="", published_at=1,
|
||||
first_seen_run_id=1, first_seen_at=1,
|
||||
last_seen_run_id=1, last_seen_at=1,
|
||||
)
|
||||
)
|
||||
return task.id
|
||||
|
||||
|
||||
async def _make_tag(client, name: str, color: str = "") -> int:
|
||||
response = await client.post("/api/monitor/tags", json={"name": name, "color": color})
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()["id"]
|
||||
|
||||
|
||||
async def _tags(client):
|
||||
return (await client.get("/api/monitor/tags")).json()["tags"]
|
||||
|
||||
|
||||
async def _notes(client, **params):
|
||||
return (await client.get("/api/monitor/notes", params=params)).json()["notes"]
|
||||
|
||||
|
||||
async def _attach(client, note_id: str, tag_ids, platform: str = "xhs"):
|
||||
return await client.put(
|
||||
f"/api/monitor/notes/{note_id}/tags",
|
||||
params={"platform": platform},
|
||||
json={"tag_ids": tag_ids},
|
||||
)
|
||||
|
||||
|
||||
class TestTagVocabulary:
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_new_tag_shows_up_in_the_list(self, client):
|
||||
await _make_tag(client, "重点", "pink")
|
||||
|
||||
tags = await _tags(client)
|
||||
|
||||
assert [(tag["name"], tag["color"]) for tag in tags] == [("重点", "pink")]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_duplicate_names_are_rejected(self, client):
|
||||
"""两个「重点」在筛选列表里是灾难 —— 选哪个都像对的。"""
|
||||
await _make_tag(client, "重点")
|
||||
|
||||
response = await client.post("/api/monitor/tags", json={"name": "重点"})
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "已经存在" in response.json()["detail"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_unknown_color_falls_back_instead_of_breaking(self, client):
|
||||
await _make_tag(client, "重点", color="chartreuse")
|
||||
|
||||
assert (await _tags(client))[0]["color"] == "cyan"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_renaming_works(self, client):
|
||||
tag_id = await _make_tag(client, "重点")
|
||||
|
||||
await client.put(f"/api/monitor/tags/{tag_id}", json={"name": "非常重点"})
|
||||
|
||||
assert (await _tags(client))[0]["name"] == "非常重点"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_renaming_onto_an_existing_name_is_rejected(self, client):
|
||||
await _make_tag(client, "重点")
|
||||
tag_id = await _make_tag(client, "次要")
|
||||
|
||||
response = await client.put(
|
||||
f"/api/monitor/tags/{tag_id}", json={"name": "重点"}
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_count_says_how_many_works_wear_it(self, client):
|
||||
"""删之前要能看清代价:用在 47 条作品上和 0 条,是两个决定。"""
|
||||
await _seed(note_ids=("note-a", "note-b"))
|
||||
tag_id = await _make_tag(client, "重点")
|
||||
|
||||
await _attach(client, "note-a", [tag_id])
|
||||
await _attach(client, "note-b", [tag_id])
|
||||
|
||||
assert (await _tags(client))[0]["note_count"] == 2
|
||||
|
||||
|
||||
class TestTaggingWorks:
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_work_can_wear_several_tags(self, client):
|
||||
"""**多对多是这个功能的重点**:一条作品可以既是「重点」又是「竞品」。只能贴一个
|
||||
的话,人就会跑去备注里写自由文字,那这份封闭词表就白建了。"""
|
||||
await _seed()
|
||||
first = await _make_tag(client, "重点")
|
||||
second = await _make_tag(client, "竞品")
|
||||
|
||||
await _attach(client, "note-a", [first, second])
|
||||
|
||||
names = [tag["name"] for tag in (await _notes(client))[0]["tags"]]
|
||||
assert names == ["重点", "竞品"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_attaching_replaces_the_whole_set(self, client):
|
||||
await _seed()
|
||||
first = await _make_tag(client, "重点")
|
||||
second = await _make_tag(client, "竞品")
|
||||
await _attach(client, "note-a", [first, second])
|
||||
|
||||
await _attach(client, "note-a", [second])
|
||||
|
||||
assert [t["name"] for t in (await _notes(client))[0]["tags"]] == ["竞品"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_empty_list_clears_them(self, client):
|
||||
await _seed()
|
||||
tag_id = await _make_tag(client, "重点")
|
||||
await _attach(client, "note-a", [tag_id])
|
||||
|
||||
await _attach(client, "note-a", [])
|
||||
|
||||
assert (await _notes(client))[0]["tags"] == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_tag_ids_are_ignored_not_stored(self, client):
|
||||
"""前端传了脏 id(比如标签刚被删掉)时,别在关联表里留下孤儿。"""
|
||||
await _seed()
|
||||
tag_id = await _make_tag(client, "重点")
|
||||
|
||||
await _attach(client, "note-a", [tag_id, 99999])
|
||||
|
||||
assert [t["id"] for t in (await _notes(client))[0]["tags"]] == [tag_id]
|
||||
assert (await _tags(client))[0]["note_count"] == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_works_start_without_tags(self, client):
|
||||
await _seed()
|
||||
|
||||
assert (await _notes(client))[0]["tags"] == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tags_do_not_leak_to_another_platform(self, client):
|
||||
"""作品的 id 分平台编号体系 —— 抖音的 123 和小红书的 123 是两条作品。"""
|
||||
await _seed(platform="xhs")
|
||||
await _seed(platform="dy")
|
||||
tag_id = await _make_tag(client, "重点")
|
||||
|
||||
await _attach(client, "note-a", [tag_id], platform="xhs")
|
||||
|
||||
assert (await _notes(client, platform="xhs"))[0]["tags"] != []
|
||||
assert (await _notes(client, platform="dy"))[0]["tags"] == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deleting_a_tag_unsticks_it_everywhere(self, client):
|
||||
await _seed(note_ids=("note-a", "note-b"))
|
||||
tag_id = await _make_tag(client, "重点")
|
||||
await _attach(client, "note-a", [tag_id])
|
||||
await _attach(client, "note-b", [tag_id])
|
||||
|
||||
response = await client.delete(f"/api/monitor/tags/{tag_id}")
|
||||
|
||||
assert response.json()["removed"] == 2
|
||||
assert (await _tags(client)) == []
|
||||
for note in await _notes(client):
|
||||
assert note["tags"] == []
|
||||
|
||||
|
||||
class TestFilteringByTag:
|
||||
@pytest.mark.asyncio
|
||||
async def test_only_works_wearing_the_tag_come_back(self, client):
|
||||
await _seed(note_ids=("note-a", "note-b"))
|
||||
tag_id = await _make_tag(client, "重点")
|
||||
await _attach(client, "note-a", [tag_id])
|
||||
|
||||
notes = await _notes(client, tag_id=tag_id)
|
||||
|
||||
assert [note["note_id"] for note in notes] == ["note-a"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_several_tags_means_any_of_them(self, client):
|
||||
"""多选是「或」不是「且」—— 想同时满足两个标签的做法是再点一个标签,而不是
|
||||
指望筛选去求交集。"""
|
||||
await _seed(note_ids=("note-a", "note-b", "note-c"))
|
||||
first = await _make_tag(client, "重点")
|
||||
second = await _make_tag(client, "竞品")
|
||||
await _attach(client, "note-a", [first])
|
||||
await _attach(client, "note-b", [second])
|
||||
|
||||
notes = await _notes(client, tag_id=[first, second])
|
||||
|
||||
assert sorted(note["note_id"] for note in notes) == ["note-a", "note-b"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_filter_returns_everything(self, client):
|
||||
await _seed(note_ids=("note-a", "note-b"))
|
||||
|
||||
assert len(await _notes(client)) == 2
|
||||
@@ -0,0 +1,210 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""视频链接 → 博主主页:链接抠取、id 解析、批量解析的容错。"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api.monitor import douyin_api, service, video_link
|
||||
|
||||
SEC_UID = "MS4wLjABAAAAcmv4-Oaxe7FN4bdQECz1knSBzKb50uhnykbLIArdkk7ennhVy6Gpwp11XkVIDPgY"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_gap(monkeypatch):
|
||||
"""测试里不需要真的等那 0.4 秒节流。"""
|
||||
monkeypatch.setattr(video_link, "REQUEST_GAP_SECONDS", 0)
|
||||
|
||||
|
||||
def test_extract_candidates_pulls_links_out_of_share_text():
|
||||
text = """7.42 复制打开抖音,看看【锋哥的作品】 https://v.douyin.com/iAbCdEf/ 复制此链接
|
||||
https://www.douyin.com/video/7353137957861084427
|
||||
7353137957861084427
|
||||
|
||||
这一行是说明文字,应该被忽略
|
||||
"""
|
||||
assert video_link.extract_candidates(text) == [
|
||||
"https://v.douyin.com/iAbCdEf/",
|
||||
"https://www.douyin.com/video/7353137957861084427",
|
||||
"7353137957861084427",
|
||||
]
|
||||
|
||||
|
||||
def test_a_line_with_two_links_yields_both():
|
||||
text = "https://v.douyin.com/aaa/ https://v.douyin.com/bbb/"
|
||||
|
||||
assert len(video_link.extract_candidates(text)) == 2
|
||||
|
||||
|
||||
def test_aweme_id_from_url_handles_the_known_shapes():
|
||||
assert video_link.aweme_id_from_url("https://www.douyin.com/video/7353137957861084427") == (
|
||||
"7353137957861084427"
|
||||
)
|
||||
# 短链展开后落到的分享页
|
||||
assert video_link.aweme_id_from_url(
|
||||
"https://www.iesdouyin.com/share/video/7353137957861084427/?region=CN"
|
||||
) == "7353137957861084427"
|
||||
# 直播/精选页那种把作品挂在 modal 参数上的
|
||||
assert video_link.aweme_id_from_url(
|
||||
"https://www.douyin.com/discover?modal_id=7353137957861084427"
|
||||
) == "7353137957861084427"
|
||||
assert video_link.aweme_id_from_url("7353137957861084427") == "7353137957861084427"
|
||||
# 超级编导导出的链接是**双斜杠**形态。浏览器里点得开,所以不能按「坏链接」处理。
|
||||
assert video_link.aweme_id_from_url(
|
||||
"https://www.douyin.com/video//7353137957861084427"
|
||||
) == "7353137957861084427"
|
||||
|
||||
|
||||
def test_aweme_id_from_url_rejects_a_creator_link():
|
||||
"""主页链接不是作品链接 —— 认不出来就该空着,而不是瞎猜一个 id。"""
|
||||
assert video_link.aweme_id_from_url(f"https://www.douyin.com/user/{SEC_UID}") == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_builds_a_profile_url(monkeypatch):
|
||||
async def fake_detail(aweme_id, **_):
|
||||
return {"aweme_id": aweme_id, "nickname": "锋哥苏州寻宝藏小店", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve("https://www.douyin.com/video/7353137957861084427")
|
||||
|
||||
assert result["truncated"] is False
|
||||
item = result["results"][0]
|
||||
assert item["ok"] is True
|
||||
assert item["nickname"] == "锋哥苏州寻宝藏小店"
|
||||
assert item["profile_url"] == f"https://www.douyin.com/user/{SEC_UID}"
|
||||
assert item["error"] == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_short_links_are_expanded_before_parsing(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def fake_expand(value, platform):
|
||||
calls.append((value, platform))
|
||||
return "https://www.iesdouyin.com/share/video/7353137957861084427/?region=CN"
|
||||
|
||||
async def fake_detail(aweme_id, **_):
|
||||
return {"aweme_id": aweme_id, "nickname": "锋哥", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(service, "expand_short_link", fake_expand)
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve("https://v.douyin.com/iAbCdEf/")
|
||||
|
||||
assert calls == [("https://v.douyin.com/iAbCdEf/", "dy")]
|
||||
assert result["results"][0]["aweme_id"] == "7353137957861084427"
|
||||
assert result["results"][0]["ok"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_same_video_twice_only_hits_the_api_once(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def fake_detail(aweme_id, **_):
|
||||
calls.append(aweme_id)
|
||||
return {"aweme_id": aweme_id, "nickname": "锋哥", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve(
|
||||
"https://www.douyin.com/video/7353137957861084427\n"
|
||||
"https://www.douyin.com/video/7353137957861084427"
|
||||
)
|
||||
|
||||
assert calls == ["7353137957861084427"]
|
||||
# 两条输入各自一行结果,但只有一次请求。
|
||||
assert [item["profile_url"] for item in result["results"]] == [
|
||||
f"https://www.douyin.com/user/{SEC_UID}",
|
||||
f"https://www.douyin.com/user/{SEC_UID}",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_one_failure_does_not_sink_the_batch(monkeypatch):
|
||||
async def fake_detail(aweme_id, **_):
|
||||
if aweme_id == "1111111111111111111":
|
||||
raise douyin_api.DouyinApiError("接口拒绝了请求")
|
||||
return {"aweme_id": aweme_id, "nickname": "好号", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve(
|
||||
"https://www.douyin.com/video/1111111111111111111\n"
|
||||
"https://www.douyin.com/video/7353137957861084427"
|
||||
)
|
||||
|
||||
first, second = result["results"]
|
||||
assert first["ok"] is False and "接口拒绝了" in first["error"]
|
||||
assert second["ok"] is True and second["profile_url"].endswith(SEC_UID)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_missing_sec_uid_is_reported_not_faked(monkeypatch):
|
||||
async def fake_detail(aweme_id, **_):
|
||||
return {"aweme_id": aweme_id, "nickname": "空号", "creator_id": ""}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve("https://www.douyin.com/video/7353137957861084427")
|
||||
|
||||
item = result["results"][0]
|
||||
assert item["ok"] is False
|
||||
assert item["profile_url"] == ""
|
||||
assert "sec_uid" in item["error"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_transport_hiccup_is_retried_once(monkeypatch):
|
||||
"""容器刚起来时第一发可能撞上 DNS 失败;重试一次就过去了,别让它红掉一行。"""
|
||||
calls = []
|
||||
|
||||
async def flaky_detail(aweme_id, **_):
|
||||
calls.append(aweme_id)
|
||||
if len(calls) == 1:
|
||||
raise httpx.ConnectError("[Errno -3] Temporary failure in name resolution")
|
||||
return {"aweme_id": aweme_id, "nickname": "锋哥", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", flaky_detail)
|
||||
monkeypatch.setattr(video_link, "_DETAIL_RETRY_SLEEP_SECONDS", 0)
|
||||
|
||||
result = await video_link.resolve("https://www.douyin.com/video/7353137957861084427")
|
||||
|
||||
assert len(calls) == 2
|
||||
assert result["results"][0]["ok"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_empty_body_is_not_retried(monkeypatch):
|
||||
"""空 body 是风控信号 —— 重试只会让它更确定。"""
|
||||
calls = []
|
||||
|
||||
async def blocked_detail(aweme_id, **_):
|
||||
calls.append(aweme_id)
|
||||
raise douyin_api.DouyinApiError("接口返回了空内容")
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", blocked_detail)
|
||||
|
||||
result = await video_link.resolve("https://www.douyin.com/video/7353137957861084427")
|
||||
|
||||
assert len(calls) == 1
|
||||
assert result["results"][0]["ok"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_more_than_the_limit_is_truncated(monkeypatch):
|
||||
async def fake_detail(aweme_id, **_):
|
||||
return {"aweme_id": aweme_id, "nickname": "x", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
text = "\n".join(f"https://www.douyin.com/video/{1000000000000000000 + i}" for i in range(25))
|
||||
|
||||
result = await video_link.resolve(text)
|
||||
|
||||
assert result["truncated"] is True
|
||||
assert len(result["results"]) == video_link.MAX_LINKS
|
||||
|
||||
|
||||
def test_garbage_input_yields_nothing():
|
||||
assert video_link.extract_candidates("随便说点什么") == []
|
||||
assert video_link.extract_candidates("") == []
|
||||
@@ -389,3 +389,30 @@ class TestLegacyKeyMigration:
|
||||
assert "xhs_cookie" not in rows
|
||||
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
class TestCreatorUrl:
|
||||
"""博主主页链接。
|
||||
|
||||
注意它要的是**平台上的主页 id**(抖音是 sec_uid),不是 ``creator_hash`` —— 哈希是
|
||||
单向的,拼不出地址。所以这条链路上少任何一环(采集没存 id、平台上没有这个博主、
|
||||
平台不认识)都必须返回空串,让界面干脆不画按钮,而不是给一个点开 404 的链接。
|
||||
"""
|
||||
|
||||
def test_douyin(self):
|
||||
assert (
|
||||
adapters.creator_url("dy", "MS4wLjABAAAAabc-123")
|
||||
== "https://www.douyin.com/user/MS4wLjABAAAAabc-123"
|
||||
)
|
||||
|
||||
def test_xiaohongshu(self):
|
||||
assert (
|
||||
adapters.creator_url("xhs", "5f8a1b2c3d4e5f6a7b8c9d0e")
|
||||
== "https://www.xiaohongshu.com/user/profile/5f8a1b2c3d4e5f6a7b8c9d0e"
|
||||
)
|
||||
|
||||
def test_no_id_is_empty_not_a_broken_link(self):
|
||||
assert adapters.creator_url("dy", "") == ""
|
||||
|
||||
def test_an_unknown_platform_is_empty_not_a_crash(self):
|
||||
assert adapters.creator_url("nope", "abc") == ""
|
||||
|
||||
@@ -28,6 +28,7 @@ from api.main import app
|
||||
from api.monitor import app_settings, db as monitor_db
|
||||
from api.monitor import scheduler as scheduler_module
|
||||
from api.monitor.scheduler import MonitorScheduler
|
||||
from api.monitor.models import MonitorTask
|
||||
from api.monitor.settings import get_setting
|
||||
|
||||
SECRET_VALUE = "web_session=SUPERSECRET; a1=abc"
|
||||
@@ -75,6 +76,43 @@ class TestReadSettings:
|
||||
|
||||
|
||||
class TestUpdateSettings:
|
||||
@pytest.mark.asyncio
|
||||
async def test_saving_superdir_credentials_retries_auto_append_now(self, client):
|
||||
"""填好账号密码之后不该再等一个间隔才生效 —— 下一 tick 就试着续期。"""
|
||||
async with monitor_db.get_session() as session:
|
||||
task = MonitorTask(
|
||||
name="自动追加",
|
||||
platform="dy",
|
||||
mode="note",
|
||||
enabled=True,
|
||||
interval_minutes=360,
|
||||
max_notes_count=20,
|
||||
enable_comments=False,
|
||||
max_comments_count=50,
|
||||
run_timeout_seconds=3600,
|
||||
superdir_auto_enabled=True,
|
||||
superdir_auto_interval_minutes=120,
|
||||
superdir_auto_next_at=9_999_999_999_999,
|
||||
superdir_auto_last_error="token 失效",
|
||||
created_at=0,
|
||||
updated_at=0,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
task_id = task.id
|
||||
|
||||
await client.put(
|
||||
"/api/settings",
|
||||
params={"platform": "dy"},
|
||||
json={"platform.dy.superdir_username": "15655035256"},
|
||||
)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
task = await session.get(MonitorTask, task_id)
|
||||
|
||||
assert task.superdir_auto_next_at < 9_999_999_999_999
|
||||
assert task.superdir_auto_last_error == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_partial_update_leaves_other_keys_alone(self, client):
|
||||
await client.put(
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""前端产物的缓存头。
|
||||
|
||||
**`index.html` 必须 no-cache。** 它没有内容哈希,一旦被浏览器启发式缓存住,打开的还是
|
||||
上一次那份 index.html、指向上一次那个 js 包 —— 现象就是「代码明明发了,界面上却看不见
|
||||
新功能」,只能靠 Ctrl+F5 自救。这个坑真的踩过:加完功能在设置页里找不到入口,查了半天
|
||||
源码,最后发现是浏览器拿着旧包。
|
||||
|
||||
带哈希的 `/assets/` 反过来,可以放心让它永久缓存。
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from api.main import app
|
||||
|
||||
# 产物是 gitignore 的:没构建过就没有静态文件可测(部署机器上一定有)。
|
||||
INDEX = pathlib.Path("api/webui/index.html")
|
||||
ASSETS = pathlib.Path("api/webui/assets")
|
||||
|
||||
needs_build = pytest.mark.skipif(
|
||||
not INDEX.exists(), reason="前端产物没构建过,测不了静态文件的缓存头"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@needs_build
|
||||
def test_the_entry_page_is_never_cached(client):
|
||||
response = client.get("/")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers["cache-control"] == "no-cache"
|
||||
|
||||
|
||||
@needs_build
|
||||
def test_hashed_bundles_are_cached_forever(client):
|
||||
"""文件名带内容哈希,变了就是新 URL —— 没有理由每次回源。"""
|
||||
bundle = next(ASSETS.glob("*.js"), None)
|
||||
if bundle is None:
|
||||
pytest.skip("没有 js 产物")
|
||||
|
||||
response = client.get(f"/assets/{bundle.name}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
|
||||
|
||||
|
||||
def test_api_responses_are_left_alone(client):
|
||||
"""接口那套缓存由客户端和 React Query 管,这里不该插手。"""
|
||||
response = client.get("/api/health")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers.get("cache-control") is None
|
||||
|
||||
|
||||
def test_the_shell_pulls_nothing_from_the_internet():
|
||||
"""外壳(index.html)里不能出现任何指向外网的 link/script。
|
||||
|
||||
真踩过:`<head>` 里挂了一个 fonts.googleapis.com 的阻塞样式表,而这套东西是
|
||||
**内网部署**,那台机器连不上 Google。样式表拿不到,它后面的
|
||||
`<script type="module">` 就不执行 —— 整个 React 应用一个请求都发不出去,
|
||||
页面白白卡满一次 TCP 连接超时。实测(Playwright,把字体请求挂住 20 秒):
|
||||
|
||||
DOM 就绪 20.070s,首个接口请求出现在导航后 20055ms
|
||||
|
||||
而字体栈里 Inter / JetBrains Mono 后面本来就跟着 system-ui / Consolas,
|
||||
缺字体只是回退,不影响可用性。为装饰性字体拖住整页 20 秒,不值得。
|
||||
"""
|
||||
html = pathlib.Path("webui/index.html").read_text(encoding="utf-8")
|
||||
|
||||
external = re.findall(
|
||||
r'<(?:link|script)\b[^>]*\b(?:href|src)="(?:https?:)?//[^"]*"', html
|
||||
)
|
||||
assert external == [], f"外壳引用了外网资源,内网部署会卡在它上面:{external}"
|
||||
+9
-3
@@ -5,9 +5,15 @@
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>综合采集平台</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
|
||||
<!--
|
||||
**这里故意不放任何外部字体。** 曾经挂过一个 fonts.googleapis.com 的
|
||||
<link rel="stylesheet">,而这是个内网部署,那台机器连不上 Google ——
|
||||
<head> 里阻塞渲染的样式表拿不到,它后面的 <script type="module"> 就不执行,
|
||||
于是整个 React 应用一个请求都发不出去,页面白白卡满一次 TCP 连接超时(实测
|
||||
20.07 秒,DOM 就绪时间与字体请求耗时一毫秒不差)。字体栈里的
|
||||
Inter / JetBrains Mono 后面本来就跟了 system-ui / Consolas,字体没到位时
|
||||
回退即可 —— 为了一个装饰性的字体把整个界面拖住 20 秒,不划算。
|
||||
-->
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { memo } from 'react'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { LogEntry } from '@/types/crawler'
|
||||
|
||||
@@ -41,7 +43,18 @@ const levelIcons: Record<string, string> = {
|
||||
debug: 'DBG',
|
||||
}
|
||||
|
||||
export function TerminalLine({ log }: TerminalLineProps) {
|
||||
/**
|
||||
* 一行日志。
|
||||
*
|
||||
* **必须 memo。** 日志是「来一条就 push 一条」,每来一条 store 里的数组就是新的,
|
||||
* 于是整个列表重渲染;而这个列表最多留 500 条 —— 不做 memo 就是每来一行重渲染 500 行,
|
||||
* 每行还要跑 5 次 `cn()`(tailwind-merge 不便宜)。爬虫在跑的时候日志是成片来的,
|
||||
* 主线程直接被占满,表现就是**点什么都没反应**(点折叠最容易注意到,因为那一下还要
|
||||
* 把整份列表挂载/卸载一遍)。
|
||||
*
|
||||
* `log` 对象在数组里是稳定引用,所以 memo 之后只有新来的那一行会渲染。
|
||||
*/
|
||||
export const TerminalLine = memo(function TerminalLine({ log }: TerminalLineProps) {
|
||||
const config = levelConfig[log.level] || levelConfig.info
|
||||
|
||||
return (
|
||||
@@ -67,4 +80,4 @@ export function TerminalLine({ log }: TerminalLineProps) {
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react'
|
||||
import { Briefcase, Bug, Wifi, BarChart3, Cog, LogOut, Radar, Settings, Terminal } from 'lucide-react'
|
||||
import { Briefcase, Bug, Wifi, BarChart3, Cog, Grid3x3, LogOut, Radar, Settings, Terminal } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { SystemSettingsDialog } from '@/components/settings/SystemSettingsDialog'
|
||||
@@ -72,6 +72,19 @@ export function Sidebar({ currentView, onViewChange, onLogout }: SidebarProps) {
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* 标签矩阵是**独立页面**(/report/matrix),不是这个 SPA 的一个 view:
|
||||
它由后端直接发一份静态 HTML,不走 Vite 构建,所以这里用普通链接打开。
|
||||
新标签页是因为它会占满整屏做宽表,来回切视图反而碍事。 */}
|
||||
<a
|
||||
href="/report/matrix"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-1.5 px-2.5 py-1 rounded text-[11px] font-mono transition-all text-cyber-text-muted border border-transparent hover:text-cyber-neon-cyan hover:border-cyber-neon-cyan/40"
|
||||
>
|
||||
<Grid3x3 className="w-3 h-3" />
|
||||
标签矩阵
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
import { useState } from 'react'
|
||||
import { CheckCircle2, KeyRound, Plus, Power, Trash2 } from 'lucide-react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
useCheckIdentity,
|
||||
useCreateIdentity,
|
||||
useDeleteIdentity,
|
||||
useMonitorIdentities,
|
||||
useUpdateIdentity,
|
||||
} from '@/hooks/useMonitor'
|
||||
import { formatRelative } from '@/lib/monitorFormat'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MonitorIdentity } from '@/types/monitor'
|
||||
|
||||
/**
|
||||
* 多身份(登录态)管理。
|
||||
*
|
||||
* **这里做的是串行分片,不是并行提速。** 抖音按「账号 + IP + 指纹」联合判定,同一个
|
||||
* 出口 IP 上并发多个 cookie,比单账号高频请求更容易被判成异常 —— 平台视角是一台设备
|
||||
* 在不停换访客。所以默认一次只跑一个身份,把目标分给不同账号,降低单个账号的请求量。
|
||||
*
|
||||
* 卡片上那句提醒是刻意留在界面上的:这个功能的收益和风险都很容易被误解。
|
||||
*/
|
||||
const STATUS: Record<
|
||||
MonitorIdentity['status'],
|
||||
{ label: string; className: string }
|
||||
> = {
|
||||
ok: {
|
||||
label: '可用',
|
||||
className: 'border-cyber-neon-green/40 bg-cyber-neon-green/10 text-cyber-neon-green',
|
||||
},
|
||||
cooldown: {
|
||||
label: '冷却中',
|
||||
className:
|
||||
'border-cyber-neon-orange/40 bg-cyber-neon-orange/10 text-cyber-neon-orange',
|
||||
},
|
||||
expired: {
|
||||
label: '已失效',
|
||||
className: 'border-cyber-neon-pink/40 bg-cyber-neon-pink/10 text-cyber-neon-pink',
|
||||
},
|
||||
disabled: {
|
||||
label: '已停用',
|
||||
className: 'border-cyber-border-DEFAULT text-cyber-text-muted',
|
||||
},
|
||||
}
|
||||
|
||||
function clockText(ms: number): string {
|
||||
return new Date(ms).toLocaleTimeString('zh-CN', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})
|
||||
}
|
||||
|
||||
export function IdentityPanel() {
|
||||
const { data: identities, isLoading } = useMonitorIdentities()
|
||||
const create = useCreateIdentity()
|
||||
const update = useUpdateIdentity()
|
||||
const remove = useDeleteIdentity()
|
||||
const check = useCheckIdentity()
|
||||
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [label, setLabel] = useState('')
|
||||
const [cookie, setCookie] = useState('')
|
||||
const [userAgent, setUserAgent] = useState('')
|
||||
|
||||
const submit = () => {
|
||||
const name = label.trim()
|
||||
const value = cookie.trim()
|
||||
if (!name || !value) return
|
||||
create.mutate(
|
||||
{ label: name, cookie: value, user_agent: userAgent.trim() },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setLabel('')
|
||||
setCookie('')
|
||||
setUserAgent('')
|
||||
setAdding(false)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg glass-panel float-panel p-4 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<KeyRound className="w-4 h-4 text-cyber-neon-cyan" />
|
||||
<span className="font-mono text-xs tracking-wider text-cyber-text-primary">
|
||||
多身份(分片采集)
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-[10px] font-mono text-cyber-text-muted leading-relaxed">
|
||||
多个登录态
|
||||
<span className="text-cyber-text-secondary"> 串行分片 </span>
|
||||
:把博主打散给不同账号,降低单个账号每轮的请求量 —— 这不是并行提速。
|
||||
同一个出口 IP 上并发多个账号,比单账号高频更容易被风控,所以默认一次只跑一个身份。
|
||||
采集策略里的「多身份采集」要选 <code className="text-cyber-text-secondary">pool</code>
|
||||
才会生效。
|
||||
</p>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
{isLoading && (
|
||||
<p className="text-[11px] font-mono text-cyber-text-muted">加载中…</p>
|
||||
)}
|
||||
{identities?.length === 0 && (
|
||||
<p className="text-[11px] font-mono text-cyber-text-muted">
|
||||
还没有身份。在下面加一条:名称 + 该账号的完整 Cookie。
|
||||
</p>
|
||||
)}
|
||||
|
||||
{identities?.map((identity) => {
|
||||
const status = STATUS[identity.status]
|
||||
const cooling =
|
||||
identity.cooldown_until !== null && identity.cooldown_until > Date.now()
|
||||
return (
|
||||
<div
|
||||
key={identity.id}
|
||||
className="flex items-center gap-2 flex-wrap rounded border border-cyber-border-subtle bg-cyber-bg-tertiary/40 px-2 py-1.5"
|
||||
>
|
||||
<span className="text-[11px] font-mono text-cyber-text-primary">
|
||||
{identity.label}
|
||||
</span>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn('text-[9px] px-1.5 py-0', status.className)}
|
||||
>
|
||||
{status.label}
|
||||
</Badge>
|
||||
<span className="text-[10px] font-mono text-cyber-text-muted">
|
||||
{identity.last_ok_at
|
||||
? `最近成功 ${formatRelative(identity.last_ok_at)}`
|
||||
: '还没成功过'}
|
||||
</span>
|
||||
{cooling && identity.cooldown_until !== null && (
|
||||
<span className="text-[10px] font-mono text-cyber-neon-orange">
|
||||
冷却到 {clockText(identity.cooldown_until)}
|
||||
</span>
|
||||
)}
|
||||
{identity.last_error && (
|
||||
<span
|
||||
className="text-[10px] font-mono text-cyber-text-muted truncate max-w-[220px]"
|
||||
title={identity.last_error}
|
||||
>
|
||||
{identity.last_error}
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-1.5"
|
||||
title="用这份身份真请求一次"
|
||||
disabled={check.isPending}
|
||||
onClick={() => check.mutate(identity.id)}
|
||||
>
|
||||
<CheckCircle2 className="w-3 h-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-1.5"
|
||||
title={identity.enabled ? '停用' : '启用'}
|
||||
onClick={() =>
|
||||
update.mutate({
|
||||
id: identity.id,
|
||||
payload: { enabled: !identity.enabled },
|
||||
})
|
||||
}
|
||||
>
|
||||
<Power className="w-3 h-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-1.5 hover:text-cyber-neon-pink"
|
||||
title="删除"
|
||||
onClick={() => {
|
||||
if (window.confirm(`删除身份「${identity.label}」?`)) {
|
||||
remove.mutate(identity.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{adding ? (
|
||||
<div className="space-y-2 pt-2 mt-1 border-t border-cyber-border-subtle">
|
||||
<input
|
||||
autoFocus
|
||||
value={label}
|
||||
onChange={(event) => setLabel(event.target.value)}
|
||||
placeholder="名称,比如「小号A」"
|
||||
className="w-full rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
/>
|
||||
<textarea
|
||||
value={cookie}
|
||||
onChange={(event) => setCookie(event.target.value)}
|
||||
rows={3}
|
||||
placeholder="粘贴这个账号的完整 Cookie(必须含 sessionid)"
|
||||
className="w-full rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
/>
|
||||
<input
|
||||
value={userAgent}
|
||||
onChange={(event) => setUserAgent(event.target.value)}
|
||||
placeholder="User-Agent(可留空:留空时从 CDP 浏览器借一份)"
|
||||
className="w-full rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!label.trim() || !cookie.trim() || create.isPending}
|
||||
onClick={submit}
|
||||
>
|
||||
添加
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => setAdding(false)}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Button size="sm" variant="ghost" onClick={() => setAdding(true)}>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
添加身份
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useState } from 'react'
|
||||
import { Activity, BellRing, FileText, MessageSquare, Plus } from 'lucide-react'
|
||||
import { Activity, BellRing, Download, FileText, Link2, MessageSquare, Plus, Radar } from 'lucide-react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { useMonitorOverview, useMonitorTasks } from '@/hooks/useMonitor'
|
||||
import { monitorApi } from '@/lib/api'
|
||||
import type { MonitorTask } from '@/types/monitor'
|
||||
import { useCookieStatus, useWebhookStatus } from '@/hooks/useMonitor'
|
||||
import { useCurrentPlatform } from '@/hooks/usePlatform'
|
||||
@@ -12,10 +13,13 @@ import { UnwiredPlatformNotice } from '@/components/layout/UnwiredPlatformNotice
|
||||
import { CommentsFeed } from './CommentsFeed'
|
||||
import { EventsFeed } from './EventsFeed'
|
||||
import { NotesTable } from './NotesTable'
|
||||
import { TagFilter } from './TagFilter'
|
||||
import { RunHistory } from './RunHistory'
|
||||
import { StatTile } from './StatTile'
|
||||
import { TaskCard } from './TaskCard'
|
||||
import { SuperDirTool } from './SuperDirTool'
|
||||
import { TaskEditorDialog } from './TaskEditorDialog'
|
||||
import { VideoLinkTool } from './VideoLinkTool'
|
||||
|
||||
export function MonitorDashboard() {
|
||||
const { data: overview } = useMonitorOverview()
|
||||
@@ -25,12 +29,18 @@ export function MonitorDashboard() {
|
||||
|
||||
const cookieOk = cookieStatus?.present ?? false
|
||||
const webhookOk = webhookStatus?.configured ?? false
|
||||
const { isWired, isLoading: platformLoading } = useCurrentPlatform()
|
||||
const { platform, isWired, isLoading: platformLoading } = useCurrentPlatform()
|
||||
|
||||
const [selectedTaskId, setSelectedTaskId] = useState<number | null>(null)
|
||||
const [editorOpen, setEditorOpen] = useState(false)
|
||||
const [linkToolOpen, setLinkToolOpen] = useState(false)
|
||||
const [superDirOpen, setSuperDirOpen] = useState(false)
|
||||
const [editingTask, setEditingTask] = useState<MonitorTask | null>(null)
|
||||
const [onlyNew, setOnlyNew] = useState(false)
|
||||
// 选中的标签。空数组 = 不筛。
|
||||
// 换任务时**刻意不清**:选中了哪几个标签在筛选条上是看得见的,空列表不会没头没脑;
|
||||
// 而切个任务就把筛选悄悄清掉,反而会让人以为筛选没生效。
|
||||
const [tagIds, setTagIds] = useState<number[]>([])
|
||||
|
||||
// Fall back to the first task so the detail panes are never empty for no
|
||||
// reason; keep an explicit selection once the user makes one.
|
||||
@@ -81,10 +91,37 @@ export function MonitorDashboard() {
|
||||
<span className="font-mono text-xs tracking-wider text-cyber-text-primary">
|
||||
监控任务
|
||||
</span>
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
新建
|
||||
</Button>
|
||||
<div className="flex flex-wrap items-center justify-end gap-1">
|
||||
{/* 手上只有一条作品链接时,先把它的号找出来 —— 建任务要的是主页里的 sec_uid。
|
||||
只有抖音接得上:小红书没有对应的接口模块,那条路要走子进程爬虫。 */}
|
||||
{platform === 'dy' && (
|
||||
<>
|
||||
{/* 超级编导那边接的就是抖音分发 —— 换到小红书工作区不该看见它。 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSuperDirOpen(true)}
|
||||
title="从超级编导按创建时间导入作品链接"
|
||||
>
|
||||
<Radar className="w-3 h-3 mr-1" />
|
||||
超级编导
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setLinkToolOpen(true)}
|
||||
title="粘贴视频链接,换出博主主页"
|
||||
>
|
||||
<Link2 className="w-3 h-3 mr-1" />
|
||||
视频转主页
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
新建
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto terminal-scroll space-y-2 pr-1">
|
||||
@@ -166,8 +203,26 @@ export function MonitorDashboard() {
|
||||
>
|
||||
只看新增
|
||||
</Button>
|
||||
{/* 导出的是**这个任务**的全部作品,不是屏幕上这 200 条 —— 屏幕上那份是
|
||||
为了好看才截断的,导出跟着截断就成了「导出来的比看到的少」。
|
||||
走 window.open 而不是 blob:鉴权在 Cookie 上,浏览器自己会带上。 */}
|
||||
<TagFilter selected={tagIds} onChange={setTagIds} />
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="ml-auto"
|
||||
onClick={() =>
|
||||
window.open(
|
||||
monitorApi.getExportUrl({ kind: 'notes', taskId: selectedTask.id }),
|
||||
'_blank',
|
||||
)
|
||||
}
|
||||
>
|
||||
<Download className="w-3 h-3 mr-1" />
|
||||
导出 CSV
|
||||
</Button>
|
||||
</div>
|
||||
<NotesTable taskId={selectedTask.id} onlyNew={onlyNew} />
|
||||
<NotesTable taskId={selectedTask.id} onlyNew={onlyNew} tagIds={tagIds} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="comments" className="flex-1 overflow-auto terminal-scroll px-3 pb-3 mt-2">
|
||||
@@ -193,6 +248,12 @@ export function MonitorDashboard() {
|
||||
</div>
|
||||
|
||||
<TaskEditorDialog open={editorOpen} onOpenChange={setEditorOpen} task={editingTask} />
|
||||
{platform === 'dy' && (
|
||||
<>
|
||||
<SuperDirTool open={superDirOpen} onOpenChange={setSuperDirOpen} />
|
||||
<VideoLinkTool open={linkToolOpen} onOpenChange={setLinkToolOpen} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { memo, useRef, useState } from 'react'
|
||||
import { ExternalLink, Pencil, Tag } from 'lucide-react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { tagColorClass } from '@/lib/tagColors'
|
||||
import { formatDate, formatDateTime, formatRelative } from '@/lib/monitorFormat'
|
||||
import type { MonitorNote } from '@/types/monitor'
|
||||
|
||||
import { COLUMN_COUNT, METRIC_COLUMNS, MetricCell } from './metricColumns'
|
||||
import { NoteCover } from './NoteCover'
|
||||
import { NoteTrendChart } from './NoteTrendChart'
|
||||
|
||||
/**
|
||||
* 作品表里的一行。
|
||||
*
|
||||
* **单独抽出来 + memo,是为了不再「点一下重渲染整张表」。** 在这之前,展开状态、备注
|
||||
* 编辑状态全都挂在 `NotesTable` 上,于是点开一条作品的趋势图,131 行全部重渲染一遍
|
||||
* —— 抖音任务有一百多条,点开就卡(小红书那条只有一行,所以感觉不出来)。
|
||||
*
|
||||
* 现在:备注编辑状态是**行内自己的**,展开状态虽然还在父级(保持「同时只开一个」),
|
||||
* 但靠 memo 把其余 130 行挡掉。同一个渲染周期里 `note` 是同一个对象引用,所以默认的
|
||||
* 浅比较就够用,不需要自定义比较函数。
|
||||
*/
|
||||
interface NoteRowProps {
|
||||
note: MonitorNote
|
||||
isOpen: boolean
|
||||
/** 展开/收起这一行。父级持有展开状态,所以它得知道是哪一行。 */
|
||||
onToggle: (rowKey: string) => void
|
||||
/** 打开贴标签的对话框。 */
|
||||
onTag: (note: MonitorNote) => void
|
||||
/** 保存备注。父级持有 mutation,行只负责发命令。 */
|
||||
onSaveAlias: (noteId: string, alias: string) => void
|
||||
}
|
||||
|
||||
export const NoteRow = memo(function NoteRow({
|
||||
note,
|
||||
isOpen,
|
||||
onToggle,
|
||||
onTag,
|
||||
onSaveAlias,
|
||||
}: NoteRowProps) {
|
||||
const rowKey = `${note.task_id}:${note.note_id}`
|
||||
// 备注编辑是**行内状态**:放父级的话,每敲一个字整张表都要重渲染一遍。
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [draft, setDraft] = useState('')
|
||||
// 按 Escape 是「取消」,而失焦是「保存」—— 取消时得让紧接着那次失焦闭嘴,
|
||||
// 否则它会把你刚放弃的内容存进去。
|
||||
const cancelled = useRef(false)
|
||||
|
||||
const commit = () => {
|
||||
if (cancelled.current) {
|
||||
cancelled.current = false
|
||||
setEditing(false)
|
||||
return
|
||||
}
|
||||
setEditing(false)
|
||||
onSaveAlias(note.note_id, draft)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<tr
|
||||
onClick={() => onToggle(rowKey)}
|
||||
className="border-t border-cyber-border-subtle hover:bg-cyber-bg-elevated/50 cursor-pointer"
|
||||
>
|
||||
<td />
|
||||
<td className="py-2 px-2 max-w-[320px]">
|
||||
<div className="flex items-center gap-2">
|
||||
<NoteCover src={note.cover} size="md" />
|
||||
{/* min-w-0 so the title can actually truncate inside the flex row */}
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{note.is_new && (
|
||||
<Badge variant="success" className="text-[9px] px-1 py-0 flex-shrink-0">
|
||||
NEW
|
||||
</Badge>
|
||||
)}
|
||||
{/* 备注是**加**在标题前面的一枚标记,不是替换 ——
|
||||
标题才是这条作品本身,扫列表时两个都要看得见。 */}
|
||||
{note.note_alias && (
|
||||
<Badge variant="default" className="text-[9px] px-1 py-0 flex-shrink-0">
|
||||
{note.note_alias}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="truncate text-cyber-text-primary" title={note.title}>
|
||||
{note.title || note.note_id}
|
||||
</span>
|
||||
{/* 跳转紧跟在标题后面 —— 它属于**这条作品**,挂在整行最右边
|
||||
时就脱离了它修饰的东西,眼睛得横穿整张表去找。
|
||||
stopPropagation,否则点它会连带展开趋势图。 */}
|
||||
{note.note_url && (
|
||||
<a
|
||||
href={note.note_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
title="打开原作品"
|
||||
className="text-cyber-text-muted hover:text-cyber-neon-cyan flex-shrink-0"
|
||||
>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
{editing ? (
|
||||
<input
|
||||
autoFocus
|
||||
value={draft}
|
||||
placeholder="备注,比如「重点跟拍」"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
event.stopPropagation()
|
||||
if (event.key === 'Enter') commit()
|
||||
if (event.key === 'Escape') {
|
||||
cancelled.current = true
|
||||
setEditing(false)
|
||||
}
|
||||
}}
|
||||
onBlur={commit}
|
||||
className="mt-1 w-full rounded border border-cyber-neon-cyan/40 bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center gap-1.5 text-[9px] text-cyber-text-muted">
|
||||
{/* 标签放在这一行而不是标题行:标题行已经有 NEW、备注和跳转,
|
||||
再塞几个标签就糊成一团了。 */}
|
||||
{note.tags.map((tag) => (
|
||||
<span
|
||||
key={tag.id}
|
||||
className={cn(
|
||||
'rounded border px-1 py-0 text-[9px] font-mono flex-shrink-0',
|
||||
tagColorClass(tag.color),
|
||||
)}
|
||||
>
|
||||
{tag.name}
|
||||
</span>
|
||||
))}
|
||||
<span className="truncate">
|
||||
{note.note_id} · {note.snapshot_count} 次快照
|
||||
</span>
|
||||
<button
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
setDraft(note.note_alias)
|
||||
setEditing(true)
|
||||
}}
|
||||
title="给这条作品起个备注"
|
||||
className="flex items-center gap-0.5 flex-shrink-0 text-cyber-text-muted hover:text-cyber-neon-cyan"
|
||||
>
|
||||
<Pencil className="w-2.5 h-2.5" />
|
||||
{note.note_alias ? '改备注' : '备注'}
|
||||
</button>
|
||||
<button
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onTag(note)
|
||||
}}
|
||||
title="给这条作品贴标签"
|
||||
className="flex items-center gap-0.5 flex-shrink-0 text-cyber-text-muted hover:text-cyber-neon-cyan"
|
||||
>
|
||||
<Tag className="w-2.5 h-2.5" />
|
||||
标签
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
{METRIC_COLUMNS.map((column) => (
|
||||
<td key={column.key} className="py-2 px-2">
|
||||
<MetricCell value={note.metrics[column.key]} delta={note.deltas[column.key]} />
|
||||
</td>
|
||||
))}
|
||||
{/* 发布日期和「首次发现」是两回事:把早就发过的作品加进监控时,
|
||||
前者是作者发的那天,后者是我们第一次看到它的那天。 */}
|
||||
<td
|
||||
className="py-2 px-2 text-right text-[10px] text-cyber-text-muted whitespace-nowrap"
|
||||
title={formatDateTime(note.published_at)}
|
||||
>
|
||||
{formatDate(note.published_at)}
|
||||
</td>
|
||||
<td className="py-2 px-2 text-right text-[10px] text-cyber-text-muted">
|
||||
{formatRelative(note.first_seen_at)}
|
||||
</td>
|
||||
</tr>
|
||||
{isOpen && (
|
||||
<tr className="bg-cyber-bg-secondary/40">
|
||||
<td colSpan={COLUMN_COUNT} className="px-4 py-3">
|
||||
<NoteTrendChart
|
||||
noteId={note.note_id}
|
||||
taskId={note.task_id}
|
||||
noteTitle={note.title}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Tag } from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { useMonitorTags, useSetNoteTags } from '@/hooks/useMonitor'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { tagColorClass } from '@/lib/tagColors'
|
||||
import type { TagRef } from '@/types/monitor'
|
||||
|
||||
interface NoteTagPickerProps {
|
||||
noteId: string
|
||||
noteTitle: string
|
||||
/** 这条作品现在贴着的标签,用来给复选框定初值。 */
|
||||
current: TagRef[]
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 给一条作品贴标签。
|
||||
*
|
||||
* 用对话框而不是下拉气泡:这是个**多选**,几个复选框摆开比塞进一个小浮层清楚得多,
|
||||
* 也不用为此引一个新的依赖。
|
||||
*
|
||||
* 点「保存」是一次**全量替换**(这条作品现在该有哪些标签),不是逐个增删 —— 复选框
|
||||
* 表达的就是一个集合,对齐差集只是徒增错处。
|
||||
*/
|
||||
export function NoteTagPicker({
|
||||
noteId,
|
||||
noteTitle,
|
||||
current,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: NoteTagPickerProps) {
|
||||
const { data: tags } = useMonitorTags()
|
||||
const setNoteTags = useSetNoteTags()
|
||||
const [selected, setSelected] = useState<number[]>([])
|
||||
|
||||
// 每次打开都从「现在的标签」重新起算,否则上一次的勾选会串到另一条作品上。
|
||||
useEffect(() => {
|
||||
if (open) setSelected(current.map((tag) => tag.id))
|
||||
// current 是每次渲染新建的数组,放进依赖会让这个 effect 每帧都跑;只在打开时同步。
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, noteId])
|
||||
|
||||
const toggle = (tagId: number) =>
|
||||
setSelected((prev) =>
|
||||
prev.includes(tagId) ? prev.filter((id) => id !== tagId) : [...prev, tagId],
|
||||
)
|
||||
|
||||
const save = () => {
|
||||
setNoteTags.mutate({ noteId, tagIds: selected })
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-xs font-mono">给作品贴标签</DialogTitle>
|
||||
<DialogDescription className="text-[10px] font-mono truncate">
|
||||
{noteTitle || noteId}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{tags && tags.length > 0 ? (
|
||||
<div className="space-y-1.5">
|
||||
{tags.map((tag) => (
|
||||
<label
|
||||
key={tag.id}
|
||||
className="flex items-center gap-2 rounded px-1.5 py-1 cursor-pointer hover:bg-cyber-bg-elevated/50"
|
||||
>
|
||||
<Checkbox
|
||||
checked={selected.includes(tag.id)}
|
||||
onCheckedChange={() => toggle(tag.id)}
|
||||
/>
|
||||
<span
|
||||
className={cn(
|
||||
'rounded border px-1.5 py-0 text-[10px] font-mono',
|
||||
tagColorClass(tag.color),
|
||||
)}
|
||||
>
|
||||
{tag.name}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-[11px] font-mono text-cyber-text-muted">
|
||||
还没有标签。先去「设置 → 作品标签」里加几个。
|
||||
</p>
|
||||
)}
|
||||
|
||||
<DialogFooter className="gap-2">
|
||||
{selected.length > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="mr-auto"
|
||||
onClick={() => setSelected([])}
|
||||
>
|
||||
<Tag className="w-3 h-3 mr-1" />
|
||||
全摘掉
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => onOpenChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button size="sm" onClick={save} disabled={setNoteTags.isPending}>
|
||||
保存
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,50 +1,57 @@
|
||||
import { Fragment, useMemo, useState } from 'react'
|
||||
import { ChevronDown, ChevronRight, ExternalLink, Users } from 'lucide-react'
|
||||
import { Fragment, useCallback, useMemo, useRef, useState } from 'react'
|
||||
import { ChevronDown, ChevronRight, ExternalLink, Pencil, Users } from 'lucide-react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { useMonitorNotes } from '@/hooks/useMonitor'
|
||||
import {
|
||||
formatCount,
|
||||
formatDate,
|
||||
formatDateTime,
|
||||
formatDelta,
|
||||
formatRelative,
|
||||
} from '@/lib/monitorFormat'
|
||||
import type { MonitorNote, NoteMetrics } from '@/types/monitor'
|
||||
import { NoteCover } from './NoteCover'
|
||||
import { NoteTrendChart } from './NoteTrendChart'
|
||||
import { useMonitorNotes, useSetCreatorAlias, useSetNoteAlias } from '@/hooks/useMonitor'
|
||||
import { formatCount, formatDateTime } from '@/lib/monitorFormat'
|
||||
import type { MonitorCreator, MonitorNote } from '@/types/monitor'
|
||||
import { METRIC_COLUMNS, MetricCell } from './metricColumns'
|
||||
import { NoteRow } from './NoteRow'
|
||||
import { NoteTagPicker } from './NoteTagPicker'
|
||||
|
||||
interface NotesTableProps {
|
||||
taskId: number | null
|
||||
onlyNew: boolean
|
||||
/** 按标签筛。空数组 = 不筛。命中的是**任意一个**选中的标签。 */
|
||||
tagIds?: number[]
|
||||
}
|
||||
|
||||
/** A metric with its change vs the previous run underneath. */
|
||||
function MetricCell({ value, delta }: { value: number | null; delta: number | null }) {
|
||||
const deltaText = formatDelta(delta)
|
||||
/**
|
||||
* 账号级指标那几个字段。
|
||||
*
|
||||
* 作品的 payload 和博主的 payload 都带这一组,值也一样(同一次采集写的同一行),
|
||||
* 所以组件只认字段、不认来源。
|
||||
*/
|
||||
type AccountStats = Pick<
|
||||
MonitorCreator,
|
||||
'creator_fans' | 'creator_total_favorited' | 'creator_works' | 'creator_stats_at'
|
||||
>
|
||||
|
||||
/**
|
||||
* 博主的**账号级**指标:粉丝 / 总获赞 / 作品数。
|
||||
*
|
||||
* 作品列表给不了这个 —— 那几列说的是「这条作品涨了多少赞」,这里说的是「这个人整个
|
||||
* 账号在涨还是在掉」。**一个都没采到时整块不画**:画成「粉丝 0」比不画糟得多,那是
|
||||
* 一句假话。
|
||||
*/
|
||||
function CreatorStats({ stats }: { stats: AccountStats }) {
|
||||
const parts = [
|
||||
stats.creator_fans !== null && `粉丝 ${formatCount(stats.creator_fans)}`,
|
||||
stats.creator_total_favorited !== null && `获赞 ${formatCount(stats.creator_total_favorited)}`,
|
||||
stats.creator_works !== null && `${formatCount(stats.creator_works)} 作品`,
|
||||
].filter(Boolean) as string[]
|
||||
|
||||
if (parts.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="text-right">
|
||||
<div className="font-mono text-xs text-cyber-text-primary">{formatCount(value)}</div>
|
||||
{deltaText && (
|
||||
<div
|
||||
className={`font-mono text-[9px] ${
|
||||
(delta ?? 0) > 0 ? 'text-cyber-neon-green' : 'text-cyber-neon-pink'
|
||||
}`}
|
||||
>
|
||||
{deltaText}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className="text-cyber-text-muted flex-shrink-0"
|
||||
title={`账号指标采集于 ${formatDateTime(stats.creator_stats_at)}`}
|
||||
>
|
||||
{parts.join(' · ')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const METRIC_COLUMNS: Array<{ key: keyof NoteMetrics; label: string }> = [
|
||||
{ key: 'liked_count', label: '点赞' },
|
||||
{ key: 'comment_count', label: '评论' },
|
||||
{ key: 'collected_count', label: '收藏' },
|
||||
{ key: 'share_count', label: '分享' },
|
||||
]
|
||||
|
||||
/**
|
||||
* 一个博主名下所有作品的指标合计。
|
||||
*
|
||||
@@ -80,9 +87,6 @@ function sumMetrics(notes: MonitorNote[]) {
|
||||
return { values, deltas }
|
||||
}
|
||||
|
||||
// 多出来的那几列:展开箭头、作品、发布日期、首次发现、跳转链接;分组表头会跨掉整行。
|
||||
const COLUMN_COUNT = METRIC_COLUMNS.length + 5
|
||||
|
||||
/**
|
||||
* 作品表,**按博主分组**。
|
||||
*
|
||||
@@ -90,31 +94,124 @@ const COLUMN_COUNT = METRIC_COLUMNS.length + 5
|
||||
* `creator_hash` —— 爬虫刻意不落原始 user_id,所以这是唯一稳定的创作者标识;
|
||||
* 显示名是已脱敏的昵称(张***三)。两者都认不出来时才退回"未知博主"。
|
||||
*/
|
||||
export function NotesTable({ taskId, onlyNew }: NotesTableProps) {
|
||||
const { data: notes, isLoading } = useMonitorNotes(taskId, onlyNew)
|
||||
export function NotesTable({ taskId, onlyNew, tagIds = [] }: NotesTableProps) {
|
||||
const { data, isLoading } = useMonitorNotes(taskId, onlyNew, tagIds)
|
||||
const notes = data?.notes
|
||||
const creators = data?.creators
|
||||
const [expandedNote, setExpandedNote] = useState<string | null>(null)
|
||||
// 折叠状态按博主记。默认全展开 —— 藏起来的数据比多滚两屏更糟。
|
||||
const [collapsed, setCollapsed] = useState<Set<string>>(new Set())
|
||||
// 正在改备注的那个博主(creator_hash);null = 没在改。
|
||||
const [editingCreator, setEditingCreator] = useState<string | null>(null)
|
||||
const [aliasDraft, setAliasDraft] = useState('')
|
||||
// 按 Escape 是「取消」,而失焦是「保存」—— 取消时得让紧接着那次失焦闭嘴,
|
||||
// 否则它会把你刚放弃的内容存进去。
|
||||
const aliasCancelled = useRef(false)
|
||||
const setAlias = useSetCreatorAlias()
|
||||
const setNoteAlias = useSetNoteAlias()
|
||||
// 正在贴标签的那条作品。null = 对话框没开。
|
||||
const [taggingNote, setTaggingNote] = useState<MonitorNote | null>(null)
|
||||
|
||||
const commitAlias = (creatorHash: string) => {
|
||||
if (aliasCancelled.current) {
|
||||
aliasCancelled.current = false
|
||||
setEditingCreator(null)
|
||||
return
|
||||
}
|
||||
setEditingCreator(null)
|
||||
setAlias.mutate({ creatorHash, alias: aliasDraft })
|
||||
}
|
||||
|
||||
// 下面三个回调是 NoteRow 的 props,**身份必须稳定** —— 一变 memo 就全失效,一次点击
|
||||
// 又变回重渲染 131 行。
|
||||
const toggleNote = useCallback(
|
||||
(rowKey: string) => setExpandedNote((prev) => (prev === rowKey ? null : rowKey)),
|
||||
[],
|
||||
)
|
||||
const tagNote = useCallback((note: MonitorNote) => setTaggingNote(note), [])
|
||||
// `useMutation` 返回的那个**对象**每次渲染都是新的,所以不能拿它当依赖(那样等于
|
||||
// 没加 useCallback)。mutate 函数经 ref 取用,这个回调就永远不变。
|
||||
const aliasMutate = useRef(setNoteAlias.mutate)
|
||||
aliasMutate.current = setNoteAlias.mutate
|
||||
const saveNoteAlias = useCallback(
|
||||
(noteId: string, alias: string) => aliasMutate.current({ noteId, alias }),
|
||||
[],
|
||||
)
|
||||
|
||||
const groups = useMemo(() => {
|
||||
const byCreator = new Map<string, { key: string; name: string; notes: MonitorNote[] }>()
|
||||
type Group = {
|
||||
key: string
|
||||
name: string
|
||||
alias: string
|
||||
/** 主页链接。空串就是不画那个按钮(见 MonitorCreator.creator_url)。 */
|
||||
url: string
|
||||
/** 服务端说的这条博主名下有多少作品 —— 列表被 `onlyNew` 滤过时和 `notes.length` 不等。 */
|
||||
totalNotes: number
|
||||
stats: MonitorCreator | null
|
||||
notes: MonitorNote[]
|
||||
}
|
||||
const byCreator = new Map<string, Group>()
|
||||
|
||||
// **先放博主,不是先放作品。** 「一条作品都没有的博主」在作品里根本推不出来 ——
|
||||
// 目标加了、资料也采到了、粉丝数就躺在库里,可界面上什么都看不见。而他恰恰是最该
|
||||
// 看见的一个:还在涨粉,只是最近没发东西。
|
||||
for (const creator of creators ?? []) {
|
||||
const key = creator.creator_hash || '__unknown__'
|
||||
const existing = byCreator.get(key)
|
||||
if (existing) {
|
||||
// 同一个博主可能挂在多个任务下(服务端按 任务×博主 给),合并成一组。
|
||||
existing.totalNotes += creator.note_count
|
||||
if (!existing.stats?.creator_stats_at && creator.creator_stats_at) {
|
||||
existing.stats = creator
|
||||
}
|
||||
existing.name ||= creator.creator_name
|
||||
// 备注按 (platform, creator_hash) 存,所以跨任务就是同一条,取到即可。
|
||||
existing.alias ||= creator.creator_alias
|
||||
existing.url ||= creator.creator_url
|
||||
continue
|
||||
}
|
||||
byCreator.set(key, {
|
||||
key,
|
||||
name: creator.creator_name || '',
|
||||
alias: creator.creator_alias || '',
|
||||
url: creator.creator_url || '',
|
||||
totalNotes: creator.note_count,
|
||||
stats: creator,
|
||||
notes: [],
|
||||
})
|
||||
}
|
||||
|
||||
for (const note of notes ?? []) {
|
||||
// 作品模式下每条作品都会带 creator_hash;真丢了也要有个兜底分组,
|
||||
// 否则那些作品会凭空消失。
|
||||
const key = note.creator_hash || '__unknown__'
|
||||
if (!byCreator.has(key)) {
|
||||
byCreator.set(key, { key, name: note.creator_name || '', notes: [] })
|
||||
let group = byCreator.get(key)
|
||||
if (!group) {
|
||||
group = {
|
||||
key,
|
||||
name: note.creator_name || '',
|
||||
alias: note.creator_alias || '',
|
||||
url: '',
|
||||
totalNotes: 0,
|
||||
stats: null,
|
||||
notes: [],
|
||||
}
|
||||
byCreator.set(key, group)
|
||||
}
|
||||
byCreator.get(key)!.notes.push(note)
|
||||
group.notes.push(note)
|
||||
group.name ||= note.creator_name || ''
|
||||
group.alias ||= note.creator_alias || ''
|
||||
}
|
||||
|
||||
return [...byCreator.values()]
|
||||
}, [notes])
|
||||
}, [notes, creators])
|
||||
|
||||
if (isLoading) {
|
||||
return <p className="py-8 text-center text-[11px] font-mono text-cyber-text-muted">加载中…</p>
|
||||
}
|
||||
|
||||
if (!notes || notes.length === 0) {
|
||||
// 博主有、作品没有也是**要画**的:那正是「这个号还没被删,只是没发东西」。
|
||||
if (groups.length === 0) {
|
||||
return (
|
||||
<p className="py-8 text-center text-[11px] font-mono text-cyber-text-muted">
|
||||
{taskId === null
|
||||
@@ -148,7 +245,6 @@ export function NotesTable({ taskId, onlyNew }: NotesTableProps) {
|
||||
))}
|
||||
<th className="text-right font-normal py-2 px-2">发布日期</th>
|
||||
<th className="text-right font-normal py-2 px-2">首次发现</th>
|
||||
<th className="w-8" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -171,13 +267,74 @@ export function NotesTable({ taskId, onlyNew }: NotesTableProps) {
|
||||
)}
|
||||
</td>
|
||||
<td className="py-1.5 px-2">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Users className="w-3 h-3 text-cyber-neon-cyan" />
|
||||
<span className="text-cyber-text-primary">
|
||||
{group.name || '未知博主'}
|
||||
{editingCreator === group.key ? (
|
||||
<input
|
||||
autoFocus
|
||||
value={aliasDraft}
|
||||
placeholder="备注,比如「竞品A」"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onChange={(event) => setAliasDraft(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
event.stopPropagation()
|
||||
if (event.key === 'Enter') commitAlias(group.key)
|
||||
if (event.key === 'Escape') {
|
||||
aliasCancelled.current = true
|
||||
setEditingCreator(null)
|
||||
}
|
||||
}}
|
||||
onBlur={() => commitAlias(group.key)}
|
||||
className="w-full rounded border border-cyber-neon-cyan/40 bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none"
|
||||
/>
|
||||
) : (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Users className="w-3 h-3 text-cyber-neon-cyan flex-shrink-0" />
|
||||
<span className="text-cyber-text-primary truncate">
|
||||
{group.alias || group.name || '未知博主'}
|
||||
</span>
|
||||
{/* 起了备注之后,平台昵称降成副标题 —— 它仍是有用的对照。 */}
|
||||
{group.alias && group.name && (
|
||||
<span className="text-cyber-text-muted truncate">{group.name}</span>
|
||||
)}
|
||||
{/* 跳到他主页。链接是采集时从资料接口带回来的(哈希拼不出地址),
|
||||
拿不到就整块不画 —— 一个点开 404 的按钮比没有按钮糟。 */}
|
||||
{group.url && (
|
||||
<a
|
||||
href={group.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
title="打开博主主页"
|
||||
className="text-cyber-text-muted hover:text-cyber-neon-cyan flex-shrink-0"
|
||||
>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
)}
|
||||
<span className="text-cyber-text-muted flex-shrink-0">
|
||||
{/* 被 onlyNew 滤过时,把「显示了几篇 / 一共几篇」都说出来,
|
||||
否则「1 篇」会让人以为这个号只发过一条。 */}
|
||||
{group.notes.length}
|
||||
{group.totalNotes > group.notes.length && `/${group.totalNotes}`} 篇
|
||||
</span>
|
||||
{group.stats && <CreatorStats stats={group.stats} />}
|
||||
{/* 博主在、作品一条都没有 —— 说清楚,别让人以为列表挂了。 */}
|
||||
{group.notes.length === 0 && (
|
||||
<span className="text-cyber-text-muted/70 flex-shrink-0">
|
||||
暂无作品
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
setAliasDraft(group.alias)
|
||||
setEditingCreator(group.key)
|
||||
}}
|
||||
title="给这个博主起个备注"
|
||||
className="text-cyber-text-muted hover:text-cyber-neon-cyan flex-shrink-0"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
</button>
|
||||
</span>
|
||||
<span className="text-cyber-text-muted">{group.notes.length} 篇</span>
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
{METRIC_COLUMNS.map((column) => (
|
||||
<td key={column.key} className="py-1.5 px-2">
|
||||
@@ -194,88 +351,15 @@ export function NotesTable({ taskId, onlyNew }: NotesTableProps) {
|
||||
{!isCollapsed &&
|
||||
group.notes.map((note) => {
|
||||
const rowKey = `${note.task_id}:${note.note_id}`
|
||||
const open = expandedNote === rowKey
|
||||
return (
|
||||
<Fragment key={rowKey}>
|
||||
<tr
|
||||
onClick={() => setExpandedNote(open ? null : rowKey)}
|
||||
className="border-t border-cyber-border-subtle hover:bg-cyber-bg-elevated/50 cursor-pointer"
|
||||
>
|
||||
<td />
|
||||
<td className="py-2 px-2 max-w-[320px]">
|
||||
<div className="flex items-center gap-2">
|
||||
<NoteCover src={note.cover} size="md" />
|
||||
{/* min-w-0 so the title can actually truncate inside the flex row */}
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{note.is_new && (
|
||||
<Badge
|
||||
variant="success"
|
||||
className="text-[9px] px-1 py-0 flex-shrink-0"
|
||||
>
|
||||
NEW
|
||||
</Badge>
|
||||
)}
|
||||
<span
|
||||
className="truncate text-cyber-text-primary"
|
||||
title={note.title}
|
||||
>
|
||||
{note.title || note.note_id}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-[9px] text-cyber-text-muted truncate">
|
||||
{note.note_id} · {note.snapshot_count} 次快照
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
{METRIC_COLUMNS.map((column) => (
|
||||
<td key={column.key} className="py-2 px-2">
|
||||
<MetricCell
|
||||
value={note.metrics[column.key]}
|
||||
delta={note.deltas[column.key]}
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
{/* 发布日期和「首次发现」是两回事:把早就发过的作品加进监控时,
|
||||
前者是作者发的那天,后者是我们第一次看到它的那天。 */}
|
||||
<td
|
||||
className="py-2 px-2 text-right text-[10px] text-cyber-text-muted whitespace-nowrap"
|
||||
title={formatDateTime(note.published_at)}
|
||||
>
|
||||
{formatDate(note.published_at)}
|
||||
</td>
|
||||
<td className="py-2 px-2 text-right text-[10px] text-cyber-text-muted">
|
||||
{formatRelative(note.first_seen_at)}
|
||||
</td>
|
||||
<td className="py-2 px-1">
|
||||
{/* 直接跳转到该作品。stopPropagation,否则点它会连带展开趋势图。 */}
|
||||
{note.note_url && (
|
||||
<a
|
||||
href={note.note_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
title="打开原作品"
|
||||
className="text-cyber-text-muted hover:text-cyber-neon-cyan"
|
||||
>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
{open && (
|
||||
<tr className="bg-cyber-bg-secondary/40">
|
||||
<td colSpan={COLUMN_COUNT} className="px-4 py-3">
|
||||
<NoteTrendChart
|
||||
noteId={note.note_id}
|
||||
taskId={note.task_id}
|
||||
noteTitle={note.title}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
<NoteRow
|
||||
key={rowKey}
|
||||
note={note}
|
||||
isOpen={expandedNote === rowKey}
|
||||
onToggle={toggleNote}
|
||||
onTag={tagNote}
|
||||
onSaveAlias={saveNoteAlias}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</Fragment>
|
||||
@@ -283,6 +367,19 @@ export function NotesTable({ taskId, onlyNew }: NotesTableProps) {
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* 对话框挂在表格**外面** —— 放在 tbody 里会因为表格的布局规则出问题。 */}
|
||||
{taggingNote && (
|
||||
<NoteTagPicker
|
||||
noteId={taggingNote.note_id}
|
||||
noteTitle={taggingNote.title}
|
||||
current={taggingNote.tags}
|
||||
open={taggingNote !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setTaggingNote(null)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import {
|
||||
AlertTriangle,
|
||||
CalendarRange,
|
||||
ExternalLink,
|
||||
Loader2,
|
||||
Plus,
|
||||
Radar,
|
||||
} from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
useCreateSuperDirTask,
|
||||
useMonitorTasks,
|
||||
useSuperDirPreview,
|
||||
} from '@/hooks/useMonitor'
|
||||
import type { SuperDirVideoRow } from '@/types/monitor'
|
||||
|
||||
interface SuperDirToolProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
const INPUT_CLASS =
|
||||
'rounded-md border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-2 py-1 font-mono text-[11px] text-cyber-text-primary outline-none focus-visible:border-cyber-neon-cyan/50'
|
||||
|
||||
function toDateInput(value: Date): string {
|
||||
// ``toISOString`` 是 UTC:东八区晚上 20:00 之后会算成「明天」,默认区间会整体后移一天。
|
||||
const month = String(value.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(value.getDate()).padStart(2, '0')
|
||||
return `${value.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
function defaultRange(): { start: string; end: string } {
|
||||
const end = new Date()
|
||||
const start = new Date()
|
||||
// 默认看最近 7 天。运营一般是「把这一周发的那批拉进来」,每天都改日期太烦。
|
||||
start.setDate(start.getDate() - 6)
|
||||
return { start: toDateInput(start), end: toDateInput(end) }
|
||||
}
|
||||
|
||||
function formatTs(seconds: number): string {
|
||||
if (!seconds) return '—'
|
||||
const date = new Date(seconds * 1000)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${month}-${day} ${String(date.getHours()).padStart(2, '0')}:${String(
|
||||
date.getMinutes(),
|
||||
).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function formatCount(value: number): string {
|
||||
return value.toLocaleString('zh-CN')
|
||||
}
|
||||
|
||||
/**
|
||||
* 超级编导 → 监控任务。
|
||||
*
|
||||
* 两步:先按「分发活动的创建时间」查出一批作品链接(只读),确认条数和博主之后,
|
||||
* 再一键建成一个作品模式的监控任务。**没有做成一个按钮直接建**:这个接口一次能带出
|
||||
* 几百条作品,误点一下就是一个每轮几百次请求的任务,事后还得一条条删。
|
||||
*
|
||||
* 预览里没有主页链接 —— 超级编导的数据中心只有昵称,没有 sec_uid。主页地址要等第一轮
|
||||
* 采集时从抖音作品详情里取(`author.sec_uid`),所以建任务后默认自动跑一轮。
|
||||
*/
|
||||
export function SuperDirTool({ open, onOpenChange }: SuperDirToolProps) {
|
||||
const initial = useMemo(defaultRange, [])
|
||||
const [start, setStart] = useState(initial.start)
|
||||
const [end, setEnd] = useState(initial.end)
|
||||
const [name, setName] = useState('')
|
||||
const [enableComments, setEnableComments] = useState(false)
|
||||
const [runNow, setRunNow] = useState(true)
|
||||
// 'new' = 新建任务;数字 = 追加到这个作品任务。默认新建:第一次导入还没有地方可追加。
|
||||
const [targetTask, setTargetTask] = useState('new')
|
||||
|
||||
const preview = useSuperDirPreview()
|
||||
const create = useCreateSuperDirTask()
|
||||
const { data: tasks } = useMonitorTasks()
|
||||
// 只能追加到作品模式的任务 —— 博主模式的目标是主页,塞作品 id 进去只会让它抓不到东西。
|
||||
const noteTasks = (tasks ?? []).filter((task) => task.mode === 'note')
|
||||
|
||||
const data = preview.data
|
||||
const rows = data?.rows ?? []
|
||||
const defaultName = data ? `超级编导 ${data.start} ~ ${data.end}` : ''
|
||||
// 记住上一次预览结果:**只在拿到新结果时**重填任务名。按「名字为空就填」写的话,
|
||||
// 用户把输入框删空、准备打新名字的瞬间又会被默认值塞回去。
|
||||
const namedFor = useRef<unknown>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (data && namedFor.current !== data) {
|
||||
namedFor.current = data
|
||||
setName(defaultName)
|
||||
}
|
||||
}, [data, defaultName])
|
||||
|
||||
const invalidRange = !start || !end || end < start
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next) {
|
||||
preview.reset()
|
||||
create.reset()
|
||||
setName('')
|
||||
setTargetTask('new')
|
||||
}
|
||||
onOpenChange(next)
|
||||
}
|
||||
|
||||
const appending = targetTask !== 'new'
|
||||
|
||||
const handleCreate = () => {
|
||||
if (!rows.length) return
|
||||
create.mutate(
|
||||
{
|
||||
links: rows.map((row) => row.share_url),
|
||||
task_id: appending ? Number(targetTask) : null,
|
||||
name: (name || defaultName).trim(),
|
||||
enable_comments: enableComments,
|
||||
run_now: runNow,
|
||||
},
|
||||
{ onSuccess: () => handleOpenChange(false) },
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-3xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 font-mono text-sm">
|
||||
<Radar className="h-4 w-4 text-cyber-neon-cyan" />
|
||||
从超级编导导入作品
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-[11px] font-mono leading-relaxed">
|
||||
按「分发活动的创建时间」选一段区间,查出这段时间里发出去的作品链接,
|
||||
再一键建成监控任务。博主主页链接要等第一轮采集从抖音详情里补全。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* 区间 */}
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="font-mono text-[10px] text-cyber-text-muted">开始日期</span>
|
||||
<input
|
||||
type="date"
|
||||
value={start}
|
||||
max={end || undefined}
|
||||
onChange={(event) => setStart(event.target.value)}
|
||||
className={INPUT_CLASS}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="font-mono text-[10px] text-cyber-text-muted">结束日期</span>
|
||||
<input
|
||||
type="date"
|
||||
value={end}
|
||||
min={start || undefined}
|
||||
onChange={(event) => setEnd(event.target.value)}
|
||||
className={INPUT_CLASS}
|
||||
/>
|
||||
</label>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={invalidRange || preview.isPending}
|
||||
onClick={() => preview.mutate({ start, end })}
|
||||
>
|
||||
{preview.isPending ? (
|
||||
<Loader2 className="mr-1 h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<CalendarRange className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
{preview.isPending ? '查询中…' : '查询'}
|
||||
</Button>
|
||||
<span className="font-mono text-[10px] text-cyber-text-muted">
|
||||
一次最多 31 天
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{data && (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 font-mono text-[11px]">
|
||||
<span className="text-cyber-text-secondary">
|
||||
活动 <span className="text-cyber-neon-cyan">{data.activities}</span> 个
|
||||
</span>
|
||||
<span className="text-cyber-text-secondary">
|
||||
作品 <span className="text-cyber-neon-cyan">{data.videos}</span> 条
|
||||
</span>
|
||||
<span className="text-cyber-text-secondary">
|
||||
博主 <span className="text-cyber-neon-cyan">{data.creators}</span> 个
|
||||
</span>
|
||||
{data.skipped > 0 && (
|
||||
<span className="text-cyber-text-muted">
|
||||
跳过 {data.skipped} 条(未发布 / 非公开 / 认不出作品 id)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{data.truncated && (
|
||||
<p className="flex items-center gap-1 font-mono text-[11px] text-cyber-neon-orange">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
超过一次能导入的上限,只显示了前 {rows.length} 条 —— 缩小时间范围分几批建。
|
||||
</p>
|
||||
)}
|
||||
|
||||
{data.failed_activities.length > 0 && (
|
||||
<p className="flex items-center gap-1 font-mono text-[11px] text-cyber-neon-orange">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
{data.failed_activities.length} 个活动取作品失败,其余已正常列出
|
||||
</p>
|
||||
)}
|
||||
|
||||
{rows.length > 0 ? (
|
||||
<div className="max-h-[300px] space-y-1 overflow-y-auto terminal-scroll pr-1">
|
||||
{rows.map((row) => (
|
||||
<VideoRow key={row.aweme_id} row={row} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1 rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/60 px-3 py-2">
|
||||
<p className="font-mono text-[11px] text-cyber-text-muted">
|
||||
这段时间创建了 {data.matched_activities.length} 个分发活动,但还没有已发布的作品:
|
||||
</p>
|
||||
{data.matched_activities.map((activity) => (
|
||||
<div
|
||||
key={activity.id}
|
||||
className="flex flex-wrap items-center gap-x-2 font-mono text-[10px]"
|
||||
>
|
||||
<span className="text-cyber-text-secondary">
|
||||
{activity.title || `活动 ${activity.id}`}
|
||||
</span>
|
||||
<span className="text-cyber-text-muted">
|
||||
创建 {formatTs(activity.created_at)} · 已发布{' '}
|
||||
{activity.published_count}/{activity.total_count}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
<p className="font-mono text-[10px] text-cyber-text-muted">
|
||||
活动名里的日期只是活动名,不是创建时间;排期在未来的活动通常还没有作品。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{rows.length > 0 && (
|
||||
<div className="space-y-2 border-t border-cyber-border-subtle pt-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="font-mono text-[10px] text-cyber-text-muted">写入方式</span>
|
||||
<select
|
||||
value={targetTask}
|
||||
onChange={(event) => setTargetTask(event.target.value)}
|
||||
className={`${INPUT_CLASS} max-w-[260px]`}
|
||||
>
|
||||
<option value="new">新建一个监控任务</option>
|
||||
{noteTasks.map((task) => (
|
||||
<option key={task.id} value={String(task.id)}>
|
||||
{task.name}(已有 {task.target_count} 条)
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{!appending && (
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="font-mono text-[10px] text-cyber-text-muted">任务名</span>
|
||||
<input
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
className={`${INPUT_CLASS} w-[260px]`}
|
||||
maxLength={200}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{/* 追加时评论开关归已有任务管 —— 补链接不该顺手改掉它的配置。 */}
|
||||
{!appending && (
|
||||
<label className="flex items-center gap-1 font-mono text-[11px] text-cyber-text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enableComments}
|
||||
onChange={(event) => setEnableComments(event.target.checked)}
|
||||
/>
|
||||
同时抓评论
|
||||
</label>
|
||||
)}
|
||||
<label className="flex items-center gap-1 font-mono text-[11px] text-cyber-text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={runNow}
|
||||
onChange={(event) => setRunNow(event.target.checked)}
|
||||
/>
|
||||
{appending ? '追加后立即采一轮' : '建完立即采一轮'}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button size="sm" disabled={create.isPending} onClick={handleCreate}>
|
||||
{create.isPending ? (
|
||||
<Loader2 className="mr-1 h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<Plus className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
{appending
|
||||
? `追加到该任务(${rows.length} 条)`
|
||||
: `新建监控任务(${rows.length} 条)`}
|
||||
</Button>
|
||||
<span className="font-mono text-[10px] text-cyber-text-muted">
|
||||
已有的作品不会重复添加;采集间隔在任务的「设置」里改
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function VideoRow({ row }: { row: SuperDirVideoRow }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/60 px-2 py-1.5">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate font-mono text-[11px] text-cyber-text-primary">
|
||||
{row.title || '(无标题)'}
|
||||
</span>
|
||||
<span className="flex-shrink-0 font-mono text-[10px] text-cyber-text-muted">
|
||||
{row.nickname || '(未知博主)'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-3 font-mono text-[10px] text-cyber-text-muted">
|
||||
<span>{row.activity_title || `活动 ${row.activity_id}`}</span>
|
||||
<span>发布 {formatTs(row.published_at)}</span>
|
||||
<span>播放 {formatCount(row.play_count)}</span>
|
||||
<span>赞 {formatCount(row.digg_count)}</span>
|
||||
<span>评 {formatCount(row.comment_count)}</span>
|
||||
<span>分享 {formatCount(row.share_count)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{row.share_url && (
|
||||
<a
|
||||
href={row.share_url}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="flex-shrink-0 text-cyber-text-muted hover:text-cyber-neon-cyan"
|
||||
title="在抖音打开"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { X } from 'lucide-react'
|
||||
|
||||
import { useMonitorTags } from '@/hooks/useMonitor'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { tagColorClass } from '@/lib/tagColors'
|
||||
|
||||
/**
|
||||
* 按标签筛作品。
|
||||
*
|
||||
* 做成**平铺的开关片**而不是下拉多选:词表是人自己维护的,通常就几个,全摆出来一眼就
|
||||
* 知道有哪些、选中了哪些 —— 下拉还得点开才知道里面有什么。
|
||||
*
|
||||
* 多选是**或**:选中「重点」和「竞品」= 两类都看。求交集的做法是再点一个标签,而不是
|
||||
* 让筛选去猜。
|
||||
*
|
||||
* 一个标签都没有时整块不画 —— 空的筛选条只是占地方。
|
||||
*/
|
||||
export function TagFilter({
|
||||
selected,
|
||||
onChange,
|
||||
}: {
|
||||
selected: number[]
|
||||
onChange: (tagIds: number[]) => void
|
||||
}) {
|
||||
const { data: tags } = useMonitorTags()
|
||||
|
||||
if (!tags || tags.length === 0) return null
|
||||
|
||||
const toggle = (tagId: number) =>
|
||||
onChange(
|
||||
selected.includes(tagId)
|
||||
? selected.filter((id) => id !== tagId)
|
||||
: [...selected, tagId],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1 flex-wrap">
|
||||
{tags.map((tag) => {
|
||||
const active = selected.includes(tag.id)
|
||||
return (
|
||||
<button
|
||||
key={tag.id}
|
||||
onClick={() => toggle(tag.id)}
|
||||
title={active ? '取消这个筛选' : `只看「${tag.name}」`}
|
||||
className={cn(
|
||||
'rounded border px-1.5 py-0.5 text-[10px] font-mono transition-colors',
|
||||
active
|
||||
? cn(tagColorClass(tag.color), 'bg-cyber-bg-elevated')
|
||||
: 'border-cyber-border-subtle text-cyber-text-muted hover:text-cyber-text-secondary',
|
||||
)}
|
||||
>
|
||||
{tag.name}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{selected.length > 0 && (
|
||||
<button
|
||||
onClick={() => onChange([])}
|
||||
className="flex items-center gap-0.5 text-[10px] font-mono text-cyber-text-muted hover:text-cyber-neon-pink"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
清除
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
} from '@/components/ui/select'
|
||||
import { useCreateTask, useSettings, useUpdateTask } from '@/hooks/useMonitor'
|
||||
import { useCurrentPlatform } from '@/hooks/usePlatform'
|
||||
import { describeSchedule } from '@/lib/monitorFormat'
|
||||
import { describeSchedule, formatDateTime } from '@/lib/monitorFormat'
|
||||
import type {
|
||||
MonitorMode,
|
||||
MonitorTask,
|
||||
@@ -59,6 +59,18 @@ const SCHEDULE_MODE_OPTIONS: Array<{ value: ScheduleMode; label: string }> = [
|
||||
|
||||
const HOURS = Array.from({ length: 24 }, (_, hour) => hour)
|
||||
|
||||
// 超级编导自动追加的检查频率。默认 2 小时 —— 分发作品陆续发布,查太勤只是多打
|
||||
// 第三方接口,查太慢则新作品要等很久才进监控。
|
||||
const SUPERDIR_INTERVAL_OPTIONS = [
|
||||
{ value: '30', label: '30 分钟' },
|
||||
{ value: '60', label: '1 小时' },
|
||||
{ value: '120', label: '2 小时' },
|
||||
{ value: '180', label: '3 小时' },
|
||||
{ value: '360', label: '6 小时' },
|
||||
{ value: '720', label: '12 小时' },
|
||||
{ value: '1440', label: '1 天' },
|
||||
]
|
||||
|
||||
/**
|
||||
* Above this many works per run, warn about the request volume.
|
||||
*
|
||||
@@ -123,9 +135,14 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
||||
const [enableComments, setEnableComments] = useState(true)
|
||||
const [maxComments, setMaxComments] = useState('50')
|
||||
const [notifyEnabled, setNotifyEnabled] = useState(false)
|
||||
const [superdirAuto, setSuperdirAuto] = useState(false)
|
||||
const [superdirInterval, setSuperdirInterval] = useState('120')
|
||||
// 异常推送默认开:失败意味着这个任务从此默默采不到东西,而你不会知道。
|
||||
const [notifyFailures, setNotifyFailures] = useState(true)
|
||||
const [targets, setTargets] = useState('')
|
||||
// 编辑时用来**追加**新目标。已有的那几百条不该逼人滚到底再粘贴 —— 上面那个框是
|
||||
// 全量列表,这个框只放这次要补的。
|
||||
const [appendTargets, setAppendTargets] = useState('')
|
||||
|
||||
// Reset the form whenever the dialog is (re)opened. For a new task the
|
||||
// starting values come from the Settings page, so those defaults actually
|
||||
@@ -150,13 +167,24 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
||||
)
|
||||
setNotifyEnabled(task?.notify_enabled ?? false)
|
||||
setNotifyFailures(task?.notify_failures ?? true)
|
||||
setSuperdirAuto(task?.superdir_auto_enabled ?? false)
|
||||
setSuperdirInterval(String(task?.superdir_auto_interval_minutes ?? 120))
|
||||
setTargets(task ? task.targets.map((t) => t.raw_value || t.external_id).join('\n') : '')
|
||||
setAppendTargets('')
|
||||
}, [open, task, settings])
|
||||
|
||||
const targetList = targets
|
||||
.split(/[\n,]+/)
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean)
|
||||
const splitTargets = (value: string) =>
|
||||
value
|
||||
.split(/[\n,]+/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const targetList = splitTargets(targets)
|
||||
const appendList = splitTargets(appendTargets)
|
||||
// 保存的是**合并后**的列表:后端按「整份替换」处理 targets,所以追加必须在这里合并。
|
||||
// 去重顺手做了 —— 重复的目标在后端也会被丢掉,这里做是为了让「将追加 N 个」是准的。
|
||||
const mergedTargets = Array.from(new Set([...targetList, ...appendList]))
|
||||
const newTargetCount = mergedTargets.length - targetList.length
|
||||
|
||||
// Switching into a clock mode with nothing chosen would be invalid, so seed a
|
||||
// sensible starting point -- the operator then edits rather than fills a blank.
|
||||
@@ -173,8 +201,10 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
||||
const clockIncomplete =
|
||||
scheduleMode !== 'interval' &&
|
||||
(scheduleHours.length === 0 || (scheduleMode === 'weekly' && scheduleDays.length === 0))
|
||||
// 超级编导只接抖音分发,追加进去的又只能是作品 id —— 只有这一种任务能用。
|
||||
const superdirEligible = platform === 'dy' && mode === 'note'
|
||||
const canSubmit =
|
||||
name.trim().length > 0 && targetList.length > 0 && !pending && !clockIncomplete
|
||||
name.trim().length > 0 && mergedTargets.length > 0 && !pending && !clockIncomplete
|
||||
|
||||
const handleSubmit = () => {
|
||||
const payload: TaskCreatePayload = {
|
||||
@@ -197,7 +227,10 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
||||
enabled: true,
|
||||
notify_enabled: notifyEnabled,
|
||||
notify_failures: notifyFailures,
|
||||
targets: targetList,
|
||||
// 非抖音/作品模式时后端会拒绝,所以这里按平台和模式清掉,别让旧状态带上去。
|
||||
superdir_auto_enabled: superdirEligible ? superdirAuto : false,
|
||||
superdir_auto_interval_minutes: Number(superdirInterval),
|
||||
targets: mergedTargets,
|
||||
}
|
||||
|
||||
const done = () => onOpenChange(false)
|
||||
@@ -384,8 +417,32 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
||||
placeholder={`每行一个,支持完整链接或纯 ID:\n${(mode === 'creator' ? hints?.creator : hints?.note) ?? ''}`}
|
||||
className={TEXTAREA_CLASS}
|
||||
/>
|
||||
{isEdit && (
|
||||
<div className="space-y-1.5 rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/40 p-2">
|
||||
<Label className="text-[10px] font-mono text-cyber-text-secondary">
|
||||
追加{mode === 'creator' ? hints?.creator_label ?? '博主主页' : hints?.note_label ?? '笔记'}
|
||||
链接或 ID
|
||||
</Label>
|
||||
<textarea
|
||||
value={appendTargets}
|
||||
onChange={(event) => setAppendTargets(event.target.value)}
|
||||
rows={3}
|
||||
placeholder={'每行一个,保存时追加到上面的列表;已经有的会自动忽略'}
|
||||
className={TEXTAREA_CLASS}
|
||||
/>
|
||||
{appendList.length > 0 && (
|
||||
<p className="text-[10px] font-mono text-cyber-text-muted">
|
||||
本次将新增{' '}
|
||||
<span className="text-cyber-neon-cyan">{newTargetCount}</span> 个
|
||||
{newTargetCount < appendList.length && '(重复的已忽略)'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-[10px] font-mono text-cyber-text-muted">
|
||||
已识别 <span className="text-cyber-neon-cyan">{targetList.length}</span> 个目标。
|
||||
已识别{' '}
|
||||
<span className="text-cyber-neon-cyan">{mergedTargets.length}</span> 个目标
|
||||
{appendList.length > 0 && `(其中本次新增 ${newTargetCount})`}。
|
||||
{/* 「只填纯 ID」是小红书专属的劝告:它链接里的 xsec_token 会过期。
|
||||
抖音的链接不带令牌,永久有效,那句话对它没有意义。 */}
|
||||
{hints?.token_expires && (
|
||||
@@ -475,6 +532,69 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{superdirEligible && (
|
||||
<div className="rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/40 p-3 space-y-2">
|
||||
<div className="flex items-start gap-2">
|
||||
<Checkbox
|
||||
id="superdir-auto"
|
||||
checked={superdirAuto}
|
||||
onCheckedChange={(checked) => setSuperdirAuto(checked === true)}
|
||||
/>
|
||||
<div className="space-y-0.5">
|
||||
<label
|
||||
htmlFor="superdir-auto"
|
||||
className="text-xs font-mono text-cyber-text-primary cursor-pointer"
|
||||
>
|
||||
自动从超级编导追加新作品
|
||||
</label>
|
||||
<p className="text-[10px] font-mono text-cyber-text-muted leading-relaxed">
|
||||
每隔一段时间查一次超级编导,把这段时间
|
||||
<span className="text-cyber-text-secondary">新发布</span>
|
||||
的作品自动加到本任务;已有的不会重复。需要先在「设置」里配好超级编导 Token。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{superdirAuto && (
|
||||
<div className="flex flex-wrap items-center gap-2 pl-6">
|
||||
<span className="text-[10px] font-mono text-cyber-text-secondary">
|
||||
检查间隔
|
||||
</span>
|
||||
<Select value={superdirInterval} onValueChange={setSuperdirInterval}>
|
||||
<SelectTrigger className="h-7 w-28 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SUPERDIR_INTERVAL_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span className="text-[10px] font-mono text-cyber-text-muted">
|
||||
保存后立即检查一次,之后按间隔跑
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isEdit && task?.superdir_auto_enabled && (
|
||||
<p className="pl-6 text-[10px] font-mono text-cyber-text-muted">
|
||||
上次检查 {formatDateTime(task.superdir_auto_last_at)},新增{' '}
|
||||
<span className="text-cyber-neon-cyan">
|
||||
{task.superdir_auto_last_added ?? 0}
|
||||
</span>{' '}
|
||||
条
|
||||
</p>
|
||||
)}
|
||||
{isEdit && task?.superdir_auto_last_error && (
|
||||
<p className="pl-6 text-[10px] font-mono text-cyber-neon-pink">
|
||||
上次失败:{task.superdir_auto_last_error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/40 p-3 space-y-3">
|
||||
{/* 两类通知的性质完全不同,所以分成两个开关:
|
||||
异常低频且意味着任务已经停止工作 —— 默认开;
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { AlertTriangle, Check, Copy, ExternalLink, Link2, Loader2 } from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { useResolveVideoLinks } from '@/hooks/useMonitor'
|
||||
import { copyText } from '@/lib/clipboard'
|
||||
|
||||
interface VideoLinkToolProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
const TEXTAREA_CLASS =
|
||||
'w-full rounded-md border border-cyber-border-DEFAULT bg-cyber-bg-tertiary p-2 font-mono text-[11px] text-cyber-text-primary outline-none focus-visible:border-cyber-neon-cyan/50'
|
||||
|
||||
/**
|
||||
* 粘贴视频链接 → 拿博主主页。
|
||||
*
|
||||
* 只读不写:解析出来的主页地址不会自动变成监控任务,建不建由人决定 —— 一次粘十几条
|
||||
* 就顺手建十几个任务,不是这里该干的事。
|
||||
*/
|
||||
export function VideoLinkTool({ open, onOpenChange }: VideoLinkToolProps) {
|
||||
const [text, setText] = useState('')
|
||||
const [copied, setCopied] = useState('')
|
||||
const resolve = useResolveVideoLinks()
|
||||
|
||||
const results = resolve.data?.results ?? []
|
||||
const okCount = results.filter((item) => item.ok).length
|
||||
// 同一个博主发了好几条时只留一行 —— 复制一堆重复地址没有意义。
|
||||
const uniqueProfiles = useMemo(
|
||||
() => Array.from(new Set(results.map((item) => item.profile_url).filter(Boolean))),
|
||||
[results],
|
||||
)
|
||||
|
||||
const copy = async (value: string) => {
|
||||
if (await copyText(value)) {
|
||||
setCopied(value)
|
||||
window.setTimeout(() => setCopied(''), 1500)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 font-mono text-sm">
|
||||
<Link2 className="h-4 w-4 text-cyber-neon-cyan" />
|
||||
视频链接转博主主页
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-[11px] font-mono leading-relaxed">
|
||||
粘贴抖音视频链接或分享文案,一行一条,一次最多 20 条。
|
||||
解析走作品详情接口,需要一个能用的登录态。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
rows={5}
|
||||
placeholder={
|
||||
'https://www.douyin.com/video/7353137957861084427\n' +
|
||||
'7.42 复制打开抖音,看看【某某的作品】 https://v.douyin.com/iAbCdEf/\n' +
|
||||
'7353137957861084427'
|
||||
}
|
||||
className={TEXTAREA_CLASS}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => resolve.mutate(text)}
|
||||
disabled={!text.trim() || resolve.isPending}
|
||||
>
|
||||
{resolve.isPending ? (
|
||||
<Loader2 className="mr-1 h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<Link2 className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
{resolve.isPending ? '解析中…' : '解析'}
|
||||
</Button>
|
||||
|
||||
{results.length > 0 && (
|
||||
<>
|
||||
<span className="font-mono text-[11px] text-cyber-text-muted">
|
||||
共 {results.length} 条,成功 {okCount} 条,去重后 {uniqueProfiles.length} 个博主
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="ml-auto"
|
||||
disabled={uniqueProfiles.length === 0}
|
||||
onClick={() => copy(uniqueProfiles.join('\n'))}
|
||||
>
|
||||
{copied === uniqueProfiles.join('\n') ? (
|
||||
<Check className="mr-1 h-3 w-3" />
|
||||
) : (
|
||||
<Copy className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
复制全部主页
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{resolve.data?.truncated && (
|
||||
<p className="flex items-center gap-1 font-mono text-[11px] text-cyber-neon-orange">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
超过 20 条,只解析了前面的 20 条。
|
||||
</p>
|
||||
)}
|
||||
|
||||
{results.length > 0 && (
|
||||
<div className="max-h-[320px] space-y-1 overflow-y-auto terminal-scroll pr-1">
|
||||
{results.map((item, index) => (
|
||||
<div
|
||||
key={`${item.input}-${index}`}
|
||||
className="flex items-center gap-2 rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/60 px-2 py-1.5"
|
||||
>
|
||||
<span
|
||||
className={`h-1.5 w-1.5 flex-shrink-0 rounded-full ${
|
||||
item.ok ? 'bg-cyber-neon-green' : 'bg-cyber-neon-pink'
|
||||
}`}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
{item.ok ? (
|
||||
<>
|
||||
<div className="truncate font-mono text-[11px] text-cyber-text-primary">
|
||||
{item.nickname || '(无昵称)'}
|
||||
</div>
|
||||
<a
|
||||
href={item.profile_url}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="block truncate font-mono text-[10px] text-cyber-neon-cyan hover:underline"
|
||||
>
|
||||
{item.profile_url}
|
||||
</a>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="truncate font-mono text-[10px] text-cyber-text-muted">
|
||||
{item.input}
|
||||
</div>
|
||||
<div className="truncate font-mono text-[10px] text-cyber-neon-pink">
|
||||
{item.error || '解析失败'}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{item.ok && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => copy(item.profile_url)}
|
||||
title="复制主页链接"
|
||||
>
|
||||
{copied === item.profile_url ? (
|
||||
<Check className="h-3 w-3" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
<a
|
||||
href={item.profile_url}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="text-cyber-text-muted hover:text-cyber-neon-cyan"
|
||||
title="在新标签页打开"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,17 @@
|
||||
import { useState } from 'react'
|
||||
import { Send, Trash2, Webhook } from 'lucide-react'
|
||||
import { Eye, Image, Send, Trash2, Webhook } from 'lucide-react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useClearWebhook, useSetWebhook, useTestWebhook, useWebhookStatus } from '@/hooks/useMonitor'
|
||||
import { monitorApi } from '@/lib/api'
|
||||
import { useCurrentPlatform } from '@/hooks/usePlatform'
|
||||
import {
|
||||
useClearWebhook,
|
||||
useSendDailyDigest,
|
||||
useSetWebhook,
|
||||
useTestWebhook,
|
||||
useWebhookStatus,
|
||||
} from '@/hooks/useMonitor'
|
||||
|
||||
/**
|
||||
* 企业微信机器人 Webhook 配置。
|
||||
@@ -16,6 +24,8 @@ export function WebhookPanel() {
|
||||
const setWebhook = useSetWebhook()
|
||||
const clearWebhook = useClearWebhook()
|
||||
const testWebhook = useTestWebhook()
|
||||
const sendDigest = useSendDailyDigest()
|
||||
const { platform } = useCurrentPlatform()
|
||||
|
||||
const [draft, setDraft] = useState('')
|
||||
const [editing, setEditing] = useState(false)
|
||||
@@ -24,7 +34,7 @@ export function WebhookPanel() {
|
||||
|
||||
return (
|
||||
<div className="rounded-lg glass-panel float-panel p-4 space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Webhook className="w-4 h-4 text-cyber-neon-cyan" />
|
||||
<span className="font-mono text-xs tracking-wider text-cyber-text-primary">
|
||||
@@ -41,32 +51,54 @@ export function WebhookPanel() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{status?.configured && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => testWebhook.mutate(undefined)}
|
||||
disabled={testWebhook.isPending}
|
||||
>
|
||||
<Send className="w-3 h-3 mr-1" />
|
||||
发测试
|
||||
</Button>
|
||||
{!editing && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditing(true)}>
|
||||
替换
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{/* 预览不依赖 Webhook —— 先看图长什么样,再决定要不要开推送。 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
window.open(monitorApi.dailyDigestPreviewUrl(platform), '_blank', 'noopener')
|
||||
}
|
||||
>
|
||||
<Eye className="w-3 h-3 mr-1" />
|
||||
预览昨天
|
||||
</Button>
|
||||
{status?.configured && (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => sendDigest.mutate()}
|
||||
disabled={sendDigest.isPending}
|
||||
>
|
||||
<Image className="w-3 h-3 mr-1" />
|
||||
发昨天图
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => clearWebhook.mutate()}
|
||||
disabled={clearWebhook.isPending}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => testWebhook.mutate(undefined)}
|
||||
disabled={testWebhook.isPending}
|
||||
>
|
||||
<Send className="w-3 h-3 mr-1" />
|
||||
发测试
|
||||
</Button>
|
||||
{!editing && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditing(true)}>
|
||||
替换
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => clearWebhook.mutate()}
|
||||
disabled={clearWebhook.isPending}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{status?.configured && !editing && (
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { formatCount, formatDelta } from '@/lib/monitorFormat'
|
||||
import type { NoteMetrics } from '@/types/monitor'
|
||||
|
||||
/**
|
||||
* 四项指标列 + 单元格。
|
||||
*
|
||||
* 单独一个模块,是因为**表格和行都要用它** —— 行已经拆成独立的 `NoteRow`,而它再去
|
||||
* 从 `NotesTable` 里 import 就成环了。
|
||||
*/
|
||||
|
||||
/** A metric with its change vs the previous run underneath. */
|
||||
export function MetricCell({ value, delta }: { value: number | null; delta: number | null }) {
|
||||
const deltaText = formatDelta(delta)
|
||||
return (
|
||||
<div className="text-right">
|
||||
<div className="font-mono text-xs text-cyber-text-primary">{formatCount(value)}</div>
|
||||
{deltaText && (
|
||||
<div
|
||||
className={`font-mono text-[9px] ${
|
||||
(delta ?? 0) > 0 ? 'text-cyber-neon-green' : 'text-cyber-neon-pink'
|
||||
}`}
|
||||
>
|
||||
{deltaText}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const METRIC_COLUMNS: Array<{ key: keyof NoteMetrics; label: string }> = [
|
||||
{ key: 'liked_count', label: '点赞' },
|
||||
{ key: 'comment_count', label: '评论' },
|
||||
{ key: 'collected_count', label: '收藏' },
|
||||
{ key: 'share_count', label: '分享' },
|
||||
]
|
||||
|
||||
// 多出来的那几列:展开箭头、作品、发布日期、首次发现;分组表头会跨掉整行。
|
||||
// 作品的跳转链接**不算一列** —— 它跟在标题后面。
|
||||
export const COLUMN_COUNT = METRIC_COLUMNS.length + 4
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { ExternalLink, MonitorPlay, RotateCw } from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
/**
|
||||
* 服务器上那个浏览器的**实时画面** —— 就是定时任务接管的那一个。
|
||||
*
|
||||
* 用途只有一个:**过验证码**。抖音/小红书弹滑块或短信验证时,采集会静默失败
|
||||
* (网关回 200 + 空 body,看起来像「这个博主没作品」),人在这个画面里点一下就好了,
|
||||
* 不用跑到机器跟前。
|
||||
*
|
||||
* 走 noVNC(websockify 在宿主机上起的静态站)。
|
||||
*
|
||||
* **别把它当成「看采集结果」的地方** —— 结果是作品栏和报表,这里是浏览器本身。
|
||||
*/
|
||||
|
||||
// websockify 监听的端口。和 18051 这个应用不是同一个,所以**必须**是绝对地址。
|
||||
const VNC_PORT = 6080
|
||||
|
||||
// 特意**留空**:服务端那边密码去掉之后,地址里不传 password 就不会弹框。
|
||||
//
|
||||
// 千万不要把密码写死在这里 —— 它会进 git 历史,还会打进前端产物,而任何能打开
|
||||
// 这个页面的人都能看到。要密码就打进 noVNC 自己的框里,或者去服务端把密码去掉。
|
||||
const VNC_PASSWORD = ''
|
||||
|
||||
/** 拼 noVNC 的地址。主机名取自当前页面,所以换域名/IP 访问都能用。 */
|
||||
function viewerUrl(host: string, password: string): string {
|
||||
const params = new URLSearchParams({
|
||||
autoconnect: '1',
|
||||
// 让远程画面缩放到容器大小,而不是撑出滚动条。
|
||||
resize: 'scale',
|
||||
// 掉线自己重连,省得每次断线都要手动点。
|
||||
reconnect: '1',
|
||||
reconnect_delay: '2000',
|
||||
})
|
||||
if (password) params.set('password', password)
|
||||
return `http://${host}:${VNC_PORT}/vnc.html?${params.toString()}`
|
||||
}
|
||||
|
||||
export function RemoteBrowserPanel() {
|
||||
const [nonce, setNonce] = useState(0)
|
||||
|
||||
const url = useMemo(
|
||||
() => viewerUrl(window.location.hostname, VNC_PASSWORD),
|
||||
// nonce 变化 = 用户点了「重连」,靠换 key 强制 iframe 重新加载。
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[nonce],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0 rounded-lg border border-cyber-border-subtle bg-cyber-bg-secondary/40 overflow-hidden">
|
||||
<div className="flex items-center gap-2 px-3 py-2 border-b border-cyber-border-subtle bg-cyber-bg-tertiary/60 flex-shrink-0">
|
||||
<MonitorPlay className="w-3.5 h-3.5 text-cyber-neon-cyan flex-shrink-0" />
|
||||
<span className="text-[11px] font-mono text-cyber-text-primary">远程浏览器</span>
|
||||
<span className="text-[10px] font-mono text-cyber-text-muted truncate">
|
||||
采集用的那个 · 弹验证码时在这里点
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1 flex-shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-1.5"
|
||||
title="重新连接"
|
||||
onClick={() => setNonce((value) => value + 1)}
|
||||
>
|
||||
<RotateCw className="w-3 h-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-1.5"
|
||||
title="在新窗口打开"
|
||||
onClick={() => window.open(url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* iframe 而不是 window.open:要的就是「抬眼就能看见」,而不是再开一个标签页。
|
||||
noVNC 那边不发 X-Frame-Options,所以嵌得进来。 */}
|
||||
<iframe
|
||||
key={nonce}
|
||||
src={url}
|
||||
title="远程浏览器"
|
||||
className="flex-1 min-h-0 w-full bg-black"
|
||||
allow="clipboard-read; clipboard-write"
|
||||
/>
|
||||
|
||||
<p className="px-3 py-1.5 text-[10px] font-mono text-cyber-text-muted border-t border-cyber-border-subtle flex-shrink-0">
|
||||
连不上就说明宿主机上的 websockify 没在跑(`{window.location.hostname}:{VNC_PORT}`)。
|
||||
这个画面里就是服务器的浏览器本人,能看到你所有登录态 —— 只在局域网里用。
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,8 +3,11 @@ import { KeyRound, QrCode, Save } from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { CookiePanel } from '@/components/monitor/CookiePanel'
|
||||
import { IdentityPanel } from '@/components/monitor/IdentityPanel'
|
||||
import { QrLoginPanel } from '@/components/monitor/QrLoginPanel'
|
||||
import { RemoteBrowserPanel } from '@/components/settings/RemoteBrowserPanel'
|
||||
import { Section, SettingField } from '@/components/settings/SettingFields'
|
||||
import { TagSettings } from '@/components/settings/TagSettings'
|
||||
import { useSettings, useUpdateSettings } from '@/hooks/useMonitor'
|
||||
import { useCurrentPlatform } from '@/hooks/usePlatform'
|
||||
import { useCrawlerStore } from '@/store/crawlerStore'
|
||||
@@ -55,8 +58,9 @@ export function SettingsView({ onNavigate }: { onNavigate?: (view: AppView) => v
|
||||
const label = capability?.label ?? platform
|
||||
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto terminal-scroll pr-1">
|
||||
<div className="max-w-3xl space-y-3 pb-6">
|
||||
<div className="flex-1 flex gap-4 min-h-0">
|
||||
{/* max-w-3xl 是为了让设置项保持好读的行宽;右边那块画面把剩下的宽度拿走。 */}
|
||||
<div className="flex-1 max-w-3xl overflow-y-auto terminal-scroll pr-1 min-w-0 space-y-3 pb-6">
|
||||
<div className="rounded-lg border border-cyber-neon-cyan/30 bg-cyber-neon-cyan/5 px-4 py-2">
|
||||
<p className="text-[11px] font-mono text-cyber-text-secondary">
|
||||
当前平台:
|
||||
@@ -75,6 +79,8 @@ export function SettingsView({ onNavigate }: { onNavigate?: (view: AppView) => v
|
||||
scan lands in the very browser profile the monitor runs reuse. */}
|
||||
<QrLoginPanel />
|
||||
<CookiePanel />
|
||||
{/* 身份池只有抖音接:那套进程内采集才能按账号分片,小红书走子进程。 */}
|
||||
{platform === 'dy' && <IdentityPanel />}
|
||||
|
||||
<div className="pt-3 mt-1 border-t border-cyber-border-subtle space-y-2">
|
||||
<p className="text-[10px] font-mono text-cyber-text-muted leading-relaxed">
|
||||
@@ -97,6 +103,8 @@ export function SettingsView({ onNavigate }: { onNavigate?: (view: AppView) => v
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<TagSettings />
|
||||
|
||||
<Section
|
||||
title="采集策略"
|
||||
description="各平台风控容忍度不同,因此按平台分别配置。"
|
||||
@@ -139,6 +147,14 @@ export function SettingsView({ onNavigate }: { onNavigate?: (view: AppView) => v
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 右边常驻一块服务器浏览器的实时画面 —— 弹验证码时要能抬眼就看见、伸手就能点,
|
||||
而不是「切页面 → 找入口 → 等加载」。
|
||||
**让它吃掉剩下的宽度**,而不是固定一个窄条:远程桌面是 1920×1080,面板越窄,
|
||||
noVNC 缩放出来的画面越小,窄条上看验证码基本没法看。 */}
|
||||
<aside className="flex-1 min-w-[380px] min-h-0">
|
||||
<RemoteBrowserPanel />
|
||||
</aside>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import { useState } from 'react'
|
||||
import { Check, Pencil, Plus, Trash2, X } from 'lucide-react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Section } from '@/components/settings/SettingFields'
|
||||
import { useCreateTag, useDeleteTag, useMonitorTags, useUpdateTag } from '@/hooks/useMonitor'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { TAG_COLOR_CHOICES, tagColorClass, tagColorLabel } from '@/lib/tagColors'
|
||||
import type { MonitorTag } from '@/types/monitor'
|
||||
|
||||
/**
|
||||
* 标签词表 —— 作品上能贴的标签在这里维护。
|
||||
*
|
||||
* 这是一份**封闭的词表**,而不是让每人在作品上随手写:分类只有在词固定下来之后才能
|
||||
* 用来筛选,否则「重点 / 重要 / 优先」会各写各的,最后谁也筛不出东西。
|
||||
*
|
||||
* 它和「作品备注」是两件事,所以没有合并:备注是一句话的自由文字(「这条标题起得好」),
|
||||
* 需要的是自由;标签是分类,需要的恰好是封闭。
|
||||
*/
|
||||
export function TagSettings() {
|
||||
const { data: tags, isLoading } = useMonitorTags()
|
||||
const createTag = useCreateTag()
|
||||
const updateTag = useUpdateTag()
|
||||
const deleteTag = useDeleteTag()
|
||||
|
||||
const [draftName, setDraftName] = useState('')
|
||||
const [draftColor, setDraftColor] = useState<string>(TAG_COLOR_CHOICES[0])
|
||||
const [draftKeywords, setDraftKeywords] = useState('')
|
||||
// 正在改名的那一个(标签 id)。
|
||||
const [editingId, setEditingId] = useState<number | null>(null)
|
||||
const [editName, setEditName] = useState('')
|
||||
const [editColor, setEditColor] = useState<string>(TAG_COLOR_CHOICES[0])
|
||||
const [editKeywords, setEditKeywords] = useState('')
|
||||
|
||||
const submit = () => {
|
||||
const name = draftName.trim()
|
||||
if (!name) return
|
||||
createTag.mutate(
|
||||
{ name, color: draftColor, keywords: draftKeywords },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setDraftName('')
|
||||
setDraftKeywords('')
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const startEdit = (tag: MonitorTag) => {
|
||||
setEditingId(tag.id)
|
||||
setEditName(tag.name)
|
||||
setEditColor(tag.color)
|
||||
setEditKeywords(tag.keywords)
|
||||
}
|
||||
|
||||
const saveEdit = () => {
|
||||
if (editingId === null) return
|
||||
const name = editName.trim()
|
||||
if (!name) return
|
||||
updateTag.mutate({ id: editingId, name, color: editColor, keywords: editKeywords })
|
||||
setEditingId(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<Section
|
||||
title="作品标签"
|
||||
description="作品上能贴的标签在这里维护。剪掉一个标签,所有作品上的它也会一起消失。"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
{isLoading && (
|
||||
<p className="text-[11px] font-mono text-cyber-text-muted">加载中…</p>
|
||||
)}
|
||||
{tags?.length === 0 && (
|
||||
<p className="text-[11px] font-mono text-cyber-text-muted">
|
||||
还没有标签。在下面加一个,比如「重点」「竞品」。
|
||||
</p>
|
||||
)}
|
||||
|
||||
{tags?.map((tag) =>
|
||||
editingId === tag.id ? (
|
||||
<div key={tag.id} className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
autoFocus
|
||||
value={editName}
|
||||
onChange={(event) => setEditName(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') saveEdit()
|
||||
if (event.key === 'Escape') setEditingId(null)
|
||||
}}
|
||||
className="w-32 rounded border border-cyber-neon-cyan/40 bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none"
|
||||
/>
|
||||
<ColorPicker value={editColor} onChange={setEditColor} />
|
||||
<input
|
||||
value={editKeywords}
|
||||
placeholder="关键词,逗号分隔:szgtdzb,探店"
|
||||
title="标题里出现其中任意一个就自动贴上这条标签"
|
||||
onChange={(event) => setEditKeywords(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') saveEdit()
|
||||
if (event.key === 'Escape') setEditingId(null)
|
||||
}}
|
||||
className="w-64 rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
/>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5" onClick={saveEdit}>
|
||||
<Check className="w-3 h-3 text-cyber-neon-green" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-1.5"
|
||||
onClick={() => setEditingId(null)}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div key={tag.id} className="flex items-center gap-2">
|
||||
<Badge
|
||||
className={cn('text-[10px] px-1.5 py-0', tagColorClass(tag.color))}
|
||||
variant="outline"
|
||||
>
|
||||
{tag.name}
|
||||
</Badge>
|
||||
{/* 规则直接摆出来 —— 「这条标签为什么会自动贴上」得一眼看得出来。 */}
|
||||
{tag.keywords ? (
|
||||
<span className="text-[10px] font-mono text-cyber-text-secondary truncate max-w-[240px]">
|
||||
命中「{tag.keywords}」
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[10px] font-mono text-cyber-text-muted">
|
||||
没配关键词(只能手动贴)
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[10px] font-mono text-cyber-text-muted flex-shrink-0">
|
||||
{tag.note_count > 0 ? `${tag.note_count} 条作品` : '还没用过'}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-1.5"
|
||||
title="改名 / 换颜色"
|
||||
onClick={() => startEdit(tag)}
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-1.5 hover:text-cyber-neon-pink"
|
||||
title={
|
||||
tag.note_count > 0
|
||||
? `删除后会从 ${tag.note_count} 条作品上一并消失`
|
||||
: '删除'
|
||||
}
|
||||
// 用过才确认 —— 0 条的那种点错了也没代价,多一次弹窗只是烦。
|
||||
onClick={() => {
|
||||
if (
|
||||
tag.note_count === 0 ||
|
||||
window.confirm(
|
||||
`「${tag.name}」正贴在 ${tag.note_count} 条作品上,删掉之后它们也会一并摘掉。继续?`,
|
||||
)
|
||||
) {
|
||||
deleteTag.mutate(tag.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 pt-2 mt-1 border-t border-cyber-border-subtle">
|
||||
<input
|
||||
value={draftName}
|
||||
placeholder="新标签,比如「大字报」"
|
||||
onChange={(event) => setDraftName(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') submit()
|
||||
}}
|
||||
className="w-32 rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
/>
|
||||
<ColorPicker value={draftColor} onChange={setDraftColor} />
|
||||
<input
|
||||
value={draftKeywords}
|
||||
placeholder="关键词,逗号分隔:szgtdzb,探店"
|
||||
title="标题里出现其中任意一个就自动贴上这条标签"
|
||||
onChange={(event) => setDraftKeywords(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') submit()
|
||||
}}
|
||||
className="w-64 rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
/>
|
||||
<Button size="sm" disabled={!draftName.trim() || createTag.isPending} onClick={submit}>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
添加
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-[10px] font-mono text-cyber-text-muted leading-relaxed">
|
||||
配了关键词的标签会
|
||||
<span className="text-cyber-text-secondary"> 自动贴上 </span>
|
||||
:作品标题里出现其中任意一个就贴,命中几条规则就贴几个标签。匹配的是标题里的子串、
|
||||
不分大小写,所以关键词别定得太宽(只写「苏州」的话几乎每条都会被贴上)。
|
||||
<span className="text-cyber-text-secondary"> 只贴不摘 </span>
|
||||
—— 你手动摘掉的,下一轮采集不会又长回来。
|
||||
</p>
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 五个颜色的小圆点。**不是取色器** —— 颜色得是固定的几个,才能和主题对得上。 */
|
||||
function ColorPicker({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: string
|
||||
onChange: (color: string) => void
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
{TAG_COLOR_CHOICES.map((color) => (
|
||||
<button
|
||||
key={color}
|
||||
type="button"
|
||||
title={tagColorLabel(color)}
|
||||
onClick={() => onChange(color)}
|
||||
className={cn(
|
||||
'h-4 w-4 rounded-full border transition-all',
|
||||
tagColorClass(color),
|
||||
value === color
|
||||
? 'ring-1 ring-offset-1 ring-cyber-text-secondary ring-offset-cyber-bg-secondary'
|
||||
: 'opacity-60 hover:opacity-100',
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { monitorApi, settingsApi } from '@/lib/api'
|
||||
import { usePlatformStore } from '@/store/platformStore'
|
||||
import type { TaskCreatePayload } from '@/types/monitor'
|
||||
import type { SuperDirTaskPayload, TaskCreatePayload } from '@/types/monitor'
|
||||
|
||||
/**
|
||||
* The platform every monitor hook is scoped to.
|
||||
@@ -97,16 +97,90 @@ export function useTaskRuns(taskId: number | null) {
|
||||
})
|
||||
}
|
||||
|
||||
export function useMonitorNotes(taskId: number | null, onlyNew: boolean) {
|
||||
/**
|
||||
* 作品**和博主**一起取。
|
||||
*
|
||||
* 博主不能从作品推出来 —— 「一条作品都没有的博主」在作品表里根本不存在,而它恰恰是
|
||||
* 最该显示的一类。所以服务端单独给一份 `creators`,两者必须来自同一次请求,否则
|
||||
* 组头和组里的作品会对不上(比如刚删掉一个任务)。
|
||||
*/
|
||||
export function useMonitorNotes(
|
||||
taskId: number | null,
|
||||
onlyNew: boolean,
|
||||
tagIds: number[] = [],
|
||||
) {
|
||||
const platform = usePlatformParam()
|
||||
return useQuery({
|
||||
queryKey: ['monitorNotes', platform, taskId, onlyNew],
|
||||
queryKey: ['monitorNotes', platform, taskId, onlyNew, tagIds],
|
||||
queryFn: async () =>
|
||||
(await monitorApi.getNotes(taskId ?? undefined, onlyNew, 200, platform)).data.notes,
|
||||
(await monitorApi.getNotes(taskId ?? undefined, onlyNew, 200, platform, tagIds)).data,
|
||||
refetchInterval: POLL_MS,
|
||||
})
|
||||
}
|
||||
|
||||
// --- 标签 ------------------------------------------------------------------
|
||||
|
||||
export function useMonitorTags() {
|
||||
return useQuery({
|
||||
queryKey: ['monitorTags'],
|
||||
queryFn: async () => (await monitorApi.listTags()).data.tags,
|
||||
// 词表是人手工维护的,没有别的写入方,不用频繁刷。
|
||||
staleTime: 60_000,
|
||||
})
|
||||
}
|
||||
|
||||
/** 标签变了要让作品列表重取 —— 标签是画在作品行上的。 */
|
||||
function useTagMutation<TArgs>(
|
||||
mutationFn: (args: TArgs) => Promise<unknown>,
|
||||
successMessage: string,
|
||||
) {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn,
|
||||
onSuccess: () => {
|
||||
toast.success(successMessage)
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorTags'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorNotes'] })
|
||||
},
|
||||
onError: (error: Error) => toast.error(`操作失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateTag() {
|
||||
return useTagMutation(
|
||||
({ name, color, keywords }: { name: string; color: string; keywords: string }) =>
|
||||
monitorApi.createTag(name, color, keywords),
|
||||
'标签已创建',
|
||||
)
|
||||
}
|
||||
|
||||
export function useUpdateTag() {
|
||||
return useTagMutation(
|
||||
({ id, name, color, keywords }: { id: number; name: string; color: string; keywords: string }) =>
|
||||
monitorApi.updateTag(id, name, color, keywords),
|
||||
'标签已保存',
|
||||
)
|
||||
}
|
||||
|
||||
export function useDeleteTag() {
|
||||
return useTagMutation((id: number) => monitorApi.deleteTag(id), '标签已删除')
|
||||
}
|
||||
|
||||
export function useSetNoteTags() {
|
||||
const queryClient = useQueryClient()
|
||||
const platform = usePlatformParam()
|
||||
return useMutation({
|
||||
mutationFn: ({ noteId, tagIds }: { noteId: string; tagIds: number[] }) =>
|
||||
monitorApi.setNoteTags(noteId, tagIds, platform),
|
||||
onSuccess: () => {
|
||||
// 不打 toast:贴标签是个连着点好几次的动作,每次都弹一条会把屏幕刷满。
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorNotes'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorTags'] })
|
||||
},
|
||||
onError: (error: Error) => toast.error(`标签保存失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
export function useNoteSeries(noteId: string | null, taskId: number | null) {
|
||||
return useQuery({
|
||||
queryKey: ['monitorNoteSeries', noteId, taskId],
|
||||
@@ -353,7 +427,100 @@ export function useTestWebhook() {
|
||||
})
|
||||
}
|
||||
|
||||
// --- 上游更新检查 ----------------------------------------------------------
|
||||
/** 手动推一次「昨天的视频情况」图。定时那条由后端调度器负责。 */
|
||||
export function useSendDailyDigest() {
|
||||
const platform = usePlatformParam()
|
||||
return useMutation({
|
||||
mutationFn: async () => (await monitorApi.sendDailyDigest(platform)).data,
|
||||
onSuccess: (result) =>
|
||||
toast.success(`已发送昨天的视频情况图(${result.rows} 条),请查看企业微信群`),
|
||||
onError: (error: Error) => toast.error(`发送失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
// --- 视频链接 → 博主主页 ---------------------------------------------------
|
||||
|
||||
export function useResolveVideoLinks() {
|
||||
return useMutation({
|
||||
mutationFn: async (text: string) => (await monitorApi.resolveVideoLinks(text)).data,
|
||||
// 单条失败在结果里各自有 error,这里只管整批都没走到的情况(网络、鉴权)。
|
||||
onError: (error: Error) => toast.error(`解析失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
// --- 超级编导导入 ----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 按创建时间区间查超级编导上的作品链接。
|
||||
*
|
||||
* 是 mutation 不是 query:点「查询」才发请求,日期还没选好、打开弹窗的那一刻不该
|
||||
* 就去翻一遍全部活动 —— 那个接口没有日期过滤,每次都挺贵。
|
||||
*/
|
||||
export function useSuperDirPreview() {
|
||||
return useMutation({
|
||||
mutationFn: async ({ start, end }: { start: string; end: string }) =>
|
||||
(await monitorApi.previewSuperDir(start, end)).data,
|
||||
onError: (error: Error) => toast.error(`查询失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateSuperDirTask() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async (payload: SuperDirTaskPayload) =>
|
||||
(await monitorApi.createSuperDirTask(payload)).data,
|
||||
onSuccess: (result, payload) => {
|
||||
if (payload.task_id !== null) {
|
||||
toast.success(
|
||||
result.added > 0
|
||||
? `已追加 ${result.added} 条,任务现在共 ${result.targets} 条`
|
||||
: '没有新作品可追加',
|
||||
)
|
||||
} else {
|
||||
toast.success(`已建监控任务,共 ${result.targets} 条作品`)
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorTasks'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorOverview'] })
|
||||
},
|
||||
onError: (error: Error) => toast.error(`建任务失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
// --- 博主备注 --------------------------------------------------------------
|
||||
|
||||
export function useSetCreatorAlias() {
|
||||
const queryClient = useQueryClient()
|
||||
const platform = usePlatformParam()
|
||||
return useMutation({
|
||||
mutationFn: ({ creatorHash, alias }: { creatorHash: string; alias: string }) =>
|
||||
monitorApi.setCreatorAlias(creatorHash, alias, platform),
|
||||
onSuccess: () => {
|
||||
toast.success('备注已保存')
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorNotes'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorCommentsGrouped'] })
|
||||
},
|
||||
onError: (error: Error) => toast.error(`备注保存失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
// --- 作品备注 --------------------------------------------------------------
|
||||
|
||||
export function useSetNoteAlias() {
|
||||
const queryClient = useQueryClient()
|
||||
const platform = usePlatformParam()
|
||||
return useMutation({
|
||||
mutationFn: ({ noteId, alias }: { noteId: string; alias: string }) =>
|
||||
monitorApi.setNoteAlias(noteId, alias, platform),
|
||||
onSuccess: () => {
|
||||
toast.success('备注已保存')
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorNotes'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorCommentsGrouped'] })
|
||||
},
|
||||
onError: (error: Error) => toast.error(`备注保存失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
// --- 上游更新检查 -----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
export function useUpstreamStatus() {
|
||||
return useQuery({
|
||||
@@ -382,3 +549,81 @@ export function useCheckUpstream() {
|
||||
onError: (error: Error) => toast.error(`检查失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
// --- 身份池(抖音多登录态) ------------------------------------------------
|
||||
|
||||
export function useMonitorIdentities() {
|
||||
const platform = usePlatformParam()
|
||||
return useQuery({
|
||||
queryKey: ['monitorIdentities', platform],
|
||||
queryFn: async () => (await monitorApi.listIdentities(platform)).data.identities,
|
||||
// 状态会随着采集轮次变化,慢点刷就够了。
|
||||
refetchInterval: 15_000,
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateIdentity() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (payload: {
|
||||
label: string
|
||||
cookie: string
|
||||
user_agent?: string
|
||||
platform?: string
|
||||
}) => monitorApi.createIdentity(payload),
|
||||
onSuccess: () => {
|
||||
toast.success('身份已添加')
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorIdentities'] })
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
// 后端会把「拿不到 UA」这类原因写在 detail 里,axios 默认会把它压成状态码。
|
||||
const detail = (error as { response?: { data?: { detail?: string } } })?.response
|
||||
?.data?.detail
|
||||
toast.error(`添加失败:${detail ?? error.message}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdateIdentity() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
id,
|
||||
payload,
|
||||
}: {
|
||||
id: number
|
||||
payload: Partial<{ label: string; cookie: string; user_agent: string; enabled: boolean }>
|
||||
}) => monitorApi.updateIdentity(id, payload),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['monitorIdentities'] }),
|
||||
onError: (error: Error) => toast.error(`更新失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteIdentity() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => monitorApi.deleteIdentity(id),
|
||||
onSuccess: () => {
|
||||
toast.success('身份已删除')
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorIdentities'] })
|
||||
},
|
||||
onError: (error: Error) => toast.error(`删除失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
export function useCheckIdentity() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => monitorApi.checkIdentity(id),
|
||||
onSuccess: (response) => {
|
||||
const data = response.data
|
||||
if (data.ok) {
|
||||
toast.success(data.verified ? '验证通过' : '格式检查通过(没有可探测的博主)')
|
||||
} else {
|
||||
toast.error(`不可用:${data.error || '未知原因'}`)
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['monitorIdentities'] })
|
||||
},
|
||||
onError: (error: Error) => toast.error(`验证失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
+37
-11
@@ -414,6 +414,7 @@
|
||||
============================ */
|
||||
|
||||
.status-dot {
|
||||
position: relative;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
@@ -421,8 +422,42 @@
|
||||
|
||||
.status-dot-online {
|
||||
background: rgb(var(--cyber-neon-green));
|
||||
box-shadow: 0 0 8px rgb(var(--cyber-neon-green) / 0.6);
|
||||
animation: pulseGlow 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/*
|
||||
「在线」圆点的呼吸光晕。
|
||||
|
||||
**绝不要把 box-shadow 放进无限动画里。** 这是踩过的坑,而且是量出来的:
|
||||
box-shadow 不可合成,每一帧都要整块重新光栅化;动画写成 infinite,页面就从
|
||||
打开那一刻起永不空闲。这个圆点在监控页上有好几处(登录态、webhook、每个任务卡、
|
||||
常驻侧边栏),而它们背后又全是 backdrop-filter 玻璃面板 —— 每次重绘都连带把
|
||||
模糊整块重算,4 个 8 像素的小点就足以让浏览器持续满负荷。
|
||||
|
||||
CDP trace 实测(静置 6 秒,页面上 4 个这样的圆点):
|
||||
|
||||
动画动 box-shadow :光栅任务 2115 次 / 689ms,GPU 2115 次 / 699ms,主帧 790
|
||||
动画只动 opacity :光栅任务 4 次 / 1ms,GPU 5 次 / 1ms,主帧 0
|
||||
|
||||
差三个数量级。所以光晕画在伪元素上,动画只改 opacity —— 那由合成器处理,
|
||||
不触发重绘。
|
||||
*/
|
||||
.status-dot-online::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 50%;
|
||||
box-shadow:
|
||||
0 0 6px rgb(var(--cyber-neon-green) / 0.9),
|
||||
0 0 14px rgb(var(--cyber-neon-green) / 0.5);
|
||||
/* 明确要求提升为合成层,否则这个 8px 的伪元素未必会被提升,
|
||||
opacity 动画就会退化成所属图层的重绘。 */
|
||||
will-change: opacity;
|
||||
animation: statusDotGlow 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes statusDotGlow {
|
||||
0%, 100% { opacity: 0.35; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
|
||||
.status-dot-offline {
|
||||
@@ -439,15 +474,6 @@
|
||||
box-shadow: 0 0 8px rgb(var(--cyber-neon-pink) / 0.6);
|
||||
}
|
||||
|
||||
@keyframes pulseGlow {
|
||||
0%, 100% {
|
||||
box-shadow: 0 0 5px currentColor;
|
||||
}
|
||||
50% {
|
||||
box-shadow: 0 0 15px currentColor, 0 0 25px currentColor;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================
|
||||
Input Focus Ring
|
||||
============================ */
|
||||
|
||||
+103
-3
@@ -5,18 +5,25 @@ import type {
|
||||
CookieStatus,
|
||||
MetricPoint,
|
||||
MonitorComment,
|
||||
MonitorCreator,
|
||||
MonitorEvent,
|
||||
MonitorIdentity,
|
||||
MonitorNote,
|
||||
MonitorOverview,
|
||||
MonitorRun,
|
||||
MonitorTag,
|
||||
MonitorTask,
|
||||
LoginState,
|
||||
PlatformCapability,
|
||||
QrLoginState,
|
||||
ReportResult,
|
||||
SettingsResponse,
|
||||
SuperDirPreviewResponse,
|
||||
SuperDirTaskPayload,
|
||||
SuperDirTaskResult,
|
||||
TaskCreatePayload,
|
||||
UpstreamStatus,
|
||||
VideoLinkResolveResponse,
|
||||
WebhookStatus,
|
||||
} from '@/types/monitor'
|
||||
import type {
|
||||
@@ -185,9 +192,16 @@ export const monitorApi = {
|
||||
getRuns: (id: number, limit = 50) =>
|
||||
api.get<{ runs: MonitorRun[] }>(`/monitor/tasks/${id}/runs`, { params: { limit } }),
|
||||
|
||||
getNotes: (taskId?: number, onlyNew = false, limit = 200, platform?: string) =>
|
||||
api.get<{ notes: MonitorNote[] }>('/monitor/notes', {
|
||||
params: { task_id: taskId, only_new: onlyNew, limit, platform },
|
||||
getNotes: (
|
||||
taskId?: number,
|
||||
onlyNew = false,
|
||||
limit = 200,
|
||||
platform?: string,
|
||||
tagIds?: number[],
|
||||
) =>
|
||||
api.get<{ notes: MonitorNote[]; creators: MonitorCreator[] }>('/monitor/notes', {
|
||||
// tag_id 可重复传 —— axios 会把数组序列化成 tag_id=1&tag_id=2,正是后端要的形状。
|
||||
params: { task_id: taskId, only_new: onlyNew, limit, platform, tag_id: tagIds },
|
||||
}),
|
||||
// Metric time series for one note; the chart reads this.
|
||||
getNoteSeries: (noteId: string, taskId?: number) =>
|
||||
@@ -253,6 +267,28 @@ export const monitorApi = {
|
||||
clearCookie: (platform?: string) =>
|
||||
api.delete('/monitor/cookie', { params: { platform } }),
|
||||
|
||||
// --- 身份池(抖音多登录态,串行分片) ------------------------------------
|
||||
listIdentities: (platform?: string) =>
|
||||
api.get<{ identities: MonitorIdentity[] }>('/monitor/identities', {
|
||||
params: { platform },
|
||||
}),
|
||||
createIdentity: (payload: {
|
||||
label: string
|
||||
cookie: string
|
||||
user_agent?: string
|
||||
platform?: string
|
||||
}) => api.post<MonitorIdentity>('/monitor/identities', payload),
|
||||
updateIdentity: (
|
||||
id: number,
|
||||
payload: Partial<{ label: string; cookie: string; user_agent: string; enabled: boolean }>,
|
||||
) => api.patch<MonitorIdentity>(`/monitor/identities/${id}`, payload),
|
||||
deleteIdentity: (id: number) => api.delete(`/monitor/identities/${id}`),
|
||||
/** 真去请求一次,验证这份身份还能不能用。 */
|
||||
checkIdentity: (id: number) =>
|
||||
api.post<{ ok: boolean; verified: boolean; error: string }>(
|
||||
`/monitor/identities/${id}/check`,
|
||||
),
|
||||
|
||||
// task_id is repeated (?task_id=1&task_id=2) rather than comma-joined, so the
|
||||
// query string is built by hand instead of relying on axios array encoding,
|
||||
// which would emit "task_id[]=" that FastAPI does not match.
|
||||
@@ -276,12 +312,76 @@ export const monitorApi = {
|
||||
api.get<LoginState>('/monitor/login/state', { params: { force } }),
|
||||
|
||||
getWebhook: () => api.get<WebhookStatus>('/monitor/webhook'),
|
||||
/**
|
||||
* 视频链接/分享文案 → 博主主页。
|
||||
*
|
||||
* 后端逐条串行请求详情接口(一次最多 20 条),所以超时给得比默认的 30 秒宽 ——
|
||||
* 按 30 秒算会把一批本来能解析完的链接误报成失败。
|
||||
*/
|
||||
resolveVideoLinks: (text: string) =>
|
||||
api.post<VideoLinkResolveResponse>('/monitor/video-links', { text }, { timeout: 90_000 }),
|
||||
|
||||
/**
|
||||
* 超级编导:按活动创建时间区间列出作品链接(只读,不写库)。
|
||||
*
|
||||
* 活动列表没有日期过滤,后端得全量翻页再本地筛,所以区间越大不一定越慢 ——
|
||||
* 真正决定耗时的是团队历史活动总量。超时按 2 分钟给,别把一次正常的慢查询报成失败。
|
||||
*/
|
||||
previewSuperDir: (start: string, end: string) =>
|
||||
api.post<SuperDirPreviewResponse>(
|
||||
'/monitor/superdir/preview',
|
||||
{ start, end },
|
||||
{ timeout: 120_000 },
|
||||
),
|
||||
/** 把预览出来的链接建成一个作品监控任务,或追加到已有任务(评论默认不抓)。 */
|
||||
createSuperDirTask: (payload: SuperDirTaskPayload) =>
|
||||
api.post<SuperDirTaskResult>('/monitor/superdir/tasks', payload, { timeout: 60_000 }),
|
||||
/** 昨天视频情况图:手动发一次(每天早上那条由后端按设置触发)。 */
|
||||
sendDailyDigest: (platform?: string) =>
|
||||
api.post<{ ok: boolean; rows: number; detail: string }>('/monitor/digest/send', null, {
|
||||
params: { platform },
|
||||
}),
|
||||
/** 预览图 —— 直接给 <img>/window.open 用,不带 Authorization 头,靠 cookie。 */
|
||||
dailyDigestPreviewUrl: (platform?: string) =>
|
||||
`/api/monitor/digest/preview${platform ? `?platform=${platform}` : ''}`,
|
||||
setWebhook: (url: string) => api.post('/monitor/webhook', { url }),
|
||||
clearWebhook: () => api.delete('/monitor/webhook'),
|
||||
testWebhook: (url?: string) => api.post('/monitor/webhook/test', { url: url ?? null }),
|
||||
|
||||
/** 最近一次上游检查的缓存结果;没有查过时是空对象。 */
|
||||
getUpstream: () => api.get<UpstreamStatus>('/monitor/upstream'),
|
||||
|
||||
/** 给博主起备注(空串 = 清掉)。键是 creator_hash,跨任务同一个博主共用一条。 */
|
||||
setCreatorAlias: (creatorHash: string, alias: string, platform?: string) =>
|
||||
api.put(
|
||||
`/monitor/creators/${encodeURIComponent(creatorHash)}`,
|
||||
{ alias },
|
||||
{ params: { platform } },
|
||||
),
|
||||
// --- 标签 ---------------------------------------------------------------
|
||||
|
||||
/** 标签词表(设置页维护),带各自被用在多少条作品上。 */
|
||||
listTags: () => api.get<{ tags: MonitorTag[] }>('/monitor/tags'),
|
||||
createTag: (name: string, color = '', keywords = '') =>
|
||||
api.post<MonitorTag>('/monitor/tags', { name, color, keywords }),
|
||||
updateTag: (id: number, name: string, color = '', keywords = '') =>
|
||||
api.put<MonitorTag>(`/monitor/tags/${id}`, { name, color, keywords }),
|
||||
deleteTag: (id: number) => api.delete<{ removed: number }>(`/monitor/tags/${id}`),
|
||||
/** 把一条作品的标签**整体替换**成这一组。空数组 = 全摘掉。 */
|
||||
setNoteTags: (noteId: string, tagIds: number[], platform?: string) =>
|
||||
api.put(
|
||||
`/monitor/notes/${encodeURIComponent(noteId)}/tags`,
|
||||
{ tag_ids: tagIds },
|
||||
{ params: { platform } },
|
||||
),
|
||||
|
||||
/** 给作品起备注(空串 = 清掉)。键是 note_id —— 和博主备注是两回事。 */
|
||||
setNoteAlias: (noteId: string, alias: string, platform?: string) =>
|
||||
api.put(
|
||||
`/monitor/notes/${encodeURIComponent(noteId)}`,
|
||||
{ alias },
|
||||
{ params: { platform } },
|
||||
),
|
||||
/**
|
||||
* 立刻检查一次。服务端要等 fetch 跑完才回答,而 axios 默认 30 秒对此不够 ——
|
||||
* 一条卡住的 git fetch 能拖到两分钟,这里必须单独放长超时,否则会误报失败。
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* 复制文本。
|
||||
*
|
||||
* **必须留兜底**:这个站点是走 http://192.168.x.x:18051 访问的,不是安全上下文,
|
||||
* 浏览器在这种情况下根本不提供 `navigator.clipboard`(不是拒绝,是 undefined)。
|
||||
* 只写新 API 的话,局域网里点「复制」永远没反应。
|
||||
*/
|
||||
export async function copyText(value: string): Promise<boolean> {
|
||||
if (!value) return false
|
||||
|
||||
if (window.isSecureContext && navigator.clipboard) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value)
|
||||
return true
|
||||
} catch {
|
||||
// 落到下面的兜底
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const area = document.createElement('textarea')
|
||||
area.value = value
|
||||
// 定位到视口外而不是 display:none —— 隐藏元素选不中,复制会失败。
|
||||
area.style.position = 'fixed'
|
||||
area.style.top = '-1000px'
|
||||
area.style.opacity = '0'
|
||||
document.body.appendChild(area)
|
||||
area.select()
|
||||
const ok = document.execCommand('copy')
|
||||
document.body.removeChild(area)
|
||||
return ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 标签颜色:调色板名字 → Tailwind 类名。
|
||||
*
|
||||
* **必须写死。** Tailwind 是在构建时静态扫描源码找类名的,`text-cyber-neon-${color}`
|
||||
* 这种拼出来的字符串它看不见 —— 而且不会报错,只是线上那些标签全变成无色。所以这里
|
||||
* 是一张查表,后端存的是键(cyan / pink / …)。
|
||||
*/
|
||||
const TAG_COLOR_CLASSES: Record<string, string> = {
|
||||
cyan: 'border-cyber-neon-cyan/40 text-cyber-neon-cyan',
|
||||
pink: 'border-cyber-neon-pink/40 text-cyber-neon-pink',
|
||||
green: 'border-cyber-neon-green/40 text-cyber-neon-green',
|
||||
orange: 'border-cyber-neon-orange/40 text-cyber-neon-orange',
|
||||
muted: 'border-cyber-border-DEFAULT text-cyber-text-secondary',
|
||||
}
|
||||
|
||||
/** 设置页里让用户选的那几个。键要和后端 `service.TAG_COLORS` 一致。 */
|
||||
export const TAG_COLOR_CHOICES = ['cyan', 'pink', 'green', 'orange', 'muted'] as const
|
||||
|
||||
const COLOR_LABELS: Record<string, string> = {
|
||||
cyan: '青',
|
||||
pink: '粉',
|
||||
green: '绿',
|
||||
orange: '橙',
|
||||
muted: '灰',
|
||||
}
|
||||
|
||||
export function tagColorClass(color: string): string {
|
||||
// 认不出来的颜色回落到默认色,而不是整块没有样式 —— 后端也会这么回落,两边一致。
|
||||
return TAG_COLOR_CLASSES[color] ?? TAG_COLOR_CLASSES.cyan
|
||||
}
|
||||
|
||||
export function tagColorLabel(color: string): string {
|
||||
return COLOR_LABELS[color] ?? COLOR_LABELS.cyan
|
||||
}
|
||||
@@ -60,6 +60,15 @@ export interface MonitorTask {
|
||||
notify_enabled: boolean
|
||||
/** 推送**异常**(登录失效/运行失败/没抓到数据)。默认开。 */
|
||||
notify_failures: boolean
|
||||
/** 超级编导自动追加(只有抖音的作品模式任务能开)。 */
|
||||
superdir_auto_enabled: boolean
|
||||
superdir_auto_interval_minutes: number
|
||||
/** 下一次自动追加的时间(毫秒);关掉时是 null。 */
|
||||
superdir_auto_next_at: number | null
|
||||
/** 上一次**成功**追加的时间(毫秒),也是下次查询的窗口起点。 */
|
||||
superdir_auto_last_at: number | null
|
||||
superdir_auto_last_added: number | null
|
||||
superdir_auto_last_error: string
|
||||
/** Epoch milliseconds. */
|
||||
next_run_at: number | null
|
||||
last_run_at: number | null
|
||||
@@ -95,6 +104,42 @@ export interface MonitorNote {
|
||||
*/
|
||||
creator_hash: string
|
||||
creator_name: string
|
||||
/**
|
||||
* 人自己给这个博主起的备注。
|
||||
*
|
||||
* 界面上**优先显示它**:`creator_name` 是平台昵称(常常认不出是谁),`creator_hash`
|
||||
* 更认不出。备注是唯一能把账号对上人的东西。空串表示没起过。
|
||||
*/
|
||||
creator_alias: string
|
||||
/**
|
||||
* 人给**这条作品**起的备注。
|
||||
*
|
||||
* 和 `creator_alias` 是两件事:那条回答「这个账号是谁」,这条回答「这条我要盯着」。
|
||||
* 一个博主底下常常只有一两件值得盯的作品,所以不能合并成一条。空串表示没起过。
|
||||
*/
|
||||
note_alias: string
|
||||
/**
|
||||
* 贴在这条作品上的标签 —— 从设置里那份**固定词表**选的分类,可以贴好几个。
|
||||
*
|
||||
* 和 `note_alias` 并存、不是一回事:备注是一句话的自由文字,标签是封闭词表里的分类。
|
||||
* 分类得是封闭的,否则「重点 / 重要 / 优先」各写各的,筛选就没法用了。
|
||||
*/
|
||||
tags: TagRef[]
|
||||
/**
|
||||
* 博主**账号级**指标 —— 作品列表给不了的东西:作品说的是「这条涨了多少赞」,
|
||||
* 它说的是「这个人整个账号在涨还是在掉」。
|
||||
*
|
||||
* 三者都可能为 null:平台没采到(小红书那条路根本不产生它),或者某一项平台没给。
|
||||
* 为 null 时界面整块不画 —— 画成「粉丝 0」就是在撒谎。
|
||||
*
|
||||
* 作品栏的组头**不要读这里**,读 `MonitorCreator` —— 一条作品都没有的博主不会出现
|
||||
* 在作品列表里,只有那份博主列表能覆盖他。这里是给「顺着一条作品问它的作者」用的。
|
||||
*/
|
||||
creator_fans: number | null
|
||||
creator_total_favorited: number | null
|
||||
creator_works: number | null
|
||||
/** 上述指标是哪一轮采到的。null = 从来没有过。 */
|
||||
creator_stats_at: number | null
|
||||
/** 作品的**发布**时间(爬虫侧:小红书 time、抖音 create_time)。可能与
|
||||
* `first_seen_at` 差很远 —— 后者是「我们第一次看到它」的时间。平台没给时为 null。 */
|
||||
published_at: number | null
|
||||
@@ -107,6 +152,60 @@ export interface MonitorNote {
|
||||
snapshot_count: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 作品栏里的一位博主 —— **不依赖于他有没有作品**。
|
||||
*
|
||||
* 作品表是按 creator_hash 从作品推出来的,所以「一条作品都没有的博主」在那边根本
|
||||
* 不存在。可这类博主恰恰是最该看见的:还在涨粉,只是最近没发东西。服务端因此单独
|
||||
* 给一份列表,来源是**账号快照 ∪ 作品**。
|
||||
*
|
||||
* 没有作品时 `note_count` 是 0,其余字段照常有;反过来,小红书那条路不产生账号
|
||||
* 快照,于是 `creator_fans` 等为 null —— 两边各缺一块,界面要都能显示。
|
||||
*/
|
||||
export interface MonitorCreator {
|
||||
task_id: number
|
||||
creator_hash: string
|
||||
creator_name: string
|
||||
creator_alias: string
|
||||
/**
|
||||
* 博主主页链接,用来一键跳过去。
|
||||
*
|
||||
* **空串是常态,不是异常**:`creator_hash` 是单向的,拼不出地址,所以这个得靠采集时
|
||||
* 单独存下来的主页 id(抖音是 sec_uid)。小红书那条路不落创作者资料,因此那边永远是
|
||||
* 空的 —— 空的时候界面不画按钮,而不是给一个点开 404 的链接。
|
||||
*/
|
||||
creator_url: string
|
||||
note_count: number
|
||||
creator_fans: number | null
|
||||
creator_total_favorited: number | null
|
||||
creator_works: number | null
|
||||
creator_stats_at: number | null
|
||||
/** 作品最后出现、或账号指标最后采集的时间 —— 排序用。 */
|
||||
last_activity_at: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个标签。`color` 是**调色板里的名字**(cyan/pink/…),不是颜色值 —— Tailwind 的类名
|
||||
* 是静态提取的,拼不出动态类名,所以要用一张写死的表去查。
|
||||
*/
|
||||
export interface TagRef {
|
||||
id: number
|
||||
name: string
|
||||
color: string
|
||||
}
|
||||
|
||||
/** 词表里的标签,额外带一个「被用在多少条作品上」—— 删之前要能看清代价。 */
|
||||
export interface MonitorTag extends TagRef {
|
||||
note_count: number
|
||||
/**
|
||||
* 自动打标签的规则:**逗号分隔的关键词**。作品标题里出现其中任意一个,这条标签就
|
||||
* 自动贴上;命中几条规则就贴几个标签。空串 = 这条标签只能手动贴。
|
||||
*
|
||||
* 关键词和标签名是两回事 —— 标签叫「大字报」,关键词可能是 `szgtdzb`。
|
||||
*/
|
||||
keywords: string
|
||||
}
|
||||
|
||||
export interface MetricPoint {
|
||||
run_id: number
|
||||
captured_at: number
|
||||
@@ -277,6 +376,8 @@ export interface TaskCreatePayload {
|
||||
enabled: boolean
|
||||
notify_enabled: boolean
|
||||
notify_failures: boolean
|
||||
superdir_auto_enabled: boolean
|
||||
superdir_auto_interval_minutes: number
|
||||
targets: string[]
|
||||
}
|
||||
|
||||
@@ -439,3 +540,118 @@ export interface UpstreamStatus {
|
||||
notified?: boolean
|
||||
notify_error?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 一份可用的采集身份(登录态)。
|
||||
*
|
||||
* **接口永远不返回 cookie 原文**,只有 `has_cookie` —— 这是从运营模块沿用下来的
|
||||
* 约定,别为了「方便」把它加回来。
|
||||
*/
|
||||
export interface MonitorIdentity {
|
||||
id: number
|
||||
platform: string
|
||||
label: string
|
||||
source: 'stored' | 'browser'
|
||||
has_cookie: boolean
|
||||
user_agent: string
|
||||
status: 'ok' | 'cooldown' | 'expired' | 'disabled'
|
||||
enabled: boolean
|
||||
consecutive_failures: number
|
||||
cooldown_until: number | null
|
||||
last_checked_at: number | null
|
||||
last_ok_at: number | null
|
||||
last_error: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 「视频链接 → 博主主页」的一条结果。
|
||||
*
|
||||
* `ok` 为 false 时 `error` 一定有值 —— 批量粘贴时每条各自成败,不能整批共用一个错误。
|
||||
*/
|
||||
export interface VideoLinkResult {
|
||||
input: string
|
||||
aweme_id: string
|
||||
ok: boolean
|
||||
nickname: string
|
||||
sec_uid: string
|
||||
profile_url: string
|
||||
error: string
|
||||
}
|
||||
|
||||
export interface VideoLinkResolveResponse {
|
||||
results: VideoLinkResult[]
|
||||
/** 超过一次能解析的上限,后面的没处理 —— 前端要说出来,不能默默截断。 */
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 超级编导预览出来的一条作品。
|
||||
*
|
||||
* 时间戳都是 **Unix 秒**(超级编导的原样值),不是监控库里的毫秒 —— 两边别混。
|
||||
*/
|
||||
export interface SuperDirVideoRow {
|
||||
activity_id: number
|
||||
activity_title: string
|
||||
activity_created_at: number
|
||||
aweme_id: string
|
||||
nickname: string
|
||||
title: string
|
||||
share_url: string
|
||||
published_at: number
|
||||
play_count: number
|
||||
digg_count: number
|
||||
comment_count: number
|
||||
share_count: number
|
||||
}
|
||||
|
||||
export interface SuperDirFailedActivity {
|
||||
activity_id: number
|
||||
title: string
|
||||
error: string
|
||||
}
|
||||
|
||||
/** 匹配到的分发活动。0 条作品时用它解释「为什么是 0」。 */
|
||||
export interface SuperDirMatchedActivity {
|
||||
id: number
|
||||
title: string
|
||||
created_at: number
|
||||
/** 活动里计划/分配的作品数。 */
|
||||
total_count: number
|
||||
/** 已经发布出来的作品数。 */
|
||||
published_count: number
|
||||
}
|
||||
|
||||
export interface SuperDirPreviewResponse {
|
||||
start: string
|
||||
end: string
|
||||
/** 区间内创建的分发活动数。 */
|
||||
activities: number
|
||||
matched_activities: SuperDirMatchedActivity[]
|
||||
/** 能用的作品条数(去重、去掉私密和没发布之后)。 */
|
||||
videos: number
|
||||
creators: number
|
||||
/** 没有抖音链接或不是公开状态,被跳过的条数。 */
|
||||
skipped: number
|
||||
/** 超过一次能建的上限,只返回了前面一部分。 */
|
||||
truncated: boolean
|
||||
failed_activities: SuperDirFailedActivity[]
|
||||
rows: SuperDirVideoRow[]
|
||||
}
|
||||
|
||||
export interface SuperDirTaskPayload {
|
||||
links: string[]
|
||||
/** 给了就追加到这个任务;不给(null)就新建。 */
|
||||
task_id: number | null
|
||||
name: string
|
||||
enable_comments: boolean
|
||||
run_now: boolean
|
||||
}
|
||||
|
||||
export interface SuperDirTaskResult {
|
||||
id: number
|
||||
/** 这次真正加进去的条数(已存在的目标不算)。 */
|
||||
added: number
|
||||
/** 任务现在的目标总数。 */
|
||||
targets: number
|
||||
message: string
|
||||
}
|
||||
|
||||
@@ -104,26 +104,22 @@ const config: Config = {
|
||||
animation: {
|
||||
'slide-up': 'slideUp 0.3s ease-out forwards',
|
||||
'pulse-fast': 'pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite',
|
||||
'pulse-glow': 'pulseGlow 2s ease-in-out infinite',
|
||||
'scanline': 'scanline 8s linear infinite',
|
||||
'cursor-blink': 'cursorBlink 1s step-end infinite',
|
||||
'border-glow': 'borderGlow 3s linear infinite',
|
||||
'accordion-down': 'accordion-down 0.2s ease-out',
|
||||
'accordion-up': 'accordion-up 0.2s ease-out',
|
||||
},
|
||||
// 这里只剩动 opacity / transform 的无限动画。**无限动画不能动不可合成的属性**
|
||||
// (box-shadow、border-color、width/height/left/top…)—— 那会让页面从打开起
|
||||
// 永远重绘。原来的 `pulse-glow`(box-shadow)和 `border-glow`(border-color)
|
||||
// 就是这么两个坑,而它们并没人用,所以删掉了;要加"发光"效果请照
|
||||
// index.css 里 .status-dot-online 的做法:光晕画在伪元素上,动画只改 opacity。
|
||||
// tests/test_css_animations.py 会挡住这类写法再溜回来。
|
||||
keyframes: {
|
||||
slideUp: {
|
||||
from: { opacity: '0', transform: 'translateY(10px)' },
|
||||
to: { opacity: '1', transform: 'translateY(0)' },
|
||||
},
|
||||
pulseGlow: {
|
||||
'0%, 100%': {
|
||||
boxShadow: '0 0 5px rgb(var(--cyber-neon-cyan) / 0.5), 0 0 10px rgb(var(--cyber-neon-cyan) / 0.3)'
|
||||
},
|
||||
'50%': {
|
||||
boxShadow: '0 0 15px rgb(var(--cyber-neon-cyan) / 0.8), 0 0 25px rgb(var(--cyber-neon-cyan) / 0.5), 0 0 35px rgb(var(--cyber-neon-cyan) / 0.3)'
|
||||
},
|
||||
},
|
||||
scanline: {
|
||||
'0%': { transform: 'translateY(-100%)' },
|
||||
'100%': { transform: 'translateY(100vh)' },
|
||||
@@ -132,10 +128,6 @@ const config: Config = {
|
||||
'0%, 100%': { opacity: '1' },
|
||||
'50%': { opacity: '0' },
|
||||
},
|
||||
borderGlow: {
|
||||
'0%, 100%': { borderColor: 'rgb(var(--cyber-neon-cyan) / 0.3)' },
|
||||
'50%': { borderColor: 'rgb(var(--cyber-neon-cyan) / 0.6)' },
|
||||
},
|
||||
'accordion-down': {
|
||||
from: { height: '0' },
|
||||
to: { height: 'var(--radix-accordion-content-height)' },
|
||||
|
||||
Reference in New Issue
Block a user