Initial commit: Douyin live monitor with sh2-aligned probe.

Next.js + FastAPI + PocketBase stack for room/session monitoring, cookie sync from sh2, and anti-risk polling defaults.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-08 09:03:00 -05:00
commit 76afafa6c9
50 changed files with 13947 additions and 0 deletions

35
.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# Python
__pycache__/
*.py[cod]
*.egg-info/
.venv/
venv/
.env
.env.*
# Node / Next
node_modules/
.next/
out/
*.tsbuildinfo
# Runtime / secrets / local data
backend/data/
*.db
*.db-*
*.sqlite
*.sqlite3
# PocketBase
pb/pb_data/
pb/pocketbase.exe
pb/CHANGELOG.md
pb/LICENSE.md
# OS / IDE
.DS_Store
Thumbs.db
.idea/
.vscode/
*.log
.cursor/

114
README.md Normal file
View File

@ -0,0 +1,114 @@
# 抖音直播间监控(douyinWEB)
独立监控项目:批量跟踪抖音直播间 **开播 / 停播 / 播放时长 / 截图**,控制台对齐 `sh2` 的 `youtube-relay-log` 可视化分析与场次列表。
探测逻辑参考 `C:\project\sh2\d2ypp2`(`web/enter + a_bogus`、Cookie、循环间隔),不靠刷直播间 HTML 页面做批量探测,降低风控概率。
## 技术栈
| 组件 | 端口 | 说明 |
|------|------|------|
| Next.js 15 | `:3000` | 雷达台 / 场次 / 直播间 / 主播 / 设置 |
| FastAPI | `:8000` | 轮询、场次、SSE、REST |
| PocketBase | `:8090` | 可选镜像同步 |
| SQLite | 本地 | 监控热路径(低延迟) |
## 功能
- 直播间管理:单条 / 批量添加、标签、启用停用、黑名单、CSV 导出
- 开播建场、停播结场、实时进行中计时(每房仅一场,幂等去重)
- 可视化分析 + 场次列表(时长、主播画像、封面墙、事件时间线)
- SSE 实时推送 + Toast
- Cookie:启动时自动从 sh2 `d2ypp2/config/config.ini` 的 `抖音cookie` 导入;也可在设置页填写,或调用 `POST /api/settings/sync-cookie`
- 防风控(对齐 sh2):
- 仅 `webcast/room/web/enter` + `a_bogus`(默认不做 HTML 回退)
- 并发 1、请求间隔抖动、离线约 300s / 在播约 120s
- 错误退避;风控短冷却(约 90s),非长时间熔断
- 大批量房间错开 `next_check_at`
## 目录
```
douyinWEB/
backend/app/ FastAPI(douyin.py / monitor.py / ab_sign.py …)
frontend/src/ Next.js App Router
pb/ PocketBase(需自行放置 pocketbase.exe)
scripts/ start.bat、导入与防风控脚本
```
## 启动
```bat
scripts\start.bat
```
或分别启动:
```bat
pb\pocketbase.exe serve --http=127.0.0.1:8090
cd backend && python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload
cd frontend && npm run dev -- --port 3000 --hostname 127.0.0.1
```
- 控制台:http://127.0.0.1:3000
- API 文档:http://127.0.0.1:8000/docs
- PocketBase:http://127.0.0.1:8090/_/
默认 PB 管理员:`admin@douyin.local` / `DouyinMonitor_Admin_2026`
### 后端依赖
```bat
cd backend
pip install -r requirements.txt
```
### 前端依赖
```bat
cd frontend
npm install
```
## 导入真实直播间
将 `主播URL` 列表(格式同 sh2 / `11.txt`:`https://live.douyin.com/{id},主播: 名称`,可按主机分组)导入:
```bat
python scripts\import_from_11.py
```
默认读取 `C:\Users\admin\Desktop\11.txt`,写入 SQLite,并按主机打标签(如 `10.88.0.4`、`真实`)。
对齐 sh2 防风控参数并重新错开检测:
```bat
python scripts\apply_sh2_antirisk.py
```
同步 Cookie 并抽样探测:
```bat
python scripts\sync_cookie_and_probe.py
```
## 关键设置(防风控)
| 项 | 建议 |
|----|------|
| `max_concurrency` | 1(上百房间时不要拉高) |
| `offline_interval_sec` | ≥ 300(与 sh2「循环时间」一致) |
| `live_interval_sec` | ≥ 90–120 |
| `min_request_gap_sec` | ≥ 3 + jitter |
| `dy_cookie` | 使用 sh2 有效 Cookie;过期后从浏览器更新 ini 再 sync |
| `capture_cover_on_start` | 大批量时可关,减少拉流 |
## 环境变量(可选)
前缀 `DY_`,见 `backend/app/config.py`(如 `DY_PB_URL`、`DY_OFFLINE_INTERVAL_SEC`)。
## 说明
- SQLite 库、封面、PocketBase 数据、`.env`、Cookie 等不入库(见 `.gitignore`)。
- `pocketbase.exe` 需自行放入 `pb/`(体积大,未纳入仓库)。
- 本项目仅做状态监控与场次统计,不含推流录制;推流逻辑仍在 sh2。

8
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
__pycache__/
*.pyc
.env
data/
*.db
*.db-*
.venv/
venv/

1
backend/app/__init__.py Normal file
View File

@ -0,0 +1 @@
# Douyin live monitor backend package

456
backend/app/ab_sign.py Normal file
View File

@ -0,0 +1,456 @@
# -*- encoding: utf-8 -*-
from __future__ import annotations
import math
import time
def rc4_encrypt(plaintext: str, key: str) -> str:
# 初始化状态数组
s = list(range(256))
# 使用密钥对状态数组进行置换
j = 0
for i in range(256):
j = (j + s[i] + ord(key[i % len(key)])) % 256
s[i], s[j] = s[j], s[i]
# 生成密钥流并加密
i = j = 0
result = []
for char in plaintext:
i = (i + 1) % 256
j = (j + s[i]) % 256
s[i], s[j] = s[j], s[i]
t = (s[i] + s[j]) % 256
result.append(chr(s[t] ^ ord(char)))
return ''.join(result)
def left_rotate(x: int, n: int) -> int:
n %= 32
return ((x << n) | (x >> (32 - n))) & 0xFFFFFFFF
def get_t_j(j: int) -> int:
if 0 <= j < 16:
return 2043430169 # 0x79CC4519
elif 16 <= j < 64:
return 2055708042 # 0x7A879D8A
else:
raise ValueError("invalid j for constant Tj")
def ff_j(j: int, x: int, y: int, z: int) -> int:
if 0 <= j < 16:
return (x ^ y ^ z) & 0xFFFFFFFF
elif 16 <= j < 64:
return ((x & y) | (x & z) | (y & z)) & 0xFFFFFFFF
else:
raise ValueError("invalid j for bool function FF")
def gg_j(j: int, x: int, y: int, z: int) -> int:
if 0 <= j < 16:
return (x ^ y ^ z) & 0xFFFFFFFF
elif 16 <= j < 64:
return ((x & y) | (~x & z)) & 0xFFFFFFFF
else:
raise ValueError("invalid j for bool function GG")
class SM3:
def __init__(self):
self.reg = []
self.chunk = []
self.size = 0
self.reset()
def reset(self):
# 初始化寄存器值 - 修正为与JS版本相同的值
self.reg = [
1937774191, 1226093241, 388252375, 3666478592,
2842636476, 372324522, 3817729613, 2969243214
]
self.chunk = []
self.size = 0
def write(self, data):
# 将输入转换为字节数组
if isinstance(data, str):
# 直接转换为UTF-8字节列表
a = list(data.encode('utf-8'))
else:
a = data
self.size += len(a)
f = 64 - len(self.chunk)
if len(a) < f:
# 如果数据长度小于剩余空间,直接添加
self.chunk.extend(a)
else:
# 否则分块处理
self.chunk.extend(a[:f])
while len(self.chunk) >= 64:
self._compress(self.chunk)
if f < len(a):
self.chunk = a[f:min(f + 64, len(a))]
else:
self.chunk = []
f += 64
def _fill(self):
# 计算比特长度
bit_length = 8 * self.size
# 添加填充位
padding_pos = len(self.chunk)
self.chunk.append(0x80)
padding_pos = (padding_pos + 1) % 64
# 如果剩余空间不足8字节,则填充到下一个块
if 64 - padding_pos < 8:
padding_pos -= 64
# 填充0直到剩余8字节用于存储长度
while padding_pos < 56:
self.chunk.append(0)
padding_pos += 1
# 添加消息长度(高32位)
high_bits = bit_length // 4294967296
for i in range(4):
self.chunk.append((high_bits >> (8 * (3 - i))) & 0xFF)
# 添加消息长度(低32位)
for i in range(4):
self.chunk.append((bit_length >> (8 * (3 - i))) & 0xFF)
def _compress(self, data):
if len(data) < 64:
raise ValueError("compress error: not enough data")
else:
# 消息扩展
w = [0] * 132
# 将字节数组转换为字
for t in range(16):
w[t] = (data[4 * t] << 24) | (data[4 * t + 1] << 16) | (data[4 * t + 2] << 8) | data[4 * t + 3]
w[t] &= 0xFFFFFFFF
# 消息扩展
for j in range(16, 68):
a = w[j - 16] ^ w[j - 9] ^ left_rotate(w[j - 3], 15)
a = a ^ left_rotate(a, 15) ^ left_rotate(a, 23)
w[j] = (a ^ left_rotate(w[j - 13], 7) ^ w[j - 6]) & 0xFFFFFFFF
# 计算w'
for j in range(64):
w[j + 68] = (w[j] ^ w[j + 4]) & 0xFFFFFFFF
# 压缩
a, b, c, d, e, f, g, h = self.reg
for j in range(64):
ss1 = left_rotate((left_rotate(a, 12) + e + left_rotate(get_t_j(j), j)) & 0xFFFFFFFF, 7)
ss2 = ss1 ^ left_rotate(a, 12)
tt1 = (ff_j(j, a, b, c) + d + ss2 + w[j + 68]) & 0xFFFFFFFF
tt2 = (gg_j(j, e, f, g) + h + ss1 + w[j]) & 0xFFFFFFFF
d = c
c = left_rotate(b, 9)
b = a
a = tt1
h = g
g = left_rotate(f, 19)
f = e
e = (tt2 ^ left_rotate(tt2, 9) ^ left_rotate(tt2, 17)) & 0xFFFFFFFF
# 更新寄存器
self.reg[0] ^= a
self.reg[1] ^= b
self.reg[2] ^= c
self.reg[3] ^= d
self.reg[4] ^= e
self.reg[5] ^= f
self.reg[6] ^= g
self.reg[7] ^= h
def sum(self, data=None, output_format=None):
"""
计算哈希值
"""
# 如果提供了输入,则重置并写入
if data is not None:
self.reset()
self.write(data)
self._fill()
# 分块压缩
for f in range(0, len(self.chunk), 64):
self._compress(self.chunk[f:f + 64])
if output_format == 'hex':
# 十六进制输出
result = ''.join(f'{val:08x}' for val in self.reg)
else:
# 字节数组输出
result = []
for f in range(8):
c = self.reg[f]
result.append((c >> 24) & 0xFF)
result.append((c >> 16) & 0xFF)
result.append((c >> 8) & 0xFF)
result.append(c & 0xFF)
self.reset()
return result
def result_encrypt(long_str: str, num: str | None = None) -> str:
# 魔改base64编码表
encoding_tables = {
"s0": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
"s1": "Dkdpgh4ZKsQB80/Mfvw36XI1R25+WUAlEi7NLboqYTOPuzmFjJnryx9HVGcaStCe=",
"s2": "Dkdpgh4ZKsQB80/Mfvw36XI1R25-WUAlEi7NLboqYTOPuzmFjJnryx9HVGcaStCe=",
"s3": "ckdp1h4ZKsUB80/Mfvw36XIgR25+WQAlEi7NLboqYTOPuzmFjJnryx9HVGDaStCe",
"s4": "Dkdpgh2ZmsQB80/MfvV36XI1R45-WUAlEixNLwoqYTOPuzKFjJnry79HbGcaStCe"
}
# 位移常量
masks = [16515072, 258048, 4032, 63] # 对应 0, 1, 2 的掩码,添加63作为第四个掩码
shifts = [18, 12, 6, 0] # 对应的位移量
encoding_table = encoding_tables[num]
result = ""
round_num = 0
long_int = get_long_int(round_num, long_str)
total_chars = math.ceil(len(long_str) / 3 * 4)
for i in range(total_chars):
# 每4个字符处理一组3字节
if i // 4 != round_num:
round_num += 1
long_int = get_long_int(round_num, long_str)
# 计算当前位置的索引
index = i % 4
# 使用掩码和位移提取6位值
char_index = (long_int & masks[index]) >> shifts[index]
result += encoding_table[char_index]
return result
def get_long_int(round_num: int, long_str: str) -> int:
round_num = round_num * 3
# 获取字符串中的字符,如果超出范围则使用0
char1 = ord(long_str[round_num]) if round_num < len(long_str) else 0
char2 = ord(long_str[round_num + 1]) if round_num + 1 < len(long_str) else 0
char3 = ord(long_str[round_num + 2]) if round_num + 2 < len(long_str) else 0
return (char1 << 16) | (char2 << 8) | char3
def gener_random(random_num: int, option: list[int]) -> list[int]:
byte1 = random_num & 255
byte2 = (random_num >> 8) & 255
return [
(byte1 & 170) | (option[0] & 85), # 偶数位与option[0]的奇数位合并
(byte1 & 85) | (option[0] & 170), # 奇数位与option[0]的偶数位合并
(byte2 & 170) | (option[1] & 85), # 偶数位与option[1]的奇数位合并
(byte2 & 85) | (option[1] & 170), # 奇数位与option[1]的偶数位合并
]
def generate_random_str() -> str:
"""
生成随机字符串
Returns:
随机字符串
"""
# 使用与JS版本相同的固定随机值
random_values = [0.123456789, 0.987654321, 0.555555555]
# 生成三组随机字节并合并
random_bytes = []
random_bytes.extend(gener_random(int(random_values[0] * 10000), [3, 45]))
random_bytes.extend(gener_random(int(random_values[1] * 10000), [1, 0]))
random_bytes.extend(gener_random(int(random_values[2] * 10000), [1, 5]))
return ''.join(chr(b) for b in random_bytes)
def generate_rc4_bb_str(url_search_params: str, user_agent: str, window_env_str: str,
suffix: str = "cus", arguments: list[int] | None = None) -> str:
if arguments is None:
arguments = [0, 1, 14]
sm3 = SM3()
start_time = int(time.time() * 1000)
# 三次加密处理
# 1: url_search_params两次sm3之的结果
url_search_params_list = sm3.sum(sm3.sum(url_search_params + suffix))
# 2: 对后缀两次sm3之的结果
cus = sm3.sum(sm3.sum(suffix))
# 3: 对ua处理之后的结果
ua_key = chr(0) + chr(1) + chr(14) # [1/256, 1, 14]
ua = sm3.sum(result_encrypt(
rc4_encrypt(user_agent, ua_key),
"s3"
))
end_time = start_time + 100
# 构建配置对象
b = {
8: 3,
10: end_time,
15: {
"aid": 6383,
"pageId": 110624,
"boe": False,
"ddrt": 7,
"paths": {
"include": [{} for _ in range(7)],
"exclude": []
},
"track": {
"mode": 0,
"delay": 300,
"paths": []
},
"dump": True,
"rpU": "hwj"
},
16: start_time,
18: 44,
19: [1, 0, 1, 5],
}
def split_to_bytes(num: int) -> list[int]:
return [
(num >> 24) & 255,
(num >> 16) & 255,
(num >> 8) & 255,
num & 255
]
# 处理时间戳
start_time_bytes = split_to_bytes(b[16])
b[20] = start_time_bytes[0]
b[21] = start_time_bytes[1]
b[22] = start_time_bytes[2]
b[23] = start_time_bytes[3]
b[24] = int(b[16] / 256 / 256 / 256 / 256) & 255
b[25] = int(b[16] / 256 / 256 / 256 / 256 / 256) & 255
# 处理Arguments参数
arg0_bytes = split_to_bytes(arguments[0])
b[26] = arg0_bytes[0]
b[27] = arg0_bytes[1]
b[28] = arg0_bytes[2]
b[29] = arg0_bytes[3]
b[30] = int(arguments[1] / 256) & 255
b[31] = (arguments[1] % 256) & 255
arg1_bytes = split_to_bytes(arguments[1])
b[32] = arg1_bytes[0]
b[33] = arg1_bytes[1]
arg2_bytes = split_to_bytes(arguments[2])
b[34] = arg2_bytes[0]
b[35] = arg2_bytes[1]
b[36] = arg2_bytes[2]
b[37] = arg2_bytes[3]
# 处理加密结果
b[38] = url_search_params_list[21]
b[39] = url_search_params_list[22]
b[40] = cus[21]
b[41] = cus[22]
b[42] = ua[23]
b[43] = ua[24]
# 处理结束时间
end_time_bytes = split_to_bytes(b[10])
b[44] = end_time_bytes[0]
b[45] = end_time_bytes[1]
b[46] = end_time_bytes[2]
b[47] = end_time_bytes[3]
b[48] = b[8]
b[49] = int(b[10] / 256 / 256 / 256 / 256) & 255
b[50] = int(b[10] / 256 / 256 / 256 / 256 / 256) & 255
# 处理配置项
b[51] = b[15]['pageId']
page_id_bytes = split_to_bytes(b[15]['pageId'])
b[52] = page_id_bytes[0]
b[53] = page_id_bytes[1]
b[54] = page_id_bytes[2]
b[55] = page_id_bytes[3]
b[56] = b[15]['aid']
b[57] = b[15]['aid'] & 255
b[58] = (b[15]['aid'] >> 8) & 255
b[59] = (b[15]['aid'] >> 16) & 255
b[60] = (b[15]['aid'] >> 24) & 255
# 处理环境信息
window_env_list = [ord(char) for char in window_env_str]
b[64] = len(window_env_list)
b[65] = b[64] & 255
b[66] = (b[64] >> 8) & 255
b[69] = 0
b[70] = 0
b[71] = 0
# 计算校验和
b[72] = b[18] ^ b[20] ^ b[26] ^ b[30] ^ b[38] ^ b[40] ^ b[42] ^ b[21] ^ b[27] ^ b[31] ^ \
b[35] ^ b[39] ^ b[41] ^ b[43] ^ b[22] ^ b[28] ^ b[32] ^ b[36] ^ b[23] ^ b[29] ^ \
b[33] ^ b[37] ^ b[44] ^ b[45] ^ b[46] ^ b[47] ^ b[48] ^ b[49] ^ b[50] ^ b[24] ^ \
b[25] ^ b[52] ^ b[53] ^ b[54] ^ b[55] ^ b[57] ^ b[58] ^ b[59] ^ b[60] ^ b[65] ^ \
b[66] ^ b[70] ^ b[71]
# 构建最终字节数组
bb = [
b[18], b[20], b[52], b[26], b[30], b[34], b[58], b[38], b[40], b[53], b[42], b[21],
b[27], b[54], b[55], b[31], b[35], b[57], b[39], b[41], b[43], b[22], b[28], b[32],
b[60], b[36], b[23], b[29], b[33], b[37], b[44], b[45], b[59], b[46], b[47], b[48],
b[49], b[50], b[24], b[25], b[65], b[66], b[70], b[71]
]
bb.extend(window_env_list)
bb.append(b[72])
return rc4_encrypt(
''.join(chr(byte) for byte in bb),
chr(121)
)
def ab_sign(url_search_params: str, user_agent: str) -> str:
window_env_str = "1920|1080|1920|1040|0|30|0|0|1872|92|1920|1040|1857|92|1|24|Win32"
# 1. 生成随机字符串前缀
# 2. 生成RC4加密的主体部分
# 3. 对结果进行最终加密并添加等号后缀
return result_encrypt(
generate_random_str() +
generate_rc4_bb_str(url_search_params, user_agent, window_env_str),
"s4"
) + "="

44
backend/app/config.py Normal file
View File

@ -0,0 +1,44 @@
from __future__ import annotations
from pathlib import Path
from pydantic_settings import BaseSettings
ROOT = Path(__file__).resolve().parents[2]
BACKEND = Path(__file__).resolve().parents[1]
class Settings(BaseSettings):
api_host: str = "127.0.0.1"
api_port: int = 8000
cors_origins: str = "http://localhost:3000,http://127.0.0.1:3000"
pb_url: str = "http://127.0.0.1:8090"
pb_admin_email: str = "admin@douyin.local"
pb_admin_password: str = "DouyinMonitor_Admin_2026"
data_dir: Path = BACKEND / "data"
covers_dir: Path = BACKEND / "data" / "covers"
sqlite_path: Path = BACKEND / "data" / "monitor.db"
# Anti risk-control defaults — aligned with sh2 config.ini
# 循环时间(秒)=300, 同一时间访问网络的线程数=3 (we use 1 for safer mass poll)
max_concurrency: int = 1
min_request_gap_sec: float = 3.0
request_jitter_sec: float = 2.0
offline_interval_sec: float = 300.0
live_interval_sec: float = 120.0
error_backoff_base_sec: float = 60.0
error_backoff_max_sec: float = 600.0
global_pause_on_risk_sec: float = 90.0
capture_cover_on_start: bool = False
ffmpeg_bin: str = "ffmpeg"
class Config:
env_prefix = "DY_"
env_file = ".env"
settings = Settings()
settings.data_dir.mkdir(parents=True, exist_ok=True)
settings.covers_dir.mkdir(parents=True, exist_ok=True)

View File

@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
"""Load Douyin cookie from sh2 config.ini (same source as DouyinLiveRecorder)."""
from __future__ import annotations
import configparser
from pathlib import Path
from typing import Optional
# Known sh2 cookie locations — first hit wins
DEFAULT_COOKIE_PATHS = [
Path(r"C:\project\sh2\d2ypp2\config\config.ini"),
Path(__file__).resolve().parents[2] / "config" / "douyin_cookie.ini",
]
def read_ini_cookie(path: Path, section: str = "Cookie", key: str = "抖音cookie") -> str:
if not path.is_file():
return ""
# RawConfigParser: cookie values contain many '%' encodings
parser = configparser.RawConfigParser()
try:
parser.read(path, encoding="utf-8")
except Exception:
try:
parser.read(path, encoding="utf-8-sig")
except Exception:
return ""
if not parser.has_section(section):
return ""
try:
return (parser.get(section, key) or "").strip()
except Exception:
# try ascii key aliases
for alt in ("douyin_cookie", "dy_cookie", "抖音cookie"):
try:
return (parser.get(section, alt) or "").strip()
except Exception:
continue
return ""
def find_sh2_cookie(extra_paths: Optional[list[Path]] = None) -> tuple[str, str]:
"""Return (cookie, source_path). Empty cookie if not found."""
paths = list(extra_paths or []) + list(DEFAULT_COOKIE_PATHS)
seen: set[str] = set()
for p in paths:
key = str(p.resolve()) if p.exists() else str(p)
if key in seen:
continue
seen.add(key)
cookie = read_ini_cookie(p)
if cookie:
return cookie, str(p)
return "", ""
def bootstrap_cookie_into_db() -> dict:
"""If dy_cookie empty, import from sh2 config.ini."""
from . import db
db.init_db()
cfg = db.get_settings_map()
current = str(cfg.get("dy_cookie") or "").strip()
if current:
return {"ok": True, "action": "keep", "length": len(current), "source": "db"}
cookie, source = find_sh2_cookie()
if not cookie:
return {"ok": False, "action": "missing", "length": 0, "source": ""}
db.update_settings_map({"dy_cookie": cookie})
return {"ok": True, "action": "imported", "length": len(cookie), "source": source}
def force_sync_cookie_from_sh2() -> dict:
"""Always overwrite dy_cookie from sh2 if present."""
from . import db
db.init_db()
cookie, source = find_sh2_cookie()
if not cookie:
return {"ok": False, "action": "missing", "length": 0, "source": ""}
db.update_settings_map({"dy_cookie": cookie})
return {"ok": True, "action": "synced", "length": len(cookie), "source": source}

60
backend/app/cover.py Normal file
View File

@ -0,0 +1,60 @@
from __future__ import annotations
import asyncio
import subprocess
from pathlib import Path
from .config import settings
from . import db
async def capture_cover(session_id: str, stream_url: str) -> str:
url = (stream_url or "").strip()
if not url:
return ""
out_path = settings.covers_dir / f"{session_id}.jpg"
headers = (
"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15\r\n"
"Referer: https://live.douyin.com/\r\n"
)
cmd = [
settings.ffmpeg_bin,
"-hide_banner",
"-loglevel",
"error",
"-y",
"-headers",
headers,
"-rw_timeout",
"15000000",
"-i",
url,
"-frames:v",
"1",
"-q:v",
"3",
str(out_path),
]
def _run() -> str:
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=25)
except Exception:
return ""
if proc.returncode != 0 or not out_path.is_file() or out_path.stat().st_size < 128:
return ""
db.set_session_cover(session_id, str(out_path))
return str(out_path)
return await asyncio.to_thread(_run)
def cover_path_for(session_id: str) -> Path | None:
session = db.get_session(session_id)
if not session:
return None
path = Path(str(session.get("cover_path") or ""))
if path.is_file():
return path
fallback = settings.covers_dir / f"{session_id}.jpg"
return fallback if fallback.is_file() else None

1172
backend/app/db.py Normal file

File diff suppressed because it is too large Load Diff

318
backend/app/douyin.py Normal file
View File

@ -0,0 +1,318 @@
# -*- coding: utf-8 -*-
"""Douyin live status probe — aligned with sh2/d2ypp2 spider (web/enter + a_bogus).
Mass monitoring deliberately avoids HTML page scrape: visiting live.douyin.com/{id}
triggers captcha far more often than webcast/room/web/enter.
"""
from __future__ import annotations
import json
import re
from typing import Any, Optional
from urllib.parse import unquote, urlencode, urlparse
import httpx
from .ab_sign import ab_sign
from .models import extract_room_id, normalize_room_url
# Match sh2 spider UA (a_bogus is tied to this fingerprint)
SH2_UA = (
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/116.0.5845.97 Safari/537.36 Core/1.116.567.400 QQBrowser/19.7.6764.400"
)
BUILTIN_COOKIE = (
"ttwid=1%7C2iDIYVmjzMcpZ20fcaFde0VghXAA3NaNXE_SLR68IyE%7C1761045455"
"%7Cab35197d5cfb21df6cbb2fa7ef1c9262206b062c315b9d04da746d0b37dfbc7d"
)
class RiskControlError(Exception):
pass
def _cookie(cookie: str = "") -> str:
return (cookie or "").strip() or BUILTIN_COOKIE
def _web_headers(cookie: str = "") -> dict[str, str]:
return {
"cookie": _cookie(cookie),
"referer": "https://live.douyin.com/",
"user-agent": SH2_UA,
"accept": "application/json, text/plain, */*",
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
}
def _html_headers(cookie: str = "") -> dict[str, str]:
return {
"Cookie": _cookie(cookie),
"Referer": "https://live.douyin.com/",
"User-Agent": SH2_UA,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}
def _pick_stream_url(room: dict[str, Any]) -> str:
stream = room.get("stream_url") or {}
flv_map = stream.get("flv_pull_url") or {}
hls_map = stream.get("hls_pull_url_map") or {}
for key in ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2"):
if key in flv_map and flv_map[key]:
return str(flv_map[key])
for key in ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2"):
if key in hls_map and hls_map[key]:
return str(hls_map[key])
if isinstance(flv_map, dict) and flv_map:
return str(next(iter(flv_map.values())))
if isinstance(hls_map, dict) and hls_map:
return str(next(iter(hls_map.values())))
return str(stream.get("flv_pull_url") or stream.get("hls_pull_url") or "")
def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]:
status_code = room.get("status")
is_live = status_code == 2
anchor = (
room.get("anchor_name")
or (room.get("owner") or {}).get("nickname")
or ""
)
title = room.get("title") or ""
room_id = str(room.get("id") or room.get("id_str") or extract_room_id(source_url) or "")
web_rid = extract_room_id(source_url)
return {
"ok": True,
"is_live": bool(is_live),
"status_code": status_code,
"status": "live" if is_live else "offline",
"anchor_name": anchor,
"title": title,
"room_id": web_rid or room_id,
"source_url": normalize_room_url(source_url),
"stream_url": _pick_stream_url(room) if is_live else "",
"raw": {
"status": status_code,
"user_count": room.get("user_count") or room.get("user_count_str") or 0,
},
}
def _find_room_info(node: Any) -> Optional[dict[str, Any]]:
if isinstance(node, dict):
if "room" in node and isinstance(node["room"], dict) and "status" in node["room"]:
room = dict(node["room"])
owner = room.get("owner") or node.get("anchor") or {}
if isinstance(owner, dict):
room["anchor_name"] = owner.get("nickname") or room.get("anchor_name") or ""
return room
if "roomInfo" in node:
found = _find_room_info(node["roomInfo"])
if found:
return found
for value in node.values():
found = _find_room_info(value)
if found:
return found
elif isinstance(node, list):
for item in node:
found = _find_room_info(item)
if found:
return found
return None
def _parse_html_room(html: str) -> dict[str, Any]:
m = re.search(
r'<script id="RENDER_DATA" type="application/json">(.*?)</script>',
html,
re.DOTALL,
)
if m:
try:
data = json.loads(unquote(m.group(1)))
found = _find_room_info(data)
if found:
return found
except Exception:
pass
match_json_str = re.search(r'(\{\\"state\\":.*?)]\\n"]\)', html)
if not match_json_str:
match_json_str = re.search(r'(\{\\"common\\":.*?)]\\n"]\)</script><div hidden', html)
if not match_json_str:
if '"status":4' in html or '\\"status\\":4' in html:
return {"status": 4, "anchor_name": "", "title": ""}
raise ValueError("未能解析直播页状态")
json_str = match_json_str.group(1)
cleaned = json_str.replace("\\", "").replace(r"u0026", r"&")
room_store_match = re.search(r'"roomStore":(.*?),"linkmicStore"', cleaned, re.DOTALL)
if not room_store_match:
raise ValueError("roomStore 缺失")
room_store = room_store_match.group(1)
anchor_match = re.search(r'"nickname":"(.*?)","avatar_thumb', room_store, re.DOTALL)
anchor_name = anchor_match.group(1) if anchor_match else ""
room_store = room_store.split(',"has_commerce_goods"')[0] + "}}}"
room = json.loads(room_store)["roomInfo"]["room"]
room["anchor_name"] = anchor_name
return room
async def _fetch_web_enter(client: httpx.AsyncClient, web_rid: str, cookie: str = "") -> dict[str, Any]:
"""Primary path: webcast/room/web/enter + a_bogus (sh2 spider.get_douyin_web_stream_data)."""
params = {
"aid": "6383",
"app_name": "douyin_web",
"live_id": "1",
"device_platform": "web",
"language": "zh-CN",
"browser_language": "zh-CN",
"browser_platform": "Win32",
"browser_name": "Chrome",
"browser_version": "116.0.0.0",
"web_rid": web_rid,
"msToken": "",
}
api = f"https://live.douyin.com/webcast/room/web/enter/?{urlencode(params)}"
query = urlparse(api).query
headers = _web_headers(cookie)
api = f"{api}&a_bogus={ab_sign(query, headers['user-agent'])}"
resp = await client.get(api, headers=headers, follow_redirects=True)
text = (resp.text or "").strip()
if not text:
raise RiskControlError("web/enter 空响应(风控)")
if "验证码" in text or "captcha" in text.lower():
raise RiskControlError("web/enter 触发验证码/风控")
try:
payload = resp.json()
except Exception as exc:
raise RiskControlError("web/enter 非 JSON") from exc
# API-level risk / auth failures
status_code = (payload or {}).get("status_code")
if status_code not in (None, 0):
msg = str((payload or {}).get("data") or (payload or {}).get("message") or status_code)
if any(k in msg for k in ("验证", "登录", "forbid", "risk", "captcha")):
raise RiskControlError(f"web/enter status_code={status_code}")
data = (payload or {}).get("data") or {}
rooms = data.get("data") or []
user = data.get("user") or {}
if not rooms:
# sh2: empty data → not usable / treat as offline for status monitor
return {
"status": 4,
"anchor_name": user.get("nickname") or "",
"title": "",
"id_str": web_rid,
}
room = rooms[0]
room["anchor_name"] = user.get("nickname") or room.get("anchor_name") or ""
return room
async def _fetch_html(client: httpx.AsyncClient, url: str, cookie: str = "") -> dict[str, Any]:
resp = await client.get(url, headers=_html_headers(cookie), follow_redirects=True)
text = resp.text or ""
if resp.status_code in (302, 403) or "验证码" in text or "captcha" in text.lower():
raise RiskControlError("页面触发验证码/风控")
if len(text) < 200:
raise RiskControlError("响应过短,疑似风控")
return _parse_html_room(text)
async def check_room(
url_or_id: str,
*,
cookie: str = "",
proxy: Optional[str] = None,
allow_html_fallback: bool = False,
) -> dict[str, Any]:
"""Check live status.
Default = web/enter only (sh2 primary path). HTML fallback is opt-in because
scraping live.douyin.com pages is what usually trips captcha under mass polling.
"""
source_url = normalize_room_url(url_or_id)
web_rid = extract_room_id(source_url)
if not web_rid:
return {"ok": False, "is_live": False, "status": "error", "error": "无效直播间地址"}
timeout = httpx.Timeout(20.0, connect=10.0)
last_err = ""
async with httpx.AsyncClient(
timeout=timeout,
proxy=proxy,
http2=False,
verify=False,
trust_env=False,
) as client:
try:
room = await _fetch_web_enter(client, web_rid, cookie=cookie)
return _normalize_result(room, source_url)
except RiskControlError as exc:
last_err = str(exc)
if not allow_html_fallback:
return {
"ok": False,
"is_live": False,
"status": "error",
"error": last_err,
"risk": True,
"source_url": source_url,
"room_id": web_rid,
"anchor_name": "",
"title": "",
"stream_url": "",
}
except Exception as exc:
last_err = str(exc)
if not allow_html_fallback:
return {
"ok": False,
"is_live": False,
"status": "error",
"error": last_err,
"source_url": source_url,
"room_id": web_rid,
"anchor_name": "",
"title": "",
"stream_url": "",
}
try:
room = await _fetch_html(client, source_url, cookie=cookie)
return _normalize_result(room, source_url)
except RiskControlError as exc:
return {
"ok": False,
"is_live": False,
"status": "error",
"error": f"{last_err}; {exc}".strip("; "),
"risk": True,
"source_url": source_url,
"room_id": web_rid,
"anchor_name": "",
"title": "",
"stream_url": "",
}
except Exception as exc:
last_err = f"{last_err}; {exc}".strip("; ")
return {
"ok": False,
"is_live": False,
"status": "error",
"error": last_err or "检查失败",
"source_url": source_url,
"room_id": web_rid,
"anchor_name": "",
"title": "",
"stream_url": "",
}

49
backend/app/events_bus.py Normal file
View File

@ -0,0 +1,49 @@
from __future__ import annotations
import asyncio
import json
from collections import deque
from typing import Any
class EventBus:
"""In-process fan-out for SSE clients."""
def __init__(self, history: int = 50) -> None:
self._subs: set[asyncio.Queue] = set()
self._history: deque[dict[str, Any]] = deque(maxlen=history)
self._lock = asyncio.Lock()
def publish_sync(self, event: dict[str, Any]) -> None:
self._history.append(event)
dead: list[asyncio.Queue] = []
for q in list(self._subs):
try:
q.put_nowait(event)
except Exception:
dead.append(q)
for q in dead:
self._subs.discard(q)
async def subscribe(self) -> asyncio.Queue:
q: asyncio.Queue = asyncio.Queue(maxsize=100)
async with self._lock:
self._subs.add(q)
for item in self._history:
try:
q.put_nowait(item)
except Exception:
break
return q
async def unsubscribe(self, q: asyncio.Queue) -> None:
async with self._lock:
self._subs.discard(q)
@staticmethod
def encode(event: dict[str, Any]) -> str:
payload = json.dumps(event, ensure_ascii=False, default=str)
return f"data: {payload}\n\n"
bus = EventBus()

548
backend/app/main.py Normal file
View File

@ -0,0 +1,548 @@
from __future__ import annotations
import asyncio
import csv
import io
import time
from contextlib import asynccontextmanager
from typing import Any, Optional
from urllib.parse import quote
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from . import cookie_loader, db, pb_sync
from .config import settings
from .cover import capture_cover, cover_path_for
from .douyin import check_room
from .events_bus import bus
from .models import (
BlacklistCreate,
PurgeEventsBody,
RoomBatchCreate,
RoomBulkAction,
RoomCreate,
RoomUpdate,
SettingsUpdate,
)
from .monitor import monitor
from .stats import summarize_sessions
@asynccontextmanager
async def lifespan(_: FastAPI):
db.init_db()
try:
cookie_loader.bootstrap_cookie_into_db()
except Exception:
pass
async def _pb_boot() -> None:
try:
await pb_sync.ensure_collections()
except Exception:
pass
asyncio.create_task(_pb_boot())
await monitor.start()
yield
await monitor.stop()
app = FastAPI(title="Douyin Live Monitor", version="0.2.0", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=[o.strip() for o in settings.cors_origins.split(",") if o.strip()],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
covers_dir = settings.covers_dir
covers_dir.mkdir(parents=True, exist_ok=True)
app.mount("/covers", StaticFiles(directory=str(covers_dir)), name="covers")
@app.get("/api/health")
async def health() -> dict[str, Any]:
pb = await pb_sync.health()
return {"ok": True, "time": time.time(), "pocketbase": pb, "monitor": monitor.status()}
@app.get("/api/monitor/status")
async def monitor_status() -> dict[str, Any]:
return monitor.status()
@app.post("/api/monitor/start")
async def monitor_start() -> dict[str, Any]:
db.update_settings_map({"monitor_enabled": True})
await monitor.start()
return monitor.status()
@app.post("/api/monitor/stop")
async def monitor_stop() -> dict[str, Any]:
db.update_settings_map({"monitor_enabled": False})
return monitor.status()
@app.post("/api/monitor/clear-risk")
async def monitor_clear_risk() -> dict[str, Any]:
monitor.clear_risk_pause()
db.add_event(kind="ops", level="info", message="手动清除风控暂停")
return monitor.status()
@app.post("/api/monitor/check/{room_pk}")
async def monitor_check_one(room_pk: str) -> dict[str, Any]:
room = db.get_room(room_pk)
if not room:
raise HTTPException(404, "直播间不存在")
result = await monitor.check_one(room)
return {"result": result, "room": db.get_room(room_pk)}
@app.get("/api/settings")
async def get_settings() -> dict[str, Any]:
return db.get_settings_map()
@app.patch("/api/settings")
async def patch_settings(body: SettingsUpdate) -> dict[str, Any]:
patch = body.model_dump(exclude_none=True)
return db.update_settings_map(patch)
@app.post("/api/settings/sync-cookie")
async def sync_cookie_from_sh2() -> dict[str, Any]:
"""Pull 抖音cookie from sh2 d2ypp2/config/config.ini into settings."""
result = cookie_loader.force_sync_cookie_from_sh2()
if not result.get("ok"):
raise HTTPException(404, "未找到 sh2 config.ini 中的抖音cookie")
cfg = db.get_settings_map()
return {
**result,
"has_cookie": bool(str(cfg.get("dy_cookie") or "").strip()),
"monitor": monitor.status(),
}
@app.get("/api/rooms")
async def rooms_list(
q: str = "",
enabled: Optional[bool] = None,
status: str = "",
tag: str = "",
limit: int = Query(500, ge=1, le=2000),
offset: int = Query(0, ge=0),
) -> dict[str, Any]:
return db.list_rooms(q=q, enabled=enabled, status=status, tag=tag, limit=limit, offset=offset)
@app.get("/api/rooms/tags")
async def rooms_tags() -> dict[str, Any]:
return {"tags": db.list_all_tags()}
@app.post("/api/rooms")
async def rooms_create(body: RoomCreate) -> dict[str, Any]:
try:
room = db.create_room(body.url, note=body.note, enabled=body.enabled, tags=body.tags)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
try:
await pb_sync.sync_room(room)
except Exception:
pass
return {"room": room}
@app.post("/api/rooms/batch")
async def rooms_batch_create(body: RoomBatchCreate) -> dict[str, Any]:
raw_lines = (body.urls or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
lines: list[str] = []
seen: set[str] = set()
for line in raw_lines:
text = line.strip()
if not text or text.startswith("#"):
continue
token = text.split(",")[0].split()[0].strip()
if not token or token in seen:
continue
seen.add(token)
lines.append(token)
if not lines:
raise HTTPException(400, "没有有效的直播间 URL / 房间号")
created: list[dict[str, Any]] = []
skipped: list[dict[str, str]] = []
for item in lines:
try:
room = db.create_room(item, note=body.note, enabled=body.enabled, tags=body.tags)
created.append(room)
try:
await pb_sync.sync_room(room)
except Exception:
pass
except ValueError as exc:
skipped.append({"url": item, "reason": str(exc)})
return {
"created": created,
"skipped": skipped,
"created_count": len(created),
"skipped_count": len(skipped),
"total_input": len(lines),
}
@app.post("/api/rooms/bulk")
async def rooms_bulk(body: RoomBulkAction) -> dict[str, Any]:
try:
result = db.bulk_rooms(body.action, body.ids, tags=body.tags)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
db.add_event(
kind="ops",
level="info",
message=f"批量 {body.action}:{result.get('affected')} 个直播间",
meta={"ids": body.ids[:20]},
)
return result
@app.patch("/api/rooms/{room_pk}")
async def rooms_update(room_pk: str, body: RoomUpdate) -> dict[str, Any]:
try:
room = db.update_room(
room_pk,
url=body.url,
note=body.note,
enabled=body.enabled,
tags=body.tags,
)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
try:
await pb_sync.sync_room(room)
except Exception:
pass
return {"room": room}
@app.delete("/api/rooms/{room_pk}")
async def rooms_delete(room_pk: str) -> dict[str, str]:
db.delete_room(room_pk)
return {"ok": "true"}
@app.post("/api/rooms/probe")
async def rooms_probe(body: RoomCreate) -> dict[str, Any]:
cfg = db.get_settings_map()
result = await check_room(
body.url,
cookie=str(cfg.get("dy_cookie") or ""),
proxy=str(cfg.get("http_proxy") or "").strip() or None,
)
return result
@app.get("/api/blacklist")
async def blacklist_list() -> dict[str, Any]:
items = db.list_blacklist()
return {"items": items, "total": len(items)}
@app.post("/api/blacklist")
async def blacklist_add(body: BlacklistCreate) -> dict[str, Any]:
try:
item = db.add_blacklist(body.value, reason=body.reason)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
db.add_event(
kind="blacklist",
level="warn",
message=f"加入黑名单:{body.value}",
room_id=item.get("room_id") or "",
meta={"disabled_rooms": item.get("disabled_rooms"), "reason": body.reason},
)
return {"item": item}
@app.delete("/api/blacklist/{item_id}")
async def blacklist_delete(item_id: str) -> dict[str, str]:
db.delete_blacklist(item_id)
return {"ok": "true"}
@app.get("/api/events")
async def events_list(
kind: str = "",
q: str = "",
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
) -> dict[str, Any]:
return db.list_events(kind=kind, q=q, limit=limit, offset=offset)
@app.get("/api/events/stream")
async def events_stream():
async def gen():
q = await bus.subscribe()
try:
yield 'event: hello\ndata: {"ok":true}\n\n'
while True:
try:
item = await asyncio.wait_for(q.get(), timeout=20)
yield bus.encode(item)
except asyncio.TimeoutError:
yield ": keepalive\n\n"
finally:
await bus.unsubscribe(q)
return StreamingResponse(
gen(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
@app.post("/api/events/purge")
async def events_purge(body: PurgeEventsBody) -> dict[str, Any]:
deleted = db.purge_events(older_than_days=body.older_than_days, kind=body.kind)
db.add_event(kind="ops", level="info", message=f"清理事件 {deleted} 条(>{body.older_than_days}天)")
return {"deleted": deleted}
@app.get("/api/sessions/active")
async def sessions_active() -> dict[str, Any]:
items = db.list_active_sessions()
return {"sessions": items, "total": len(items)}
@app.post("/api/sessions/end-all-active")
async def sessions_end_all_active() -> dict[str, Any]:
n = db.end_all_active_sessions(end_reason="manual")
db.add_event(kind="ops", level="warn", message=f"手动结束全部进行中场次:{n}")
return {"ended": n}
@app.get("/api/anchors")
async def anchors_list(limit: int = Query(50, ge=1, le=200)) -> dict[str, Any]:
return {"anchors": db.list_anchors(limit=limit)}
@app.get("/api/anchors/{key}")
async def anchors_detail(key: str) -> dict[str, Any]:
profile = db.anchor_profile(key)
if not profile:
raise HTTPException(404, "未找到主播画像")
return profile
@app.get("/api/rooms/export")
async def rooms_export(format: str = Query("csv", pattern="^(csv|json)$")) -> Any:
rows = db.export_rooms_rows()
if format == "json":
return {"rooms": rows, "total": len(rows)}
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(["id", "room_id", "url", "note", "tags", "enabled", "last_status", "last_anchor", "last_checked_at"])
for r in rows:
writer.writerow(
[
r.get("id"),
r.get("room_id"),
r.get("url"),
r.get("note"),
",".join(r.get("tags") or []),
1 if r.get("enabled") else 0,
r.get("last_status"),
r.get("last_anchor"),
r.get("last_checked_at"),
]
)
buf.seek(0)
filename = f"rooms_{time.strftime('%Y%m%d_%H%M%S')}.csv"
return StreamingResponse(
iter(["\ufeff" + buf.getvalue()]),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"},
)
@app.get("/api/sessions")
async def sessions_list(
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
) -> dict[str, Any]:
return db.list_sessions(q=q, date_from=date_from, date_to=date_to, status=status, limit=limit, offset=offset)
@app.get("/api/sessions/stats")
async def sessions_stats(
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
top_anchors: int = Query(25, ge=1, le=50),
) -> dict[str, Any]:
return summarize_sessions(q=q, date_from=date_from, date_to=date_to, status=status, top_anchors=top_anchors)
@app.get("/api/sessions/export")
async def sessions_export(
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
format: str = Query("csv", pattern="^(csv|json)$"),
) -> Any:
rows = db.export_sessions_rows(q=q, date_from=date_from, date_to=date_to, status=status, limit=5000)
if format == "json":
return {"sessions": rows, "total": len(rows)}
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(
["id", "anchor_name", "room_id", "source_url", "title", "started_at", "ended_at", "duration_seconds", "push_date", "status", "end_reason"]
)
for s in rows:
writer.writerow(
[
s.get("id"),
s.get("anchor_name"),
s.get("room_id"),
s.get("source_url"),
s.get("title"),
s.get("started_at"),
s.get("ended_at") or "",
s.get("duration_seconds"),
s.get("push_date"),
s.get("status"),
s.get("end_reason"),
]
)
buf.seek(0)
filename = f"sessions_{time.strftime('%Y%m%d_%H%M%S')}.csv"
return StreamingResponse(
iter([buf.getvalue()]),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
@app.get("/api/sessions/{session_id}")
async def sessions_detail(session_id: str) -> dict[str, Any]:
session = db.get_session(session_id)
if not session:
raise HTTPException(404, "场次不存在")
return {"session": session}
@app.get("/api/sessions/{session_id}/cover")
async def sessions_cover(session_id: str):
path = cover_path_for(session_id)
if not path:
raise HTTPException(404, "无截图")
return FileResponse(path, media_type="image/jpeg")
@app.post("/api/sessions/{session_id}/recapture")
async def sessions_recapture(session_id: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
session = db.get_session(session_id)
if not session:
raise HTTPException(404, "场次不存在")
stream_url = ""
if body:
stream_url = str(body.get("stream_url") or "")
if not stream_url:
# probe room for current stream if still live
room = db.get_room(session.get("room_pk") or "")
if room:
cfg = db.get_settings_map()
result = await check_room(
room["url"],
cookie=str(cfg.get("dy_cookie") or ""),
proxy=str(cfg.get("http_proxy") or "").strip() or None,
)
stream_url = str(result.get("stream_url") or "")
if not stream_url:
raise HTTPException(400, "无法获取流地址,直播间可能已停播")
path = await capture_cover(session_id, stream_url)
if not path:
raise HTTPException(500, "截图失败")
return {"cover_url": f"/api/sessions/{session_id}/cover", "path": path}
@app.post("/api/pb/bootstrap")
async def pb_bootstrap() -> dict[str, Any]:
return await pb_sync.ensure_collections()
@app.post("/api/demo/seed")
async def demo_seed() -> dict[str, Any]:
created_rooms = []
samples = [
("https://live.douyin.com/123456789012", "示例直播间 A", "demo"),
("https://live.douyin.com/234567890123", "示例直播间 B", "demo"),
("https://live.douyin.com/345678901234", "示例直播间 C", "demo"),
]
for url, note, tags in samples:
try:
created_rooms.append(db.create_room(url, note=note, enabled=True, tags=tags))
except ValueError:
pass
now = time.time()
if created_rooms:
for i, room in enumerate(created_rooms[:2]):
sid = db.start_session(
room_pk=room["id"],
room_id=room["room_id"],
source_url=room["url"],
anchor_name=f"示例主播{i+1}",
title="演示场次",
)
with db._lock:
conn = db._connect()
try:
started = now - (3600 * (i + 2)) - (i * 86400)
ended = started + 3600 * (1.5 + i)
conn.execute(
"""
UPDATE sessions SET started_at = ?, ended_at = ?, duration_seconds = ?,
status = 'ended', end_reason = 'demo', push_date = date(?, 'unixepoch', 'localtime'),
updated_at = ? WHERE id = ?
""",
(started, ended, ended - started, started, now, sid["id"]),
)
conn.execute(
"UPDATE rooms SET active_session_id = '', last_status = 'offline', last_anchor = ?, updated_at = ? WHERE id = ?",
(f"示例主播{i+1}", now, room["id"]),
)
conn.commit()
finally:
conn.close()
db.add_event(
kind="demo",
level="info",
message=f"演示场次:示例主播{i+1}",
room_id=room["room_id"],
room_pk=room["id"],
session_id=sid["id"],
anchor_name=f"示例主播{i+1}",
)
return {"rooms": created_rooms, "message": "已写入演示数据"}

107
backend/app/models.py Normal file
View File

@ -0,0 +1,107 @@
from __future__ import annotations
import re
from datetime import datetime
from typing import Any, Optional
from pydantic import BaseModel, Field
def extract_room_id(url_or_id: str) -> str:
text = (url_or_id or "").strip()
if not text:
return ""
if re.fullmatch(r"\d{6,}", text):
return text
m = re.search(r"live\.douyin\.com/([A-Za-z0-9_\-]+)", text)
if m:
return m.group(1).split("?")[0]
m = re.search(r"/(\d{8,})", text)
return m.group(1) if m else ""
def normalize_room_url(url_or_id: str) -> str:
rid = extract_room_id(url_or_id)
if rid:
return f"https://live.douyin.com/{rid}"
text = (url_or_id or "").strip()
if text.startswith("http"):
return text.split("?")[0].rstrip("/")
return text
def push_date_from_ts(ts: float) -> str:
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d")
class RoomCreate(BaseModel):
url: str
note: str = ""
enabled: bool = True
tags: str = ""
class RoomBatchCreate(BaseModel):
urls: str = Field(..., description="多行直播间 URL / 房间号,每行一个")
note: str = ""
enabled: bool = True
tags: str = ""
class RoomUpdate(BaseModel):
url: Optional[str] = None
note: Optional[str] = None
enabled: Optional[bool] = None
tags: Optional[str] = None
class RoomBulkAction(BaseModel):
action: str = Field(..., description="enable|disable|delete|set_tags|add_tags|check_queue")
ids: list[str]
tags: str = ""
class BlacklistCreate(BaseModel):
value: str = Field(..., description="房间号、URL 或关键词")
reason: str = ""
class SettingsUpdate(BaseModel):
max_concurrency: Optional[int] = None
min_request_gap_sec: Optional[float] = None
request_jitter_sec: Optional[float] = None
offline_interval_sec: Optional[float] = None
live_interval_sec: Optional[float] = None
error_backoff_base_sec: Optional[float] = None
error_backoff_max_sec: Optional[float] = None
global_pause_on_risk_sec: Optional[float] = None
capture_cover_on_start: Optional[bool] = None
monitor_enabled: Optional[bool] = None
dy_cookie: Optional[str] = None
http_proxy: Optional[str] = None
notify_webhook_url: Optional[str] = None
notify_on_live: Optional[bool] = None
notify_on_offline: Optional[bool] = None
notify_on_risk: Optional[bool] = None
quiet_hours_enabled: Optional[bool] = None
quiet_hours_start: Optional[int] = None
quiet_hours_end: Optional[int] = None
priority_interval_sec: Optional[float] = None
class PurgeEventsBody(BaseModel):
older_than_days: float = 7
kind: str = ""
class MonitorStatus(BaseModel):
running: bool
monitor_enabled: bool
checked_total: int = 0
live_count: int = 0
room_count: int = 0
blacklist_count: int = 0
risk_paused_until: float = 0
last_error: str = ""
last_check_at: float = 0
config: dict[str, Any] = Field(default_factory=dict)

344
backend/app/monitor.py Normal file
View File

@ -0,0 +1,344 @@
from __future__ import annotations
import asyncio
import random
import time
from typing import Any, Optional
from . import db
from . import pb_sync
from .config import settings
from .cover import capture_cover
from .douyin import RiskControlError, check_room
from .notify import send_webhook
class MonitorService:
def __init__(self) -> None:
self._task: Optional[asyncio.Task] = None
self._stop = asyncio.Event()
self.checked_total = 0
self.last_error = ""
self.last_check_at = 0.0
self.risk_paused_until = 0.0
self._last_request_at = 0.0
self._lock = asyncio.Lock()
@property
def running(self) -> bool:
return self._task is not None and not self._task.done()
def clear_risk_pause(self) -> None:
self.risk_paused_until = 0.0
self.last_error = ""
def status(self) -> dict[str, Any]:
cfg = db.get_settings_map()
counts = db.counts()
return {
"running": self.running,
"monitor_enabled": bool(cfg.get("monitor_enabled", True)),
"checked_total": self.checked_total,
"live_count": counts["live_rooms"],
"room_count": counts["rooms"],
"blacklist_count": counts["blacklist"],
"events_count": counts.get("events", 0),
"risk_paused_until": self.risk_paused_until,
"last_error": self.last_error,
"last_check_at": self.last_check_at,
"config": {
"max_concurrency": cfg.get("max_concurrency", settings.max_concurrency),
"min_request_gap_sec": cfg.get("min_request_gap_sec", settings.min_request_gap_sec),
"request_jitter_sec": cfg.get("request_jitter_sec", settings.request_jitter_sec),
"offline_interval_sec": cfg.get("offline_interval_sec", settings.offline_interval_sec),
"live_interval_sec": cfg.get("live_interval_sec", settings.live_interval_sec),
"error_backoff_base_sec": cfg.get("error_backoff_base_sec", settings.error_backoff_base_sec),
"error_backoff_max_sec": cfg.get("error_backoff_max_sec", settings.error_backoff_max_sec),
"global_pause_on_risk_sec": cfg.get("global_pause_on_risk_sec", settings.global_pause_on_risk_sec),
"capture_cover_on_start": cfg.get("capture_cover_on_start", settings.capture_cover_on_start),
"has_cookie": bool(str(cfg.get("dy_cookie") or "").strip()),
"has_proxy": bool(str(cfg.get("http_proxy") or "").strip()),
"has_webhook": bool(str(cfg.get("notify_webhook_url") or "").strip()),
},
}
async def start(self) -> None:
if self.running:
return
self._stop.clear()
self._task = asyncio.create_task(self._loop(), name="douyin-monitor")
async def stop(self) -> None:
self._stop.set()
if self._task:
try:
await asyncio.wait_for(self._task, timeout=5)
except Exception:
self._task.cancel()
self._task = None
async def _throttle(self, cfg: dict[str, Any]) -> None:
gap = float(cfg.get("min_request_gap_sec", settings.min_request_gap_sec))
jitter = float(cfg.get("request_jitter_sec", settings.request_jitter_sec))
wait = gap + random.uniform(0, max(0.0, jitter))
elapsed = time.time() - self._last_request_at
if elapsed < wait:
await asyncio.sleep(wait - elapsed)
self._last_request_at = time.time()
def _next_interval(self, cfg: dict[str, Any], *, live: bool, errors: int, priority: bool = False) -> float:
# sh2: delay_default ± random(-5, 5); extra +60 when error spike
if errors > 0:
base = float(cfg.get("error_backoff_base_sec", settings.error_backoff_base_sec))
cap = float(cfg.get("error_backoff_max_sec", settings.error_backoff_max_sec))
return min(cap, base * (2 ** min(errors, 3))) + random.uniform(0, 30)
if live:
base = float(cfg.get("live_interval_sec", settings.live_interval_sec))
elif priority:
base = float(cfg.get("priority_interval_sec", 90.0))
else:
base = float(cfg.get("offline_interval_sec", settings.offline_interval_sec))
# sh2-style jitter around loop interval
return max(30.0, base + random.uniform(-5, 5) + random.uniform(0, min(20.0, base * 0.1)))
@staticmethod
def _in_quiet_hours(cfg: dict[str, Any]) -> bool:
if not cfg.get("quiet_hours_enabled"):
return False
start = int(cfg.get("quiet_hours_start", 2)) % 24
end = int(cfg.get("quiet_hours_end", 7)) % 24
hour = time.localtime().tm_hour
if start == end:
return False
if start < end:
return start <= hour < end
return hour >= start or hour < end
@staticmethod
def _is_priority(room: dict[str, Any]) -> bool:
tags = room.get("tags") or []
if isinstance(tags, str):
tags = [t.strip() for t in tags.split(",") if t.strip()]
return any(t in {"重点", "priority", "vip", "高优"} for t in tags)
async def check_one(self, room: dict[str, Any]) -> dict[str, Any]:
cfg = db.get_settings_map()
cookie = str(cfg.get("dy_cookie") or "")
proxy = str(cfg.get("http_proxy") or "").strip() or None
async with self._lock:
await self._throttle(cfg)
try:
result = await check_room(room["url"], cookie=cookie, proxy=proxy)
except RiskControlError as exc:
result = {
"ok": False,
"is_live": False,
"status": "error",
"error": str(exc),
"risk": True,
"room_id": room.get("room_id"),
}
self.checked_total += 1
self.last_check_at = time.time()
if result.get("risk") and not result.get("ok"):
self.last_error = str(result.get("error") or "风控")
# sh2-style: short cool-down (+60s when errors spike), not multi-minute melt
pause = float(cfg.get("global_pause_on_risk_sec", settings.global_pause_on_risk_sec))
pause = max(30.0, min(pause, 120.0)) + random.uniform(0, 15)
self.risk_paused_until = time.time() + pause
nxt = time.time() + pause
db.touch_room(
room["id"],
last_status=room.get("last_status") or "unknown",
next_check_at=nxt,
error_count=int(room.get("error_count") or 0) + 1,
last_error=self.last_error,
active_session_id=room.get("active_session_id") or "",
)
db.add_event(
kind="risk",
level="warn",
message=f"触发风控,冷却 {int(pause)}s:{self.last_error}",
room_id=room.get("room_id") or "",
room_pk=room["id"],
anchor_name=room.get("last_anchor") or "",
)
await send_webhook(
"risk",
{
"message": f"抖音风控:{self.last_error}",
"room_id": room.get("room_id"),
"pause_sec": pause,
},
)
return {"room_id": room["room_id"], "error": self.last_error, "risk": True}
if not result.get("ok"):
errors = int(room.get("error_count") or 0) + 1
nxt = time.time() + self._next_interval(
cfg, live=False, errors=errors, priority=self._is_priority(room)
)
err = str(result.get("error") or "check failed")
db.touch_room(
room["id"],
last_status="error",
next_check_at=nxt,
error_count=errors,
last_error=err,
active_session_id=room.get("active_session_id") or "",
)
self.last_error = err
if errors == 1 or errors % 5 == 0:
db.add_event(
kind="error",
level="warn",
message=err,
room_id=room.get("room_id") or "",
room_pk=room["id"],
)
return result
is_live = bool(result.get("is_live"))
# Re-read room to avoid duplicate go-live under concurrent checks
fresh = db.get_room(room["id"]) or room
prev = fresh.get("last_status")
active_sid = fresh.get("active_session_id") or ""
anchor = result.get("anchor_name") or fresh.get("last_anchor") or ""
if is_live:
if prev != "live" or not active_sid:
session = db.start_session(
room_pk=room["id"],
room_id=result.get("room_id") or room["room_id"],
source_url=result.get("source_url") or room["url"],
anchor_name=anchor,
title=result.get("title") or "",
metadata={"raw": result.get("raw") or {}},
)
active_sid = session["id"]
# Only emit live event / cover when a NEW session was created
if not session.get("_reused"):
db.add_event(
kind="live",
level="info",
message=f"开播:{anchor or room.get('room_id')}",
room_id=result.get("room_id") or room["room_id"],
room_pk=room["id"],
session_id=active_sid,
anchor_name=anchor,
)
await send_webhook(
"live",
{
"message": f"开播 {anchor or room.get('room_id')}",
"room_id": room.get("room_id"),
"url": room.get("url"),
"session_id": active_sid,
"anchor_name": anchor,
},
)
try:
await pb_sync.sync_session(session)
except Exception:
pass
if cfg.get("capture_cover_on_start", True) and result.get("stream_url"):
asyncio.create_task(capture_cover(active_sid, result["stream_url"]))
nxt = time.time() + self._next_interval(cfg, live=True, errors=0, priority=self._is_priority(room))
db.touch_room(
room["id"],
last_status="live",
last_anchor=anchor,
last_title=result.get("title") or "",
next_check_at=nxt,
error_count=0,
last_error="",
active_session_id=active_sid,
)
else:
if prev == "live" and active_sid:
ended = db.end_session(active_sid, end_reason="offline")
db.add_event(
kind="offline",
level="info",
message=f"停播:{anchor or room.get('room_id')}",
room_id=room.get("room_id") or "",
room_pk=room["id"],
session_id=active_sid,
anchor_name=anchor,
meta={"duration_seconds": (ended or {}).get("duration_seconds")},
)
await send_webhook(
"offline",
{
"message": f"停播 {anchor or room.get('room_id')}",
"room_id": room.get("room_id"),
"session_id": active_sid,
"duration_seconds": (ended or {}).get("duration_seconds"),
},
)
if ended:
try:
await pb_sync.sync_session(ended)
except Exception:
pass
active_sid = ""
nxt = time.time() + self._next_interval(
cfg, live=False, errors=0, priority=self._is_priority(room)
)
db.touch_room(
room["id"],
last_status="offline",
last_anchor=anchor,
last_title=result.get("title") or "",
next_check_at=nxt,
error_count=0,
last_error="",
active_session_id=active_sid,
)
try:
updated = db.get_room(room["id"])
if updated:
await pb_sync.sync_room(updated)
except Exception:
pass
return result
async def _loop(self) -> None:
while not self._stop.is_set():
cfg = db.get_settings_map()
if not cfg.get("monitor_enabled", True):
await asyncio.sleep(2)
continue
if time.time() < self.risk_paused_until:
await asyncio.sleep(1)
continue
if self._in_quiet_hours(cfg):
await asyncio.sleep(5)
continue
rooms = db.due_rooms(limit=int(cfg.get("max_concurrency", settings.max_concurrency)) * 3)
if not rooms:
await asyncio.sleep(1.5)
continue
# priority rooms first
rooms.sort(key=lambda r: (0 if self._is_priority(r) else 1, float(r.get("next_check_at") or 0)))
concurrency = max(1, int(cfg.get("max_concurrency", settings.max_concurrency)))
sem = asyncio.Semaphore(concurrency)
async def _wrapped(room: dict[str, Any]) -> None:
async with sem:
try:
await self.check_one(room)
except Exception as exc:
self.last_error = str(exc)
await asyncio.gather(*[_wrapped(r) for r in rooms[:concurrency]])
await asyncio.sleep(0.2)
monitor = MonitorService()

36
backend/app/notify.py Normal file
View File

@ -0,0 +1,36 @@
from __future__ import annotations
import asyncio
from typing import Any
import httpx
from . import db
async def send_webhook(event: str, payload: dict[str, Any]) -> None:
cfg = db.get_settings_map()
url = str(cfg.get("notify_webhook_url") or "").strip()
if not url:
return
if event == "live" and not cfg.get("notify_on_live", True):
return
if event == "offline" and not cfg.get("notify_on_offline", False):
return
if event == "risk" and not cfg.get("notify_on_risk", True):
return
body = {
"event": event,
"text": payload.get("message") or event,
"payload": payload,
}
async def _post() -> None:
try:
async with httpx.AsyncClient(timeout=8.0, trust_env=False) as client:
await client.post(url, json=body)
except Exception:
pass
asyncio.create_task(_post())

227
backend/app/pb_sync.py Normal file
View File

@ -0,0 +1,227 @@
"""
PocketBase bootstrap + lightweight sync helpers.
Local SQLite is the hot path for the monitor worker.
PocketBase is used as the admin-facing datastore / backup mirror.
"""
from __future__ import annotations
import time
from typing import Any, Optional
import httpx
from .config import settings
_token: str = ""
_token_expire: float = 0
async def _client() -> httpx.AsyncClient:
return httpx.AsyncClient(
base_url=settings.pb_url.rstrip("/"),
timeout=20.0,
trust_env=False,
)
async def ensure_admin() -> None:
global _token, _token_expire
async with await _client() as client:
# try login
try:
resp = await client.post(
"/api/collections/_superusers/auth-with-password",
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
)
if resp.status_code == 200:
data = resp.json()
_token = data.get("token") or ""
_token_expire = time.time() + 3600
return
except Exception:
pass
# first-time install
try:
resp = await client.post(
"/api/collections/_superusers/records",
json={
"email": settings.pb_admin_email,
"password": settings.pb_admin_password,
"passwordConfirm": settings.pb_admin_password,
},
)
if resp.status_code in (200, 201):
login = await client.post(
"/api/collections/_superusers/auth-with-password",
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
)
if login.status_code == 200:
_token = login.json().get("token") or ""
_token_expire = time.time() + 3600
except Exception:
pass
async def _auth_headers() -> dict[str, str]:
global _token, _token_expire
if not _token or time.time() > _token_expire - 60:
await ensure_admin()
return {"Authorization": _token} if _token else {}
COLLECTION_DEFS: list[dict[str, Any]] = [
{
"name": "dy_rooms",
"type": "base",
"fields": [
{"name": "url", "type": "url", "required": True},
{"name": "room_id", "type": "text", "required": True},
{"name": "note", "type": "text"},
{"name": "enabled", "type": "bool"},
{"name": "last_status", "type": "text"},
{"name": "last_anchor", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
{
"name": "dy_blacklist",
"type": "base",
"fields": [
{"name": "value", "type": "text", "required": True},
{"name": "room_id", "type": "text"},
{"name": "reason", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
{
"name": "dy_sessions",
"type": "base",
"fields": [
{"name": "room_id", "type": "text"},
{"name": "source_url", "type": "url"},
{"name": "anchor_name", "type": "text"},
{"name": "title", "type": "text"},
{"name": "started_at", "type": "number"},
{"name": "ended_at", "type": "number"},
{"name": "duration_seconds", "type": "number"},
{"name": "push_date", "type": "text"},
{"name": "status", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
]
async def ensure_collections() -> dict[str, Any]:
await ensure_admin()
headers = await _auth_headers()
created: list[str] = []
skipped: list[str] = []
errors: list[str] = []
async with await _client() as client:
existing = await client.get("/api/collections", headers=headers)
names = set()
if existing.status_code == 200:
for item in existing.json().get("items") or []:
names.add(item.get("name"))
for col in COLLECTION_DEFS:
if col["name"] in names:
skipped.append(col["name"])
continue
payload = {
"name": col["name"],
"type": col["type"],
"fields": [
{"name": "id", "type": "text", "primaryKey": True, "system": True},
*col["fields"],
{"name": "created", "type": "autodate", "onCreate": True, "onUpdate": False},
{"name": "updated", "type": "autodate", "onCreate": True, "onUpdate": True},
],
}
resp = await client.post("/api/collections", headers=headers, json=payload)
if resp.status_code in (200, 201):
created.append(col["name"])
else:
errors.append(f"{col['name']}: {resp.status_code} {resp.text[:200]}")
return {"created": created, "skipped": skipped, "errors": errors, "ok": not errors}
async def upsert_record(collection: str, sqlite_id: str, data: dict[str, Any]) -> Optional[str]:
headers = await _auth_headers()
if not headers:
return None
async with await _client() as client:
filt = f'sqlite_id="{sqlite_id}"'
found = await client.get(
f"/api/collections/{collection}/records",
headers=headers,
params={"filter": filt, "perPage": 1},
)
body = {**data, "sqlite_id": sqlite_id}
if found.status_code == 200 and (found.json().get("items") or []):
rid = found.json()["items"][0]["id"]
await client.patch(
f"/api/collections/{collection}/records/{rid}",
headers=headers,
json=body,
)
return rid
resp = await client.post(
f"/api/collections/{collection}/records",
headers=headers,
json=body,
)
if resp.status_code in (200, 201):
return resp.json().get("id")
return None
async def sync_room(room: dict[str, Any]) -> None:
await upsert_record(
"dy_rooms",
room["id"],
{
"url": room.get("url") or "",
"room_id": room.get("room_id") or "",
"note": room.get("note") or "",
"enabled": bool(room.get("enabled")),
"last_status": room.get("last_status") or "",
"last_anchor": room.get("last_anchor") or "",
},
)
async def sync_session(session: dict[str, Any]) -> None:
await upsert_record(
"dy_sessions",
session["id"],
{
"room_id": session.get("room_id") or "",
"source_url": session.get("source_url") or "",
"anchor_name": session.get("anchor_name") or "",
"title": session.get("title") or "",
"started_at": session.get("started_at") or 0,
"ended_at": session.get("ended_at") or 0,
"duration_seconds": session.get("duration_seconds") or 0,
"push_date": session.get("push_date") or "",
"status": session.get("status") or "",
},
)
async def health() -> dict[str, Any]:
try:
async with await _client() as client:
resp = await client.get("/api/health")
ok = resp.status_code == 200
body: Any
try:
body = resp.json()
except Exception:
body = resp.text[:200]
return {"ok": ok, "status_code": resp.status_code, "body": body}
except Exception as exc:
return {"ok": False, "error": str(exc)}

213
backend/app/stats.py Normal file
View File

@ -0,0 +1,213 @@
from __future__ import annotations
import statistics
import time
from collections import defaultdict
from datetime import datetime
from typing import Any
from . import db
WEEKDAY_ZH = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
WEEKDAY_EN = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
def _effective_duration(session: dict[str, Any], now: float) -> float:
started = float(session.get("started_at") or 0)
ended = session.get("ended_at")
stored = float(session.get("duration_seconds") or 0)
if ended:
return max(0.0, float(ended) - started) if started else max(0.0, stored)
if started > 0:
return max(0.0, now - started)
return max(0.0, stored)
def summarize_sessions(
*,
q: str = "",
date_from: str = "",
date_to: str = "",
status: str = "",
top_anchors: int = 20,
) -> dict[str, Any]:
sessions = db.all_sessions_for_stats(q=q, date_from=date_from, date_to=date_to, status=status)
now = time.time()
by_hour_starts = [0] * 24
by_hour_minutes = [0.0] * 24
by_weekday_starts = [0] * 7
by_weekday_minutes = [0.0] * 7
heatmap_starts = [[0 for _ in range(24)] for _ in range(7)]
heatmap_minutes = [[0.0 for _ in range(24)] for _ in range(7)]
by_date: dict[str, dict[str, Any]] = {}
by_anchor: dict[str, dict[str, Any]] = {}
duration_values: list[float] = []
duration_buckets = {"<15m": 0, "15-60m": 0, "1-3h": 0, "3-6h": 0, "6-12h": 0, ">12h": 0}
active_sessions = 0
for s in sessions:
started = float(s.get("started_at") or 0)
if not started:
continue
duration = _effective_duration(s, now)
duration_values.append(duration)
if not s.get("ended_at"):
active_sessions += 1
dt = datetime.fromtimestamp(started)
hour = dt.hour
weekday = dt.weekday()
by_hour_starts[hour] += 1
by_weekday_starts[weekday] += 1
heatmap_starts[weekday][hour] += 1
# occupancy minutes across hours
end_ts = float(s["ended_at"]) if s.get("ended_at") else now
cursor = started
while cursor < end_ts and (end_ts - started) < 48 * 3600:
slot = datetime.fromtimestamp(cursor)
slot_end = min(end_ts, datetime(slot.year, slot.month, slot.day, slot.hour).timestamp() + 3600)
minutes = max(0.0, (slot_end - cursor) / 60.0)
by_hour_minutes[slot.hour] += minutes
by_weekday_minutes[slot.weekday()] += minutes
heatmap_minutes[slot.weekday()][slot.hour] += minutes
cursor = slot_end
if minutes <= 0:
break
date_key = s.get("push_date") or dt.strftime("%Y-%m-%d")
bucket = by_date.setdefault(date_key, {"date": date_key, "sessions": 0, "hours": 0.0, "anchors": set()})
bucket["sessions"] += 1
bucket["hours"] += duration / 3600.0
bucket["anchors"].add(s.get("anchor_name") or s.get("room_id") or "?")
anchor = (s.get("anchor_name") or "").strip() or s.get("room_id") or "未知"
a = by_anchor.setdefault(
anchor,
{
"anchor_name": anchor,
"source_room_id": s.get("room_id") or "",
"sessions": 0,
"hours_total": 0.0,
"durations": [],
"hours": [],
"weekdays": [],
"starts": [],
"dates": set(),
},
)
a["sessions"] += 1
a["hours_total"] += duration / 3600.0
a["durations"].append(duration)
a["hours"].append(hour)
a["weekdays"].append(weekday)
a["starts"].append(started)
a["dates"].add(date_key)
mins = duration / 60.0
if mins < 15:
duration_buckets["<15m"] += 1
elif mins < 60:
duration_buckets["15-60m"] += 1
elif mins < 180:
duration_buckets["1-3h"] += 1
elif mins < 360:
duration_buckets["3-6h"] += 1
elif mins < 720:
duration_buckets["6-12h"] += 1
else:
duration_buckets[">12h"] += 1
top = []
for a in by_anchor.values():
peak_hour = max(range(24), key=lambda h: a["hours"].count(h)) if a["hours"] else 0
peak_wd = max(range(7), key=lambda d: a["weekdays"].count(d)) if a["weekdays"] else 0
starts_sorted = sorted(a["starts"])
gaps = [
(starts_sorted[i] - starts_sorted[i - 1]) / 3600.0
for i in range(1, len(starts_sorted))
if starts_sorted[i] - starts_sorted[i - 1] > 0
]
dates_active = len(a["dates"]) or 1
top.append(
{
"anchor_name": a["anchor_name"],
"source_room_id": a["source_room_id"],
"sessions": a["sessions"],
"hours_total": round(a["hours_total"], 2),
"avg_duration_seconds": int(statistics.mean(a["durations"])) if a["durations"] else 0,
"peak_hour": peak_hour,
"peak_weekday_label": WEEKDAY_ZH[peak_wd],
"dates_active": dates_active,
"sessions_per_active_day": round(a["sessions"] / dates_active, 2),
"avg_gap_hours": round(statistics.mean(gaps), 2) if gaps else None,
}
)
top.sort(key=lambda x: (x["sessions"], x["hours_total"]), reverse=True)
top = top[: max(1, min(top_anchors, 50))]
by_date_list = []
for key in sorted(by_date.keys()):
item = by_date[key]
by_date_list.append(
{
"date": item["date"],
"sessions": item["sessions"],
"hours": round(item["hours"], 2),
"unique_anchors": len(item["anchors"]),
}
)
total_hours = sum(duration_values) / 3600.0 if duration_values else 0.0
insights = []
if duration_values:
busiest_hour = max(range(24), key=lambda h: by_hour_starts[h])
busiest_day = max(range(7), key=lambda d: by_weekday_starts[d])
insights.append(
{
"zh": f"最常开播时段:{busiest_hour:02d}:00–{busiest_hour:02d}:59;最常开播星期:{WEEKDAY_ZH[busiest_day]}。",
"en": f"Busiest hour: {busiest_hour:02d}:00; busiest weekday: {WEEKDAY_EN[busiest_day]}.",
}
)
if top:
insights.append(
{
"zh": f"开播最多主播:{top[0]['anchor_name']}({top[0]['sessions']} 场 / {top[0]['hours_total']} 小时)。",
"en": f"Top anchor: {top[0]['anchor_name']} ({top[0]['sessions']} sessions / {top[0]['hours_total']}h).",
}
)
return {
"overview": {
"sessions": len(sessions),
"unique_anchors": len(by_anchor),
"active_sessions": active_sessions,
"total_hours": round(total_hours, 2),
"avg_duration_seconds": int(statistics.mean(duration_values)) if duration_values else 0,
"median_duration_seconds": int(statistics.median(duration_values)) if duration_values else 0,
"days_span": len(by_date),
"date_from": by_date_list[0]["date"] if by_date_list else "",
"date_to": by_date_list[-1]["date"] if by_date_list else "",
},
"top_anchors": top,
"by_hour": {
"starts": by_hour_starts,
"minutes": [round(x, 1) for x in by_hour_minutes],
"labels": [f"{h:02d}:00" for h in range(24)],
},
"by_weekday": {
"starts": by_weekday_starts,
"minutes": [round(x, 1) for x in by_weekday_minutes],
"labels": WEEKDAY_EN,
"labels_zh": WEEKDAY_ZH,
},
"heatmap": {
"starts": heatmap_starts,
"minutes": [[round(x, 1) for x in row] for row in heatmap_minutes],
"weekday_labels": WEEKDAY_EN,
"weekday_labels_zh": WEEKDAY_ZH,
"hour_labels": [str(h) for h in range(24)],
},
"by_date": by_date_list,
"duration_buckets": duration_buckets,
"insights": insights,
}

7
backend/requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi==0.115.6
uvicorn[standard]==0.34.0
httpx==0.28.1
pydantic==2.10.4
pydantic-settings==2.7.0
python-multipart==0.0.20
aiofiles==24.1.0

4
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
next-env.d.ts
node_modules
.next
out

17
frontend/next.config.mjs Normal file
View File

@ -0,0 +1,17 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return [
{
source: "/api/:path*",
destination: "http://127.0.0.1:8000/api/:path*",
},
{
source: "/covers/:path*",
destination: "http://127.0.0.1:8000/covers/:path*",
},
];
},
};
export default nextConfig;

6451
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

29
frontend/package.json Normal file
View File

@ -0,0 +1,29 @@
{
"name": "douyin-live-monitor",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"echarts": "^5.5.1",
"lucide-react": "^0.468.0",
"next": "15.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"autoprefixer": "^10.4.20",
"eslint": "^9",
"eslint-config-next": "15.1.0",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"typescript": "^5"
}
}

View File

@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

View File

@ -0,0 +1,193 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Loader2, RefreshCw, UserRound } from "lucide-react";
import { Shell } from "@/components/Shell";
import { AnimatedNumber, EmptyState, LivePulse } from "@/components/ui";
import { fetchJson, fmtDuration, fmtTs } from "@/lib/api";
type AnchorRow = {
anchor_name: string;
room_id?: string;
sessions: number;
hours_total: number;
last_started_at?: number;
active?: number;
};
type Profile = {
anchor_name: string;
room_id?: string;
overview: {
sessions: number;
total_hours: number;
avg_duration_seconds: number;
active: number;
last_started_at?: number;
};
sessions: Array<{
id: string;
started_at?: number;
ended_at?: number | null;
duration_seconds?: number;
cover_url?: string;
title?: string;
status?: string;
}>;
rooms: Array<{ id: string; url: string; room_id: string; last_status?: string; enabled?: boolean }>;
};
export default function AnchorsPage() {
const [anchors, setAnchors] = useState<AnchorRow[]>([]);
const [selected, setSelected] = useState<string>("");
const [profile, setProfile] = useState<Profile | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const loadList = useCallback(async () => {
setLoading(true);
setError("");
try {
const data = await fetchJson("/api/anchors?limit=80");
setAnchors(data.anchors || []);
if (!selected && data.anchors?.[0]?.anchor_name) {
setSelected(data.anchors[0].anchor_name);
}
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [selected]);
const loadProfile = useCallback(async (key: string) => {
if (!key) return;
try {
const data = await fetchJson(`/api/anchors/${encodeURIComponent(key)}`);
setProfile(data);
} catch (e) {
setError((e as Error).message);
}
}, []);
useEffect(() => {
void loadList();
}, [loadList]);
useEffect(() => {
if (selected) void loadProfile(selected);
}, [selected, loadProfile]);
return (
<Shell>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">👤 主播画像</h2>
<p className="text-sm text-slate-400">按主播汇总场次、时长与最近表现。</p>
</div>
<button type="button" onClick={() => void loadList()} className="btn-glow inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
</div>
{error ? <div className="mb-4 rounded-xl border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
{!anchors.length && !loading ? (
<EmptyState emoji="🎤" title="还没有主播数据" desc="有开播场次后,这里会自动生成主播排行与画像。" />
) : (
<div className="grid gap-4 lg:grid-cols-[20rem_1fr]">
<aside className="glass-panel max-h-[70vh] space-y-2 overflow-auto rounded-2xl p-3">
{anchors.map((a) => (
<button
key={`${a.anchor_name}-${a.room_id}`}
type="button"
onClick={() => setSelected(a.anchor_name)}
className={`hover-lift w-full rounded-xl border px-3 py-2 text-left text-sm ${
selected === a.anchor_name ? "border-teal-400/40 bg-teal-500/10" : "border-white/10 bg-black/20"
}`}
>
<div className="flex items-center justify-between gap-2">
<span className="truncate font-medium text-white">{a.anchor_name}</span>
{a.active ? <LivePulse label="LIVE" /> : null}
</div>
<div className="mt-1 text-[11px] text-slate-500">
{a.sessions} 场 · {Number(a.hours_total || 0).toFixed(1)}h
</div>
</button>
))}
</aside>
<section className="glass-panel rounded-2xl p-4">
{profile ? (
<>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<div className="flex items-center gap-2">
<UserRound className="h-5 w-5 text-teal-300" />
<h3 className="font-display text-xl font-semibold">{profile.anchor_name}</h3>
{profile.overview.active ? <LivePulse /> : null}
</div>
<p className="mt-1 font-mono text-xs text-cyan-300/80">{profile.room_id || "—"}</p>
</div>
{profile.rooms?.[0]?.url ? (
<a href={profile.rooms[0].url} target="_blank" rel="noreferrer" className="rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs hover:bg-white/10">
打开直播间
</a>
) : null}
</div>
<div className="mb-4 grid gap-3 sm:grid-cols-4">
<div className="rounded-xl border border-white/10 bg-black/20 px-3 py-3">
<div className="text-[11px] text-slate-500">场次</div>
<div className="font-display text-xl"><AnimatedNumber value={profile.overview.sessions} /></div>
</div>
<div className="rounded-xl border border-white/10 bg-black/20 px-3 py-3">
<div className="text-[11px] text-slate-500">累计小时</div>
<div className="font-display text-xl"><AnimatedNumber value={profile.overview.total_hours} decimals={1} /></div>
</div>
<div className="rounded-xl border border-white/10 bg-black/20 px-3 py-3">
<div className="text-[11px] text-slate-500">平均场长</div>
<div className="font-display text-xl">{fmtDuration(profile.overview.avg_duration_seconds)}</div>
</div>
<div className="rounded-xl border border-white/10 bg-black/20 px-3 py-3">
<div className="text-[11px] text-slate-500">最近开播</div>
<div className="text-sm text-slate-200">{fmtTs(profile.overview.last_started_at)}</div>
</div>
</div>
<h4 className="mb-2 text-sm font-medium text-slate-200">最近场次</h4>
<div className="max-h-[420px] space-y-2 overflow-auto">
{profile.sessions.map((s) => (
<div key={s.id} className="flex items-center gap-3 rounded-xl border border-white/5 bg-black/20 p-2">
{s.cover_url ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={`${s.cover_url}?ts=${s.started_at || 0}`} alt="" className="h-14 w-9 rounded object-cover" />
) : (
<div className="flex h-14 w-9 items-center justify-center rounded bg-slate-900 text-[10px] text-slate-600">N/A</div>
)}
<div className="min-w-0 flex-1 text-sm">
<div className="truncate text-slate-200">{s.title || "场次"}</div>
<div className="text-xs text-slate-500">
{fmtTs(s.started_at)} · {fmtDuration(s.duration_seconds)} · {s.status}
</div>
</div>
</div>
))}
</div>
<div className="mt-4 text-xs text-slate-500">
也可在 <Link href="/sessions" className="text-teal-300 hover:underline">场次日志</Link> 中按主播名筛选。
</div>
</>
) : (
<div className="py-16 text-center text-slate-500">选择左侧主播查看画像</div>
)}
</section>
</div>
)}
</Shell>
);
}

View File

@ -0,0 +1,127 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Loader2, Plus, Trash2 } from "lucide-react";
import { Shell } from "@/components/Shell";
import { fetchJson, fmtTs } from "@/lib/api";
type Item = {
id: string;
value: string;
room_id?: string;
reason?: string;
created_at?: number;
};
export default function BlacklistPage() {
const [items, setItems] = useState<Item[]>([]);
const [value, setValue] = useState("");
const [reason, setReason] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const load = useCallback(async () => {
setLoading(true);
setError("");
try {
const data = await fetchJson("/api/blacklist");
setItems(data.items || []);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
async function add() {
try {
await fetchJson("/api/blacklist", {
method: "POST",
body: JSON.stringify({ value, reason }),
});
setValue("");
setReason("");
await load();
} catch (e) {
setError((e as Error).message);
}
}
async function remove(id: string) {
await fetchJson(`/api/blacklist/${id}`, { method: "DELETE" });
await load();
}
return (
<Shell>
<div className="mb-4">
<h2 className="font-display text-2xl font-semibold">🚫 直播间黑名单</h2>
<p className="text-sm text-slate-400">命中后自动停用相关房间并结束进行中场次,不再进入轮询。</p>
</div>
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-[1fr_1fr_auto]">
<label className="block text-xs text-slate-400">
房间号 / URL / 关键词
<input value={value} onChange={(e) => setValue(e.target.value)} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</label>
<label className="block text-xs text-slate-400">
原因
<input value={reason} onChange={(e) => setReason(e.target.value)} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</label>
<div className="flex items-end">
<button
type="button"
disabled={!value.trim()}
onClick={() => void add()}
className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-white/10 px-4 py-2 text-sm hover:bg-white/15 disabled:opacity-50"
>
<Plus className="h-4 w-4" />
加入黑名单
</button>
</div>
</div>
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
<table className="min-w-full text-left text-sm">
<thead className="bg-white/5 text-xs uppercase text-slate-400">
<tr>
<th className="px-3 py-3">内容</th>
<th className="px-3 py-3">房间号</th>
<th className="px-3 py-3">原因</th>
<th className="px-3 py-3">时间</th>
<th className="px-3 py-3">操作</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id} className="border-t border-white/5">
<td className="px-3 py-3 font-mono text-xs">{item.value}</td>
<td className="px-3 py-3">{item.room_id || "—"}</td>
<td className="px-3 py-3 text-slate-400">{item.reason || "—"}</td>
<td className="px-3 py-3 text-slate-400">{fmtTs(item.created_at)}</td>
<td className="px-3 py-3">
<button type="button" onClick={() => void remove(item.id)} className="inline-flex items-center gap-1 rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200">
{loading ? <Loader2 className="h-3 w-3 animate-spin" /> : <Trash2 className="h-3 w-3" />}
移除
</button>
</td>
</tr>
))}
{items.length === 0 ? (
<tr>
<td colSpan={5} className="px-3 py-10 text-center text-slate-500">黑名单为空</td>
</tr>
) : null}
</tbody>
</table>
</div>
</Shell>
);
}

View File

@ -0,0 +1,112 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Loader2, RefreshCw } from "lucide-react";
import { Shell } from "@/components/Shell";
import { fetchJson, fmtDuration, fmtTs } from "@/lib/api";
type Session = {
id: string;
anchor_name?: string;
room_id?: string;
source_url?: string;
started_at?: number;
ended_at?: number | null;
duration_seconds?: number;
cover_url?: string;
push_date?: string;
title?: string;
};
export default function CoversPage() {
const [sessions, setSessions] = useState<Session[]>([]);
const [q, setQ] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [selected, setSelected] = useState<Session | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError("");
try {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
params.set("limit", "100");
const data = await fetchJson(`/api/sessions?${params}`);
setSessions((data.sessions || []).filter((s: Session) => s.cover_url));
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [q]);
useEffect(() => {
void load();
}, [load]);
return (
<Shell>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">🖼️ 截图库</h2>
<p className="text-sm text-slate-400">开播瞬间一帧存证,点击放大查看。</p>
</div>
<button type="button" onClick={() => void load()} className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
</div>
<div className="mb-4">
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="筛选主播 / 房间号…" className="w-full max-w-md rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</div>
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
<div className="stagger grid gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
{sessions.map((s) => (
<button
key={s.id}
type="button"
onClick={() => setSelected(s)}
className="hover-lift group overflow-hidden rounded-2xl border border-white/10 bg-black/30 text-left"
>
<div className="relative overflow-hidden">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={`${s.cover_url}?ts=${s.started_at || 0}`} alt="" className="aspect-[9/16] w-full object-cover transition duration-500 group-hover:scale-105" />
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 pt-8">
<div className="truncate text-xs font-medium text-white">{s.anchor_name || s.room_id || "—"}</div>
</div>
</div>
<div className="p-2 text-[11px] text-slate-500">{fmtTs(s.started_at)}</div>
</button>
))}
</div>
{!loading && sessions.length === 0 ? (
<div className="animate-fade-up rounded-2xl border border-dashed border-white/10 px-4 py-12 text-center">
<div className="mb-2 text-4xl">📷</div>
<div className="font-display text-lg text-white">还没有截图</div>
<p className="mt-1 text-sm text-slate-500">真实开播并成功抓帧后会出现在这里。</p>
</div>
) : null}
{selected ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4" onClick={() => setSelected(null)}>
<div className="max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-2xl border border-white/10 bg-[#0b1626] p-5" onClick={(e) => e.stopPropagation()}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={`${selected.cover_url}?ts=${selected.started_at || 0}`} alt="" className="mx-auto max-h-[60vh] rounded-lg object-contain" />
<div className="mt-3 space-y-1 text-sm">
<div className="font-medium">{selected.anchor_name || "—"}</div>
<div className="font-mono text-xs text-cyan-300">{selected.source_url}</div>
<div className="text-slate-400">开播 {fmtTs(selected.started_at)} · 时长 {fmtDuration(selected.duration_seconds)}</div>
</div>
<button type="button" className="mt-4 text-sm text-slate-400 hover:text-white" onClick={() => setSelected(null)}>关闭</button>
</div>
</div>
) : null}
</Shell>
);
}

View File

@ -0,0 +1,146 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Loader2, RefreshCw } from "lucide-react";
import { Shell } from "@/components/Shell";
import { EmptyState } from "@/components/ui";
import { fetchJson, fmtTs } from "@/lib/api";
type EventItem = {
id: string;
ts: number;
level?: string;
kind?: string;
room_id?: string;
anchor_name?: string;
message?: string;
session_id?: string;
};
const KIND_META: Record<string, { emoji: string; color: string; label: string }> = {
live: { emoji: "🎬", color: "text-rose-300 border-rose-500/30 bg-rose-500/10", label: "开播" },
offline: { emoji: "📴", color: "text-slate-300 border-slate-500/30 bg-slate-500/10", label: "停播" },
risk: { emoji: "⚠️", color: "text-amber-200 border-amber-500/30 bg-amber-500/10", label: "风控" },
error: { emoji: "💥", color: "text-orange-200 border-orange-500/30 bg-orange-500/10", label: "错误" },
blacklist: { emoji: "🚫", color: "text-fuchsia-200 border-fuchsia-500/30 bg-fuchsia-500/10", label: "黑名单" },
ops: { emoji: "🛠️", color: "text-sky-200 border-sky-500/30 bg-sky-500/10", label: "运维" },
demo: { emoji: "✨", color: "text-teal-200 border-teal-500/30 bg-teal-500/10", label: "演示" },
};
export default function EventsPage() {
const [events, setEvents] = useState<EventItem[]>([]);
const [total, setTotal] = useState(0);
const [kind, setKind] = useState("");
const [q, setQ] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const load = useCallback(async () => {
setLoading(true);
setError("");
try {
const params = new URLSearchParams();
if (kind) params.set("kind", kind);
if (q.trim()) params.set("q", q.trim());
params.set("limit", "150");
const data = await fetchJson(`/api/events?${params}`);
setEvents(data.events || []);
setTotal(Number(data.total) || 0);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [kind, q]);
useEffect(() => {
void load();
const t = setInterval(() => void load(), 10000);
return () => clearInterval(t);
}, [load]);
return (
<Shell>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">⚡ 事件时间线</h2>
<p className="text-sm text-slate-400">开播 / 停播 / 风控 / 错误的实时审计流。</p>
</div>
<button type="button" onClick={() => void load()} className="btn-glow inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
</div>
<div className="mb-4 flex flex-wrap gap-2">
{[
["", "全部"],
["live", "开播"],
["offline", "停播"],
["risk", "风控"],
["error", "错误"],
["blacklist", "黑名单"],
].map(([value, label]) => (
<button
key={value || "all"}
type="button"
onClick={() => setKind(value)}
className={`rounded-xl px-3 py-1.5 text-sm transition ${
kind === value ? "bg-white/15 text-white ring-1 ring-teal-400/30" : "bg-white/5 text-slate-400 hover:bg-white/10"
}`}
>
{label}
</button>
))}
<input
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="🔍 搜索消息 / 主播 / 房间号"
className="w-full max-w-sm rounded-xl border border-white/10 bg-slate-900/80 px-3 py-2 text-sm"
/>
<button
type="button"
onClick={async () => {
if (!confirm("清理 7 天前的事件?")) return;
await fetchJson("/api/events/purge", {
method: "POST",
body: JSON.stringify({ older_than_days: 7 }),
});
await load();
}}
className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-sm text-amber-100"
>
🧹 清理 7 天前
</button>
<span className="self-center text-xs text-slate-500">共 {total} 条</span>
</div>
{error ? <div className="mb-4 rounded-xl border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
<div className="timeline-rail stagger space-y-3 pl-1">
{events.map((ev) => {
const meta = KIND_META[ev.kind || ""] || { emoji: "📌", color: "text-teal-200 border-teal-500/30 bg-teal-500/10", label: ev.kind || "event" };
return (
<div key={ev.id} className="hover-lift relative ml-1 rounded-2xl border border-white/10 bg-black/25 px-4 py-3 pl-10">
<span className="absolute left-[4px] top-4 flex h-5 w-5 items-center justify-center rounded-full bg-[#0b1626] text-xs ring-2 ring-teal-400/20">
{meta.emoji}
</span>
<div className="flex flex-wrap items-center gap-2 text-xs text-slate-500">
<span>{fmtTs(ev.ts)}</span>
<span className={`rounded-md border px-1.5 py-0.5 ${meta.color}`}>{meta.label}</span>
{ev.anchor_name ? <span className="text-slate-300">{ev.anchor_name}</span> : null}
{ev.room_id ? <span className="font-mono text-cyan-300/80">{ev.room_id}</span> : null}
</div>
<div className="mt-1.5 text-sm text-slate-100">{ev.message}</div>
</div>
);
})}
</div>
{!loading && events.length === 0 ? (
<EmptyState emoji="🛰️" title="雷达静默中" desc="还没有事件。开播、停播或风控触发后会出现在这条时间线上。" />
) : null}
</Shell>
);
}

View File

@ -0,0 +1,312 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--bg0: #071018;
--bg1: #0f1c2e;
--line: rgba(255, 255, 255, 0.08);
--text: #edf3ff;
--muted: #93a4bd;
--accent: #ff2d55;
--teal: #2dd4bf;
--amber: #fbbf24;
}
html,
body {
min-height: 100%;
}
body {
margin: 0;
color: var(--text);
font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif;
background:
radial-gradient(1100px 520px at 8% -8%, rgba(255, 45, 85, 0.2), transparent 55%),
radial-gradient(900px 480px at 92% 0%, rgba(45, 212, 191, 0.14), transparent 52%),
radial-gradient(700px 400px at 50% 100%, rgba(56, 189, 248, 0.06), transparent 60%),
linear-gradient(160deg, #071018 0%, #0f1c2e 45%, #0a1422 100%);
background-attachment: fixed;
}
* {
box-sizing: border-box;
}
::selection {
background: rgba(255, 45, 85, 0.35);
color: #fff;
}
/* ambient drifting orbs */
.ambient-orb {
position: fixed;
border-radius: 9999px;
filter: blur(60px);
pointer-events: none;
z-index: 0;
opacity: 0.45;
animation: orb-drift 18s ease-in-out infinite;
}
.ambient-orb.a {
width: 280px;
height: 280px;
left: -40px;
top: 120px;
background: rgba(255, 45, 85, 0.35);
}
.ambient-orb.b {
width: 220px;
height: 220px;
right: -30px;
top: 40%;
background: rgba(45, 212, 191, 0.28);
animation-delay: -6s;
animation-duration: 22s;
}
.ambient-orb.c {
width: 180px;
height: 180px;
left: 40%;
bottom: -40px;
background: rgba(56, 189, 248, 0.2);
animation-delay: -11s;
animation-duration: 26s;
}
@keyframes orb-drift {
0%,
100% {
transform: translate3d(0, 0, 0) scale(1);
}
50% {
transform: translate3d(24px, -18px, 0) scale(1.08);
}
}
@keyframes fade-up {
from {
opacity: 0;
transform: translateY(14px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes pulse-ring {
0% {
transform: scale(0.85);
opacity: 0.7;
}
70% {
transform: scale(1.55);
opacity: 0;
}
100% {
transform: scale(1.55);
opacity: 0;
}
}
@keyframes live-blink {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.35;
}
}
@keyframes shimmer {
0% {
background-position: -200% 0;
}
100% {
background-position: 200% 0;
}
}
@keyframes marquee {
from {
transform: translateX(0);
}
to {
transform: translateX(-50%);
}
}
@keyframes float-y {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-6px);
}
}
@keyframes draw-stroke {
from {
stroke-dashoffset: 120;
}
to {
stroke-dashoffset: 0;
}
}
.animate-fade-up {
animation: fade-up 0.55s ease both;
}
.animate-fade-in {
animation: fade-in 0.4s ease both;
}
.stagger > * {
animation: fade-up 0.5s ease both;
}
.stagger > *:nth-child(1) {
animation-delay: 0.02s;
}
.stagger > *:nth-child(2) {
animation-delay: 0.06s;
}
.stagger > *:nth-child(3) {
animation-delay: 0.1s;
}
.stagger > *:nth-child(4) {
animation-delay: 0.14s;
}
.stagger > *:nth-child(5) {
animation-delay: 0.18s;
}
.stagger > *:nth-child(6) {
animation-delay: 0.22s;
}
.stagger > *:nth-child(7) {
animation-delay: 0.26s;
}
.stagger > *:nth-child(8) {
animation-delay: 0.3s;
}
.live-dot {
position: relative;
display: inline-flex;
width: 0.55rem;
height: 0.55rem;
border-radius: 9999px;
background: #ff2d55;
box-shadow: 0 0 0 0 rgba(255, 45, 85, 0.5);
}
.live-dot::after {
content: "";
position: absolute;
inset: -3px;
border-radius: 9999px;
border: 1.5px solid rgba(255, 45, 85, 0.7);
animation: pulse-ring 1.6s ease-out infinite;
}
.glass-panel {
border: 1px solid rgba(255, 255, 255, 0.1);
background: linear-gradient(160deg, rgba(255, 255, 255, 0.07), rgba(255, 255, 255, 0.02));
backdrop-filter: blur(10px);
}
.btn-glow {
transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
}
.btn-glow:hover {
transform: translateY(-1px);
box-shadow: 0 8px 24px rgba(255, 45, 85, 0.25);
}
.nav-chip {
position: relative;
overflow: hidden;
transition: color 0.2s ease, background 0.2s ease, transform 0.2s ease;
}
.nav-chip:hover {
transform: translateY(-1px);
}
.nav-chip.active::before {
content: "";
position: absolute;
inset: 0;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.08), transparent);
background-size: 200% 100%;
animation: shimmer 2.4s linear infinite;
}
.ticker-track {
display: flex;
width: max-content;
animation: marquee 28s linear infinite;
}
.ticker-track:hover {
animation-play-state: paused;
}
.float-slow {
animation: float-y 4.5s ease-in-out infinite;
}
.logo-stroke {
fill: none;
stroke: #2dd4bf;
stroke-width: 2.2;
stroke-linecap: round;
stroke-linejoin: round;
stroke-dasharray: 120;
animation: draw-stroke 1.4s ease forwards;
}
.page-enter {
animation: fade-up 0.45s ease both;
}
.hover-lift {
transition: transform 0.25s ease, border-color 0.25s ease, background 0.25s ease;
}
.hover-lift:hover {
transform: translateY(-3px);
border-color: rgba(45, 212, 191, 0.35);
}
.timeline-rail {
position: relative;
}
.timeline-rail::before {
content: "";
position: absolute;
left: 11px;
top: 8px;
bottom: 8px;
width: 2px;
background: linear-gradient(180deg, rgba(45, 212, 191, 0.5), rgba(255, 45, 85, 0.15), transparent);
}

View File

@ -0,0 +1,25 @@
import "./globals.css";
import { Providers } from "@/components/Providers";
export const metadata = {
title: "抖音直播间监控",
description: "开播/停播/时长/截图监控与可视化分析",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="zh-CN">
<head>
<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=IBM+Plex+Sans:wght@400;500;600&family=Noto+Sans+SC:wght@400;500;700&family=Space+Grotesk:wght@500;700&display=swap"
rel="stylesheet"
/>
</head>
<body className="min-h-screen antialiased">
<Providers>{children}</Providers>
</body>
</html>
);
}

290
frontend/src/app/page.tsx Normal file
View File

@ -0,0 +1,290 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Loader2, RefreshCw, ArrowRight, ShieldOff } from "lucide-react";
import { Shell } from "@/components/Shell";
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
import { AnimatedNumber, LivePulse, StatTile } from "@/components/ui";
import { useToast } from "@/components/Toast";
import { fetchJson, fmtTs } from "@/lib/api";
import { liveElapsed, useEventStream, useNow } from "@/lib/realtime";
type MonitorStatus = {
running: boolean;
monitor_enabled: boolean;
checked_total: number;
live_count: number;
room_count: number;
blacklist_count: number;
events_count?: number;
risk_paused_until: number;
last_error: string;
last_check_at: number;
};
type Room = {
id: string;
url: string;
room_id: string;
last_status: string;
last_anchor?: string;
};
type EventItem = {
id: string;
ts: number;
kind?: string;
message?: string;
anchor_name?: string;
room_id?: string;
};
type ActiveSession = {
id: string;
anchor_name?: string;
room_id?: string;
source_url?: string;
started_at?: number;
cover_url?: string;
};
export default function HomePage() {
const [stats, setStats] = useState<RelayStats | null>(null);
const [status, setStatus] = useState<MonitorStatus | null>(null);
const [rooms, setRooms] = useState<Room[]>([]);
const [events, setEvents] = useState<EventItem[]>([]);
const [active, setActive] = useState<ActiveSession[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const toast = useToast();
const now = useNow(1000);
const { connected, last, tick } = useEventStream(true);
const load = useCallback(async () => {
setLoading(true);
setError("");
try {
const [s, m, r, e, a] = await Promise.all([
fetchJson("/api/sessions/stats?top_anchors=25"),
fetchJson("/api/monitor/status"),
fetchJson("/api/rooms?limit=200"),
fetchJson("/api/events?limit=20"),
fetchJson("/api/sessions/active"),
]);
setStats(s);
setStatus(m);
setRooms(r.rooms || []);
setEvents(e.events || []);
// one card per room_id (guard against stale duplicate actives)
const sessions = (a.sessions || []) as ActiveSession[];
const seen = new Set<string>();
setActive(
sessions.filter((s) => {
const key = s.room_id || s.id;
if (!key || seen.has(key)) return false;
seen.add(key);
return true;
}),
);
} catch (err) {
setError((err as Error).message);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
const t = setInterval(() => void load(), 20000);
return () => clearInterval(t);
}, [load]);
useEffect(() => {
if (!last?.message) return;
setEvents((prev) => {
const next = [{ ...(last as EventItem), id: last.id || `${tick}` }, ...prev.filter((x) => x.id !== last.id)];
return next.slice(0, 30);
});
if (last.kind === "live" || last.kind === "risk") {
toast.push(last.message, last.kind === "risk" ? "warn" : "ok");
void load();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tick]);
const liveRooms = rooms.filter((r) => r.last_status === "live");
const riskActive = !!(status?.risk_paused_until && status.risk_paused_until * 1000 > Date.now());
return (
<Shell>
<section className="mb-6 flex flex-wrap items-end justify-between gap-4">
<div>
<div className="mb-2 flex flex-wrap items-center gap-2">
{status?.monitor_enabled ? <LivePulse label="MONITOR ON" /> : (
<span className="rounded-md border border-slate-500/30 bg-slate-500/10 px-2 py-1 text-[11px] text-slate-300">⏸ 已暂停</span>
)}
{liveRooms.length > 0 ? <LivePulse label={`${liveRooms.length} 路在播`} /> : null}
<span className={`rounded-md border px-2 py-1 text-[11px] ${connected ? "border-teal-500/30 bg-teal-500/10 text-teal-100" : "border-slate-500/30 bg-slate-500/10 text-slate-400"}`}>
{connected ? "🟢 SSE 已连接" : "⚪ SSE 重连中"}
</span>
{riskActive ? (
<span className="rounded-md border border-amber-500/30 bg-amber-500/10 px-2 py-1 text-[11px] text-amber-100">⚠️ 风控熔断中</span>
) : null}
</div>
<h2 className="font-display text-2xl font-semibold tracking-tight">监控雷达台</h2>
<p className="mt-1 text-sm text-slate-400">实时开播态势 · 时段规律 · 事件回放</p>
</div>
<div className="flex flex-wrap gap-2">
<button type="button" onClick={() => void load()} className="btn-glow inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
{riskActive ? (
<button
type="button"
onClick={async () => {
await fetchJson("/api/monitor/clear-risk", { method: "POST" });
await load();
}}
className="btn-glow inline-flex items-center gap-2 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100"
>
<ShieldOff className="h-4 w-4" />
解除风控
</button>
) : null}
<button
type="button"
onClick={async () => {
await fetchJson("/api/demo/seed", { method: "POST" });
await load();
}}
className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
✨ 演示数据
</button>
</div>
</section>
{error ? <div className="mb-4 animate-fade-up rounded-xl border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
<div className="stagger mb-6 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<StatTile emoji="🏠" label="直播间" value={<AnimatedNumber value={status?.room_count || 0} />} hint="已纳入监控队列" accent="sky" />
<StatTile emoji="🔴" label="当前在播" value={<AnimatedNumber value={status?.live_count || 0} />} hint="正在直播中的房间" accent="rose" />
<StatTile emoji="⏱️" label="累计时长" value={<AnimatedNumber value={Number(stats?.overview?.total_hours || 0)} decimals={1} suffix="h" />} hint="历史场次合计" accent="teal" />
<StatTile emoji="🎯" label="检查次数" value={<AnimatedNumber value={status?.checked_total || 0} />} hint={`上次 ${fmtTs(status?.last_check_at)}`} accent="amber" />
</div>
{active.length > 0 ? (
<section className="mb-6 glass-panel rounded-2xl p-4">
<div className="mb-3 flex items-center justify-between">
<h3 className="font-display text-sm font-medium text-slate-100">🔴 进行中场次(实时计时)</h3>
<span className="text-xs text-slate-500">{active.length} 路</span>
</div>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{active.map((s) => (
<a
key={s.id}
href={s.source_url || "#"}
target="_blank"
rel="noreferrer"
className="hover-lift flex items-center gap-3 rounded-xl border border-rose-500/20 bg-rose-500/5 px-3 py-2"
>
{s.cover_url ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={`${s.cover_url}?ts=${s.started_at || 0}`} alt="" className="h-12 w-8 rounded object-cover" />
) : (
<div className="flex h-12 w-8 items-center justify-center rounded bg-slate-900 text-[10px] text-slate-600">LIVE</div>
)}
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-white">{s.anchor_name || s.room_id}</div>
<div className="font-mono text-xs text-rose-200">{liveElapsed(s.started_at, now)}</div>
</div>
</a>
))}
</div>
</section>
) : null}
{(liveRooms.length > 0 || events.length > 0) ? (
<div className="mb-6 overflow-hidden rounded-2xl border border-rose-500/20 bg-rose-500/5">
<div className="flex items-center gap-2 border-b border-white/5 px-4 py-2 text-xs text-rose-100/80">
<span className="live-dot" />
实时动态条
</div>
<div className="relative overflow-hidden py-3">
<div className="ticker-track gap-8 px-4 text-sm text-slate-200">
{[...liveRooms, ...liveRooms].length ? (
[...liveRooms, ...liveRooms, ...events.slice(0, 8), ...events.slice(0, 8)].map((item, idx) => {
if ("last_status" in item) {
return (
<a key={`live-${item.id}-${idx}`} href={item.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-2 whitespace-nowrap hover:text-white">
<span>🔴</span>
<span className="font-medium">{item.last_anchor || item.room_id}</span>
<span className="text-slate-500">在播中</span>
</a>
);
}
return (
<span key={`ev-${item.id}-${idx}`} className="inline-flex items-center gap-2 whitespace-nowrap text-slate-300">
<span>{item.kind === "live" ? "🎬" : item.kind === "risk" ? "⚠️" : "⚡"}</span>
<span>{item.message}</span>
</span>
);
})
) : (
<span className="text-slate-500">等待开播事件…</span>
)}
</div>
</div>
</div>
) : null}
<div className="mb-6 grid gap-4 lg:grid-cols-[1.4fr_1fr]">
<section className="glass-panel rounded-2xl p-4">
<div className="mb-3 flex items-center justify-between">
<h3 className="font-display text-sm font-medium text-slate-100">📊 可视化分析</h3>
<Link href="/sessions" className="inline-flex items-center gap-1 text-xs text-teal-300 hover:underline">
场次明细 <ArrowRight className="h-3 w-3" />
</Link>
</div>
<SessionCharts stats={stats} />
</section>
<section className="glass-panel rounded-2xl p-4">
<div className="mb-3 flex items-center justify-between">
<h3 className="font-display text-sm font-medium text-slate-100">⚡ 最近事件</h3>
<Link href="/events" className="inline-flex items-center gap-1 text-xs text-teal-300 hover:underline">
全部 <ArrowRight className="h-3 w-3" />
</Link>
</div>
<div className="timeline-rail max-h-[560px] space-y-3 overflow-auto pl-1">
{events.map((ev) => (
<div key={ev.id} className="relative ml-1 rounded-xl border border-white/5 bg-black/20 px-3 py-2 pl-8 text-sm hover-lift">
<span className="absolute left-[6px] top-3 h-3 w-3 rounded-full bg-teal-400/80 ring-4 ring-teal-400/10" />
<div className="flex flex-wrap items-center gap-2 text-[11px] text-slate-500">
<span>{fmtTs(ev.ts)}</span>
<span className="uppercase text-teal-300/80">{ev.kind}</span>
</div>
<div className="mt-1 text-slate-200">{ev.message}</div>
</div>
))}
{!events.length ? (
<div className="rounded-xl border border-dashed border-white/10 px-3 py-8 text-center text-sm text-slate-500">
暂无事件,开播后会出现在这里
</div>
) : null}
</div>
</section>
</div>
<div className="flex flex-wrap gap-3 text-sm">
<Link href="/rooms" className="hover-lift glass-panel rounded-xl px-4 py-3 text-teal-200">🏠 管理直播间</Link>
<Link href="/anchors" className="hover-lift glass-panel rounded-xl px-4 py-3 text-fuchsia-200">👤 主播画像</Link>
<Link href="/covers" className="hover-lift glass-panel rounded-xl px-4 py-3 text-sky-200">🖼️ 浏览截图库</Link>
<Link href="/settings" className="hover-lift glass-panel rounded-xl px-4 py-3 text-amber-200">⚙️ 防风控设置</Link>
</div>
</Shell>
);
}

View File

@ -0,0 +1,371 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Ban, Loader2, Plus, RefreshCw, Trash2, Zap } from "lucide-react";
import { Shell } from "@/components/Shell";
import { fetchJson, fmtTs } from "@/lib/api";
type Room = {
id: string;
url: string;
room_id: string;
note?: string;
tags?: string[];
enabled: boolean;
last_status: string;
last_anchor?: string;
last_title?: string;
last_checked_at?: number;
last_error?: string;
error_count?: number;
};
export default function RoomsPage() {
const [rooms, setRooms] = useState<Room[]>([]);
const [total, setTotal] = useState(0);
const [allTags, setAllTags] = useState<string[]>([]);
const [urlsText, setUrlsText] = useState("");
const [note, setNote] = useState("");
const [tagsInput, setTagsInput] = useState("");
const [q, setQ] = useState("");
const [status, setStatus] = useState("");
const [enabledFilter, setEnabledFilter] = useState("");
const [tag, setTag] = useState("");
const [selected, setSelected] = useState<Set<string>>(new Set());
const [loading, setLoading] = useState(false);
const [busy, setBusy] = useState("");
const [error, setError] = useState("");
const [msg, setMsg] = useState("");
const [bulkTags, setBulkTags] = useState("");
const lineCount = urlsText
.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => l && !l.startsWith("#")).length;
const query = useMemo(() => {
const p = new URLSearchParams();
if (q.trim()) p.set("q", q.trim());
if (status) p.set("status", status);
if (tag) p.set("tag", tag);
if (enabledFilter === "1") p.set("enabled", "true");
if (enabledFilter === "0") p.set("enabled", "false");
p.set("limit", "500");
return p.toString();
}, [q, status, tag, enabledFilter]);
const load = useCallback(async () => {
setLoading(true);
setError("");
try {
const [data, tagsData] = await Promise.all([
fetchJson(`/api/rooms?${query}`),
fetchJson("/api/rooms/tags"),
]);
setRooms(data.rooms || []);
setTotal(Number(data.total) || 0);
setAllTags(tagsData.tags || []);
setSelected(new Set());
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [query]);
useEffect(() => {
void load();
}, [load]);
async function doAddRooms() {
setBusy("add");
setError("");
setMsg("");
try {
const data = await fetchJson("/api/rooms/batch", {
method: "POST",
body: JSON.stringify({ urls: urlsText, note, enabled: true, tags: tagsInput }),
});
setUrlsText("");
setNote("");
setTagsInput("");
const parts = [`成功 ${data.created_count} 个`];
if (data.skipped_count) {
const reasons = (data.skipped || [])
.slice(0, 5)
.map((s: { url: string; reason: string }) => `${s.url}(${s.reason})`)
.join(";");
parts.push(`跳过 ${data.skipped_count} 个:${reasons}${data.skipped_count > 5 ? "…" : ""}`);
}
setMsg(parts.join(" · "));
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function bulk(action: string) {
const ids = Array.from(selected);
if (!ids.length) return;
if (action === "delete" && !confirm(`删除选中的 ${ids.length} 个直播间?`)) return;
setBusy(action);
setError("");
try {
const data = await fetchJson("/api/rooms/bulk", {
method: "POST",
body: JSON.stringify({ action, ids, tags: bulkTags }),
});
setMsg(`批量 ${action}:${data.affected} 个`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function toggle(room: Room) {
setBusy(room.id);
try {
await fetchJson(`/api/rooms/${room.id}`, {
method: "PATCH",
body: JSON.stringify({ enabled: !room.enabled }),
});
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function remove(room: Room) {
if (!confirm(`删除直播间 ${room.room_id}?`)) return;
setBusy(room.id);
try {
await fetchJson(`/api/rooms/${room.id}`, { method: "DELETE" });
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function ban(room: Room) {
if (!confirm(`将 ${room.room_id} 加入黑名单并停用?`)) return;
setBusy(`ban-${room.id}`);
try {
await fetchJson("/api/blacklist", {
method: "POST",
body: JSON.stringify({ value: room.url, reason: "从直播间列表拉黑" }),
});
setMsg(`已拉黑 ${room.room_id}`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
async function checkNow(room: Room) {
setBusy(`check-${room.id}`);
setMsg("");
try {
const data = await fetchJson(`/api/monitor/check/${room.id}`, { method: "POST" });
const r = data.result || {};
setMsg(`检查完成:${r.status || r.error || JSON.stringify(r)}`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy("");
}
}
function toggleSelect(id: string) {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
function toggleAll() {
if (selected.size === rooms.length) setSelected(new Set());
else setSelected(new Set(rooms.map((r) => r.id)));
}
const statusBadge = (s: string) => {
const map: Record<string, string> = {
live: "bg-rose-500/20 text-rose-200 border-rose-500/30",
offline: "bg-slate-500/20 text-slate-300 border-slate-500/30",
error: "bg-amber-500/20 text-amber-100 border-amber-500/30",
unknown: "bg-white/5 text-slate-400 border-white/10",
};
return map[s] || map.unknown;
};
return (
<Shell>
<div className="mb-4">
<h2 className="font-display text-2xl font-semibold">🏠 直播间管理</h2>
<p className="text-sm text-slate-400">批量多行添加、标签分组、多选批量操作、一键拉黑。</p>
</div>
<div className="mb-4 space-y-3 rounded-xl border border-white/10 bg-black/30 p-4">
<label className="block text-xs text-slate-400">
直播间 URL / 房间号(每行一个)
<textarea
value={urlsText}
onChange={(e) => setUrlsText(e.target.value)}
rows={7}
placeholder={`https://live.douyin.com/123456789\n745277409780\n# 注释行忽略`}
className="mt-1 w-full resize-y rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm leading-relaxed"
/>
</label>
<div className="grid gap-3 md:grid-cols-3">
<label className="block text-xs text-slate-400">
统一备注
<input value={note} onChange={(e) => setNote(e.target.value)} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</label>
<label className="block text-xs text-slate-400">
标签(逗号分隔)
<input value={tagsInput} onChange={(e) => setTagsInput(e.target.value)} placeholder="重点,竞品" className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</label>
<div className="flex items-end">
<button
type="button"
disabled={lineCount === 0 || busy === "add"}
onClick={() => void doAddRooms()}
className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-[#ff2d55] px-4 py-2 text-sm font-medium text-white hover:bg-[#ff4d6d] disabled:opacity-50"
>
{busy === "add" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
批量添加{lineCount > 0 ? `(${lineCount})` : ""}
</button>
</div>
</div>
</div>
<div className="mb-3 flex flex-wrap items-center gap-2">
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="筛选昵称/URL/房间号/标签…" className="w-full max-w-xs rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
<select value={status} onChange={(e) => setStatus(e.target.value)} className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
<option value="">全部状态</option>
<option value="live">在播</option>
<option value="offline">离线</option>
<option value="error">错误</option>
<option value="unknown">未知</option>
</select>
<select value={enabledFilter} onChange={(e) => setEnabledFilter(e.target.value)} className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
<option value="">启用状态</option>
<option value="1">已启用</option>
<option value="0">已停用</option>
</select>
<select value={tag} onChange={(e) => setTag(e.target.value)} className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
<option value="">全部标签</option>
{allTags.map((t) => (
<option key={t} value={t}>{t}</option>
))}
</select>
<button type="button" onClick={() => void load()} className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
<a href="/api/rooms/export?format=csv" className="rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100 hover:bg-teal-500/20">
导出 CSV
</a>
<span className="text-xs text-slate-500">共 {total} 个</span>
</div>
{selected.size > 0 ? (
<div className="mb-3 flex flex-wrap items-center gap-2 rounded-xl border border-teal-500/20 bg-teal-500/5 px-3 py-2 text-sm">
<span className="text-teal-100">已选 {selected.size}</span>
<button type="button" onClick={() => void bulk("enable")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">启用</button>
<button type="button" onClick={() => void bulk("disable")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">停用</button>
<button type="button" onClick={() => void bulk("check_queue")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">加入检查队列</button>
<button type="button" onClick={() => void bulk("delete")} className="rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200">删除</button>
<input value={bulkTags} onChange={(e) => setBulkTags(e.target.value)} placeholder="批量标签" className="rounded border border-white/10 bg-slate-900 px-2 py-1 text-xs" />
<button type="button" onClick={() => void bulk("set_tags")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">设置标签</button>
<button type="button" onClick={() => void bulk("add_tags")} className="rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">追加标签</button>
</div>
) : null}
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
{msg ? <div className="mb-4 rounded-lg border border-teal-500/30 bg-teal-500/10 px-4 py-3 text-sm text-teal-50">{msg}</div> : null}
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
<table className="min-w-full text-left text-sm">
<thead className="bg-white/5 text-xs uppercase text-slate-400">
<tr>
<th className="px-3 py-3"><input type="checkbox" checked={rooms.length > 0 && selected.size === rooms.length} onChange={toggleAll} /></th>
<th className="px-3 py-3">状态</th>
<th className="px-3 py-3">主播</th>
<th className="px-3 py-3">房间</th>
<th className="px-3 py-3">标签</th>
<th className="px-3 py-3">最近检查</th>
<th className="px-3 py-3">启用</th>
<th className="px-3 py-3">操作</th>
</tr>
</thead>
<tbody>
{rooms.map((room) => (
<tr key={room.id} className="border-t border-white/5">
<td className="px-3 py-3">
<input type="checkbox" checked={selected.has(room.id)} onChange={() => toggleSelect(room.id)} />
</td>
<td className="px-3 py-3">
<span className={`rounded border px-2 py-0.5 text-xs ${statusBadge(room.last_status)}`}>{room.last_status}</span>
</td>
<td className="px-3 py-3">{room.last_anchor || "—"}</td>
<td className="px-3 py-3">
<a href={room.url} target="_blank" rel="noreferrer" className="font-mono text-xs text-cyan-300 hover:underline">{room.room_id}</a>
{room.note ? <div className="text-[11px] text-slate-500">{room.note}</div> : null}
{room.last_error ? <div className="mt-1 max-w-[16rem] truncate text-[11px] text-amber-300/80">{room.last_error}</div> : null}
</td>
<td className="px-3 py-3">
<div className="flex flex-wrap gap-1">
{(room.tags || []).map((t) => (
<button key={t} type="button" onClick={() => setTag(t)} className="rounded bg-white/5 px-1.5 py-0.5 text-[10px] text-slate-300 hover:bg-white/10">{t}</button>
))}
{!room.tags?.length ? <span className="text-slate-600">—</span> : null}
</div>
</td>
<td className="whitespace-nowrap px-3 py-3 text-slate-400">{fmtTs(room.last_checked_at)}</td>
<td className="px-3 py-3">
<button type="button" onClick={() => void toggle(room)} className="text-xs text-teal-300 hover:underline">
{room.enabled ? "已启用" : "已停用"}
</button>
</td>
<td className="px-3 py-3">
<div className="flex flex-wrap gap-1">
<button type="button" onClick={() => void checkNow(room)} className="inline-flex items-center gap-1 rounded border border-white/10 px-2 py-1 text-xs hover:bg-white/5">
{busy === `check-${room.id}` ? <Loader2 className="h-3 w-3 animate-spin" /> : <Zap className="h-3 w-3" />}
检查
</button>
<button type="button" onClick={() => void ban(room)} className="inline-flex items-center gap-1 rounded border border-amber-500/30 px-2 py-1 text-xs text-amber-100 hover:bg-amber-500/10">
<Ban className="h-3 w-3" />
拉黑
</button>
<button type="button" onClick={() => void remove(room)} className="inline-flex items-center gap-1 rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200 hover:bg-rose-500/10">
<Trash2 className="h-3 w-3" />
</button>
</div>
</td>
</tr>
))}
{!loading && rooms.length === 0 ? (
<tr>
<td colSpan={8} className="px-3 py-10 text-center text-slate-500">没有匹配的直播间</td>
</tr>
) : null}
</tbody>
</table>
</div>
</Shell>
);
}

View File

@ -0,0 +1,283 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ExternalLink, Loader2, RefreshCw, Search } from "lucide-react";
import { Shell } from "@/components/Shell";
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
import { fetchJson, fmtDuration, fmtTs } from "@/lib/api";
type Session = {
id: string;
anchor_name?: string;
source_url?: string;
room_id?: string;
title?: string;
started_at?: number;
ended_at?: number | null;
duration_seconds?: number;
push_date?: string;
cover_url?: string;
status?: string;
end_reason?: string;
};
export default function SessionsPage() {
const [tab, setTab] = useState<"charts" | "list">("list");
const [q, setQ] = useState("");
const [dateFrom, setDateFrom] = useState("");
const [dateTo, setDateTo] = useState("");
const [status, setStatus] = useState("");
const [sessions, setSessions] = useState<Session[]>([]);
const [stats, setStats] = useState<RelayStats | null>(null);
const [total, setTotal] = useState(0);
const [offset, setOffset] = useState(0);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [selected, setSelected] = useState<Session | null>(null);
const limit = 50;
const queryString = useMemo(() => {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
if (dateFrom) params.set("date_from", dateFrom);
if (dateTo) params.set("date_to", dateTo);
if (status) params.set("status", status);
params.set("limit", String(limit));
params.set("offset", String(offset));
return params.toString();
}, [q, dateFrom, dateTo, status, offset]);
const statsQuery = useMemo(() => {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
if (dateFrom) params.set("date_from", dateFrom);
if (dateTo) params.set("date_to", dateTo);
if (status) params.set("status", status);
params.set("top_anchors", "25");
return params.toString();
}, [q, dateFrom, dateTo, status]);
const exportHref = useMemo(() => {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
if (dateFrom) params.set("date_from", dateFrom);
if (dateTo) params.set("date_to", dateTo);
if (status) params.set("status", status);
params.set("format", "csv");
return `/api/sessions/export?${params.toString()}`;
}, [q, dateFrom, dateTo, status]);
const load = useCallback(async () => {
setLoading(true);
setError("");
try {
const [listData, statsData] = await Promise.all([
fetchJson(`/api/sessions?${queryString}`),
fetchJson(`/api/sessions/stats?${statsQuery}`),
]);
setSessions(listData.sessions || []);
setTotal(Number(listData.total) || 0);
setStats(statsData);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [queryString, statsQuery]);
useEffect(() => {
void load();
}, [load]);
const pageCount = Math.max(1, Math.ceil(total / limit));
const pageIndex = Math.floor(offset / limit) + 1;
return (
<Shell>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">🎬 场次日志</h2>
<p className="text-sm text-slate-400">开播/停播明细、播放时长与截图,支持 CSV 导出。</p>
</div>
<div className="flex gap-2">
<button
type="button"
onClick={() => void load()}
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
<a
href={exportHref}
className="inline-flex items-center gap-2 rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100 hover:bg-teal-500/20"
>
导出 CSV
</a>
<button
type="button"
onClick={async () => {
if (!confirm("确认结束全部进行中的场次?")) return;
try {
const data = await fetchJson("/api/sessions/end-all-active", { method: "POST" });
setError("");
alert(`已结束 ${data.ended || 0} 场`);
await load();
} catch (e) {
setError((e as Error).message);
}
}}
className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100 hover:bg-amber-500/20"
>
⏹ 结束进行中
</button>
</div>
</div>
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2 xl:grid-cols-5">
<label className="block text-xs text-slate-400 xl:col-span-2">
检索(昵称 / URL / 房间号)
<div className="relative mt-1">
<Search className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-slate-500" />
<input
value={q}
onChange={(e) => {
setOffset(0);
setQ(e.target.value);
}}
className="w-full rounded-lg border border-white/10 bg-slate-900 py-2 pl-9 pr-3 text-sm"
placeholder="例如:房间号或主播名"
/>
</div>
</label>
<label className="block text-xs text-slate-400">
开始日期
<input type="date" value={dateFrom} onChange={(e) => { setOffset(0); setDateFrom(e.target.value); }} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</label>
<label className="block text-xs text-slate-400">
结束日期
<input type="date" value={dateTo} onChange={(e) => { setOffset(0); setDateTo(e.target.value); }} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
</label>
<label className="block text-xs text-slate-400">
状态
<select value={status} onChange={(e) => { setOffset(0); setStatus(e.target.value); }} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
<option value="">全部</option>
<option value="active">进行中</option>
<option value="ended">已结束</option>
</select>
</label>
</div>
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
<div className="mb-4 flex gap-2">
<button type="button" onClick={() => setTab("charts")} className={`rounded-lg px-3 py-1.5 text-sm ${tab === "charts" ? "bg-white/15 text-white" : "bg-white/5 text-slate-400"}`}>
可视化分析
</button>
<button type="button" onClick={() => setTab("list")} className={`rounded-lg px-3 py-1.5 text-sm ${tab === "list" ? "bg-white/15 text-white" : "bg-white/5 text-slate-400"}`}>
场次列表 ({total})
</button>
</div>
{tab === "charts" ? <SessionCharts stats={stats} /> : null}
{tab === "list" ? (
<>
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
<div className="overflow-x-auto">
<table className="min-w-full text-left text-sm">
<thead className="bg-white/5 text-xs uppercase tracking-wide text-slate-400">
<tr>
<th className="px-3 py-3">截图</th>
<th className="px-3 py-3">主播昵称</th>
<th className="px-3 py-3">直播间 URL</th>
<th className="px-3 py-3">开播</th>
<th className="px-3 py-3">停播</th>
<th className="px-3 py-3">总时长</th>
<th className="px-3 py-3">日期</th>
</tr>
</thead>
<tbody>
{sessions.map((session) => (
<tr key={session.id} className="cursor-pointer border-t border-white/5 hover:bg-white/[0.03]" onClick={() => setSelected(session)}>
<td className="px-3 py-3">
{session.cover_url ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={`${session.cover_url}?ts=${session.started_at || 0}`} alt="" className="h-16 w-10 rounded object-cover ring-1 ring-white/10" />
) : (
<div className="flex h-16 w-10 items-center justify-center rounded bg-slate-900 text-[10px] text-slate-500 ring-1 ring-white/10">N/A</div>
)}
</td>
<td className="px-3 py-3 font-medium">{session.anchor_name || "—"}</td>
<td className="max-w-[14rem] truncate px-3 py-3 font-mono text-xs text-cyan-300/90">
{session.source_url ? (
<a href={session.source_url} target="_blank" rel="noreferrer" className="hover:underline" onClick={(e) => e.stopPropagation()}>
{session.source_url.replace(/^https?:\/\//, "")}
</a>
) : "—"}
</td>
<td className="whitespace-nowrap px-3 py-3 text-slate-300">{fmtTs(session.started_at)}</td>
<td className="whitespace-nowrap px-3 py-3 text-slate-300">{session.ended_at ? fmtTs(session.ended_at) : "进行中"}</td>
<td className="whitespace-nowrap px-3 py-3 font-mono">{fmtDuration(session.duration_seconds)}</td>
<td className="whitespace-nowrap px-3 py-3">{session.push_date || "—"}</td>
</tr>
))}
{!loading && sessions.length === 0 ? (
<tr>
<td colSpan={7} className="px-3 py-10 text-center text-slate-500">暂无场次。添加直播间后,开播会自动记入。</td>
</tr>
) : null}
</tbody>
</table>
</div>
</div>
<div className="mt-4 flex items-center justify-between text-sm text-slate-400">
<span>共 {total} 条 · 第 {pageIndex}/{pageCount}</span>
<div className="flex gap-2">
<button type="button" disabled={offset <= 0 || loading} onClick={() => setOffset(Math.max(0, offset - limit))} className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40">上一页</button>
<button type="button" disabled={offset + limit >= total || loading} onClick={() => setOffset(offset + limit)} className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40">下一页</button>
</div>
</div>
</>
) : null}
{selected ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4" onClick={() => setSelected(null)}>
<div className="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl border border-white/10 bg-[#0b1626] p-5 shadow-2xl" onClick={(e) => e.stopPropagation()}>
<div className="flex items-start justify-between gap-3">
<div>
<h2 className="text-lg font-semibold">{selected.anchor_name || "场次详情"}</h2>
<p className="mt-1 text-sm text-slate-400">{selected.title || "—"}</p>
</div>
<button type="button" className="text-slate-400 hover:text-slate-200" onClick={() => setSelected(null)}>✕</button>
</div>
<div className="mt-4 grid gap-4 md:grid-cols-[8rem_1fr]">
{selected.cover_url ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={`${selected.cover_url}?ts=${selected.started_at || 0}`} alt="" className="h-36 w-full rounded-lg object-cover ring-1 ring-white/10" />
) : null}
<dl className="grid gap-2 text-sm">
<div>
<dt className="text-slate-500">直播间 URL</dt>
<dd className="break-all font-mono text-cyan-300">
{selected.source_url ? (
<a href={selected.source_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 hover:underline">
{selected.source_url} <ExternalLink className="h-3.5 w-3.5" />
</a>
) : "—"}
</dd>
</div>
<div><dt className="text-slate-500">房间号</dt><dd>{selected.room_id || "—"}</dd></div>
<div><dt className="text-slate-500">开播</dt><dd>{fmtTs(selected.started_at)}</dd></div>
<div><dt className="text-slate-500">停播</dt><dd>{selected.ended_at ? fmtTs(selected.ended_at) : "进行中"}</dd></div>
<div><dt className="text-slate-500">总时长</dt><dd>{fmtDuration(selected.duration_seconds)}</dd></div>
<div><dt className="text-slate-500">结束原因</dt><dd>{selected.end_reason || "—"}</dd></div>
</dl>
</div>
</div>
</div>
) : null}
</Shell>
);
}

View File

@ -0,0 +1,228 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Loader2, Save, ShieldOff } from "lucide-react";
import { Shell } from "@/components/Shell";
import { fetchJson, fmtTs } from "@/lib/api";
type Settings = Record<string, number | boolean | string>;
const FIELDS: Array<{ key: string; label: string; hint: string; step?: number }> = [
{ key: "max_concurrency", label: "最大并发", hint: "同时检查的直播间数,建议 1–3", step: 1 },
{ key: "min_request_gap_sec", label: "最小请求间隔(秒)", hint: "任意两次请求之间的最小间隔", step: 0.1 },
{ key: "request_jitter_sec", label: "随机抖动(秒)", hint: "在间隔上叠加随机延迟", step: 0.1 },
{ key: "offline_interval_sec", label: "未开播复查间隔(秒)", hint: "离线房间下次检查等待", step: 1 },
{ key: "live_interval_sec", label: "在播复查间隔(秒)", hint: "直播中更勤,便于捕捉停播", step: 1 },
{ key: "error_backoff_base_sec", label: "错误退避基数(秒)", hint: "失败后指数退避", step: 1 },
{ key: "error_backoff_max_sec", label: "错误退避上限(秒)", hint: "退避封顶", step: 1 },
{ key: "global_pause_on_risk_sec", label: "风控全局暂停(秒)", hint: "触发验证码后全体停检", step: 1 },
];
export default function SettingsPage() {
const [settings, setSettings] = useState<Settings>({});
const [status, setStatus] = useState<Record<string, unknown> | null>(null);
const [loading, setLoading] = useState(false);
const [msg, setMsg] = useState("");
const [error, setError] = useState("");
const load = useCallback(async () => {
setLoading(true);
try {
const [s, m] = await Promise.all([fetchJson("/api/settings"), fetchJson("/api/monitor/status")]);
setSettings(s);
setStatus(m);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
async function save() {
setMsg("");
setError("");
try {
const body: Record<string, unknown> = {};
for (const f of FIELDS) body[f.key] = Number(settings[f.key]);
body.capture_cover_on_start = Boolean(settings.capture_cover_on_start);
body.monitor_enabled = Boolean(settings.monitor_enabled);
body.dy_cookie = String(settings.dy_cookie || "");
body.http_proxy = String(settings.http_proxy || "");
body.notify_webhook_url = String(settings.notify_webhook_url || "");
body.notify_on_live = Boolean(settings.notify_on_live);
body.notify_on_offline = Boolean(settings.notify_on_offline);
body.notify_on_risk = Boolean(settings.notify_on_risk);
body.quiet_hours_enabled = Boolean(settings.quiet_hours_enabled);
body.quiet_hours_start = Number(settings.quiet_hours_start ?? 2);
body.quiet_hours_end = Number(settings.quiet_hours_end ?? 7);
body.priority_interval_sec = Number(settings.priority_interval_sec ?? 25);
const next = await fetchJson("/api/settings", { method: "PATCH", body: JSON.stringify(body) });
setSettings(next);
setMsg("已保存");
await load();
} catch (e) {
setError((e as Error).message);
}
}
async function toggleMonitor(enabled: boolean) {
await fetchJson(enabled ? "/api/monitor/start" : "/api/monitor/stop", { method: "POST" });
await load();
}
async function clearRisk() {
await fetchJson("/api/monitor/clear-risk", { method: "POST" });
setMsg("已清除风控暂停");
await load();
}
return (
<Shell>
<div className="mb-4">
<h2 className="font-display text-2xl font-semibold">⚙️ 设置中心</h2>
<p className="text-sm text-slate-400">防风控参数、Cookie/代理、Webhook 通知。</p>
</div>
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-white/10 bg-black/30 p-4 text-sm">
<span>监控开关:</span>
<button type="button" onClick={() => void toggleMonitor(true)} className={`rounded-lg px-3 py-1.5 ${settings.monitor_enabled ? "bg-teal-500/20 text-teal-100" : "bg-white/5"}`}>启用</button>
<button type="button" onClick={() => void toggleMonitor(false)} className={`rounded-lg px-3 py-1.5 ${!settings.monitor_enabled ? "bg-rose-500/20 text-rose-100" : "bg-white/5"}`}>暂停</button>
<button type="button" onClick={() => void clearRisk()} className="inline-flex items-center gap-1 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-amber-100">
<ShieldOff className="h-3.5 w-3.5" />
清除风控暂停
</button>
<span className="text-slate-400">
状态:{status?.running ? "循环运行中" : "未运行"} · 上次检查 {fmtTs(Number(status?.last_check_at || 0))}
</span>
</div>
<div className="mb-6 grid gap-3 md:grid-cols-2">
{FIELDS.map((f) => (
<label key={f.key} className="rounded-xl border border-white/10 bg-black/25 p-4 text-sm">
<div className="font-medium text-slate-200">{f.label}</div>
<div className="mt-1 text-xs text-slate-500">{f.hint}</div>
<input
type="number"
step={f.step || 1}
value={Number(settings[f.key] ?? 0)}
onChange={(e) => setSettings((prev) => ({ ...prev, [f.key]: Number(e.target.value) }))}
className="mt-2 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2"
/>
</label>
))}
</div>
<div className="mb-6 space-y-3 rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="text-sm font-medium text-slate-200">🌙 静默时段 / 重点加速</h3>
<label className="inline-flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={Boolean(settings.quiet_hours_enabled)}
onChange={(e) => setSettings((prev) => ({ ...prev, quiet_hours_enabled: e.target.checked }))}
/>
启用静默时段(该时段暂停轮询,降低夜间请求)
</label>
<div className="grid gap-3 sm:grid-cols-3">
<label className="block text-xs text-slate-400">
开始小时 (0-23)
<input
type="number"
min={0}
max={23}
value={Number(settings.quiet_hours_start ?? 2)}
onChange={(e) => setSettings((prev) => ({ ...prev, quiet_hours_start: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2"
/>
</label>
<label className="block text-xs text-slate-400">
结束小时 (0-23)
<input
type="number"
min={0}
max={23}
value={Number(settings.quiet_hours_end ?? 7)}
onChange={(e) => setSettings((prev) => ({ ...prev, quiet_hours_end: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2"
/>
</label>
<label className="block text-xs text-slate-400">
重点标签复查间隔(秒)
<input
type="number"
value={Number(settings.priority_interval_sec ?? 25)}
onChange={(e) => setSettings((prev) => ({ ...prev, priority_interval_sec: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2"
/>
</label>
</div>
<p className="text-xs text-slate-500">给直播间打上标签「重点 / priority / vip / 高优」会优先检查、间隔更短。</p>
</div>
<div className="mb-6 space-y-3 rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="text-sm font-medium text-slate-200">Cookie / 代理(降低风控)</h3>
<label className="block text-xs text-slate-400">
抖音 Cookie(浏览器登录后复制)
<textarea
value={String(settings.dy_cookie || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, dy_cookie: e.target.value }))}
rows={3}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
placeholder="ttwid=...; ..."
/>
</label>
<label className="block text-xs text-slate-400">
HTTP 代理(可选,如 http://127.0.0.1:7890)
<input
value={String(settings.http_proxy || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, http_proxy: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
</div>
<div className="mb-6 space-y-3 rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="text-sm font-medium text-slate-200">Webhook 通知</h3>
<label className="block text-xs text-slate-400">
Webhook URL(开播/停播/风控 POST JSON)
<input
value={String(settings.notify_webhook_url || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, notify_webhook_url: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
placeholder="https://hooks.example.com/..."
/>
</label>
<div className="flex flex-wrap gap-4 text-sm">
{[
["notify_on_live", "开播通知"],
["notify_on_offline", "停播通知"],
["notify_on_risk", "风控通知"],
["capture_cover_on_start", "开播截图"],
].map(([key, label]) => (
<label key={key} className="inline-flex items-center gap-2">
<input
type="checkbox"
checked={Boolean(settings[key])}
onChange={(e) => setSettings((prev) => ({ ...prev, [key]: e.target.checked }))}
/>
{label}
</label>
))}
</div>
</div>
<div className="flex items-center gap-3">
<button type="button" onClick={() => void save()} className="inline-flex items-center gap-2 rounded-lg bg-[#ff2d55] px-4 py-2 text-sm font-medium text-white hover:bg-[#ff4d6d]">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
保存设置
</button>
{msg ? <span className="text-sm text-teal-300">{msg}</span> : null}
{error ? <span className="text-sm text-rose-300">{error}</span> : null}
</div>
</Shell>
);
}

View File

@ -0,0 +1,7 @@
"use client";
import { ToastProvider } from "@/components/Toast";
export function Providers({ children }: { children: React.ReactNode }) {
return <ToastProvider>{children}</ToastProvider>;
}

View File

@ -0,0 +1,341 @@
"use client";
import { useEffect, useMemo, useRef } from "react";
export type RelayStats = {
overview?: {
sessions?: number;
unique_anchors?: number;
active_sessions?: number;
total_hours?: number;
avg_duration_seconds?: number;
median_duration_seconds?: number;
};
top_anchors?: Array<{
anchor_name?: string;
sessions?: number;
hours_total?: number;
avg_duration_seconds?: number;
peak_hour?: number;
peak_weekday_label?: string;
dates_active?: number;
sessions_per_active_day?: number;
avg_gap_hours?: number | null;
source_room_id?: string;
}>;
by_hour?: { starts?: number[]; minutes?: number[]; labels?: string[] };
by_weekday?: { starts?: number[]; minutes?: number[]; labels?: string[]; labels_zh?: string[] };
heatmap?: {
starts?: number[][];
weekday_labels?: string[];
weekday_labels_zh?: string[];
hour_labels?: string[];
};
by_date?: Array<{ date: string; sessions: number; hours: number; unique_anchors: number }>;
duration_buckets?: Record<string, number>;
insights?: Array<{ zh: string; en: string }>;
};
function useEchart(option: Record<string, unknown> | null, height: number) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = ref.current;
if (!el || !option) return;
let disposed = false;
let chart: import("echarts").ECharts | null = null;
const onResize = () => chart?.resize();
import("echarts").then((echarts) => {
if (disposed || !ref.current) return;
chart = echarts.init(ref.current, undefined, { renderer: "canvas" });
chart.setOption(option, true);
window.addEventListener("resize", onResize);
});
return () => {
disposed = true;
window.removeEventListener("resize", onResize);
chart?.dispose();
};
}, [option]);
return <div ref={ref} style={{ height }} className="w-full" />;
}
const FG = "#edf3ff";
const MUTED = "#93a4bd";
const GRID = "rgba(255,255,255,0.06)";
const TOOLTIP = {
backgroundColor: "#0f1c2e",
borderColor: GRID,
textStyle: { color: FG, fontSize: 12 },
};
export function SessionCharts({ stats }: { stats: RelayStats | null }) {
const overview = stats?.overview;
const weekdayLabels = stats?.by_weekday?.labels_zh || stats?.by_weekday?.labels;
const heatWeekday = stats?.heatmap?.weekday_labels_zh || stats?.heatmap?.weekday_labels;
const dailyOption = useMemo(() => {
const rows = stats?.by_date || [];
if (!rows.length) return null;
return {
color: ["#2dd4bf", "#fb7185"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
legend: { data: ["场次", "时长(小时)"], textStyle: { color: MUTED } },
grid: { left: 48, right: 48, top: 40, bottom: 48 },
xAxis: {
type: "category",
data: rows.map((r) => r.date.slice(5)),
axisLabel: { color: MUTED, rotate: rows.length > 14 ? 45 : 0 },
axisLine: { lineStyle: { color: GRID } },
},
yAxis: [
{ type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
{ type: "value", axisLabel: { color: MUTED }, splitLine: { show: false } },
],
series: [
{ name: "场次", type: "bar", data: rows.map((r) => r.sessions), barMaxWidth: 18 },
{ name: "时长(小时)", type: "line", yAxisIndex: 1, smooth: true, data: rows.map((r) => Number(r.hours.toFixed(2))) },
],
};
}, [stats?.by_date]);
const anchorOption = useMemo(() => {
const rows = (stats?.top_anchors || []).slice(0, 12).reverse();
if (!rows.length) return null;
return {
color: ["#34d399", "#38bdf8"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis", axisPointer: { type: "shadow" } },
legend: { data: ["场次", "累计小时"], textStyle: { color: MUTED } },
grid: { left: 110, right: 48, top: 36, bottom: 28 },
xAxis: { type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
yAxis: {
type: "category",
data: rows.map((r) => (r.anchor_name || "—").slice(0, 14)),
axisLabel: { color: MUTED, fontSize: 11 },
},
series: [
{ name: "场次", type: "bar", data: rows.map((r) => r.sessions || 0), barMaxWidth: 14 },
{ name: "累计小时", type: "bar", data: rows.map((r) => Number((r.hours_total || 0).toFixed(2))), barMaxWidth: 14 },
],
};
}, [stats?.top_anchors]);
const hourOption = useMemo(() => {
const starts = stats?.by_hour?.starts || [];
const minutes = stats?.by_hour?.minutes || [];
if (!starts.some((n) => n > 0) && !minutes.some((n) => n > 0)) return null;
return {
color: ["#fbbf24", "#fb7185"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
legend: { data: ["开播次数", "在播分钟"], textStyle: { color: MUTED } },
grid: { left: 48, right: 48, top: 40, bottom: 36 },
xAxis: {
type: "category",
data: stats?.by_hour?.labels || Array.from({ length: 24 }, (_, h) => `${String(h).padStart(2, "0")}:00`),
axisLabel: { color: MUTED, fontSize: 10 },
},
yAxis: [
{ type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
{ type: "value", axisLabel: { color: MUTED }, splitLine: { show: false } },
],
series: [
{ name: "开播次数", type: "bar", data: starts, barMaxWidth: 12 },
{ name: "在播分钟", type: "line", yAxisIndex: 1, smooth: true, areaStyle: { opacity: 0.12 }, data: minutes.map((n) => Number(n.toFixed(1))) },
],
};
}, [stats?.by_hour]);
const weekdayOption = useMemo(() => {
const starts = stats?.by_weekday?.starts || [];
if (!starts.some((n) => n > 0)) return null;
return {
color: ["#818cf8"],
textStyle: { color: FG },
tooltip: { ...TOOLTIP, trigger: "axis" },
grid: { left: 48, right: 16, top: 28, bottom: 36 },
xAxis: { type: "category", data: weekdayLabels || [], axisLabel: { color: MUTED } },
yAxis: { type: "value", axisLabel: { color: MUTED }, splitLine: { lineStyle: { color: GRID } } },
series: [{ type: "bar", data: starts, barMaxWidth: 28, name: "开播场次" }],
};
}, [stats?.by_weekday, weekdayLabels]);
const heatmapOption = useMemo(() => {
const matrix = stats?.heatmap?.starts || [];
if (!matrix.length) return null;
const data: [number, number, number][] = [];
let max = 0;
matrix.forEach((row, wd) => {
row.forEach((val, hour) => {
data.push([hour, wd, val]);
if (val > max) max = val;
});
});
if (max <= 0) return null;
return {
textStyle: { color: FG },
tooltip: {
...TOOLTIP,
formatter: (p: { data?: [number, number, number] }) => {
const d = p.data;
if (!d) return "";
const label = (heatWeekday || [])[d[1]] || String(d[1]);
return `${label} ${String(d[0]).padStart(2, "0")}:00<br/>开播: <b>${d[2]}</b>`;
},
},
grid: { left: 56, right: 24, top: 16, bottom: 40 },
xAxis: {
type: "category",
data: stats?.heatmap?.hour_labels || Array.from({ length: 24 }, (_, h) => `${h}`),
splitArea: { show: true },
axisLabel: { color: MUTED, fontSize: 10 },
},
yAxis: { type: "category", data: heatWeekday || [], splitArea: { show: true }, axisLabel: { color: MUTED } },
visualMap: {
min: 0,
max: Math.max(1, max),
calculable: true,
orient: "horizontal",
left: "center",
bottom: 0,
textStyle: { color: MUTED },
inRange: { color: ["#0f1c2e", "#0e7490", "#2dd4bf", "#fbbf24", "#ff2d55"] },
},
series: [{ type: "heatmap", data, label: { show: false } }],
};
}, [stats?.heatmap, heatWeekday]);
const durationOption = useMemo(() => {
const buckets = stats?.duration_buckets || {};
const keys = Object.keys(buckets);
if (!keys.length || !Object.values(buckets).some((n) => n > 0)) return null;
return {
color: ["#2dd4bf"],
tooltip: { ...TOOLTIP, trigger: "item" },
series: [
{
type: "pie",
radius: ["42%", "68%"],
data: keys.map((k) => ({ name: k, value: buckets[k] })),
label: { color: MUTED, formatter: "{b}\n{c}" },
},
],
};
}, [stats?.duration_buckets]);
const dailyChart = useEchart(dailyOption, 280);
const anchorChart = useEchart(anchorOption, 340);
const hourChart = useEchart(hourOption, 280);
const weekdayChart = useEchart(weekdayOption, 240);
const heatChart = useEchart(heatmapOption, 300);
const durationChart = useEchart(durationOption, 260);
if (!stats || !(overview?.sessions || 0)) {
return (
<div className="animate-fade-up rounded-2xl border border-dashed border-white/10 bg-black/20 px-4 py-10 text-center">
<div className="mx-auto mb-3 text-4xl">📈</div>
<div className="font-display text-base text-white">暂无统计数据</div>
<p className="mt-1 text-sm text-slate-500">添加直播间并积累开播记录后,这里会显示频率与时段规律。</p>
</div>
);
}
const fmtDur = (seconds?: number) => {
const total = Math.max(0, Math.floor(Number(seconds) || 0));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
if (h > 0) return `${h}小时${m}分`;
return `${m}分`;
};
return (
<div className="space-y-4">
<div className="stagger grid gap-3 sm:grid-cols-2 xl:grid-cols-6">
{[
["🎬 总场次", String(overview?.sessions ?? 0)],
["👤 主播数", String(overview?.unique_anchors ?? 0)],
["⏱️ 累计时长", `${Number(overview?.total_hours || 0).toFixed(1)}h`],
["📏 平均场长", fmtDur(overview?.avg_duration_seconds)],
["📐 中位场长", fmtDur(overview?.median_duration_seconds)],
["🔴 进行中", String(overview?.active_sessions ?? 0)],
].map(([label, value]) => (
<div key={label} className="hover-lift rounded-xl border border-white/10 bg-gradient-to-br from-white/[0.07] to-transparent px-4 py-3">
<div className="text-[11px] tracking-wide text-slate-500">{label}</div>
<div className="mt-1 font-display text-xl font-semibold tabular-nums text-white">{value}</div>
</div>
))}
</div>
{stats.insights?.length ? (
<div className="animate-fade-up rounded-xl border border-teal-500/20 bg-teal-500/5 px-4 py-3 text-sm text-teal-50/90">
<div className="mb-1 text-xs font-medium uppercase tracking-wide text-teal-300/80">💡 规律速览</div>
<ul className="space-y-1 text-slate-200">
{stats.insights.map((item, idx) => (
<li key={idx}>· {item.zh}</li>
))}
</ul>
</div>
) : null}
<div className="stagger grid gap-4 xl:grid-cols-2">
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">📅 每日开播频率与时长</h3>
{dailyChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">🏆 主播排行(场次 / 累计小时)</h3>
{anchorChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">🕐 一天内时段分布</h3>
{hourChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">📆 星期分布</h3>
{weekdayChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4 xl:col-span-2">
<h3 className="mb-1 text-sm font-medium text-slate-200">🔥 星期 × 小时 热力图</h3>
{heatChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-1 text-sm font-medium text-slate-200">🥧 单场时长分布</h3>
{durationChart}
</section>
<section className="hover-lift rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-3 text-sm font-medium text-slate-200">📋 主播明细</h3>
<div className="max-h-[260px] overflow-auto">
<table className="min-w-full text-left text-xs">
<thead className="sticky top-0 bg-[#0b1626] text-slate-500">
<tr>
<th className="px-2 py-2">主播</th>
<th className="px-2 py-2">场次</th>
<th className="px-2 py-2">小时</th>
<th className="px-2 py-2">日均场</th>
<th className="px-2 py-2">峰值</th>
<th className="px-2 py-2">间隔</th>
</tr>
</thead>
<tbody>
{(stats.top_anchors || []).map((row) => (
<tr key={`${row.anchor_name}-${row.source_room_id}`} className="border-t border-white/5 text-slate-300">
<td className="px-2 py-2 font-medium text-slate-100">{row.anchor_name || "—"}</td>
<td className="px-2 py-2 tabular-nums">{row.sessions ?? 0}</td>
<td className="px-2 py-2 tabular-nums">{Number(row.hours_total || 0).toFixed(1)}</td>
<td className="px-2 py-2 tabular-nums">{Number(row.sessions_per_active_day || 0).toFixed(2)}</td>
<td className="px-2 py-2">
{String(row.peak_hour ?? 0).padStart(2, "0")}:00
{row.peak_weekday_label ? ` · ${row.peak_weekday_label}` : ""}
</td>
<td className="px-2 py-2 tabular-nums">{row.avg_gap_hours == null ? "—" : `${Number(row.avg_gap_hours).toFixed(1)}h`}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
</div>
</div>
);
}

View File

@ -0,0 +1,70 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { BrandMark } from "@/components/ui";
const NAV = [
{ href: "/", label: "概览", emoji: "📡" },
{ href: "/sessions", label: "场次", emoji: "🎬" },
{ href: "/anchors", label: "主播", emoji: "👤" },
{ href: "/covers", label: "截图", emoji: "🖼️" },
{ href: "/events", label: "事件", emoji: "⚡" },
{ href: "/rooms", label: "直播间", emoji: "🏠" },
{ href: "/blacklist", label: "黑名单", emoji: "🚫" },
{ href: "/settings", label: "设置", emoji: "⚙️" },
];
export function Shell({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
return (
<div className="relative min-h-screen">
<div className="ambient-orb a" />
<div className="ambient-orb b" />
<div className="ambient-orb c" />
<div className="relative z-10 mx-auto flex min-h-screen max-w-7xl flex-col px-4 py-5 sm:px-6">
<header className="mb-6 animate-fade-up border-b border-white/10 pb-5">
<div className="flex flex-wrap items-end justify-between gap-4">
<div className="flex items-start gap-3">
<BrandMark className="mt-1 h-12 w-12" />
<div>
<p className="font-display text-xs uppercase tracking-[0.28em] text-teal-300/90">Douyin Live Radar</p>
<h1 className="font-display text-3xl font-bold tracking-tight text-white sm:text-4xl">
抖音直播间监控
</h1>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
开播捕捉 · 停播结场 · 时长统计 · 截图存证 · 防风控轮询
</p>
</div>
</div>
<nav className="flex flex-wrap gap-2">
{NAV.map((item) => {
const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
return (
<Link
key={item.href}
href={item.href}
className={`nav-chip rounded-xl px-3 py-1.5 text-sm ${
active
? "active bg-white/15 text-white ring-1 ring-teal-400/30"
: "bg-white/5 text-slate-400 hover:bg-white/10 hover:text-white"
}`}
>
<span className="mr-1.5">{item.emoji}</span>
{item.label}
</Link>
);
})}
</nav>
</div>
</header>
<main className="page-enter flex-1 pb-10">{children}</main>
<footer className="border-t border-white/5 py-4 text-center text-[11px] text-slate-600">
Douyin Monitor · realtime radar for live rooms
</footer>
</div>
</div>
);
}

View File

@ -0,0 +1,49 @@
"use client";
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
type ToastItem = { id: string; text: string; tone?: "ok" | "warn" | "err" };
const ToastCtx = createContext<{ push: (text: string, tone?: ToastItem["tone"]) => void } | null>(null);
export function ToastProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<ToastItem[]>([]);
const push = useCallback((text: string, tone: ToastItem["tone"] = "ok") => {
const id = `${Date.now()}-${Math.random()}`;
setItems((prev) => [...prev.slice(-4), { id, text, tone }]);
window.setTimeout(() => {
setItems((prev) => prev.filter((x) => x.id !== id));
}, 3200);
}, []);
const value = useMemo(() => ({ push }), [push]);
return (
<ToastCtx.Provider value={value}>
{children}
<div className="pointer-events-none fixed bottom-4 right-4 z-[80] flex w-[min(92vw,22rem)] flex-col gap-2">
{items.map((t) => (
<div
key={t.id}
className={`animate-fade-up rounded-xl border px-3 py-2 text-sm shadow-lg backdrop-blur ${
t.tone === "err"
? "border-rose-500/40 bg-rose-500/20 text-rose-50"
: t.tone === "warn"
? "border-amber-500/40 bg-amber-500/20 text-amber-50"
: "border-teal-500/40 bg-teal-500/20 text-teal-50"
}`}
>
{t.text}
</div>
))}
</div>
</ToastCtx.Provider>
);
}
export function useToast() {
const ctx = useContext(ToastCtx);
if (!ctx) return { push: (_t: string, _tone?: ToastItem["tone"]) => undefined };
return ctx;
}

View File

@ -0,0 +1,123 @@
"use client";
import { useEffect, useState, type ReactNode } from "react";
export function AnimatedNumber({
value,
decimals = 0,
duration = 700,
suffix = "",
}: {
value: number;
decimals?: number;
duration?: number;
suffix?: string;
}) {
const [display, setDisplay] = useState(0);
useEffect(() => {
const target = Number(value) || 0;
const start = performance.now();
let from = 0;
setDisplay((prev) => {
from = prev;
return prev;
});
let raf = 0;
const tick = (now: number) => {
const t = Math.min(1, (now - start) / duration);
const eased = 1 - Math.pow(1 - t, 3);
setDisplay(from + (target - from) * eased);
if (t < 1) raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [value, duration]);
return (
<span className="tabular-nums">
{display.toFixed(decimals)}
{suffix}
</span>
);
}
export function LivePulse({ label = "LIVE" }: { label?: string }) {
return (
<span className="inline-flex items-center gap-2 rounded-md border border-rose-500/30 bg-rose-500/10 px-2 py-1 text-[11px] font-semibold tracking-wide text-rose-100">
<span className="live-dot" />
{label}
</span>
);
}
export function BrandMark({ className = "h-10 w-10" }: { className?: string }) {
return (
<svg className={`${className} float-slow`} viewBox="0 0 64 64" aria-hidden>
<defs>
<linearGradient id="bm" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stopColor="#ff2d55" />
<stop offset="100%" stopColor="#2dd4bf" />
</linearGradient>
</defs>
<rect x="4" y="4" width="56" height="56" rx="16" fill="url(#bm)" opacity="0.18" />
<path className="logo-stroke" d="M18 40 V24 l12 16 12-16 v16 M14 48 h36" stroke="url(#bm)" />
<circle cx="48" cy="16" r="4" fill="#ff2d55">
<animate attributeName="opacity" values="1;0.35;1" dur="1.4s" repeatCount="indefinite" />
</circle>
</svg>
);
}
export function StatTile({
emoji,
label,
value,
hint,
accent = "teal",
}: {
emoji: string;
label: string;
value: ReactNode;
hint?: string;
accent?: "teal" | "rose" | "amber" | "sky";
}) {
const ring =
accent === "rose"
? "from-rose-500/20"
: accent === "amber"
? "from-amber-500/20"
: accent === "sky"
? "from-sky-500/20"
: "from-teal-500/20";
return (
<div className={`hover-lift glass-panel relative overflow-hidden rounded-2xl bg-gradient-to-br px-4 py-4 ${ring} to-transparent`}>
<div className="flex items-start justify-between gap-2">
<div className="text-2xl leading-none">{emoji}</div>
<div className="text-right">
<div className="text-[11px] uppercase tracking-wide text-slate-500">{label}</div>
<div className="mt-1 font-display text-2xl font-semibold text-white">{value}</div>
</div>
</div>
{hint ? <div className="mt-3 text-xs text-slate-500">{hint}</div> : null}
</div>
);
}
export function EmptyState({
emoji,
title,
desc,
}: {
emoji: string;
title: string;
desc: string;
}) {
return (
<div className="animate-fade-up rounded-2xl border border-dashed border-white/10 bg-black/20 px-6 py-12 text-center">
<div className="mx-auto mb-3 flex h-16 w-16 items-center justify-center rounded-2xl bg-white/5 text-3xl">{emoji}</div>
<div className="font-display text-lg text-white">{title}</div>
<p className="mx-auto mt-1 max-w-md text-sm text-slate-500">{desc}</p>
</div>
);
}

48
frontend/src/lib/api.js Normal file
View File

@ -0,0 +1,48 @@
export async function fetchJson(url, init) {
const res = await fetch(url, {
...init,
headers: {
"Content-Type": "application/json",
...(init?.headers || {}),
},
});
const text = await res.text();
let data = null;
try {
data = text ? JSON.parse(text) : null;
} catch {
data = { raw: text };
}
if (!res.ok) {
const detail = data?.detail || data?.message || text || res.statusText;
throw new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
}
return data;
}
export function fmtDuration(seconds) {
const total = Math.max(0, Math.floor(Number(seconds) || 0));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
if (h > 0) return `${h}小时${m}分${s}秒`;
if (m > 0) return `${m}分${s}秒`;
return `${s}秒`;
}
export function fmtTs(ts) {
if (!ts) return "—";
try {
return new Date(ts * 1000).toLocaleString("zh-CN", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
});
} catch {
return String(ts);
}
}

View File

@ -0,0 +1,75 @@
"use client";
import { useEffect, useRef, useState } from "react";
export type StreamEvent = {
id?: string;
ts?: number;
kind?: string;
message?: string;
anchor_name?: string;
room_id?: string;
};
export function useEventStream(enabled = true) {
const [connected, setConnected] = useState(false);
const [last, setLast] = useState<StreamEvent | null>(null);
const [tick, setTick] = useState(0);
const esRef = useRef<EventSource | null>(null);
useEffect(() => {
if (!enabled) return;
let closed = false;
let retryTimer = 0;
const connect = () => {
if (closed) return;
const es = new EventSource("/api/events/stream");
esRef.current = es;
es.onopen = () => setConnected(true);
es.onerror = () => {
setConnected(false);
es.close();
retryTimer = window.setTimeout(connect, 2500);
};
es.onmessage = (msg) => {
try {
const data = JSON.parse(msg.data) as StreamEvent;
setLast(data);
setTick((n) => n + 1);
} catch {
/* ignore */
}
};
};
connect();
return () => {
closed = true;
window.clearTimeout(retryTimer);
esRef.current?.close();
};
}, [enabled]);
return { connected, last, tick };
}
export function useNow(intervalMs = 1000) {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const t = setInterval(() => setNow(Date.now()), intervalMs);
return () => clearInterval(t);
}, [intervalMs]);
return now;
}
export function liveElapsed(startedAt?: number, nowMs?: number) {
if (!startedAt) return "—";
const now = (nowMs || Date.now()) / 1000;
const total = Math.max(0, Math.floor(now - startedAt));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
if (h > 0) return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
return `${m}:${String(s).padStart(2, "0")}`;
}

View File

@ -0,0 +1,13 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{js,ts,jsx,tsx,mdx}"],
theme: {
extend: {
fontFamily: {
display: ['"Space Grotesk"', '"Noto Sans SC"', "sans-serif"],
body: ['"IBM Plex Sans"', '"Noto Sans SC"', "sans-serif"],
},
},
},
plugins: [],
};

21
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./src/*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

4
pb/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
pb_data/
*.exe
CHANGELOG.md
LICENSE.md

View File

@ -0,0 +1,113 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = new Collection({
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3208210256",
"max": 0,
"min": 0,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text494360628",
"max": 0,
"min": 0,
"name": "value",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1410822291",
"max": 0,
"min": 0,
"name": "room_id",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1001949196",
"max": 0,
"min": 0,
"name": "reason",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3046793135",
"max": 0,
"min": 0,
"name": "sqlite_id",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_393683846",
"indexes": [],
"listRule": null,
"name": "dy_blacklist",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
});
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_393683846");
return app.delete(collection);
})

View File

@ -0,0 +1,147 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = new Collection({
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3208210256",
"max": 0,
"min": 0,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"exceptDomains": null,
"hidden": false,
"id": "url4101391790",
"name": "url",
"onlyDomains": null,
"presentable": false,
"required": true,
"system": false,
"type": "url"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1410822291",
"max": 0,
"min": 0,
"name": "room_id",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3485334036",
"max": 0,
"min": 0,
"name": "note",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "bool1358543748",
"name": "enabled",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text4043827142",
"max": 0,
"min": 0,
"name": "last_status",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3981874087",
"max": 0,
"min": 0,
"name": "last_anchor",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3046793135",
"max": 0,
"min": 0,
"name": "sqlite_id",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_1332144992",
"indexes": [],
"listRule": null,
"name": "dy_rooms",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
});
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_1332144992");
return app.delete(collection);
})

View File

@ -0,0 +1,188 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = new Collection({
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3208210256",
"max": 0,
"min": 0,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1410822291",
"max": 0,
"min": 0,
"name": "room_id",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"exceptDomains": null,
"hidden": false,
"id": "url2776776943",
"name": "source_url",
"onlyDomains": null,
"presentable": false,
"required": false,
"system": false,
"type": "url"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text2904793982",
"max": 0,
"min": 0,
"name": "anchor_name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text724990059",
"max": 0,
"min": 0,
"name": "title",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "number222754019",
"max": null,
"min": null,
"name": "started_at",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"hidden": false,
"id": "number473765221",
"max": null,
"min": null,
"name": "ended_at",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"hidden": false,
"id": "number1783675470",
"max": null,
"min": null,
"name": "duration_seconds",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text4205100914",
"max": 0,
"min": 0,
"name": "push_date",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text2063623452",
"max": 0,
"min": 0,
"name": "status",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text3046793135",
"max": 0,
"min": 0,
"name": "sqlite_id",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_596514221",
"indexes": [],
"listRule": null,
"name": "dy_sessions",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
});
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_596514221");
return app.delete(collection);
})

View File

@ -0,0 +1,67 @@
# -*- coding: utf-8 -*-
"""Apply sh2-aligned anti-risk settings and restagger room checks."""
from __future__ import annotations
import random
import sys
import time
from pathlib import Path
BACKEND = Path(r"C:\Users\admin\Desktop\douyinWEB\backend")
sys.path.insert(0, str(BACKEND))
from app import cookie_loader, db # noqa: E402
def main() -> None:
db.init_db()
sync = cookie_loader.force_sync_cookie_from_sh2()
print("cookie", sync, flush=True)
# Match sh2 config.ini: 循环时间=300, 线程数偏保守
db.update_settings_map(
{
"monitor_enabled": True,
"max_concurrency": 1,
"min_request_gap_sec": 3.0,
"request_jitter_sec": 2.0,
"offline_interval_sec": 300.0,
"live_interval_sec": 120.0,
"priority_interval_sec": 90.0,
"error_backoff_base_sec": 60.0,
"error_backoff_max_sec": 600.0,
"global_pause_on_risk_sec": 90.0,
"capture_cover_on_start": False,
}
)
rooms = db.list_rooms(limit=2000).get("rooms") or []
now = time.time()
# Spread first wave over ~ (n * ~4s) with 60s headroom — no burst after cool-down clear
with db._lock: # noqa: SLF001
conn = db._connect() # noqa: SLF001
try:
for i, r in enumerate(rooms):
# live rooms keep a shorter but still gentle cadence
if r.get("last_status") == "live":
delay = 30.0 + i * 2.0 + random.uniform(0, 3)
else:
delay = 90.0 + i * 4.0 + random.uniform(0, 5)
conn.execute(
"UPDATE rooms SET next_check_at = ?, last_error = '', updated_at = ? WHERE id = ?",
(now + delay, now, r["id"]),
)
conn.commit()
finally:
conn.close()
print(f"restaggered={len(rooms)}", flush=True)
print("settings", {k: db.get_settings_map().get(k) for k in [
"max_concurrency", "offline_interval_sec", "live_interval_sec",
"min_request_gap_sec", "global_pause_on_risk_sec", "capture_cover_on_start",
"monitor_enabled",
]}, flush=True)
if __name__ == "__main__":
main()

182
scripts/import_from_11.py Normal file
View File

@ -0,0 +1,182 @@
# -*- coding: utf-8 -*-
"""Parse Desktop/11.txt and import real Douyin rooms (direct SQLite, no PB wait)."""
from __future__ import annotations
import json
import re
import sys
import time
from collections import Counter
from pathlib import Path
SRC = Path(r"C:\Users\admin\Desktop\11.txt")
OUT = Path(r"C:\Users\admin\Desktop\douyinWEB\backend\data\import_rooms.json")
BACKEND = Path(r"C:\Users\admin\Desktop\douyinWEB\backend")
HOST_RE = re.compile(r"(10\.\d+\.\d+\.\d+)\s*(?:\(([A-Za-z])\))?", re.I)
URL_RE = re.compile(
r"https://live\.douyin\.com/(\d+)\s*(?:,\s*主播:\s*([^h]*?))?(?=https://live\.douyin\.com/|$)"
)
DEMO_ROOM_IDS = {
"123456789012",
"234567890123",
"345678901234",
"111111111111",
"222222222222",
}
def _host_label(m: re.Match[str]) -> str:
ip = m.group(1)
lane = (m.group(2) or "").upper()
return f"{ip}-{lane}" if lane else ip
def parse_rooms(text: str) -> list[dict]:
host = "unknown"
bag: dict[str, dict] = {}
for raw in text.splitlines():
line = raw.strip().lstrip("\ufeff")
if not line:
continue
has_url = "live.douyin.com" in line
hm = HOST_RE.search(line)
# host-only lines (skip incomplete fragments like "10.88.")
if not has_url:
if hm:
host = _host_label(hm)
continue
# dense line may start with "10.88.0.5 (B) https://..."
if hm:
prefix = line[: hm.start()].strip()
# only treat as host marker when it appears before the first URL
if hm.start() < line.find("https://"):
host = _host_label(hm)
for m in URL_RE.finditer(line):
rid = m.group(1)
name = (m.group(2) or "").strip()
name = re.sub(r"\s+", " ", name).strip(" ,,")
if rid not in bag:
bag[rid] = {
"url": f"https://live.douyin.com/{rid}",
"room_id": rid,
"name": name,
"hosts": {host},
}
else:
if name and not bag[rid]["name"]:
bag[rid]["name"] = name
bag[rid]["hosts"].add(host)
rooms: list[dict] = []
for item in bag.values():
hosts = sorted(h for h in item["hosts"] if h and h != "unknown")
primary = hosts[0] if hosts else "unknown"
tags = ["真实"]
for h in hosts:
tags.append(h)
rooms.append(
{
"url": item["url"],
"room_id": item["room_id"],
"name": item["name"],
"host": primary,
"hosts": hosts,
"tags": ",".join(tags),
}
)
rooms.sort(key=lambda r: (r["host"], r["room_id"]))
return rooms
def main() -> None:
sys.path.insert(0, str(BACKEND))
from app import db
print("init db...", flush=True)
db.init_db()
text = SRC.read_text(encoding="utf-8-sig")
rooms = parse_rooms(text)
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(rooms, ensure_ascii=False, indent=2), encoding="utf-8")
named = sum(1 for r in rooms if r["name"])
print(f"parsed unique={len(rooms)} named={named}", flush=True)
print("hosts=", dict(Counter(r["host"] for r in rooms)), flush=True)
# Pause monitor traffic while we rewrite the list
db.update_settings_map(
{
"monitor_enabled": False,
"max_concurrency": 1,
"min_request_gap_sec": 4.0,
"request_jitter_sec": 2.5,
"offline_interval_sec": 300.0,
"live_interval_sec": 90.0,
"global_pause_on_risk_sec": 600.0,
}
)
print("monitor paused", flush=True)
existing = db.list_rooms(limit=2000).get("rooms") or []
demo_ids = [
r["id"]
for r in existing
if str(r.get("room_id") or "") in DEMO_ROOM_IDS
or str(r.get("note") or "").startswith("示例")
or "demo" in ",".join(r.get("tags") or []).lower()
]
if demo_ids:
db.bulk_rooms("delete", demo_ids)
print(f"removed_demo={len(demo_ids)}", flush=True)
existing = db.list_rooms(limit=2000).get("rooms") or []
by_rid = {str(r.get("room_id")): r for r in existing}
created = 0
updated = 0
pks: list[str] = []
now = time.time()
for r in rooms:
note = r["name"] or r["room_id"]
tags = r["tags"]
if r["room_id"] in by_rid:
pk = by_rid[r["room_id"]]["id"]
db.update_room(pk, note=note, enabled=True, tags=tags)
updated += 1
pks.append(pk)
else:
room = db.create_room(r["url"], note=note, enabled=True, tags=tags)
created += 1
pks.append(room["id"])
# Stagger first checks: ~8s apart after 60s quiet
with db._lock: # noqa: SLF001
conn = db._connect() # noqa: SLF001
try:
for i, pk in enumerate(pks):
conn.execute(
"UPDATE rooms SET next_check_at = ?, updated_at = ?, last_error = '', error_count = 0 WHERE id = ?",
(now + 60.0 + i * 8.0, now, pk),
)
conn.commit()
finally:
conn.close()
db.update_settings_map({"monitor_enabled": True})
counts = db.counts()
print(f"created={created} updated={updated}", flush=True)
print(f"counts={counts}", flush=True)
print(f"stagger_minutes≈{(len(pks) * 8) / 60:.1f}", flush=True)
sample = (db.list_rooms(limit=3).get("rooms") or [])
for s in sample:
print("sample", s.get("room_id"), s.get("note"), s.get("tags"), flush=True)
if __name__ == "__main__":
main()

22
scripts/start.bat Normal file
View File

@ -0,0 +1,22 @@
@echo off
setlocal
cd /d %~dp0\..
echo [1/3] Starting PocketBase on :8090 ...
start "pocketbase" cmd /c "cd /d %~dp0\..\pb && pocketbase.exe serve --http=127.0.0.1:8090"
timeout /t 2 /nobreak >nul
echo [2/3] Starting FastAPI on :8000 ...
start "fastapi" cmd /c "cd /d %~dp0\..\backend && python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload"
timeout /t 2 /nobreak >nul
echo [3/3] Starting Next.js on :3000 ...
start "nextjs" cmd /c "cd /d %~dp0\..\frontend && npx --yes next dev --port 3000 --hostname 127.0.0.1"
echo.
echo Open http://127.0.0.1:3000
echo API http://127.0.0.1:8000/docs
echo PB http://127.0.0.1:8090/_/
endlocal

View File

@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
"""Sync sh2 cookie + probe a few real rooms."""
from __future__ import annotations
import asyncio
import sys
from pathlib import Path
BACKEND = Path(r"C:\Users\admin\Desktop\douyinWEB\backend")
sys.path.insert(0, str(BACKEND))
from app import cookie_loader, db # noqa: E402
from app.douyin import check_room # noqa: E402
async def main() -> None:
db.init_db()
sync = cookie_loader.force_sync_cookie_from_sh2()
print("sync", {k: v for k, v in sync.items() if k != "cookie"}, flush=True)
cfg = db.get_settings_map()
cookie = str(cfg.get("dy_cookie") or "")
print("has_cookie", bool(cookie), "len", len(cookie), flush=True)
rooms = (db.list_rooms(limit=2000).get("rooms") or [])[:5]
if not rooms:
print("no rooms", flush=True)
return
for r in rooms:
url = r["url"]
note = r.get("note") or ""
try:
result = await check_room(url, cookie=cookie)
print(
"probe",
r.get("room_id"),
note[:20],
"ok=",
result.get("ok"),
"status=",
result.get("status"),
"live=",
result.get("is_live"),
"anchor=",
(result.get("anchor_name") or "")[:20],
"err=",
result.get("error") or "",
flush=True,
)
except Exception as exc:
print("probe_fail", r.get("room_id"), type(exc).__name__, exc, flush=True)
await asyncio.sleep(2.5)
# clear risk pause after successful path validation
db.update_settings_map({"monitor_enabled": True})
print("done rooms=", db.counts(), flush=True)
if __name__ == "__main__":
asyncio.run(main())