Document Pro relay/time-slot ops and harden relay worker stability.

README covers YouTube RTMPS relay, time-slot mode, ops/Netdata, and global SOCKS plan. Relay pipeline keeps FFmpeg alive across probe flicker, stabilizes time-slot source selection, and fixes misleading start-button copy in the UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-09-01 10:53:29 -05:00
parent e3d7d7a813
commit 11394a2a80
67 changed files with 5503 additions and 1587 deletions

438
README.md
View File

@ -22,30 +22,77 @@ cd desktop && npm install && npm run electron:dev
默认本机端口:API `8014` · PB `8090` · youtube-svc `8020` · UI `5173`。说明见 [desktop/README.md](desktop/README.md)。打包:`cd desktop && npm run pack`。
## 线上地址
## 部署与访问地址(多环境)
| 用途 | URL |
|------|-----|
| 控制台 | https://dylive.nomadro.com/ |
| 登录 | https://dylive.nomadro.com/login |
| API Health | https://dylive.nomadro.com/api/health |
| PocketBase | https://dylive.nomadro.com/_/ |
| SeaweedFS S3 | https://feiniu.nomadro.com/ |
| S3 别名 | https://s3.nomadro.com/ |
| Shorts | https://dylive.nomadro.com/shorts |
| YouTube | https://dylive.nomadro.com/youtube |
**文档不写死任何生产域名或公网 IP。** 每台机器 / 每个环境用你自己的变量;下面用占位符说明。
HTTPS 由服务器 **Caddy** 自动签发。进程端口:
| 占位符 | 含义 | 典型来源 |
|--------|------|----------|
| `${DOMAIN}` | 对外 HTTPS 域名 | `bootstrap_vps.sh` 必填 |
| `${PUBLIC_BASE}` | 站点根 URL | 默认 `https://${DOMAIN}`,写入 `DY_PUBLIC_BASE_URL` |
| `${APP_DIR}` | 代码目录 | 默认 `/opt/douyinWEB` |
| `${API_PORT}` / `${WEB_PORT}` | 本机监听端口 | 默认 `8014` / `4015`(仅 `127.0.0.1`) |
| 服务 | 端口 | systemd |
|------|------|---------|
部署完成后,控制台与 API 路径为:
| 用途 | URL 模板 |
|------|----------|
| 控制台 | `${PUBLIC_BASE}/` |
| 登录 | `${PUBLIC_BASE}/login` |
| API Health | `${PUBLIC_BASE}/api/health` |
| OpenAPI | `${PUBLIC_BASE}/api/docs`(经 Next 反代)或 `http://127.0.0.1:${API_PORT}/docs` |
| PocketBase 管理 | `${PUBLIC_BASE}/_/` |
| Shorts | `${PUBLIC_BASE}/shorts` |
| YouTube | `${PUBLIC_BASE}/youtube` |
| 运维 | `${PUBLIC_BASE}/ops` |
| Web 分析 | `${PUBLIC_BASE}/web` |
| Netdata(可选,需登录) | `${PUBLIC_BASE}/netdata/`(反代 `127.0.0.1:19999`,见 [运维与 Netdata](#运维与-netdata)) |
| S3 封面(若启用) | `${PUBLIC_BASE}/${S3_BUCKET}/…` 或独立 `DY_S3_PUBLIC_BASE` |
> **OAuth / 回调**:Google、TikTok 等第三方控制台里登记的 redirect URI 必须与 **`DY_PUBLIC_BASE_URL`** 一致,例如 `${PUBLIC_BASE}/api/shorts/oauth/callback`。换域名后需同步改 Google Cloud 与设置页里的 OAuth 配置。
### 新 VPS 一键引导(推荐)
在目标机器上以 root 执行(**先设好域名 DNS 与 TLS 证书**,脚本只加 vhost、不装 Caddy):
```bash
DOMAIN=your.example.com \
ADMIN_USER=admin ADMIN_PASS='your-secure-password' \
GIT_URL='https://git.example.com/you/douyinWEB.git' \
GIT_BRANCH=dev \
FRESH=1 \
bash scripts/bootstrap_vps.sh
```
可选环境变量见脚本头部注释:`APP_DIR`、`PUBLIC_BASE`、`WEB_PORT`、`API_PORT`、`PB_PORT`、`YT_PORT`、`S3_PORT` 等。
引导会生成 **`/etc/douyinweb.env`**(含 `SESSION_SECRET`、`S3_SECRET`),并创建 systemd 单元;**不会**打包或恢复 `monitor.db`(新装零房间,见仓库规则)。
### 本机进程端口(默认)
应用进程绑定 **127.0.0.1**,由 Nginx / 宝塔反代对外;公网只暴露 443(及 WebRTC 等按需放行)。
| 服务 | 默认端口 | systemd 单元名 |
|------|----------|----------------|
| Next.js | `4015` | `douyinweb-web` |
| FastAPI | `8014` | `douyinweb-api` |
| PocketBase | `8092` | `douyinweb-pb` |
| youtube-svc | `8020` | (与 API 同机,InnerTube) |
| SeaweedFS S3 | `8333` | `seaweed-master\|volume\|filer\|s3` |
| youtube-svc | `8020` | `douyinweb-yt` |
| SeaweedFS S3 | `8333` | `douyinweb-s3` (+ master/volume/filer) |
| Netdata(可选) | `19999` | `netdata` |
部署目录:`/opt/douyinWEB`(VPS `107.173.30.245`)。时区:`Asia/Shanghai`(北京时间)。
时区建议:`TZ=Asia/Shanghai`(界面与「北京日」配额逻辑使用北京时间)。
### 已有机器增量更新
```bash
cd "${APP_DIR:-/opt/douyinWEB}"
git pull origin "${GIT_BRANCH:-dev}"
systemctl restart douyinweb-api
cd frontend && npm run build
systemctl restart douyinweb-web
```
Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**勿把服务器 IP 写进仓库**)。
## 技术栈与数据流
@ -99,7 +146,34 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
| 视频列表、改元数据、删视频 | GET / PATCH / DELETE `.../videos/{video_id}` |
| 播放列表 | `.../playlists` |
### Shorts 旁路(默认关)
### YouTube Pro 转播(Douyin → YouTube RTMPS)
控制台 **`/youtube` → 分配**:按频道分组配置直播 KEY、精选抖音源、可选 **Neko 工作室**(Docker 内 Chrome 打开 YouTube Studio),由后台 **FFmpeg** 将抖音 FLV 转码后推到 YouTube RTMP/RTMPS。
| 概念 | 说明 |
|------|------|
| **自动推流** | 设置 `youtube_relay_enabled=true` 或 UI「自动推流」;Worker 约 7s 轮询 |
| **手动开始/停止** | 单频道「开始」= 武装监听(`manual_hold`),开播后自动推;「停止」释放 |
| **时间段模式** | `youtube_relay_time_slot_mode`;**与自动推流独立开关**。开启后:仅 **已配置 KEY 的 N 个频道** 按北京时 **24/N 小时** 轮播独占;**源 = 监控库当前在播抖音房**(非精选列表);非当前时段自动停 FFmpeg + Neko |
| **单频道独占** | 时间段模式强制开启;同一时刻仅一个分组推流 + 一个 Neko 运行 |
| **画质预设** | `youtube_relay_quality_preset`(如 `720p`、`vps_ultra`);含分辨率、码率、AAC **128k** |
| **Cookie** | 解析拉流地址依赖 `dy_cookie`(同 sh2 `[Cookie]抖音cookie`);缺失时保持监听、不退出 Worker |
**状态(UI)**:推流中 / 转推启动中 / 等待直播 / 监听中 / 低速推流 等,由 `youtube_relay_status.py` 根据 FFmpeg 日志与进程态汇总;**推流中不会显示「无法开始」**。
**与 Shorts 关系**:不复用 sh2 RTMP 旁路;Shorts 仍为可选短成片上传。全局 SOCKS 规划见 [全局 SOCKS5](#全局-socks5sing-box--proxychains)。
| API(节选) | 说明 |
|-------------|------|
| `GET /api/youtube/relay/status` | 各分组推流态、排班、Neko 快照 |
| `POST /api/youtube/relay/start` \| `/stop` | 启停自动推流 Worker |
| `POST /api/youtube/relay/groups/{id}/start` \| `/stop` \| `/restart` | 单频道手动控制 |
| `POST /api/youtube/relay/time-slot-mode` | `{ "enabled": true/false }` 时间段模式 |
| `POST /api/youtube/relay/quality-preset` | 切换画质并重启在推分组 |
| `POST /api/youtube/relay/exclusive-live` | 单频道独占(时间段模式强制开) |
| `GET /api/youtube/assign/schedule` | 24/N 时段表(北京时间) |
部署增量脚本(SSH 目标勿写入仓库):`scripts/_deploy_netdata.py`、`scripts/_deploy_youtube_relay.py` 等。
详见 [docs/SHORTS.md](docs/SHORTS.md)。摘要:
@ -110,7 +184,7 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
- **上传**:每频道 Google OAuth 一键授权;每频道北京日配额固定 **9** 条
- **OAuth Client 分组**:频道绑定 **A / B / C / D**(对应不同 Google Cloud 项目);上传配额按 Client **独立计数展示**,A 用尽不影响 B
- **YouTube 项目配额**:官方默认 **100 次 `videos.insert`/天/项目**(太平洋日独立桶);页面展示本地参考计数(默认 90/Client)。**不自行暂停/拦截上传**;收到 HTTP **429** 时仅把接口反馈写到任务错误,手动「立即上传」始终可点,以 YouTube 返回为准
- **SOCKS5 代理**(默认关):设置页可选;仅 Shorts 上传与 OAuth token 刷新走代理,不影响抖音监控
- **全局 SOCKS5**(默认关,目标方案见 [全局 SOCKS5(sing-box + proxychains)](#全局-socks5sing-box--proxychains)):静态住宅 IP;规划覆盖 Shorts / 长视频 / TikTok / X / Neko / FFmpeg;与 v2ray-agent 翻墙 sing-box **隔离共存**
- **频道级联清理**:删除 Shorts 频道时同步删除关联任务与本地成片;孤儿任务可运维 purge
- **不复用** sh2 RTMP 转播通道
@ -135,11 +209,21 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
| `/events` | SSE 时间线;场次详情;导出 |
| `/groups` | YouTube 频道分组 + 分析页签 |
| `/youtube` | 频道管理(默认)+ InnerTube 探测 |
| `/youtube` → **分配** | Pro 转播:KEY / 精选源 / 时间段 / Neko / FFmpeg 实况 |
| `/shorts` | 授权 / 任务 / 排程 / 立即上传 / 在播分析 |
| `/settings` | 防风控、通知、静默、YT/Shorts、SOCKS 上传代理、改密、PB/S3 运维 |
| `/settings` | 防风控、通知、静默、YT/Shorts、**全局 SOCKS5**、改密、PB/S3 运维 |
| `/ops` | 运维:Umami / ntfy / DNS / systemd;顶栏另有 CPU·内存条 |
| `/web` | Umami 多站点访问分析 |
| `/blacklist` | 黑名单 |
### 运维与通知
### 运维与 Netdata
- **`/ops`**:多站点 DNS 探测、systemd 服务态、ntfy 测试推送;**不内嵌 Netdata iframe**(避免子路径/登录页导致前端 JSON 解析报错)
- **顶栏主机指标**:`GET /api/ops/host-metrics`(CPU / 内存 / load,本机 psutil)
- **Netdata(可选)**:仅监听 `127.0.0.1:19999`;Nginx 反代 `${PUBLIC_BASE}/netdata/`,`auth_request` → `GET /api/auth/netdata-gate`(须已登录 DouyinWEB);`NETDATA_WEB_PATH=/netdata`,`[cloud] enabled = no`
- 安装/更新:`python scripts/_deploy_netdata.py`(勿把 SSH 密码写入仓库)
### 运维与通知(监控侧)
- Cookie:设置页保存会记录年龄;可从 sh2 `config.ini` 同步(`POST /api/settings/sync-cookie`)
- 静默时段:降低夜间探测频率(重点房可继续)
@ -151,14 +235,14 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
```
douyinWEB/
backend/app/ FastAPI(auth / monitor / cover / shorts_* / shorts_socks / shorts_yt_quota / youtube_* …)
backend/app/ FastAPI(auth / monitor / cover / shorts_* / youtube_relay_* / youtube_neko / host_metrics …)
backend/tests/ pytest(Shorts / live / reconcile 等)
backend/data/ SQLite、封面/成片缓存
frontend/src/ Next.js 控制台(Web)
desktop/ Windows Electron 客户端(本机 PB+API+UI)
youtube-svc/ YouTube.js sidecar(InnerTube)
pb/ PocketBase 数据与 migrations
docs/ 专题文档(如 Shorts)
docs/ 专题文档(如 Shorts);全局 SOCKS5 方案见 README
scripts/ 本地启动与 VPS 增量部署
```
@ -181,8 +265,10 @@ cd frontend && npm run dev -- --port 3000 --hostname 127.0.0.1
- API:http://127.0.0.1:8000/docs
- PB:http://127.0.0.1:8090/_/
默认 PB:`admin@douyin.local` / `DouyinMonitor_Admin_2026`
站点登录:见 `DY_ADMIN_*`(首次写入库后可在设置页改密)。
本地默认账号由环境变量注入(**勿将生产密码写入仓库**):
- 站点登录:`DY_ADMIN_USERNAME` / `DY_ADMIN_PASSWORD`(首次启动写入 SQLite,可在设置页改密)
- PocketBase:`DY_PB_ADMIN_EMAIL` / `DY_PB_ADMIN_PASSWORD`
```bat
cd backend && pip install -r requirements.txt
@ -200,6 +286,11 @@ cd youtube-svc && npm install
| GET | `/api/monitor/status` | 抖音监控运行态 |
| GET | `/api/youtube-monitor/status` | YouTube 分组轮询态 |
| GET | `/api/youtube/live-map` | YT 分组 + Shorts 在播地图 |
| GET | `/api/youtube/relay/status` | Pro 转播 Worker / 分组 FFmpeg 态 |
| POST | `/api/youtube/relay/groups/{id}/start` | 单频道开始监听(手动武装) |
| POST | `/api/youtube/relay/time-slot-mode` | 时间段模式开关 |
| GET | `/api/ops/host-metrics` | 本机 CPU / 内存(需登录) |
| GET | `/api/auth/netdata-gate` | Netdata Nginx 鉴权(204/401) |
| GET | `/api/youtube/manage/channels` | OAuth 频道管理入口 |
| GET | `/api/groups/analytics` | 分组场次分析 |
| GET | `/api/shorts/status` | Shorts worker / 北京日配额 / OAuth Client / **YouTube 上传配额**(`yt_quota_by_profile`、`yt_quota_exhausted_hint`) |
@ -228,29 +319,21 @@ python scripts\apply_sh2_antirisk.py # 对齐 sh2 防风控并错开检测
python scripts\sync_cookie_and_probe.py # 同步 Cookie 并抽样探测
```
VPS(需 SSH):
VPS 相关(在 **目标 Linux 机** 上执行 bootstrap;Windows 仅用于带 SSH 的增量脚本,**勿在仓库写死 IP/密码**):
```bash
# 新机器(在 VPS 上)
bash scripts/bootstrap_vps.sh # 需先 export DOMAIN、GIT_URL、ADMIN_* 等,见上文
# 旧版 / 专项(按需)
python scripts/deploy_ubuntu.py
python scripts/deploy_seaweedfs.py
python scripts/deploy_shorts.py
```
```bat
python scripts\deploy_ubuntu.py # 基础 Ubuntu 部署
python scripts\deploy_seaweedfs.py # SeaweedFS + 封面能力
python scripts\setup_caddy_dylive.py # dylive / feiniu / s3 反代
python scripts\deploy_shorts.py # Shorts 旁路增量
python scripts\deploy_yt_quota_fix.py # YouTube 上传配额:按 Client 展示、取消本地拦截
python scripts\deploy_shorts_socks.py # Shorts 上传 SOCKS5 代理
python scripts\deploy_channel_cascade.py # 删频道级联清理任务/成片
python scripts\deploy_dup_upload_fix.py # 重复上传修复
python scripts\deploy_dual_platform.py # 双平台 / 分组相关增量
python scripts\deploy_site_auth.py # 站点登录
python scripts\deploy_youtube_live.py # 在播地图 / LIVE 角标
python scripts\deploy_youtube_manage.py # 频道管理 CRUD
python scripts\deploy_yt_analytics.py # 分组分析
python scripts\deploy_shorts_live_analytics.py # Shorts 在播分析
python scripts\deploy_oauth_scopes.py # OAuth scope 扩展
python scripts\deploy_ux.py # 确认框 / 上传 UX / ticker
python scripts\deploy_feature_pass.py # 综合特性增量
python scripts\deploy_all_features.py # 多特性打包部署
python scripts\reconcile_clips_vps.py # VPS 成片对账
python scripts\restart_vps.py # 重启 douyinWEB 进程
REM Windows 本机:pull + 重启(SSH 目标用私有配置,勿提交仓库)
python scripts\_deploy.py
```
## 关键设置(防风控)
@ -271,9 +354,16 @@ python scripts\restart_vps.py # 重启 douyinWEB 进程
| `shorts_dedupe_room_day` | 默认 `true`;同房北京日仅一次 |
| `shorts_upload_spread` | 默认 `true`;错峰排程 |
| `shorts_yt_daily_upload_limit` | 默认 `90`;各 OAuth Client 本地参考上限(太平洋日,仅展示) |
| `shorts_upload_socks_enabled` | 默认 `false`;Shorts 上传走 SOCKS5 代理 |
| `shorts_upload_socks_profile_id` | `residential-1`;当前 SOCKS 配置 ID |
| `shorts_upload_socks_profiles` | 内置默认;SOCKS5 配置列表(server / port / 认证) |
| `youtube_relay_enabled` | 默认 `false`;Pro 转播自动推流 Worker |
| `youtube_relay_time_slot_mode` | 默认 `false`;时间段模式(与上项独立) |
| `youtube_relay_exclusive_live` | 默认 `true`;单频道独占 FFmpeg+Neko |
| `youtube_relay_quality_preset` | 默认 `720p`;转播画质预设 |
| `youtube_relay_use_rtmps` | 默认 `true`;推 YouTube RTMPS |
| `global_socks_enabled` | 默认 `false`;全局 SOCKS5 总开关(实现前 DB 可能仍用 `shorts_upload_socks_*` 别名) |
| `global_socks_profile_id` | `residential-1`;当前静态住宅 SOCKS 配置 ID |
| `global_socks_profiles` | SOCKS5 列表:`server` / `port` / `username` / `password` / `type`(`socks5` / `socks5h`) |
> **说明**:下表旧键 `shorts_upload_socks_*` 与 `global_socks_*` 为同一套配置的兼容名;新方案落地后以「全局 SOCKS5」为准,见 [全局 SOCKS5](#全局-socks5sing-box--proxychains)。
### YouTube 上传配额(429)
@ -283,70 +373,248 @@ python scripts\restart_vps.py # 重启 douyinWEB 进程
- 多 Google 项目:Shorts 频道绑定 OAuth Client **A/B/C/D**,各 Client 独立计数、互不影响
- 实现:`backend/app/shorts_yt_quota.py`(按 Client 计数展示、429 识别);Shorts 页展示用量提示与接口错误,**禁止本地自设上传暂停**
## 全局 SOCKS5(sing-box + proxychains)
> **文档状态**:以下为推荐生产架构(静态住宅 IP + 与 [mack-a/v2ray-agent](https://github.com/mack-a/v2ray-agent) 翻墙 sing-box **隔离共存**)。代码按此方案迭代;**当前仓库实现可能仍为「仅 Shorts 上传可选 SOCKS」**,以 `backend/app/shorts_socks.py` 为准。
### 目标
| 开关 | 行为 |
|------|------|
| **开启** | Shorts / 长视频 / TikTok / X / OAuth / Neko 浏览器 / FFmpeg 拉流与推流等业务出站,尽量统一走 **静态住宅 SOCKS5** |
| **关闭** | 停止 DouyinWEB 专用代理组件,**本机业务直连 VPS 出口**(不影响 v2ray-agent 翻墙) |
设置页规划名称:**全局 SOCKS5**(不再叫「仅 Shorts 上传 SOCKS」)。
### 架构(推荐组合)
```text
┌─────────────────────────────────────────────────────────────────┐
│ DouyinWEB 业务 │
│ httpx / requests / Neko Chromium / TikTok 上传 / X 发帖 … │
│ │ │
│ ▼ http://127.0.0.1:17891 (仅本机) │
│ ┌──────────────────┐ │
│ │ douyinweb-singbox │ sing-box mixed 入站(HTTP + SOCKS) │
│ │ 独立进程/独立配置 │ │
│ └────────┬─────────┘ │
│ │ outbound socks5 │
│ ▼ │
│ ┌──────────────────┐ │
│ │ 静态住宅 SOCKS5 │ 运营商提供的 socks5h 上游 │
│ └──────────────────┘ │
│ │
│ YouTube RTMP 推流(FFmpeg → rtmps://a.rtmps.youtube.com) │
│ │ │
│ ▼ proxychains4 仅包裹该 ffmpeg 进程(TCP 级代理) │
│ 同上 127.0.0.1:17891 或直连住宅 SOCKS5 │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ v2ray-agent sing-box(已有,勿动) │
│ /etc/v2ray-agent/… · systemd: sing-box · 443/Reality/… │
│ → Clash / 手机客户端翻墙 │
└─────────────────────────────────────────────────────────────────┘
```
**为何用两层?**
| 组件 | 作用 |
|------|------|
| **sing-box(DouyinWEB 专用)** | 本机统一入口 `127.0.0.1:17891`;HTTP API、浏览器、大部分 Python 出站走 mixed;DNS 走代理(`socks5h`) |
| **proxychains-ng** | FFmpeg 推 **RTMPS** 不走 HTTP 代理;用 `proxychains4` **只包 relay 的 ffmpeg 子进程**,使推流出口也为住宅 IP |
### 与 v2ray-agent / 翻墙 sing-box 的隔离规则(硬约束)
若 VPS 已用 [v2ray-agent](https://github.com/mack-a/v2ray-agent) 部署 sing-box 供 Clash 使用,DouyinWEB **必须**遵守:
| 允许 | 禁止 |
|------|------|
| 新 systemd 单元 **`douyinweb-singbox`** | `systemctl restart sing-box`(会断 Clash) |
| 配置仅写在 **`${APP_DIR}/config/sing-box.json`** | 修改 **`/etc/v2ray-agent/`** 下任何配置 |
| 监听 **`127.0.0.1:17891`**(部署前 `ss -lntp` 确认端口空闲) | 占用 443 / 与 v2ray 相同的本地 Socks 端口 |
| 关全局代理时 **只停 `douyinweb-singbox`** | 开启 TUN / 改系统默认路由(易伤 SSH 与本机 API) |
上线前在目标机检查:
```bash
systemctl status sing-box 2>/dev/null
systemctl list-units '*sing*' '*v2ray*' 2>/dev/null
ss -lntp | grep -E 'sing-box|17891|1080|7890'
ls -la /etc/v2ray-agent/sing-box/ 2>/dev/null # 只读查看,勿由 DouyinWEB 改写
```
### 各模块走代理方式(目标)
| 模块 | 机制 | 备注 |
|------|------|------|
| Shorts 上传 / OAuth 刷新 | httpx → `http://127.0.0.1:17891` | 替代现网直连 `socks5h://` |
| 长视频上传 / Studio API | 同上 | |
| TikTok 上传 | `requests` proxies → 本机 mixed | 全局开时不必每账号单独勾 SOCKS |
| X / x2 发帖 | httpx 或进程 env | |
| Neko 浏览器 | `NEKO_BROWSER_PROXY=http://127.0.0.1:17891` | Studio 页面与住宅 IP 一致 |
| FFmpeg **拉**抖音 FLV | `-http_proxy` 或 `HTTP_PROXY` → 本机 mixed | |
| FFmpeg **推** YouTube RTMP | **`proxychains4 -f … ffmpeg …`** | RTMP 非 HTTP,必须 TCP 级代理 |
| 抖音监控轮询 | **默认直连 VPS**(可配置是否走代理) | 住宅 IP 非必须时可保持直连减负载 |
### DouyinWEB 专用 sing-box 配置要点(示意)
- **inbound**:`mixed`,`listen` = `127.0.0.1`,`listen_port` = `17891`
- **outbound**:`socks`,指向上游静态住宅(`server` / `server_port` / `username` / `password` / `version: 5`)
- **route**:`final` → 上游 outbound;**不要**在本实例开 TUN
配置路径(规划):`${APP_DIR}/config/sing-box.json`
进程(规划):`sing-box run -c ${APP_DIR}/config/sing-box.json`
服务名(规划):`douyinweb-singbox.service`(与系统 `sing-box` 服务分离)
### proxychains 配置要点(RTMP 推流)
安装:`apt install proxychains4`(或发行版等价包)。
`${APP_DIR}/config/proxychains.conf` 示例逻辑:
```ini
strict_chain
proxy_dns
[ProxyList]
socks5 127.0.0.1 17891
```
relay 启动 FFmpeg 时(规划):
```bash
proxychains4 -f /opt/douyinWEB/config/proxychains.conf \
ffmpeg -y ... -f flv 'rtmps://a.rtmps.youtube.com/live2/STREAM_KEY'
```
全局 SOCKS **关闭**时:普通 `ffmpeg` 直连,不调用 proxychains。
### 设置项(规划)
| 键 | 说明 |
|----|------|
| `global_socks_enabled` | 总开关 |
| `global_socks_profile_id` | 当前住宅配置 ID |
| `global_socks_profiles[]` | `id`, `label`, `type`, `server`, `port`, `username`, `password` |
保存设置时(规划):生成 sing-box 配置 → `systemctl restart douyinweb-singbox`;**永不**重启 v2ray-agent 的 `sing-box`。
兼容:读写可同时支持旧键 `shorts_upload_socks_enabled` / `shorts_upload_socks_profiles`(迁移期)。
### 依赖(VPS 一次性)
| 包 | 用途 |
|----|------|
| `sing-box` | DouyinWEB 专用本机 mixed 转发(与 v2ray-agent 二进制可共存,**服务与配置分离**) |
| `proxychains4` | 仅包裹 YouTube RTMP 的 ffmpeg 进程 |
### 风险与边界
- **延迟**:住宅 SOCKS 可能比 VPS 直连慢;推流需关注 FFmpeg `speed` 与断流。
- **RTMP**:仅靠 `HTTP_PROXY` / sing-box mixed 的 HTTP 语义 **无法** 让推流走代理;必须 proxychains(或 netns / 精细 TUN,不推荐默认)。
- **抖音监控**:若也走住宅 IP,可能增加代理流量与风控特征;建议默认监控直连、上传类走代理。
- **两套 sing-box**:Linux 允许多实例;冲突仅当**端口、服务名、配置路径**搞混时发生。
### 与现网代码的对应关系
| 现状(实现前) | 目标 |
|----------------|------|
| `backend/app/shorts_socks.py` | 收敛为 `global_socks` + `singbox_manager`;对外统一 `resolve_app_proxy()` |
| 设置页「Shorts 上传 SOCKS5」 | 改名为「全局 SOCKS5(sing-box)」 |
| `youtube_relay.py` 直接 `Popen(ffmpeg)` | 全局开时用 proxychains 包装 |
| `youtube_neko.py` `NEKO_BROWSER_PROXY=""` | 全局开时写入本机 mixed URL |
## 环境变量(`DY_` 前缀)
见 `backend/app/config.py`,线上 API 示例:
完整定义见 `backend/app/config.py`。生产环境推荐写入 **`/etc/douyinweb.env`** 或 systemd `Environment=`,bootstrap 会自动生成部分密钥。
```
### 必配(新机器)
| 变量 | 说明 |
|------|------|
| `DY_PUBLIC_BASE_URL` | 对外 HTTPS 根 URL,如 `https://${DOMAIN}`;OAuth 回调、封面公网 URL、Neko ICE 依赖此项 |
| `DY_SESSION_SECRET` | 会话签名密钥;**换机勿随意改**(否则全员掉线) |
| `DY_ADMIN_USERNAME` / `DY_ADMIN_PASSWORD` | 首次写入站点管理员(之后以库内哈希为准) |
| `DY_PB_URL` | PocketBase 地址,通常 `http://127.0.0.1:${PB_PORT}` |
| `DY_PB_ADMIN_EMAIL` / `DY_PB_ADMIN_PASSWORD` | PB 超管 |
### 封面 / S3(生产建议开启)
| 变量 | 说明 |
|------|------|
| `DY_S3_ENABLED` | `true` |
| `DY_S3_ENDPOINT` | 本机 SeaweedFS,如 `http://127.0.0.1:8333` |
| `DY_S3_PUBLIC_BASE` | 浏览器可访问的 HTTPS 前缀;可与 `DY_PUBLIC_BASE_URL` 相同(反代 `/${S3_BUCKET}/`),或独立 CDN 域名 |
| `DY_S3_ACCESS_KEY` / `DY_S3_SECRET_KEY` | 与 `/etc/seaweedfs/douyinweb-s3.json` 一致 |
| `DY_S3_BUCKET` | 默认 `douyin-covers` |
### 可选
| 变量 | 说明 |
|------|------|
| `DY_YOUTUBE_SVC_URL` | InnerTube sidecar,默认 `http://127.0.0.1:8020` |
| `DY_AUTH_ENABLED` | 站点登录,默认 `true`;本地调试可 `false` |
| `DY_API_KEY` | 非空时写操作需 `X-API-Key` |
| `DY_NEKO_NAT1TO1` | Neko WebRTC 对外 IP(留空则自动探测) |
| `TZ` | 建议 `Asia/Shanghai` |
示例(**请替换占位符,勿照抄到生产**):
```bash
DY_PUBLIC_BASE_URL=https://your.example.com
DY_PB_URL=http://127.0.0.1:8092
DY_S3_ENABLED=true
DY_S3_ENDPOINT=http://127.0.0.1:8333
DY_S3_PUBLIC_BASE=https://feiniu.nomadro.com
DY_S3_PUBLIC_BASE=https://your.example.com
DY_S3_ACCESS_KEY=douyin
DY_S3_SECRET_KEY=…
DY_S3_BUCKET=douyin-covers
DY_YOUTUBE_SVC_URL=http://127.0.0.1:8020
DY_AUTH_ENABLED=true
DY_ADMIN_USERNAME=…
DY_ADMIN_USERNAME=admin
DY_ADMIN_PASSWORD=…
DY_SESSION_SECRET=…
DY_API_KEY= # 可选;非空则写操作需密钥
TZ=Asia/Shanghai
```
## Git 管理规范
## Git 与发布
**仓库**:`https://gitea.dsx2020.com/eric/douyinWEB.git`(账号 `eric`)
**远程仓库地址因环境而异**(自建 Gitea / GitHub / Cursor 等),在本地执行:
**分支策略**:
```bash
git remote -v # 查看当前 origin
```
**分支策略**(可按团队调整):
| 分支 | 用途 |
|------|------|
| `main` | 本地 Windows 快照;不直接部署到服务器 |
| `dev` | 服务器线上运行代码;所有功能开发在此分支 |
| `main` | 稳定快照;可不直接部署 |
| `dev` | 日常开发与服务器跟踪分支 |
**开发流程(必须严格执行)**:
**推荐发布流程**:
```
本地修改代码
→ git add / git commit(dev 分支)
→ git push origin dev
→ 服务器: git pull origin dev
→ systemctl restart douyinweb-api
→ cd /opt/douyinWEB/frontend && npm run build
→ systemctl restart douyinweb-web
本地 commit → push 到 origin
→ SSH 到目标机:cd ${APP_DIR} && git pull
→ systemctl restart douyinweb-api
→ cd frontend && npm run build && systemctl restart douyinweb-web
```
**每次 git push 后,必须立即同步**:
1. Windows 本机:`git pull origin dev`(保持本地与远端一致)
2. 服务器:`git pull origin dev` + 重启相关服务 + 重新 build 前端
**禁止**:
**禁止行为**:
- 禁止在服务器上直接修改代码文件(必须走 git)
- 禁止用 sftp/scp 覆盖服务器上的代码文件
- 禁止 `git reset --hard` / `git stash apply` 等操作破坏服务器工作区
- 禁止将 `monitor.db` / `pb_data/` 等运行时数据文件纳入 git commit
- 在服务器上直接改代码而不走 git
- 用 tar/scp **覆盖**服务器上的应用代码时带入旧机 `monitor.db`(新装须空库)
- 将 `monitor.db`、`pb_data/`、`.env`、`/etc/douyinweb.env` 提交进 git
- 将 Google `client_secret_*.json`、SSH 密码、API 密钥写入仓库或 README
**快速部署脚本**:
```bat
python scripts\_deploy.py # git pull + restart API + npm build + restart web
```
本地 Windows 可用 `python scripts\_deploy.py` 做 pull + 重启(脚本内目标主机应通过环境变量或本机私有配置指定,**不要写死在仓库里**)。
## 说明
- 仓库含 `backend/data/` 与 `pb/pb_data/`,便于部署后带真实房间与 Cookie 开箱可用。
- Windows `pocketbase.exe` 不入库;Ubuntu 使用 Linux 版 `pocketbase`。
- **勿提交** Google `client_secret_*.json`;Client ID/Secret 走设置页或环境配置。
- **监控主路径**不含推流转播(推流仍在 sh2);**Shorts** 为可选短成片旁路,不占用 sh2 RTMP 车道。
- 「无图」历史场次:停播后接口常无封面,多数无法回补;以在播补抓与后续开播为准。
- 新装 **不要** 预置抖音房间 URL;房间由 UI 或运维脚本导入(勿在 bootstrap 里自动跑 `import_from_11.py`)。
- Windows `pocketbase.exe` 不入库;Linux 使用对应架构的 `pocketbase` 二进制。
- **勿提交** OAuth Client Secret、SSH 凭据、生产域名专属 nginx 片段到公共分支。
- **监控主路径**不含 sh2 RTMP 推流;**Shorts** 为可选短成片旁路。
- 「无图」历史场次:停播后接口常无封面,以在播补抓与后续开播为准。
- **运维面板**(`/api/ops`)中的 Umami / ntfy / 多站点 DNS 列表来自 `ops_panel.py` 内配置;换环境时应在该模块或独立 env 中维护 **本机** 域名与 IP,勿假设与某台历史 VPS 相同。

View File

@ -17,6 +17,8 @@ _PUBLIC_PATHS = {
"/api/x2/ingest",
"/api/x2/extension/poll",
"/api/x2/extension/ws",
"/api/youtube/studio/ingest",
"/hub/youtube/live/ingest",
}

View File

@ -72,6 +72,33 @@ def cut_segment(
pass
start = max(0.0, float(start_sec))
dur = max(5, int(duration_sec))
# Prefer stream-copy (near-zero CPU); fall back to ultrafast re-encode.
copy_cmd = [
settings.ffmpeg_bin,
"-y",
"-hide_banner",
"-loglevel",
"error",
"-ss",
f"{start:.3f}",
"-i",
str(src_p),
"-t",
str(dur),
"-c",
"copy",
"-movflags",
"+faststart",
"-avoid_negative_ts",
"make_zero",
str(out),
]
try:
proc = subprocess.run(copy_cmd, capture_output=True, text=True, timeout=dur + 60)
except Exception as exc:
return {"ok": False, "error": str(exc)[:300]}
if proc.returncode == 0 and out.is_file() and out.stat().st_size >= 20_000:
return {"ok": True, "path": str(out), "seconds": dur, "mode": "copy"}
cmd = [
settings.ffmpeg_bin,
"-y",
@ -86,14 +113,16 @@ def cut_segment(
str(dur),
"-c:v",
"libx264",
"-threads",
"2",
"-preset",
"veryfast",
"ultrafast",
"-crf",
"23",
"26",
"-c:a",
"aac",
"-b:a",
"128k",
"96k",
"-movflags",
"+faststart",
"-avoid_negative_ts",
@ -108,7 +137,7 @@ def cut_segment(
return {"ok": False, "error": (proc.stderr or proc.stdout or "cut failed")[:400]}
if not out.is_file() or out.stat().st_size < 20_000:
return {"ok": False, "error": "cut too small"}
return {"ok": True, "path": str(out), "seconds": dur}
return {"ok": True, "path": str(out), "seconds": dur, "mode": "reencode"}
def _pick_start(master_sec: float, cut_sec: int, window: tuple[float, float]) -> float:

View File

@ -69,8 +69,20 @@ class Settings(BaseSettings):
neko_webrtc_mux_base: int = 52300
neko_user_pass: str = "douyinweb"
neko_admin_pass: str = "Xiao4669805@"
neko_image: str = "ghcr.io/m1k1o/neko/chromium:3.0.0"
neko_nat1to1: str = ""
# x86 VPS: google-chrome (sh2); ARM would use chromium
neko_image: str = "ghcr.io/m1k1o/neko/google-chrome:3.0.0"
neko_nat1to1: str = "" # empty → auto-detect public IP
neko_webrtc_icelite: str = "0" # sh2: OFF for remote ICE stability
neko_shm_size: str = "512mb"
neko_desktop_screen: str = "1024x576@10"
neko_max_fps: str = "10"
neko_video_bitrate: str = "700"
neko_start_url: str = (
"https://accounts.google.com/ServiceLogin?continue=https://studio.youtube.com/"
)
# 1 = Chrome managed policies force-install Tampermonkey + import Auto Dismiss
# (sh2 seed LevelDB in-repo is empty; jsonImport is the real script path)
neko_managed_policies: str = "1"
class Config:
env_prefix = "DY_"

View File

@ -10,6 +10,7 @@ from typing import Optional
DEFAULT_COOKIE_PATHS = [
Path(r"C:\project\sh2\d2ypp2\config\config.ini"),
Path(__file__).resolve().parents[2] / "config" / "douyin_cookie.ini",
Path("/opt/douyinWEB/config/douyin_cookie.ini"),
]

View File

@ -135,6 +135,72 @@ async def save_cover_from_image_url(session_id: str, image_url: str) -> str:
return stored
async def ensure_room_avatar(
room_id: str,
avatar_image: str,
*,
force: bool = False,
) -> dict[str, Any]:
"""Mirror Douyin owner avatar → S3 covers/avatars/{room_id}.jpg → rooms.avatar_url + pool thumbs."""
rid = str(room_id or "").strip()
src = str(avatar_image or "").strip()
if not rid or not src.startswith("http"):
return {"ok": False, "error": "missing room_id or avatar_image"}
existing = ""
try:
room = db.get_room_by_room_id(rid)
existing = str((room or {}).get("avatar_url") or "").strip()
except Exception:
existing = ""
if existing.startswith("http") and not force:
return {"ok": True, "skipped": True, "avatar": existing}
out_path = settings.covers_dir / f"avatar_{rid}.jpg"
def _download_and_upload() -> str:
try:
req = Request(
src,
headers={
"User-Agent": (
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) "
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1"
),
"Referer": "https://live.douyin.com/",
"Accept": "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
},
)
with urlopen(req, timeout=15) as resp:
data = resp.read()
if not data or len(data) < 64:
return ""
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_bytes(data)
if not s3_storage.s3_enabled():
return ""
return s3_storage.upload_room_avatar(rid, out_path) or ""
except Exception:
return ""
stored = await asyncio.to_thread(_download_and_upload)
try:
out_path.unlink(missing_ok=True)
except Exception:
pass
if not stored or not (stored.startswith("http://") or stored.startswith("https://")):
return {
"ok": False,
"error": "s3 avatar upload failed",
"s3_enabled": s3_storage.s3_enabled(),
}
try:
db.set_room_avatar(rid, stored)
except Exception as exc:
return {"ok": False, "error": f"db: {exc}", "avatar": stored}
return {"ok": True, "avatar": stored, "s3": True}
async def ensure_session_cover(
session_id: str,
*,

View File

@ -18,6 +18,12 @@ SHORTS_DAILY_FORCE = 9
# TikTok official Content Posting / Direct Post guideline ~15/day
TIKTOK_DAILY_FORCE = 15
# journal_mode=WAL is expensive to re-apply on every connect; once per process is enough.
_sqlite_pragmas_ready = False
_settings_cache: dict[str, Any] | None = None
_settings_cache_at = 0.0
_SETTINGS_CACHE_TTL_SEC = 1.5
def _normalize_daily_quota(value: Any = None, *, default: int = 9, lo: int = 1, hi: int = 50) -> int:
"""Clamp channel daily quota to a sane range. No longer hard-forces a single global value."""
@ -34,14 +40,26 @@ def _force_daily_quota(value: Any = None) -> int:
def _connect() -> sqlite3.Connection:
global _sqlite_pragmas_ready
conn = sqlite3.connect(str(settings.sqlite_path), check_same_thread=False, timeout=8.0)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=8000")
conn.execute("PRAGMA foreign_keys=ON")
if not _sqlite_pragmas_ready:
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA temp_store=MEMORY")
conn.execute("PRAGMA cache_size=-64000") # ~64MB page cache
_sqlite_pragmas_ready = True
return conn
def _invalidate_settings_cache() -> None:
global _settings_cache, _settings_cache_at
_settings_cache = None
_settings_cache_at = 0.0
def init_db() -> None:
with _lock:
conn = _connect()
@ -196,6 +214,8 @@ def init_db() -> None:
conn.execute("ALTER TABLE rooms ADD COLUMN tags TEXT NOT NULL DEFAULT ''")
if "clip_sec" not in cols:
conn.execute("ALTER TABLE rooms ADD COLUMN clip_sec INTEGER NOT NULL DEFAULT 0")
if "avatar_url" not in cols:
conn.execute("ALTER TABLE rooms ADD COLUMN avatar_url TEXT NOT NULL DEFAULT ''")
gcols = {r[1] for r in conn.execute("PRAGMA table_info(channel_groups)").fetchall()}
for col, ddl in [
("last_status", "TEXT NOT NULL DEFAULT 'unknown'"),
@ -342,6 +362,7 @@ def init_db() -> None:
("last_live_video_id", "TEXT NOT NULL DEFAULT ''"),
("active_session_id", "TEXT NOT NULL DEFAULT ''"),
("oauth_profile_id", "TEXT NOT NULL DEFAULT ''"),
("oauth_email", "TEXT NOT NULL DEFAULT ''"),
("yt_profile_json", "TEXT NOT NULL DEFAULT ''"),
("yt_profile_at", "REAL NOT NULL DEFAULT 0"),
]:
@ -410,11 +431,11 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"quiet_hours_start": 2,
"quiet_hours_end": 7,
"quiet_hours_allow_priority": True,
"priority_interval_sec": 25.0,
"priority_interval_sec": 60.0,
# YouTube channel-group poller (youtubei.js sidecar)
"yt_monitor_enabled": True,
"yt_offline_interval_sec": 180.0,
"yt_live_interval_sec": 90.0,
"yt_live_interval_sec": 120.0,
"yt_batch_size": 8,
"yt_request_gap_sec": 2.0,
# YouTube Douyin→YT live relay (FFmpeg RTMPS)
@ -422,6 +443,11 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"youtube_relay_bitrate": 2500,
"youtube_relay_use_rtmps": True,
"youtube_relay_respect_schedule": True,
"youtube_relay_quality_preset": "vps_ultra",
# When one channel pushes live, stop other groups' FFmpeg + Neko (save VPS CPU/RAM).
"youtube_relay_exclusive_live": True,
# Time-slot mode: N=keyed channels → each gets 24/N Beijing hours; source=live Douyin rooms.
"youtube_relay_time_slot_mode": False,
# Shorts pipeline
"shorts_enabled": False,
"shorts_clip_sec": 15,
@ -581,12 +607,26 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
def get_settings_map() -> dict[str, Any]:
"""Hot-path friendly: short TTL cache (invalidated on write)."""
global _settings_cache, _settings_cache_at
now = time.time()
cached = _settings_cache
if cached is not None and (now - _settings_cache_at) < _SETTINGS_CACHE_TTL_SEC:
return dict(cached)
with _lock:
# Re-check under lock to avoid stampedes after expiry.
now = time.time()
cached = _settings_cache
if cached is not None and (now - _settings_cache_at) < _SETTINGS_CACHE_TTL_SEC:
return dict(cached)
conn = _connect()
try:
return _settings_map_from_conn(conn)
out = _settings_map_from_conn(conn)
finally:
conn.close()
_settings_cache = out
_settings_cache_at = now
return dict(out)
def _settings_map_from_conn(conn: sqlite3.Connection) -> dict[str, Any]:
@ -741,6 +781,7 @@ def update_settings_map(patch: dict[str, Any], *, audit_actor: str = "") -> dict
conn.commit()
finally:
conn.close()
_invalidate_settings_cache()
try:
from .settings_audit import log_settings_patch
@ -853,6 +894,22 @@ def _platform_clause(platform: str, *, room_col: str, meta_col: str) -> tuple[st
return ("", [])
def _is_douyin_room_id(room_id: str | None) -> bool:
rid = str(room_id or "").strip()
if not rid:
return False
return not (rid.startswith("yt:") or rid.startswith("shorts:"))
_DOUYIN_SESSIONS_SQL = (
"room_id NOT LIKE 'yt:%' AND room_id NOT LIKE 'shorts:%' "
"AND IFNULL(metadata_json,'') NOT LIKE '%\"platform\": \"youtube\"%' "
"AND IFNULL(metadata_json,'') NOT LIKE '%\"platform\":\"youtube\"%' "
"AND IFNULL(metadata_json,'') NOT LIKE '%\"source\": \"shorts_live\"%' "
"AND IFNULL(metadata_json,'') NOT LIKE '%\"source\":\"shorts_live\"%'"
)
def _row_to_dict(row: sqlite3.Row | None) -> dict[str, Any] | None:
if row is None:
return None
@ -881,8 +938,14 @@ def _row_to_dict(row: sqlite3.Row | None) -> dict[str, Any] | None:
raw = str(data.get("cover_path") or "").strip()
# Prefer public S3 URL directly; keep proxy path as fallback for private/local
if raw.startswith("http://") or raw.startswith("https://"):
data["cover_url"] = raw
data["cover_proxy_url"] = f"/api/sessions/{data['id']}/cover"
public_base = str(settings.s3_public_base or "").rstrip("/")
# Same-origin S3 proxy is private — use API cover route for reliable auth fetch.
if public_base and raw.startswith(public_base):
data["cover_url"] = f"/api/sessions/{data['id']}/cover"
data["cover_proxy_url"] = data["cover_url"]
else:
data["cover_url"] = raw
data["cover_proxy_url"] = f"/api/sessions/{data['id']}/cover"
else:
data["cover_url"] = f"/api/sessions/{data['id']}/cover"
data["cover_proxy_url"] = data["cover_url"]
@ -972,6 +1035,50 @@ def get_room(room_pk: str) -> dict[str, Any] | None:
conn.close()
def get_room_by_room_id(room_id: str) -> dict[str, Any] | None:
rid = str(room_id or "").strip()
if not rid:
return None
with _lock:
conn = _connect()
try:
row = conn.execute(
"SELECT * FROM rooms WHERE room_id = ? ORDER BY updated_at DESC LIMIT 1",
(rid,),
).fetchone()
return _row_to_dict(row)
finally:
conn.close()
def set_room_avatar(room_id: str, avatar_url: str) -> None:
"""Persist S3/mirrored owner avatar and push into assign pool thumbs."""
rid = str(room_id or "").strip()
url = str(avatar_url or "").strip()
if not rid or not url:
return
now = time.time()
with _lock:
conn = _connect()
try:
conn.execute(
"UPDATE rooms SET avatar_url = ?, updated_at = ? WHERE room_id = ?",
(url[:800], now, rid),
)
# Ordinary/featured list thumbs should show channel avatar, not stream frame.
conn.execute(
"""
UPDATE yt_assign_pool_urls
SET cover_url = ?, updated_at = ?
WHERE room_id = ?
""",
(url[:800], now, rid),
)
conn.commit()
finally:
conn.close()
PRIORITY_TAGS = {"重点", "收藏", "priority", "vip", "高优"}
FAVORITE_TAG = "收藏"
@ -1318,6 +1425,7 @@ def touch_room(
with _lock:
conn = _connect()
try:
row = conn.execute("SELECT room_id FROM rooms WHERE id = ?", (room_pk,)).fetchone()
conn.execute(
"""
UPDATE rooms SET
@ -1345,6 +1453,16 @@ def touch_room(
room_pk,
),
)
# Keep assign ordinary/featured titles in sync with live pool nicknames.
if last_anchor and row:
try:
from .douyin_ingest import sync_pool_titles_from_anchor_conn
sync_pool_titles_from_anchor_conn(
conn, str(row["room_id"] or ""), str(last_anchor)
)
except Exception:
pass
conn.commit()
finally:
conn.close()
@ -1634,6 +1752,26 @@ def dedupe_active_sessions() -> int:
conn.close()
def _attach_room_avatar(conn: sqlite3.Connection, data: dict[str, Any] | None) -> dict[str, Any] | None:
if not data:
return data
rid = str(data.get("room_id") or "").strip()
if not rid or rid.startswith("yt:") or rid.startswith("shorts:"):
return data
try:
row = conn.execute(
"SELECT avatar_url FROM rooms WHERE room_id = ? LIMIT 1",
(rid,),
).fetchone()
if row:
av = str(row["avatar_url"] or "").strip()
if av:
data["avatar_url"] = av
except Exception:
pass
return data
def list_active_sessions(*, dedupe: bool = True, platform: str = "") -> list[dict[str, Any]]:
if dedupe:
dedupe_active_sessions()
@ -1652,7 +1790,11 @@ def list_active_sessions(*, dedupe: bool = True, platform: str = "") -> list[dic
f"SELECT * FROM sessions {where} ORDER BY started_at DESC",
params,
).fetchall()
return [_row_to_dict(r) for r in rows] # type: ignore
out = []
for r in rows:
d = _row_to_dict(r)
out.append(_attach_room_avatar(conn, d) or d)
return out # type: ignore
finally:
conn.close()
@ -1697,9 +1839,10 @@ def anchor_profile(name_or_room: str) -> dict[str, Any] | None:
sessions = [
_row_to_dict(r)
for r in conn.execute(
"""
f"""
SELECT * FROM sessions
WHERE anchor_name = ? OR room_id = ? OR anchor_name LIKE ? OR room_id LIKE ?
WHERE ({_DOUYIN_SESSIONS_SQL})
AND (anchor_name = ? OR room_id = ? OR anchor_name LIKE ? OR room_id LIKE ?)
ORDER BY started_at DESC LIMIT 200
""",
(key, key, like, like),
@ -1716,6 +1859,7 @@ def anchor_profile(name_or_room: str) -> dict[str, Any] | None:
(key, key, like, like),
).fetchall()
]
rooms = [r for r in rooms if r and _is_douyin_room_id(r.get("room_id"))]
finally:
conn.close()
if not sessions and not rooms:
@ -1755,11 +1899,12 @@ def anchor_profile(name_or_room: str) -> dict[str, Any] | None:
def list_anchors(*, limit: int = 50) -> list[dict[str, Any]]:
"""Douyin-only anchor ranking (excludes YouTube/Shorts synthetic room_ids)."""
with _lock:
conn = _connect()
try:
rows = conn.execute(
"""
f"""
SELECT
COALESCE(NULLIF(anchor_name, ''), room_id) AS name,
room_id,
@ -1768,6 +1913,7 @@ def list_anchors(*, limit: int = 50) -> list[dict[str, Any]]:
MAX(started_at) AS last_started_at,
SUM(CASE WHEN ended_at IS NULL THEN 1 ELSE 0 END) AS active
FROM sessions
WHERE {_DOUYIN_SESSIONS_SQL}
GROUP BY COALESCE(NULLIF(anchor_name, ''), room_id), room_id
ORDER BY sessions DESC, duration_seconds DESC
LIMIT ?
@ -2238,7 +2384,8 @@ def get_session(session_id: str) -> dict[str, Any] | None:
with _lock:
conn = _connect()
try:
return _row_to_dict(conn.execute("SELECT * FROM sessions WHERE id = ?", (session_id,)).fetchone())
data = _row_to_dict(conn.execute("SELECT * FROM sessions WHERE id = ?", (session_id,)).fetchone())
return _attach_room_avatar(conn, data)
finally:
conn.close()
@ -2341,11 +2488,12 @@ def list_upcoming_opens(*, limit: int = 20, priority_only: bool = False) -> list
rooms_by_rid = {str(r["room_id"]): _row_to_dict(r) for r in room_rows if r["room_id"]}
# Recent anchors with enough history
sess_groups = conn.execute(
"""
f"""
SELECT COALESCE(NULLIF(anchor_name, ''), room_id) AS name, room_id,
COUNT(*) AS c
FROM sessions
WHERE started_at > ?
AND ({_DOUYIN_SESSIONS_SQL})
GROUP BY COALESCE(NULLIF(anchor_name, ''), room_id), room_id
HAVING c >= 1
ORDER BY c DESC
@ -2357,13 +2505,16 @@ def list_upcoming_opens(*, limit: int = 20, priority_only: bool = False) -> list
for g in sess_groups:
name = str(g["name"] or "")
rid = str(g["room_id"] or "")
if not _is_douyin_room_id(rid):
continue
key = name or rid
if not key:
continue
rows = conn.execute(
"""
f"""
SELECT * FROM sessions
WHERE (anchor_name = ? OR room_id = ?)
WHERE ({_DOUYIN_SESSIONS_SQL})
AND (anchor_name = ? OR room_id = ?)
ORDER BY started_at DESC LIMIT 80
""",
(key, rid or key),
@ -3049,6 +3200,7 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]:
"privacy",
"note",
"oauth_profile_id",
"oauth_email",
"last_assigned_at",
"oauth_ok",
"oauth_checked_at",

View File

@ -131,19 +131,25 @@ def _pick_url_list(node: Any) -> str:
return ""
def _pick_avatar_image(room: dict[str, Any]) -> str:
"""Owner profile avatar (频道/主播头像) — not the live room poster."""
owner = room.get("owner") or {}
if not isinstance(owner, dict):
return ""
for key in ("avatar_large", "avatar_medium", "avatar_thumb"):
url = _pick_url_list(owner.get(key))
if url:
return url
return ""
def _pick_cover_image(room: dict[str, Any]) -> str:
"""Prefer live room cover, then owner avatar — usable even without stream."""
"""Prefer live room cover/poster, then owner avatar — usable even without stream."""
for key in ("cover", "origin_cover", "keyframe_image"):
url = _pick_url_list(room.get(key))
if url:
return url
owner = room.get("owner") or {}
if isinstance(owner, dict):
for key in ("avatar_medium", "avatar_thumb", "avatar_large"):
url = _pick_url_list(owner.get(key))
if url:
return url
return ""
return _pick_avatar_image(room)
def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]:
@ -157,6 +163,7 @@ def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]:
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)
avatar_image = _pick_avatar_image(room)
cover_image = _pick_cover_image(room)
candidates = pick_stream_candidates(room) if is_live else []
stream_url = candidates[0] if candidates else ""
@ -172,11 +179,13 @@ def _normalize_result(room: dict[str, Any], source_url: str) -> dict[str, Any]:
"stream_url": stream_url,
"stream_candidates": candidates,
"cover_image": cover_image,
"avatar_image": avatar_image,
"raw": {
"status": status_code,
"user_count": room.get("user_count") or room.get("user_count_str") or 0,
"has_stream": bool(stream_url),
"has_cover_image": bool(cover_image),
"has_avatar_image": bool(avatar_image),
"stream_candidate_count": len(candidates),
},
}

View File

@ -8,7 +8,7 @@ from typing import Any
from . import db
_CACHE: dict[str, Any] = {"at": 0.0, "payload": None, "key": ""}
_CACHE_TTL_SEC = 8.0
_CACHE_TTL_SEC = 12.0
def _entry(row: dict[str, Any]) -> dict[str, Any]:
@ -16,11 +16,13 @@ def _entry(row: dict[str, Any]) -> dict[str, Any]:
rid = str(row.get("room_id") or "").strip()
url = str(row.get("url") or "").strip()
anchor = str(row.get("last_anchor") or row.get("note") or "").strip()
avatar = str(row.get("avatar_url") or "").strip()
return {
"is_live": status == "live",
"last_status": status,
"anchor": anchor,
"url": url,
"avatar_url": avatar,
"last_checked_at": row.get("last_checked_at"),
"active_session_id": str(row.get("active_session_id") or ""),
}

100
backend/app/host_metrics.py Normal file
View File

@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
"""Host CPU / memory snapshot (no extra deps — reads /proc)."""
from __future__ import annotations
import os
import time
from pathlib import Path
from typing import Any
_prev_cpu: tuple[int, int] | None = None
_snapshot_cache: dict[str, Any] | None = None
_snapshot_cache_at = 0.0
_SNAPSHOT_TTL_SEC = 2.0
def _read_cpu_totals() -> tuple[int, int]:
line = Path("/proc/stat").read_text(encoding="utf-8", errors="replace").splitlines()[0]
parts = line.split()
if not parts or parts[0] != "cpu":
return 0, 0
nums = [int(x) for x in parts[1:]]
idle = nums[3] + (nums[4] if len(nums) > 4 else 0)
total = sum(nums[:10]) if len(nums) >= 10 else sum(nums)
return idle, total
def _cpu_percent(sample: bool = True) -> float:
"""Return busy CPU % since last call (or brief sleep sample on first call)."""
global _prev_cpu
idle, total = _read_cpu_totals()
if _prev_cpu is None:
if sample:
time.sleep(0.12)
idle2, total2 = _read_cpu_totals()
_prev_cpu = (idle2, total2)
dt = total2 - total
if dt <= 0:
return 0.0
return round(100.0 * (1.0 - (idle2 - idle) / dt), 1)
_prev_cpu = (idle, total)
return 0.0
prev_idle, prev_total = _prev_cpu
_prev_cpu = (idle, total)
dt = total - prev_total
if dt <= 0:
return 0.0
busy = 100.0 * (1.0 - (idle - prev_idle) / dt)
return round(max(0.0, min(100.0, busy)), 1)
def _mem_info() -> dict[str, float]:
kv: dict[str, int] = {}
for line in Path("/proc/meminfo").read_text(encoding="utf-8", errors="replace").splitlines():
if ":" not in line:
continue
k, v = line.split(":", 1)
num = v.strip().split()[0]
try:
kv[k.strip()] = int(num)
except ValueError:
continue
total_kb = float(kv.get("MemTotal") or 0)
avail_kb = float(kv.get("MemAvailable") or kv.get("MemFree") or 0)
used_kb = max(0.0, total_kb - avail_kb)
pct = round(100.0 * used_kb / total_kb, 1) if total_kb > 0 else 0.0
return {
"memory_total_gb": round(total_kb / 1024 / 1024, 2),
"memory_used_gb": round(used_kb / 1024 / 1024, 2),
"memory_available_gb": round(avail_kb / 1024 / 1024, 2),
"memory_percent": pct,
}
def snapshot(*, sample_cpu: bool = False) -> dict[str, Any]:
"""CPU % uses /proc delta between calls (no blocking sleep). First call may be 0."""
global _snapshot_cache, _snapshot_cache_at
now = time.time()
if (
not sample_cpu
and _snapshot_cache is not None
and (now - _snapshot_cache_at) < _SNAPSHOT_TTL_SEC
):
return dict(_snapshot_cache)
mem = _mem_info()
load1 = 0.0
try:
load1 = round(float(Path("/proc/loadavg").read_text().split()[0]), 2)
except Exception:
pass
nproc = max(1, int(os.cpu_count() or 1))
out = {
"ts": now,
"cpu_percent": _cpu_percent(sample=sample_cpu),
"load1": load1,
"cpu_cores": nproc,
**mem,
}
_snapshot_cache = out
_snapshot_cache_at = now
return dict(out)

View File

@ -180,6 +180,12 @@ async def lifespan(_: FastAPI):
await _boot("yt_long", yt_long_pipeline.start)
await _boot("youtube_relay", youtube_relay_pipeline.start)
async def _neko_boot() -> None:
groups = await asyncio.to_thread(yt_assign_db.list_groups, False)
await asyncio.to_thread(youtube_neko.sync_for_groups, groups)
await _boot("neko", _neko_boot)
asyncio.create_task(_start_workers())
yield
try:
@ -260,8 +266,8 @@ async def ping() -> dict[str, Any]:
@app.get("/api/health")
async def health() -> dict[str, Any]:
"""Fast health — desktop banner must never touch SQLite."""
async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
"""Fast health — no full pipeline builders unless ?detail=1."""
if _DESKTOP_LIGHT:
return {"ok": True, "time": time.time(), "desktop_light": True}
out: dict[str, Any] = {
@ -270,12 +276,52 @@ async def health() -> dict[str, Any]:
"api_key_required": bool(str(settings.api_key or "").strip()),
"desktop_light": False,
}
def _light_health() -> dict[str, Any]:
cfg = db.get_settings_map()
mon = monitor.status(light=True)
return {
"monitor": {
"running": bool(mon.get("running")),
"live_count": int(mon.get("live_count") or 0),
"monitor_enabled": bool(mon.get("monitor_enabled", True)),
},
"shorts": {
"enabled": bool(cfg.get("shorts_enabled")),
"running": bool(
getattr(shorts_pipeline, "_task", None)
and not shorts_pipeline._task.done() # noqa: SLF001
),
},
"tiktok": {"enabled": bool(cfg.get("tiktok_enabled"))},
"yt_long": {
"enabled": bool(cfg.get("yt_long_enabled")),
"running": bool(
getattr(yt_long_pipeline, "_task", None)
and not yt_long_pipeline._task.done() # noqa: SLF001
),
},
"youtube_relay": {
"enabled": bool(cfg.get("youtube_relay_enabled")),
"running": bool(
getattr(youtube_relay_pipeline, "_task", None)
and not youtube_relay_pipeline._task.done() # noqa: SLF001
),
},
}
try:
out["monitor"] = await asyncio.to_thread(monitor.status)
out["shorts"] = await asyncio.to_thread(shorts_pipeline.status)
out["yt_long"] = await asyncio.to_thread(yt_long_pipeline.status)
out["youtube_monitor"] = await asyncio.to_thread(yt_monitor.status)
out["youtube_relay"] = await asyncio.to_thread(youtube_relay_pipeline.status)
if detail:
out["monitor"] = await asyncio.to_thread(monitor.status)
out["shorts"] = await asyncio.to_thread(shorts_pipeline.status)
out["yt_long"] = await asyncio.to_thread(yt_long_pipeline.status)
out["youtube_monitor"] = await asyncio.to_thread(yt_monitor.status)
out["youtube_relay"] = await asyncio.to_thread(youtube_relay_pipeline.status)
cfg = await _db(db.get_settings_map)
out["tiktok"] = {"enabled": bool(cfg.get("tiktok_enabled"))}
else:
light = await asyncio.to_thread(_light_health)
out.update(light)
except Exception as exc:
out["status_error"] = str(exc)[:120]
@ -341,6 +387,15 @@ async def auth_status(request: Request) -> dict[str, Any]:
}
@app.get("/api/auth/netdata-gate")
async def auth_netdata_gate(request: Request) -> Response:
"""nginx auth_request: 204 when logged in, 401 otherwise."""
user = session_user_from_request(request)
if settings.auth_enabled and not user:
raise HTTPException(401, "未登录")
return Response(status_code=204)
@app.get("/api/auth/me")
async def auth_me(request: Request) -> dict[str, Any]:
from .authz import session_role_from_request
@ -398,8 +453,8 @@ async def auth_change_password(request: Request, body: dict[str, Any]) -> dict[s
@app.get("/api/monitor/status")
async def monitor_status() -> dict[str, Any]:
fn = monitor.status_light if _DESKTOP_LIGHT else monitor.status
async def monitor_status(light: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
fn = monitor.status_light if (_DESKTOP_LIGHT or light) else monitor.status
try:
return await asyncio.wait_for(asyncio.to_thread(fn), timeout=12.0)
except asyncio.TimeoutError as exc:
@ -515,15 +570,27 @@ def _public_settings(cfg: dict[str, Any]) -> dict[str, Any]:
def _request_public_base(request: Request) -> str:
"""Prefer reverse-proxy headers for OAuth redirect base."""
"""Prefer reverse-proxy headers for OAuth redirect base (whichever host user opened)."""
proto = (request.headers.get("x-forwarded-proto") or request.url.scheme or "https").split(",")[0].strip()
host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "").split(",")[0].strip()
if host:
# strip port from Host if present for standard :443
if host.endswith(":443") and proto == "https":
host = host[:-4]
elif host.endswith(":80") and proto == "http":
host = host[:-3]
return f"{proto}://{host}"
return "https://dylive.nomadro.com"
pub = str(settings.public_base_url or "").strip().rstrip("/")
if pub:
return pub
return ""
def _enrich_shorts_job(job: dict[str, Any] | None) -> dict[str, Any] | None:
def _enrich_shorts_job(
job: dict[str, Any] | None,
*,
ch_map: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any] | None:
if not job:
return None
from pathlib import Path
@ -534,7 +601,12 @@ def _enrich_shorts_job(job: dict[str, Any] | None) -> dict[str, Any] | None:
out = dict(job)
clip = str(out.get("clip_path") or "").strip()
out["clip_ready"] = bool(clip) and Path(clip).is_file()
ch = db.get_shorts_channel(str(out.get("channel_pk") or "")) or {}
pk = str(out.get("channel_pk") or "")
ch = (ch_map or {}).get(pk) if ch_map is not None else None
if ch is None and pk:
ch = db.get_shorts_channel(pk) or {}
elif ch is None:
ch = {}
if ch:
out["channel_name"] = str(ch.get("name") or out.get("channel_name") or "")
out["oauth_profile_id"] = str(ch.get("oauth_profile_id") or "").strip().upper()
@ -551,6 +623,11 @@ def _enrich_shorts_job(job: dict[str, Any] | None) -> dict[str, Any] | None:
return out
def _enrich_shorts_jobs(jobs: list[dict[str, Any]]) -> list[dict[str, Any]]:
ch_map = {str(c.get("id") or ""): c for c in db.list_shorts_channels()}
return [_enrich_shorts_job(j, ch_map=ch_map) for j in jobs if j]
def _retry_shorts_job_record(job_id: str) -> dict[str, Any]:
from pathlib import Path
@ -590,14 +667,18 @@ def _retry_shorts_job_record(job_id: str) -> dict[str, Any]:
@app.get("/api/shorts/status")
async def shorts_status(request: Request) -> dict[str, Any]:
st = await asyncio.to_thread(shorts_pipeline.status)
async def shorts_status(
request: Request,
light: int = Query(0, ge=0, le=1),
) -> dict[str, Any]:
st = await asyncio.to_thread(shorts_pipeline.status_light if light else shorts_pipeline.status)
st["oauth_configured"] = shorts_oauth.oauth_client_configured()
st["oauth_redirect_uri"] = shorts_oauth.resolve_redirect_uri(_request_public_base(request))
st["oauth_scopes"] = shorts_oauth.requested_scopes()
cfg = await _db(db.get_settings_map)
st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104")
st["oauth_profiles"] = shorts_oauth.list_oauth_profiles(cfg, public=True)
if not light:
st["oauth_profiles"] = shorts_oauth.list_oauth_profiles(cfg, public=True)
return st
@ -608,44 +689,49 @@ async def shorts_live_analytics(
top_anchors: int = Query(25, ge=1, le=50),
) -> dict[str, Any]:
"""Shorts 上传频道自身开播分析(live-map 轮询写入的 sessions)。"""
stats = summarize_sessions(
date_from=date_from,
date_to=date_to,
platform="shorts",
top_anchors=top_anchors,
)
channels = db.shorts_live_channel_stats(date_from=date_from, date_to=date_to)
ypp_by_shorts: dict[str, int] = {}
try:
from . import yt_long_db, youtube_manage
ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk()
enriched = []
for c in channels:
row = dict(c)
pk = str(row.get("id") or "")
if pk:
ch = db.get_shorts_channel(pk) or {}
row["yt_profile"] = youtube_manage._snippet_from_channel_row(ch)
row["authorized"] = bool(str(ch.get("refresh_token") or "").strip())
row["oauth_ok"] = ch.get("oauth_ok")
row["oauth_profile_id"] = str(ch.get("oauth_profile_id") or "").strip().upper()
row["ypp_ok"] = ypp_by_shorts.get(pk, -1)
enriched.append(row)
channels = enriched
except Exception:
pass
recent = db.list_sessions(platform="shorts", limit=20, offset=0)
live_now = sum(1 for c in channels if int(c.get("active") or 0) > 0 or str(c.get("last_status") or "") == "live")
return {
"ok": True,
"platform": "shorts",
"stats": stats,
"channels": channels,
"recent_sessions": recent.get("sessions") or [],
"recent_total": recent.get("total") or 0,
"live_now": live_now,
}
def _build() -> dict[str, Any]:
stats = summarize_sessions(
date_from=date_from,
date_to=date_to,
platform="shorts",
top_anchors=top_anchors,
)
channels = db.shorts_live_channel_stats(date_from=date_from, date_to=date_to)
ypp_by_shorts: dict[str, int] = {}
try:
from . import yt_long_db, youtube_manage
ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk()
ch_map = {str(c.get("id") or ""): c for c in db.list_shorts_channels()}
enriched = []
for c in channels:
row = dict(c)
pk = str(row.get("id") or "")
if pk:
ch = ch_map.get(pk) or {}
row["yt_profile"] = youtube_manage._snippet_from_channel_row(ch)
row["authorized"] = bool(str(ch.get("refresh_token") or "").strip())
row["oauth_ok"] = ch.get("oauth_ok")
row["oauth_profile_id"] = str(ch.get("oauth_profile_id") or "").strip().upper()
row["ypp_ok"] = ypp_by_shorts.get(pk, -1)
enriched.append(row)
channels = enriched
except Exception:
pass
recent = db.list_sessions(platform="shorts", limit=20, offset=0)
live_now = sum(1 for c in channels if int(c.get("active") or 0) > 0 or str(c.get("last_status") or "") == "live")
return {
"ok": True,
"platform": "shorts",
"stats": stats,
"channels": channels,
"recent_sessions": recent.get("sessions") or [],
"recent_total": recent.get("total") or 0,
"live_now": live_now,
}
return await _db(_build)
@app.get("/api/shorts/oauth/start")
@ -684,16 +770,11 @@ async def shorts_oauth_callback(
title = quote(str(result.get("youtube_title") or "ok"))
handle = quote(str(result.get("youtube_handle") or ""))
ret = str(result.get("return_to") or "").strip()
extra = f"&title={title}" + (f"&handle={handle}" if handle else "")
if ret:
sep = "&" if "?" in ret else "?"
return RedirectResponse(
f"{base}{ret}{sep}oauth=ok&title={title}" + (f"&handle={handle}" if handle else ""),
status_code=302,
)
return RedirectResponse(
f"{base}/shorts?oauth=ok&title={title}" + (f"&handle={handle}" if handle else ""),
status_code=302,
)
return RedirectResponse(f"{base}{ret}{sep}oauth=ok{extra}", status_code=302)
return RedirectResponse(f"{base}/shorts?oauth=ok{extra}", status_code=302)
except Exception as exc:
ret = str(request.query_params.get("return_to") or "").strip()
msg = quote(str(exc)[:320])
@ -757,7 +838,7 @@ async def shorts_fill_quota() -> dict[str, Any]:
@app.get("/api/shorts/channels")
async def shorts_channels_list(enabled: Optional[bool] = None) -> dict[str, Any]:
rows = db.list_shorts_channels(enabled=enabled)
rows = await _db(lambda: db.list_shorts_channels(enabled=enabled))
return {"channels": [_public_shorts_channel(c) for c in rows]}
@ -807,17 +888,20 @@ async def shorts_jobs_list(
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
) -> dict[str, Any]:
data = db.list_shorts_jobs(
status=status,
push_date=push_date,
channel_pk=channel_pk,
session_id=session_id,
room_id=room_id,
limit=limit,
offset=offset,
)
data["jobs"] = [_enrich_shorts_job(j) for j in data.get("jobs") or []]
return data
def _load() -> dict[str, Any]:
data = db.list_shorts_jobs(
status=status,
push_date=push_date,
channel_pk=channel_pk,
session_id=session_id,
room_id=room_id,
limit=limit,
offset=offset,
)
data["jobs"] = _enrich_shorts_jobs(list(data.get("jobs") or []))
return data
return await _db(_load)
@app.post("/api/shorts/jobs/{job_id}/retry")
@ -1354,8 +1438,9 @@ async def x_clips_job_retry(job_id: str) -> dict[str, Any]:
@app.get("/api/yt-long/status")
async def yt_long_status() -> dict[str, Any]:
return await asyncio.to_thread(yt_long_pipeline.status)
async def yt_long_status(light: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
fn = yt_long_pipeline.status_light if light else yt_long_pipeline.status
return await asyncio.to_thread(fn)
@app.post("/api/yt-long/start")
@ -1838,8 +1923,11 @@ def _enrich_tiktok_job(job: dict[str, Any] | None) -> dict[str, Any] | None:
@app.get("/api/tiktok/status")
async def tiktok_status() -> dict[str, Any]:
async def tiktok_status(light: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
st = await asyncio.to_thread(tiktok_pipeline.status)
if light:
st["light"] = True
return st
cfg = await _db(db.get_settings_map)
setup = tiktok_session.setup_checklist(cfg)
st["auth_mode"] = "cookie"
@ -2160,6 +2248,20 @@ async def get_settings() -> dict[str, Any]:
return _public_settings(cfg)
@app.get("/api/settings/notify-flags")
async def settings_notify_flags() -> dict[str, Any]:
"""Tiny payload for GlobalEventAlerts — no full settings map."""
cfg = await asyncio.to_thread(db.get_settings_map)
return {
"notify_on_live": cfg.get("notify_on_live"),
"notify_on_offline": cfg.get("notify_on_offline"),
"notify_on_risk": cfg.get("notify_on_risk"),
"notify_on_shorts_fail": cfg.get("notify_on_shorts_fail"),
"notify_on_shorts_ok": cfg.get("notify_on_shorts_ok"),
"notify_on_shorts_quota": cfg.get("notify_on_shorts_quota"),
}
@app.get("/api/dashboard/jobs")
async def dashboard_jobs(
limit: int = Query(60, ge=1, le=200),
@ -2340,41 +2442,66 @@ async def rooms_create(body: RoomCreate) -> dict[str, Any]:
@app.post("/api/rooms/batch")
async def rooms_batch_create(body: RoomBatchCreate) -> dict[str, Any]:
from .douyin_ingest import ensure_in_live_pool, parse_douyin_line
raw_lines = (body.urls or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
lines: list[str] = []
items: list[dict[str, 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:
parsed = parse_douyin_line(text)
if not parsed.get("url"):
continue
seen.add(token)
lines.append(token)
rid = str(parsed.get("room_id") or "")
key = f"rid:{rid}" if rid else f"url:{parsed['url']}"
if key in seen:
continue
seen.add(key)
items.append(parsed)
if not lines:
if not items:
raise HTTPException(400, "没有有效的直播间 URL / 房间号")
created: list[dict[str, Any]] = []
skipped: list[dict[str, str]] = []
for item in lines:
updated = 0
for item in items:
note = str(item.get("title") or "").strip() or str(body.note or "")
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
result = ensure_in_live_pool(
item["url"],
note=note,
title=note,
enabled=body.enabled,
tags=body.tags,
)
if result.get("skipped_blacklist"):
skipped.append({"url": item["url"], "reason": str(result.get("reason") or "黑名单")})
continue
if not result.get("ok"):
skipped.append({"url": item["url"], "reason": str(result.get("reason") or "跳过")})
continue
room = result.get("room") or {}
if result.get("created"):
created.append(room)
try:
await pb_sync.sync_room(room)
except Exception:
pass
else:
updated += 1
except ValueError as exc:
skipped.append({"url": item, "reason": str(exc)})
skipped.append({"url": item["url"], "reason": str(exc)})
return {
"created": created,
"skipped": skipped,
"created_count": len(created),
"updated_count": updated,
"skipped_count": len(skipped),
"total_input": len(lines),
"total_input": len(items),
}
@ -2677,12 +2804,12 @@ async def youtube_health() -> dict[str, Any]:
@app.get("/api/youtube/manage/channels")
async def youtube_manage_channels() -> dict[str, Any]:
return {"channels": youtube_manage.list_managed_channels()}
return {"channels": await _db(youtube_manage.list_managed_channels)}
@app.get("/api/youtube/manage/profiles")
async def youtube_manage_profiles() -> dict[str, Any]:
return {"profiles": youtube_manage.list_yt_profile_caches()}
return {"profiles": await _db(youtube_manage.list_yt_profile_caches)}
@app.post("/api/youtube/manage/profiles/refresh")
@ -2769,20 +2896,26 @@ async def youtube_manage_playlists(channel_pk: str) -> dict[str, Any]:
@app.get("/api/youtube/assign/groups")
async def yt_assign_list_groups() -> dict[str, Any]:
try:
yt_assign_db.ensure_default_assign_data()
except Exception:
pass
return {"groups": yt_assign_db.list_groups(include_urls=True)}
def _load() -> list[dict[str, Any]]:
try:
yt_assign_db.ensure_default_assign_data()
except Exception:
pass
return yt_assign_db.list_groups(include_urls=True)
return {"groups": await _db(_load)}
@app.get("/api/youtube/assign/schedule")
async def yt_assign_schedule() -> dict[str, Any]:
try:
yt_assign_db.ensure_default_assign_data()
except Exception:
pass
return yt_assign_db.build_rotation_schedule(include_urls=True)
def _load() -> dict[str, Any]:
try:
yt_assign_db.ensure_default_assign_data()
except Exception:
pass
return yt_assign_db.build_rotation_schedule(include_urls=True)
return await _db(_load)
@app.post("/api/youtube/assign/groups")
@ -2796,7 +2929,8 @@ async def yt_assign_create_group(body: YtAssignGroupCreate) -> dict[str, Any]:
note=body.note,
enabled=body.enabled,
)
return {"ok": True, "group": g}
neko_sync = g.pop("neko_sync", None) if isinstance(g, dict) else None
return {"ok": True, "group": g, "neko_sync": neko_sync}
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
@ -2864,6 +2998,37 @@ async def youtube_relay_group_restart(group_id: str) -> dict[str, Any]:
raise HTTPException(400, str(exc)) from exc
@app.post("/api/youtube/relay/quality-preset")
async def youtube_relay_quality_preset(body: dict[str, Any]) -> dict[str, Any]:
preset = str(body.get("preset") or body.get("quality_preset") or "").strip()
try:
return await youtube_relay_pipeline.apply_quality_preset(preset)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
@app.post("/api/youtube/relay/exclusive-live")
async def youtube_relay_exclusive_live(body: dict[str, Any]) -> dict[str, Any]:
"""Toggle single-channel exclusive live (pause other FFmpeg + Neko while one pushes)."""
enabled = body.get("enabled")
if enabled is None:
enabled = body.get("on")
if enabled is None:
raise HTTPException(400, "缺少 enabled")
return await youtube_relay_pipeline.set_exclusive_live(bool(enabled))
@app.post("/api/youtube/relay/time-slot-mode")
async def youtube_relay_time_slot_mode(body: dict[str, Any]) -> dict[str, Any]:
"""Toggle 时间段模式: keyed channels share 24h; source = live Douyin rooms; exclusive Neko/FFmpeg."""
enabled = body.get("enabled")
if enabled is None:
enabled = body.get("on")
if enabled is None:
raise HTTPException(400, "缺少 enabled")
return await youtube_relay_pipeline.set_time_slot_mode(bool(enabled))
@app.get("/api/youtube/relay/process_monitor")
async def youtube_relay_process_monitor() -> dict[str, Any]:
"""PM2-compatible process monitor snapshot (cloud pipeline)."""
@ -2926,12 +3091,20 @@ async def youtube_relay_session_detail(session_id: int) -> dict[str, Any]:
@app.get("/api/youtube/neko/status")
async def youtube_neko_status() -> dict[str, Any]:
"""Read-only Neko status — no compose/nginx sync (avoids 12s poll thrash)."""
groups = await asyncio.to_thread(yt_assign_db.list_groups, False)
ids = [int(g.get("neko_instance_id") or 0) for g in groups]
desired = max(ids) if ids else 0
return await asyncio.to_thread(youtube_neko.status_summary, desired=desired)
@app.post("/api/youtube/studio/ingest")
@app.post("/hub/youtube/live/ingest")
async def youtube_studio_ingest(body: dict[str, Any] | None = None) -> dict[str, Any]:
"""Ingest from Neko live-ops Chrome extension (sh2-compatible)."""
return await asyncio.to_thread(youtube_neko.ingest_studio_telemetry, body or {})
@app.post("/api/youtube/neko/instances/{instance_id}/{action}")
async def youtube_neko_instance_action(instance_id: int, action: str) -> dict[str, Any]:
try:
@ -2966,11 +3139,13 @@ async def youtube_assign_group_neko(group_id: str, body: dict[str, Any] | None =
neko_result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, action)
except (ValueError, RuntimeError) as exc:
raise HTTPException(400, str(exc)) from exc
elif g.get("neko_enabled"):
elif "enabled" in body:
# Enable → start; disable → stop. Surface failures to UI.
act = "start" if g.get("neko_enabled") else "stop"
try:
neko_result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, "start")
except RuntimeError:
neko_result = None
neko_result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, act)
except RuntimeError as exc:
raise HTTPException(400, str(exc)) from exc
inst = await asyncio.to_thread(youtube_neko._container_state, instance_id)
return {"ok": True, "group": g, "neko": neko_result or inst}
@ -3382,6 +3557,14 @@ async def notify_test() -> dict[str, Any]:
return {"ok": True, "webhook": url or None, "ntfy_topic": NTFY_TOPIC if ntfy_ok else None}
@app.get("/api/ops/host-metrics")
async def ops_host_metrics() -> dict[str, Any]:
"""Real-time CPU / memory for header resource bars."""
from . import host_metrics
return await asyncio.to_thread(host_metrics.snapshot)
@app.get("/api/ops")
async def ops_snapshot() -> dict[str, Any]:
"""Umami / ntfy / DNS / systemd health snapshot for the ops control page."""
@ -3745,15 +3928,7 @@ async def sessions_cover(session_id: str):
"Cache-Control": "public, max-age=86400, immutable",
}
if cp.startswith("http://") or cp.startswith("https://"):
# Fast path: redirect to public object URL (s3/feiniu) instead of proxying bytes.
public_bases = [
str(settings.s3_public_base or "").rstrip("/"),
"https://s3.nomadro.com",
"https://feiniu.nomadro.com",
]
if any(cp.startswith(b) for b in public_bases if b):
return RedirectResponse(url=cp, status_code=302, headers=cache_headers)
# Private bucket fallback: signed fetch via S3 API, then stream once.
# Stream via S3 API when URL points at our bucket (dy.nomadro.live proxies private S3).
try:
from . import s3_storage
@ -3765,6 +3940,13 @@ async def sessions_cover(session_id: str):
return StreamingResponse(iter([body]), media_type="image/jpeg", headers=cache_headers)
except Exception:
pass
# Redirect only for known public CDNs (not same-origin nginx → private bucket).
public_bases = [
"https://s3.nomadro.com",
"https://feiniu.nomadro.com",
]
if any(cp.startswith(b) for b in public_bases if b):
return RedirectResponse(url=cp, status_code=302, headers=cache_headers)
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
resp = await client.get(cp)

View File

@ -8,7 +8,7 @@ from typing import Any, Optional
from . import db
from . import pb_sync
from .config import settings
from .cover import ensure_session_cover
from .cover import ensure_session_cover, ensure_room_avatar
from .douyin import RiskControlError, check_room
from .notify import send_webhook
from .timeutil import beijing_hour
@ -232,6 +232,14 @@ class MonitorService:
active_sid = fresh.get("active_session_id") or ""
anchor = result.get("anchor_name") or fresh.get("last_anchor") or ""
# Always try to mirror owner avatar → S3 (list thumbs / overview face).
avatar_img = str(result.get("avatar_image") or "").strip()
web_rid = str(result.get("room_id") or room.get("room_id") or "").strip()
if avatar_img and web_rid and not web_rid.startswith(("yt:", "shorts:")):
need_avatar = not str(fresh.get("avatar_url") or "").strip()
if need_avatar:
asyncio.create_task(ensure_room_avatar(web_rid, avatar_img))
if is_live:
if prev != "live" or not active_sid:
session = db.start_session(

View File

@ -9,6 +9,7 @@ import time
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
SERVER_IP = "107.173.30.245"
@ -16,6 +17,10 @@ NTFY_ENV = Path("/etc/nomadro/ntfy.env")
UMAMI_ENV = Path("/etc/nomadro/umami.env")
UMAMI_SITES = Path("/etc/nomadro/umami-sites.env")
_snapshot_cache: dict[str, Any] | None = None
_snapshot_cache_at = 0.0
_SNAPSHOT_TTL_SEC = 20.0
# Public web surfaces managed on this host
SITES: list[dict[str, str]] = [
{
@ -167,7 +172,7 @@ def ntfy_config() -> dict[str, Any]:
return {
"configured": bool(token),
"base_url": env.get("NTFY_BASE_URL", "https://ntfy.nomadro.com"),
"topic": env.get("NTFY_TOPIC", "server-alerts"),
"topic": env.get("NTFY_TOPIC", "dylive"),
"user": env.get("NTFY_USER", ""),
"has_token": bool(token),
# never expose full token to UI — only suffix
@ -398,18 +403,15 @@ def send_ntfy(title: str, message: str, priority: str = "default", tags: str = "
raise ValueError("ntfy 未配置:缺少 /etc/nomadro/ntfy.env 中的 NTFY_TOKEN")
base = cfg["base_url"].rstrip("/")
use_topic = topic or cfg["topic"]
url = f"{base}/{use_topic}"
# Title/tags may contain UTF-8; query params avoid latin-1 header encoding errors.
qs = urlencode({"title": title, "priority": priority, "tags": tags})
url = f"{base}/{use_topic}?{qs}"
body = message.encode("utf-8")
req = Request(
url,
data=body,
method="POST",
headers={
"Authorization": f"Bearer {token}",
"Title": title,
"Priority": priority,
"Tags": tags,
},
headers={"Authorization": f"Bearer {token}"},
)
try:
with urlopen(req, timeout=15) as resp:
@ -438,47 +440,78 @@ def run_healthcheck_script() -> dict[str, Any]:
}
def snapshot() -> dict[str, Any]:
def snapshot(*, force: bool = False) -> dict[str, Any]:
global _snapshot_cache, _snapshot_cache_at
now = time.time()
if (
not force
and _snapshot_cache is not None
and (now - _snapshot_cache_at) < _SNAPSHOT_TTL_SEC
):
return dict(_snapshot_cache)
from concurrent.futures import ThreadPoolExecutor, as_completed
umami = umami_config()
ntfy = ntfy_config()
site_rows = []
for s in SITES:
def _site_row(s: dict[str, str]) -> dict[str, Any]:
ips = _resolve_a(s["domain"])
dns_ok = SERVER_IP in ips
probe = _http_probe(s["health_url"]) if s.get("health_url") else {"ok": None, "status": None, "ms": None}
wid = umami["sites"].get(s["umami_key"], "") if s.get("umami_key") else ""
site_rows.append(
{
**s,
"ips": ips,
"dns_ok": dns_ok,
"expected_ip": SERVER_IP,
"umami_website_id": wid,
"health": probe,
}
)
return {
**s,
"ips": ips,
"dns_ok": dns_ok,
"expected_ip": SERVER_IP,
"umami_website_id": wid,
"health": probe,
}
site_rows: list[dict[str, Any]] = []
services: list[dict[str, Any]] = []
extra: dict[str, Any] = {}
with ThreadPoolExecutor(max_workers=12) as pool:
site_futs = {pool.submit(_site_row, s): i for i, s in enumerate(SITES)}
svc_futs = {pool.submit(_systemctl_active, u): i for i, (u, _label) in enumerate(SERVICES)}
fut_umami = pool.submit(_http_probe, "https://umami.nomadro.com/api/heartbeat")
fut_ntfy = pool.submit(_http_probe, "https://ntfy.nomadro.com/v1/health")
fut_netdata = pool.submit(_http_probe, "http://127.0.0.1:19999/netdata/api/v1/info")
site_rows = [None] * len(SITES) # type: ignore[list-item]
for fut in as_completed(site_futs):
site_rows[site_futs[fut]] = fut.result()
services = [None] * len(SERVICES) # type: ignore[list-item]
for fut in as_completed(svc_futs):
services[svc_futs[fut]] = fut.result()
extra["umami_hb"] = fut_umami.result()
extra["ntfy_h"] = fut_ntfy.result()
extra["netdata"] = fut_netdata.result()
services = [_systemctl_active(u) for u, _label in SERVICES]
for svc, (_u, label) in zip(services, SERVICES):
svc["label"] = label
if isinstance(svc, dict):
svc["label"] = label
return {
"generated_at": time.time(),
out = {
"generated_at": now,
"server_ip": SERVER_IP,
"umami": {
**umami,
"heartbeat": _http_probe("https://umami.nomadro.com/api/heartbeat"),
"heartbeat": extra.get("umami_hb"),
},
"ntfy": {
**ntfy,
"health": _http_probe("https://ntfy.nomadro.com/v1/health"),
"health": extra.get("ntfy_h"),
},
"sites": site_rows,
"services": services,
"netdata": extra.get("netdata"),
"paths": {
"ntfy_env": str(NTFY_ENV),
"umami_env": str(UMAMI_ENV),
"umami_sites": str(UMAMI_SITES),
"netdata_url": "/netdata/",
"healthcheck": "/usr/local/bin/nomadro-healthcheck",
"notify": "/usr/local/bin/notify-ntfy",
},
@ -488,4 +521,8 @@ def snapshot() -> dict[str, Any]:
"has_ntfy_env": NTFY_ENV.is_file(),
"has_umami_env": UMAMI_ENV.is_file(),
},
"cache_ttl_sec": _SNAPSHOT_TTL_SEC,
}
_snapshot_cache = out
_snapshot_cache_at = time.time()
return dict(out)

View File

@ -123,3 +123,13 @@ def delete_object(key: str) -> bool:
def upload_cover(session_id: str, local_path: str | Path) -> str:
key = f"covers/{session_id}.jpg"
return upload_file(local_path, key, content_type="image/jpeg")
def upload_room_avatar(room_id: str, local_path: str | Path) -> str:
"""Stable per-room avatar object (频道头像), not session stream frame."""
rid = str(room_id or "").strip()
if not rid:
return ""
safe = "".join(ch if ch.isalnum() or ch in "-_" else "_" for ch in rid)[:80]
key = f"covers/avatars/{safe}.jpg"
return upload_file(local_path, key, content_type="image/jpeg")

View File

@ -34,6 +34,8 @@ _PUBLIC_API_EXACT = {
"/api/x2/ingest",
"/api/x2/extension/poll",
"/api/x2/extension/ws",
"/api/youtube/studio/ingest",
"/hub/youtube/live/ingest",
}
@ -194,6 +196,11 @@ class SessionAuthMiddleware:
request = Request(scope, receive=receive)
path = request.url.path
method = str(scope.get("method") or "GET").upper()
# Live session thumbnails — allow <img> without cookie (uuid is unguessable).
if method in {"GET", "HEAD"} and path.startswith("/api/sessions/") and path.endswith("/cover"):
await self.app(scope, receive, send)
return
if path.startswith("/covers/"):
if session_user_from_request(request):
await self.app(scope, receive, send)

View File

@ -170,10 +170,10 @@ async def record_clip(
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{job_id}.mp4"
# Scale to 1080x1920 Shorts canvas (crop center).
# 720x1280 Shorts canvas — enough for YT; 1080p encode burns 4c VPS CPU.
vf = (
"scale=1080:1920:force_original_aspect_ratio=increase,"
"crop=1080:1920,setsar=1"
"scale=720:1280:force_original_aspect_ratio=increase,"
"crop=720:1280,setsar=1"
)
last_err = ""
@ -227,14 +227,16 @@ async def record_clip(
vf,
"-c:v",
"libx264",
"-threads",
"2",
"-preset",
"veryfast",
"ultrafast",
"-crf",
"23",
"26",
"-c:a",
"aac",
"-b:a",
"128k",
"96k",
"-movflags",
"+faststart",
"-avoid_negative_ts",

View File

@ -17,9 +17,10 @@ import httpx
from . import db
# Required for upload / YPP — used by missing_required_scopes / oauth_ok.
YOUTUBE_SCOPES = " ".join(
[
# Upload + identity + Studio monetize (force-ssl).
# Upload + Studio monetize (force-ssl).
# Avoid youtubepartner / yt-analytics — they often break
# unverified OAuth consent (Google 500 / access_denied).
"https://www.googleapis.com/auth/youtube.upload",
@ -27,12 +28,14 @@ YOUTUBE_SCOPES = " ".join(
"https://www.googleapis.com/auth/youtube.force-ssl",
]
)
# Requested on authorize so we can show Gmail on A/B/C/D; not required for oauth_ok.
IDENTITY_SCOPES = "openid email profile"
DEFAULT_OAUTH_PROFILES: list[dict[str, str]] = [
{"id": "A", "label": "谷歌账号 A", "client_id": "", "client_secret": ""},
{"id": "B", "label": "谷歌账号 B", "client_id": "", "client_secret": ""},
{"id": "C", "label": "谷歌账号 C", "client_id": "", "client_secret": ""},
{"id": "D", "label": "谷歌账号 D", "client_id": "", "client_secret": ""},
{"id": "A", "label": "谷歌账号 A", "client_id": "", "client_secret": "", "email": ""},
{"id": "B", "label": "谷歌账号 B", "client_id": "", "client_secret": "", "email": ""},
{"id": "C", "label": "谷歌账号 C", "client_id": "", "client_secret": "", "email": ""},
{"id": "D", "label": "谷歌账号 D", "client_id": "", "client_secret": "", "email": ""},
]
# state -> (channel_pk, expires_at, client_id, client_secret, return_to?)
@ -65,6 +68,7 @@ def normalize_oauth_profiles(raw: Any) -> list[dict[str, str]]:
"label": str(item.get("label") or f"谷歌账号 {pid}").strip() or f"谷歌账号 {pid}",
"client_id": str(item.get("client_id") or "").strip(),
"client_secret": str(item.get("client_secret") or "").strip(),
"email": str(item.get("email") or "").strip(),
}
out: list[dict[str, str]] = []
for d in DEFAULT_OAUTH_PROFILES:
@ -102,6 +106,7 @@ def list_oauth_profiles(cfg: dict[str, Any] | None = None, *, public: bool = Fal
{
"id": row["id"],
"label": row["label"],
"email": str(row.get("email") or "").strip(),
"client_id": row.get("client_id") or "",
"has_client_secret": bool(str(secret).strip()),
"client_secret": _mask_secret(str(secret)),
@ -142,17 +147,64 @@ def merge_oauth_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | Non
client_id = str(old.get("client_id") or "").strip()
if not client_id and pid == "A":
client_id = g_id
email = str(row.get("email") or "").strip() or str(old.get("email") or "").strip()
out.append(
{
"id": pid,
"label": str(row.get("label") or old.get("label") or f"谷歌账号 {pid}").strip(),
"client_id": client_id,
"client_secret": secret,
"email": email,
}
)
return out
def set_oauth_profile_email(profile_id: str, email: str) -> None:
"""Persist Gmail onto shorts_oauth_profiles[profile_id]."""
pid = str(profile_id or "").strip().upper()
mail = str(email or "").strip()
if not pid or not mail:
return
cfg = _cfg()
rows = normalize_oauth_profiles(cfg.get("shorts_oauth_profiles"))
changed = False
out: list[dict[str, str]] = []
for row in rows:
r = dict(row)
if r.get("id") == pid:
if str(r.get("email") or "").strip() != mail:
r["email"] = mail
changed = True
out.append(r)
if changed:
db.update_settings_map({"shorts_oauth_profiles": out})
async def fetch_google_account_email(access_token: str) -> str:
"""Best-effort Gmail from OpenID userinfo (needs email scope)."""
token = str(access_token or "").strip()
if not token:
return ""
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
resp = await client.get(
"https://openidconnect.googleapis.com/v1/userinfo",
headers={"Authorization": f"Bearer {token}"},
)
if resp.status_code >= 400:
resp = await client.get(
"https://www.googleapis.com/oauth2/v2/userinfo",
headers={"Authorization": f"Bearer {token}"},
)
data = resp.json() if resp.content else {}
if resp.status_code >= 400:
return ""
return str(data.get("email") or "").strip()
except Exception:
return ""
def oauth_client_configured() -> bool:
cfg = _cfg()
if str(cfg.get("shorts_oauth_client_id") or "").strip() and str(cfg.get("shorts_oauth_client_secret") or "").strip():
@ -164,25 +216,22 @@ def oauth_client_configured() -> bool:
def resolve_redirect_uri(request_base: str = "") -> str:
cfg = _cfg()
from urllib.parse import urlparse
"""OAuth callback must match the origin that started the flow.
Priority: request Host (dy.nomadro.live / …) → DY_PUBLIC_BASE_URL → settings fallback.
Never pin a stale hardcoded domain.
"""
from .config import settings as app_settings
req = str(request_base or "").strip().rstrip("/")
pub = str(getattr(app_settings, "public_base_url", "") or "").strip().rstrip("/")
base = pub or (request_base or "").rstrip("/")
derived = f"{base}/api/shorts/oauth/callback" if base else ""
custom = str(cfg.get("shorts_oauth_redirect_uri") or "").strip().rstrip("/")
if custom and pub:
if urlparse(custom).netloc == urlparse(pub).netloc:
return custom
return derived or custom
base = req or pub
if base:
return f"{base}/api/shorts/oauth/callback"
custom = str(_cfg().get("shorts_oauth_redirect_uri") or "").strip().rstrip("/")
if custom:
return custom
if derived:
return derived
return "https://dylive.nomadro.com/api/shorts/oauth/callback"
raise ValueError("无法推导 OAuth 回调地址:请用站点域名打开,或设置 DY_PUBLIC_BASE_URL")
def resolve_oauth_client(
@ -254,7 +303,7 @@ def build_authorize_url(*, channel_pk: str, request_base: str = "", return_to: s
"client_id": client_id,
"redirect_uri": resolve_redirect_uri(request_base),
"response_type": "code",
"scope": YOUTUBE_SCOPES,
"scope": authorize_scopes(),
"access_type": "offline",
"prompt": "consent select_account",
"include_granted_scopes": "true",
@ -264,9 +313,15 @@ def build_authorize_url(*, channel_pk: str, request_base: str = "", return_to: s
def requested_scopes() -> list[str]:
"""YouTube scopes required for oauth_ok (identity scopes are optional extras)."""
return [s for s in YOUTUBE_SCOPES.split() if s]
def authorize_scopes() -> str:
"""Scopes for Google consent. YouTube only — brand accounts break with openid/email."""
return " ".join(s for s in YOUTUBE_SCOPES.split() if s)
FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
@ -310,22 +365,14 @@ async def revoke_refresh_token(*, refresh_token: str, client_id: str = "", clien
async def prepare_reauthorize(channel_pk: str) -> None:
"""Drop stale refresh_token before OAuth — fixes silent scope downgrade on re-auth."""
"""Soft-mark OAuth start on the clicked card — never revoke sibling brands."""
ch = db.get_shorts_channel(channel_pk) or {}
creds = channel_oauth_creds(ch)
rt = str(creds.get("refresh_token") or "").strip()
if rt:
await revoke_refresh_token(
refresh_token=rt,
client_id=str(creds.get("client_id") or ""),
client_secret=str(creds.get("client_secret") or ""),
)
if not ch:
return
db.update_shorts_channel(
channel_pk,
refresh_token="",
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error="重授权中:已撤销旧 token,完成 Google 授权后将写入新权限",
oauth_error="授权中:完成 Google 后凭证写入本卡片",
)
@ -333,6 +380,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
packed = _oauth_states.pop(state, None)
if not packed:
raise ValueError("授权 state 无效或已过期,请重新点击授权")
# Always bind OAuth result to the card the operator clicked.
channel_pk = packed[0]
exp = packed[1]
return_to = str(packed[4]).strip() if len(packed) >= 5 else ""
@ -350,6 +398,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
client_secret = str(client.get("client_secret") or "")
source_meta = resolve_oauth_client(channel, cfg)
source = str(source_meta.get("source") or "none")
profile_id = str(source_meta.get("profile_id") or channel.get("oauth_profile_id") or "").strip().upper()
if not client_id or not client_secret:
raise ValueError("缺少 OAuth Client 配置")
redirect_uri = resolve_redirect_uri(request_base)
@ -369,7 +418,6 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
raise ValueError(f"换取 token 失败: {token.get('error_description') or token or token_resp.text}")
access = str(token["access_token"])
refresh = str(token.get("refresh_token") or "").strip()
had_old = bool(str(channel.get("refresh_token") or "").strip())
granted = await token_scopes(access)
missing = missing_required_scopes(granted)
if missing:
@ -378,13 +426,6 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
f"授权权限不完整(缺 {scope_hint})。"
f"请再点「重授权」;若仍失败,到 Google 账号 → 第三方应用访问权限,移除本应用后再授权。"
)
if not refresh:
if had_old:
raise ValueError(
"Google 未下发新 refresh_token,旧 token 无法升级 YPP 所需权限。"
"请再点一次「重授权」(系统已自动撤销旧 token)。"
)
raise ValueError("未拿到 refresh_token,请在 Google 账号权限里撤销本应用后重试")
ch_resp = await client.get(
"https://www.googleapis.com/youtube/v3/channels",
@ -392,6 +433,14 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
headers={"Authorization": f"Bearer {access}"},
)
ch_data = ch_resp.json() if ch_resp.content else {}
if ch_resp.status_code >= 400:
err = (ch_data.get("error") or {}).get("message") or ch_resp.text
if "has not been used in project" in str(err) or "youtube.googleapis.com" in str(err):
raise ValueError(
f"OAuth 配置档 {profile_id or '?'} 的 Google 项目未启用 YouTube Data API v3。"
"请到 Google Cloud Console → API 和服务 → 启用「YouTube Data API v3」后,再点「重授权」。"
)
raise ValueError(f"读取 YouTube 频道失败: {err}")
items = ch_data.get("items") or []
yt_id = ""
yt_title = ""
@ -402,26 +451,15 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
yt_title = str(sn.get("title") or "")
yt_handle = str(sn.get("customUrl") or "").strip()
# Re-auth safety: brand-account picker names often differ from YouTube titles.
# If this card already has a known channel id, reject mismatches without writing.
expected_id = str(channel.get("youtube_channel_id") or "").strip()
if expected_id and yt_id and yt_id != expected_id:
need_title = str(channel.get("name") or "").strip() or "本卡频道"
need_handle = ""
try:
from . import youtube_manage as ytm
google_email = await fetch_google_account_email(access)
cached = ytm.get_yt_profile_cache(channel_pk) or {}
need_title = str(cached.get("title") or need_title).strip() or need_title
need_handle = str(cached.get("custom_url") or "").strip()
except Exception:
pass
got = f"「{yt_title or yt_id}」" + (f" {yt_handle}" if yt_handle else "")
need = f"「{need_title}」" + (f" {need_handle}" if need_handle else "")
raise ValueError(
f"点错品牌账号了:这次选中的是 {got},本卡需要 {need}。"
f"未写入授权,请再点「重授权」换列表里下一个试。"
)
# Clicked card wins: accept whatever brand Google returned; never reject / never rewrite siblings.
had_old = bool(str(channel.get("refresh_token") or "").strip())
if not refresh:
if had_old:
refresh = str(channel.get("refresh_token") or "").strip()
else:
raise ValueError("未拿到 refresh_token,请在 Google 账号权限里撤销本应用后重试")
patch: dict[str, Any] = {
"client_id": client_id,
@ -430,9 +468,13 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
}
if yt_id:
patch["youtube_channel_id"] = yt_id
name = str(channel.get("name") or "").strip()
if yt_title and (not name or name.startswith("Shorts") or name == "未命名频道"):
if google_email:
patch["oauth_email"] = google_email
# Refresh display name/handle from Google — brand label may differ from old card title.
if yt_title:
patch["name"] = yt_title
if profile_id and not str(channel.get("oauth_profile_id") or "").strip():
patch["oauth_profile_id"] = profile_id
updated = db.update_shorts_channel(
channel_pk,
**patch,
@ -440,6 +482,11 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
oauth_checked_at=time.time(),
oauth_error="",
)
if google_email and profile_id:
try:
set_oauth_profile_email(profile_id, google_email)
except Exception:
pass
try:
from . import yt_long_db
@ -452,17 +499,19 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
await ytm.fetch_channel_profile(channel_pk)
await refresh_ypp_for_shorts_channel(channel_pk)
except Exception:
pass
except Exception as exc:
err = str(exc).strip() or "拉取频道资料失败"
db.update_shorts_channel(channel_pk, oauth_error=err)
return {
"ok": True,
"channel": updated,
"youtube_channel_id": yt_id,
"youtube_title": yt_title,
"youtube_title": yt_title or str((updated or {}).get("name") or ""),
"youtube_handle": yt_handle,
"oauth_email": google_email,
"oauth_scopes_ok": True,
"oauth_client_source": source,
"oauth_profile_id": source_meta.get("profile_id") or "",
"oauth_profile_id": profile_id,
"return_to": return_to,
}
@ -505,8 +554,18 @@ async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | Non
err = "OAuth 权限不足(缺 force-ssl),请点「重授权」升级 YPP 获利权限"
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)
return {"ok": False, "error": err, "channel_id": cid, "missing_scopes": missing}
db.update_shorts_channel(cid, oauth_ok=1, oauth_checked_at=now, oauth_error="")
return {"ok": True, "channel_id": cid}
google_email = await fetch_google_account_email(str(access))
patch: dict[str, Any] = {"oauth_ok": 1, "oauth_checked_at": now, "oauth_error": ""}
if google_email:
patch["oauth_email"] = google_email
pid = str(channel.get("oauth_profile_id") or "").strip().upper()
if pid:
try:
set_oauth_profile_email(pid, google_email)
except Exception:
pass
db.update_shorts_channel(cid, **patch)
return {"ok": True, "channel_id": cid, "oauth_email": google_email}
except Exception as exc:
err = str(exc)[:240]
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)

View File

@ -472,6 +472,12 @@ class ShortsPipeline:
return max(1, int(cfg.get("shorts_max_concurrent") or 1))
def status(self) -> dict[str, Any]:
now = time.time()
cached = getattr(self, "_status_cache", None)
cache_at = float(getattr(self, "_status_cache_at", 0) or 0)
if cached is not None and (now - cache_at) < 2.0:
return cached
cfg = db.get_settings_map()
try:
stats = db.shorts_stats()
@ -519,16 +525,32 @@ class ShortsPipeline:
)
except Exception:
pass
try:
clear_all_upload_self_blocks(cfg)
clear_stale_quota_errors_for_open_profiles(cfg)
except Exception:
pass
# Mutations belong in the worker loop / start(), not on every UI poll GET.
last_error = self.last_error
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A")
yt_by_profile = quota_budgets_by_profile(cfg)
exhausted = [r for r in yt_by_profile if r.get("exhausted_hint")]
return {
try:
from . import douyin_live
live_count = int(douyin_live.build_live_map().get("live_count") or 0)
except Exception:
live_count = 0
live_rooms = []
try:
live_rooms = [
{
"room_id": r.get("room_id"),
"anchor": r.get("last_anchor") or r.get("last_title") or r.get("room_id"),
"session_id": r.get("active_session_id"),
}
for r in db.list_live_douyin_rooms_for_shorts(limit=12)
]
if live_count <= 0:
live_count = len(live_rooms)
except Exception:
pass
payload = {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
"active_jobs": self._active_records + self._active_uploads,
@ -555,15 +577,8 @@ class ShortsPipeline:
"clip_sec": int(cfg.get("shorts_clip_sec") or 15),
"live_sample": bool(cfg.get("shorts_live_sample", True)),
"sample_any_live": bool(cfg.get("shorts_sample_any_live", True)),
"douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)),
"douyin_live_rooms": [
{
"room_id": r.get("room_id"),
"anchor": r.get("last_anchor") or r.get("last_title") or r.get("room_id"),
"session_id": r.get("active_session_id"),
}
for r in db.list_live_douyin_rooms_for_shorts(limit=12)
],
"douyin_live_count": live_count,
"douyin_live_rooms": live_rooms,
"upload_spread": bool(cfg.get("shorts_upload_spread", True)),
"upload_min_gap_sec": float(cfg.get("shorts_upload_min_gap_sec") or 720),
"channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or 2400),
@ -578,6 +593,87 @@ class ShortsPipeline:
"heatmap": heatmap,
"oauth_issues": oauth_issues,
}
self._status_cache = payload
self._status_cache_at = time.time()
return payload
def status_light(self) -> dict[str, Any]:
"""Poll-friendly counters without schedule board / heatmap / history."""
now = time.time()
cached = getattr(self, "_status_light_cache", None)
cache_at = float(getattr(self, "_status_light_cache_at", 0) or 0)
if cached is not None and (now - cache_at) < 1.5:
return cached
cfg = db.get_settings_map()
try:
stats = db.shorts_stats()
except Exception:
stats = {}
oauth_issues = []
try:
for ch in db.list_shorts_channels(enabled=True):
ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1)
err = str(ch.get("oauth_error") or "")
has_rt = bool(str(ch.get("refresh_token") or "").strip())
if has_rt and "重授权中" in err:
continue
if not has_rt or ok_flag == 0:
oauth_issues.append(
{
"id": ch.get("id"),
"name": ch.get("name"),
"oauth_ok": ok_flag,
"oauth_error": err or ("未授权" if not has_rt else ""),
"oauth_checked_at": ch.get("oauth_checked_at") or 0,
}
)
except Exception:
pass
try:
from . import douyin_live
live_count = int(douyin_live.build_live_map().get("live_count") or 0)
except Exception:
live_count = 0
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A")
yt_by_profile = quota_budgets_by_profile(cfg)
exhausted = [r for r in yt_by_profile if r.get("exhausted_hint")]
payload = {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
"active_jobs": self._active_records + self._active_uploads,
"active_records": self._active_records,
"active_uploads": self._active_uploads,
"enabled": bool(cfg.get("shorts_enabled")),
"processed": self.processed,
"sampled": self.sampled,
"quota_filled": self.quota_filled,
"auto_retried": self.auto_retried,
"quota_gap": db.shorts_total_quota_gap(),
"upload_quota_blocked": False,
"yt_quota_exhausted_hint": [str(r.get("id") or "") for r in exhausted],
"yt_quota_reset_at": max((float(r.get("reset_at") or 0) for r in exhausted), default=0),
"yt_upload_limit": yt_limit,
"yt_upload_used": yt_used,
"yt_upload_remaining": yt_remaining,
"yt_quota_by_profile": yt_by_profile,
"last_error": self.last_error,
"douyin_live_count": live_count,
"stats": stats,
"oauth_issues": oauth_issues,
"light": True,
}
# Reuse heavy analytics from recent full status if still warm.
full = getattr(self, "_status_cache", None)
full_at = float(getattr(self, "_status_cache_at", 0) or 0)
if isinstance(full, dict) and (now - full_at) < 60:
for key in ("board", "history", "failed_groups", "channel_perf", "heatmap", "douyin_live_rooms"):
if key in full:
payload[key] = full[key]
self._status_light_cache = payload
self._status_light_cache_at = time.time()
return payload
async def start(self) -> None:
if self._task and not self._task.done():
@ -727,7 +823,7 @@ class ShortsPipeline:
break
except Exception as exc:
self.last_error = str(exc)[:300]
await asyncio.sleep(3)
await asyncio.sleep(5)
async def _run_job(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
try:

View File

@ -34,24 +34,18 @@ def oauth_configured(cfg: dict[str, Any] | None = None) -> bool:
def resolve_redirect_uri(request_base: str = "") -> str:
cfg = _cfg()
from urllib.parse import urlparse
"""Callback follows the origin that started OAuth (request host first)."""
from .config import settings as app_settings
req = str(request_base or "").strip().rstrip("/")
pub = str(getattr(app_settings, "public_base_url", "") or "").strip().rstrip("/")
base = pub or (request_base or "").rstrip("/")
derived = f"{base}/api/tiktok/oauth/callback/" if base else ""
custom = str(cfg.get("tiktok_oauth_redirect_uri") or "").strip().rstrip("/")
base = req or pub
if base:
return f"{base}/api/tiktok/oauth/callback/"
custom = str(_cfg().get("tiktok_oauth_redirect_uri") or "").strip().rstrip("/")
if custom:
custom_uri = custom.rstrip("/") + "/"
if pub and urlparse(custom_uri).netloc != urlparse(pub).netloc:
return derived or custom_uri
return custom_uri
if derived:
return derived
return "https://dylive.nomadro.com/api/tiktok/oauth/callback/"
return custom.rstrip("/") + "/"
raise ValueError("无法推导 TikTok OAuth 回调地址:请用站点域名打开,或设置 DY_PUBLIC_BASE_URL")
def setup_checklist(cfg: dict[str, Any] | None = None) -> dict[str, Any]:

View File

@ -241,6 +241,12 @@ class TikTokPipeline:
self._upload_inflight: set[str] = set()
def status(self) -> dict[str, Any]:
now = time.time()
cached = getattr(self, "_status_cache", None)
cache_at = float(getattr(self, "_status_cache_at", 0) or 0)
if cached is not None and (now - cache_at) < 2.0:
return cached
cfg = db.get_settings_map()
try:
board = schedule_board(limit=30)
@ -257,7 +263,13 @@ class TikTokPipeline:
"oauth_error": ch.get("oauth_error") or "未授权",
}
)
return {
try:
from . import douyin_live
live_count = int(douyin_live.build_live_map().get("live_count") or 0)
except Exception:
live_count = 0
payload = {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
"enabled": bool(cfg.get("tiktok_enabled")),
@ -266,11 +278,14 @@ class TikTokPipeline:
"quota_gap": tiktok_db.tiktok_total_quota_gap(),
"last_error": self.last_error,
"clip_sec": max(60, min(90, int(cfg.get("tiktok_clip_sec") or 75))),
"douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)),
"douyin_live_count": live_count,
"board": board,
"oauth_issues": oauth_issues,
"stats": tiktok_db.tiktok_stats(),
}
self._status_cache = payload
self._status_cache_at = time.time()
return payload
async def start(self) -> None:
if self._task and not self._task.done():
@ -410,8 +425,7 @@ class TikTokPipeline:
break
self._active_uploads += 1
asyncio.create_task(self._run_upload(job))
# 1 分钟成片时并发 1 会把队列拖很长,后面房间容易下播;最多 2 路并行录制
max_rec = max(1, min(2, int(cfg.get("tiktok_max_concurrent") or 1) + 1))
max_rec = max(1, int(cfg.get("tiktok_max_concurrent") or 1))
while self._active_records < max_rec:
job = tiktok_db.claim_pending_tiktok_record()
if not job:
@ -420,7 +434,7 @@ class TikTokPipeline:
asyncio.create_task(self._run_record(job))
except Exception as exc:
self.last_error = str(exc)[:240]
await asyncio.sleep(3)
await asyncio.sleep(5)
async def _run_upload(self, job: dict[str, Any], *, probe: bool = False) -> None:
jid = str(job.get("id") or "")

View File

@ -428,7 +428,7 @@ class XClipsPipeline:
asyncio.create_task(self._run_post(job))
except Exception as exc:
self.last_error = str(exc)[:240]
await asyncio.sleep(2.5)
await asyncio.sleep(5)
async def _run_record(self, job: dict[str, Any]) -> None:
try:

View File

@ -245,8 +245,13 @@ async def build_live_map(*, force: bool = False) -> dict[str, Any]:
async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
global _LAST_OAUTH_AT
groups = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or [])
shorts = db.list_shorts_channels()
def _load_db_targets() -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
groups = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or [])
shorts = db.list_shorts_channels()
return groups, shorts
groups, shorts = await asyncio.to_thread(_load_db_targets)
targets: list[dict[str, Any]] = []
url_to_refs: dict[str, list[tuple[str, dict[str, Any]]]] = {}

View File

@ -20,7 +20,7 @@ log = logging.getLogger("youtube_manage")
_refresh_profiles_lock: Optional[Any] = None
_refresh_profiles_running = False
_S3_PUBLIC_HOSTS = ("s3.nomadro.com", "feiniu.nomadro.com")
_S3_PUBLIC_HOSTS = ("s3.nomadro.com", "feiniu.nomadro.com", "dy.nomadro.live")
def _get_refresh_lock():
@ -30,6 +30,27 @@ def _get_refresh_lock():
return _refresh_profiles_lock
def _is_s3_public_url(url: str) -> bool:
try:
host = (urlparse(str(url or "")).hostname or "").lower()
except Exception:
return False
if not host:
return False
hosts = set(_S3_PUBLIC_HOSTS)
try:
from .config import settings
base = str(settings.s3_public_base or "").strip()
if base:
h = (urlparse(base).hostname or "").lower()
if h:
hosts.add(h)
except Exception:
pass
return any(host == h or host.endswith("." + h) for h in hosts)
async def _access_for_channel(channel_pk: str) -> tuple[str, dict[str, Any]]:
ch = db.get_shorts_channel(channel_pk)
if not ch:
@ -150,14 +171,6 @@ def list_managed_channels() -> list[dict[str, Any]]:
return out
def _is_s3_public_url(url: str) -> bool:
try:
host = (urlparse(str(url or "")).hostname or "").lower()
except Exception:
return False
return any(host == h or host.endswith("." + h) for h in _S3_PUBLIC_HOSTS)
async def _mirror_avatar_to_s3(channel_pk: str, cdn_url: str) -> str:
"""Download YouTube CDN avatar and store a stable S3 URL. Falls back to CDN on failure."""
url = str(cdn_url or "").strip()
@ -190,14 +203,24 @@ async def _mirror_avatar_to_s3(channel_pk: str, cdn_url: str) -> str:
async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
token, ch = await _access_for_channel(channel_pk)
data = await _get(
"channels",
token=token,
params={"part": "snippet,contentDetails,statistics,brandingSettings", "mine": "true"},
)
yt_id = str(ch.get("youtube_channel_id") or "").strip()
params: dict[str, Any] = {"part": "snippet,contentDetails,statistics,brandingSettings"}
if yt_id:
params["id"] = yt_id
else:
params["mine"] = "true"
data = await _get("channels", token=token, params=params)
items = data.get("items") or []
if not items and yt_id:
# Stored id may be stale — fall back to mine=true (brand picker during OAuth).
data = await _get(
"channels",
token=token,
params={"part": "snippet,contentDetails,statistics,brandingSettings", "mine": "true"},
)
items = data.get("items") or []
if not items:
raise ValueError("未拿到频道资料(请确认授权账号下有频道)")
raise ValueError("未拿到频道资料(请确认授权账号下有频道,且 Google 项目已启用 YouTube Data API v3)")
item = items[0]
# If stored youtube_channel_id differs, still return mine (Brand account caveat)
yt_id = str(item.get("id") or "")

File diff suppressed because it is too large Load Diff

View File

@ -13,15 +13,40 @@ from .config import settings
class RelayStreamEnded(Exception):
"""Source ended (anchor offline)."""
"""Source ended / CDN terminal (404) — outer loop must re-resolve with Cookie."""
class RelaySourceStalled(Exception):
"""No progress from FFmpeg — try another source URL."""
"""No progress — try next fallback URL from same parse batch."""
MAX_RELAY_LOG_LINES = 200
# Aligned with sh2/douyin_youtube_ffplay.py TERMINAL / TRANSIENT split.
_TERMINAL_HINTS = (
"404 not found",
"server returned 404",
"403 forbidden",
"server returned 403",
"live has ended",
"stream ends prematurely",
"end of file",
"stream ended",
"access denied",
"ingestion error",
)
_TRANSIENT_HINTS = (
"connection reset",
"connection timed out",
"connection refused",
"broken pipe",
"i/o error",
"input/output error",
"server returned 500",
"error writing output",
"no route to host",
)
@dataclass
class RelayStats:
@ -81,12 +106,25 @@ def build_ffmpeg_relay_cmd(
*,
bitrate_kbps: int = 4000,
ffmpeg_bin: str | None = None,
width: int = 720,
height: int = 1280,
fps: int = 30,
x264_preset: str = "veryfast",
gop: int = 60,
profile: str = "high",
level: str = "4.0",
audio_bitrate_kbps: int = 128,
x264_threads: int = 0,
scale_flags: str = "bilinear",
) -> list[str]:
b_v, maxrate, bufsize = _bitrate_triplet(bitrate_kbps)
ff = str(ffmpeg_bin or settings.ffmpeg_bin or "ffmpeg")
w, h = max(360, int(width)), max(640, int(height))
out_fps = max(15, min(int(fps), 60))
gop_frames = max(out_fps, int(gop))
vf = (
"fps=30,scale=720:1280:force_original_aspect_ratio=decrease:flags=bilinear,"
"pad=720:1280:(ow-iw)/2:(oh-ih)/2:black"
f"fps={out_fps},scale={w}:{h}:force_original_aspect_ratio=decrease:flags={scale_flags},"
f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:black"
)
is_flv = ".flv" in input_url.lower() or "pull-" in input_url.lower()
input_args: list[str] = []
@ -115,14 +153,15 @@ def build_ffmpeg_relay_cmd(
vf,
"-c:v",
"libx264",
*([] if int(x264_threads or 0) <= 0 else ["-threads", str(int(x264_threads))]),
"-preset",
"veryfast",
str(x264_preset or "veryfast"),
"-tune",
"zerolatency",
"-profile:v",
"high",
str(profile or "high"),
"-level",
"4.0",
str(level or "4.0"),
"-b:v",
b_v,
"-minrate",
@ -132,17 +171,24 @@ def build_ffmpeg_relay_cmd(
"-bufsize",
bufsize,
"-g",
"60",
str(gop_frames),
"-keyint_min",
"60",
str(gop_frames),
"-r",
"30",
str(out_fps),
"-pix_fmt",
"yuv420p",
# Douyin FLV often has audio as stream 0 — explicit maps keep AAC on YouTube ingest.
"-map",
"0:v:0",
"-map",
"0:a:0?",
"-c:a",
"aac",
"-profile:a",
"aac_low",
"-b:a",
"128k",
f"{max(128, min(int(audio_bitrate_kbps), 192))}k",
"-ar",
"48000",
"-ac",
@ -174,34 +220,54 @@ def _terminate_proc(proc: subprocess.Popen | None) -> None:
class RelayPushSession:
"""One FFmpeg push subprocess with stderr monitoring."""
"""One FFmpeg push subprocess with stderr monitoring.
STALE_SEC = 90.0
Aligned with sh2 start_douyin_youtube_ffplay:
- TRANSIENT errors: rebuild same URL after short backoff
- SourceStalled / no progress: advance to next fallback URL (same spider batch)
- TERMINAL (404 / live ended): exit session → outer pipeline re-resolves with Cookie
"""
STALE_SEC = 40.0
NO_FRAME_SEC = 120.0
START_GRACE_SEC = 25.0
def __init__(
self,
*,
group_id: str,
input_url: str,
input_url: str = "",
input_urls: list[str] | None = None,
youtube_rtmp: str,
anchor_name: str = "",
source_url: str = "",
room_id: str = "",
bitrate_kbps: int = 4000,
encoding: dict[str, Any] | None = None,
on_stats: Callable[[RelayStats], None] | None = None,
) -> None:
self.group_id = group_id
self.input_url = input_url
urls: list[str] = []
for u in list(input_urls or []) + ([input_url] if input_url else []):
s = str(u or "").strip()
if s.startswith("http") and s not in urls:
urls.append(s)
if not urls:
raise ValueError("缺少抖音拉流地址")
self.input_urls = urls
self.input_url = urls[0]
self.youtube_rtmp = youtube_rtmp
self.anchor_name = anchor_name
self.source_url = source_url
self.room_id = room_id
self.bitrate_kbps = bitrate_kbps
self.encoding = dict(encoding or {})
self.on_stats = on_stats
self._proc: subprocess.Popen | None = None
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self.stats = RelayStats()
self._source_index = 0
def start(self) -> None:
if self._thread and self._thread.is_alive():
@ -217,34 +283,68 @@ class RelayPushSession:
self._thread.join(timeout=8)
self.stats.running = False
def _run(self) -> None:
cmd = build_ffmpeg_relay_cmd(
self.input_url,
def _build_cmd(self, input_url: str) -> list[str]:
enc = self.encoding
return build_ffmpeg_relay_cmd(
input_url,
self.youtube_rtmp,
bitrate_kbps=self.bitrate_kbps,
width=int(enc.get("width") or 720),
height=int(enc.get("height") or 1280),
fps=int(enc.get("fps") or 30),
x264_preset=str(enc.get("x264_preset") or "veryfast"),
gop=int(enc.get("gop") or 60),
profile=str(enc.get("profile") or "high"),
level=str(enc.get("level") or "4.0"),
audio_bitrate_kbps=int(enc.get("audio_bitrate_kbps") or 128),
x264_threads=int(enc.get("x264_threads") or 0),
scale_flags=str(enc.get("scale_flags") or "bilinear"),
)
def _run(self) -> None:
import queue as _queue
q: _queue.Queue[str | None] = _queue.Queue()
self.stats.recent_log.append(f"[ffmpeg] cmd={cmd[0]} bitrate={self.bitrate_kbps}k")
self.stats.recent_log.append(f"[ffmpeg] -i {self.input_url[:180]}")
enc = self.encoding
preset_id = str(enc.get("preset_id") or "720p")
self.stats.recent_log.append(
f"[ffmpeg] quality={preset_id} {enc.get('width')}x{enc.get('height')}@{enc.get('fps')} "
f"preset={enc.get('x264_preset')} bitrate={self.bitrate_kbps}k candidates={len(self.input_urls)}"
)
retry_delay = 0.0
def _reader() -> None:
proc = self._proc
if not proc or not proc.stderr:
q.put(None)
return
try:
for line in proc.stderr:
if self._stop.is_set():
break
q.put(line.rstrip("\n"))
except Exception as exc:
q.put(f"[ffmpeg] reader error: {exc}")
finally:
q.put(None)
while not self._stop.is_set() and self._source_index < len(self.input_urls):
self.input_url = self.input_urls[self._source_index]
cmd = self._build_cmd(self.input_url)
q: _queue.Queue[str | None] = _queue.Queue()
if retry_delay > 0:
self.stats.recent_log.append(f"[ffmpeg] backoff {retry_delay:.0f}s then retry same URL")
time.sleep(min(retry_delay, 90.0))
if self._stop.is_set():
break
self.stats.recent_log.append(
f"[ffmpeg] source {self._source_index + 1}/{len(self.input_urls)} -i {self.input_url[:160]}"
)
def _reader() -> None:
proc = self._proc
if not proc or not proc.stderr:
q.put(None)
return
try:
for line in proc.stderr:
if self._stop.is_set():
break
# FFmpeg progress often uses \r without \n
for part in line.replace("\r", "\n").split("\n"):
part = part.strip()
if part:
q.put(part)
except Exception as exc:
q.put(f"[ffmpeg] reader error: {exc}")
finally:
q.put(None)
while not self._stop.is_set():
try:
self._proc = subprocess.Popen(
cmd,
@ -257,20 +357,10 @@ class RelayPushSession:
except FileNotFoundError:
self.stats.recent_log.append("[ffmpeg] ERROR: ffmpeg binary not found")
self.stats.running = False
if self.on_stats:
try:
self.on_stats(self.stats)
except Exception:
pass
return
except Exception as exc:
self.stats.recent_log.append(f"[ffmpeg] ERROR spawn failed: {exc}")
self.stats.running = False
if self.on_stats:
try:
self.on_stats(self.stats)
except Exception:
pass
return
self.stats.pid = int(self._proc.pid or 0)
@ -281,16 +371,33 @@ class RelayPushSession:
self.on_stats(self.stats)
except Exception:
pass
last_out = time.time()
started = time.time()
last_frame_at = time.time()
last_frame_n = 0
reader = threading.Thread(target=_reader, daemon=True)
reader.start()
terminal = False
stalled = False
transient = False
while not self._stop.is_set():
try:
line = q.get(timeout=2.0)
except _queue.Empty:
if time.time() - last_out > self.STALE_SEC:
self.stats.recent_log.append("[ffmpeg] stale: no stderr for 90s, restarting")
now = time.time()
if now - last_out > self.STALE_SEC:
self.stats.recent_log.append("[ffmpeg] stale: no stderr — try fallback / refresh")
stalled = True
_terminate_proc(self._proc)
break
if (
now - started > self.START_GRACE_SEC
and now - last_frame_at > self.NO_FRAME_SEC
):
self.stats.recent_log.append("[ffmpeg] no frame progress 120s — try fallback")
stalled = True
_terminate_proc(self._proc)
break
continue
@ -305,6 +412,9 @@ class RelayPushSession:
if sp is not None:
self.stats.speed = sp
if fr is not None:
if fr > last_frame_n:
last_frame_n = fr
last_frame_at = time.time()
self.stats.frame = fr
if self.on_stats:
try:
@ -312,26 +422,39 @@ class RelayPushSession:
except Exception:
pass
low = line.lower()
if "end of file" in low or "stream ended" in low:
_terminate_proc(self._proc)
break
if "404 not found" in low or "403 forbidden" in low:
if any(h in low for h in _TERMINAL_HINTS):
self.stats.recent_log.append("[ffmpeg] TERMINAL — exit for Cookie re-resolve (sh2)")
terminal = True
_terminate_proc(self._proc)
break
if any(h in low for h in _TRANSIENT_HINTS):
transient = True
code = self._proc.poll() if self._proc else None
self.stats.recent_log.append(f"[ffmpeg] exited code={code}")
if self.on_stats:
try:
self.on_stats(self.stats)
except Exception:
pass
_terminate_proc(self._proc)
self.stats.running = False
if self._stop.is_set():
return
time.sleep(3)
if self._stop.is_set():
if terminal:
# Outer youtube_relay_pipeline must re-spider with dy_cookie.
return
if stalled or (not transient and self._source_index + 1 < len(self.input_urls)):
if self._source_index + 1 < len(self.input_urls):
self._source_index += 1
retry_delay = 0.0
self.stats.recent_log.append(
f"[ffmpeg] source_failover → {self._source_index + 1}/{len(self.input_urls)}"
)
continue
# Fallbacks exhausted — exit for outer Cookie re-resolve (sh2 SourceStalled end).
self.stats.recent_log.append("[ffmpeg] fallbacks exhausted — exit for refresh")
return
if transient:
retry_delay = 3.0 if retry_delay <= 0 else min(90.0, retry_delay * 2)
continue
# Unknown exit: brief retry then give outer loop a chance.
retry_delay = 3.0 if retry_delay <= 0 else min(30.0, retry_delay * 1.5)
if retry_delay >= 20:
self.stats.recent_log.append("[ffmpeg] repeated exit — leave for outer refresh")
return
self.stats.running = False

View File

@ -9,9 +9,11 @@ from typing import Any
from . import db
from . import yt_assign_db
from . import youtube_relay_db
from .douyin import check_room
from .shorts_clip import resolve_stream_candidates
from . import youtube_relay_sessions as relay_sessions
from .youtube_relay import RelayPushSession, RelayStats, build_youtube_rtmp_url
from .youtube_relay_presets import list_relay_quality_presets, resolve_relay_encoding
from .youtube_relay_status import log_age_seconds, summarize_relay_group, _key_suffix
@ -20,18 +22,90 @@ def _live_room_ids() -> set[str]:
return {str(r.get("room_id") or "").strip() for r in rows if r.get("room_id")}
def pick_source_for_group(group: dict[str, Any], *, respect_schedule: bool = True) -> dict[str, str] | None:
"""Choose Douyin source from 精选列表 only; prefer live rooms, then list order."""
def _douyin_live_count_cached() -> int:
try:
from . import douyin_live
return int(douyin_live.build_live_map().get("live_count") or 0)
except Exception:
try:
return len(_live_room_ids())
except Exception:
return 0
def _time_slot_mode(cfg: dict[str, Any] | None = None) -> bool:
cfg = cfg or db.get_settings_map()
return bool(cfg.get("youtube_relay_time_slot_mode"))
def _group_in_active_slot(group_id: str, *, keyed_only: bool = False) -> bool:
sched = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=keyed_only)
for c in sched.get("channels") or []:
if str(c.get("group_id") or "") == str(group_id):
return bool(c.get("active"))
# No schedule rows → treat as not active when keyed_only (nothing to rotate).
if keyed_only:
return False
return True
def pick_source_for_group(
group: dict[str, Any],
*,
respect_schedule: bool = True,
time_slot_mode: bool | None = None,
prefer_room_id: str = "",
prefer_source_url: str = "",
) -> dict[str, str] | None:
"""Choose Douyin source.
- 时间段模式: only when group is in active 24/N slot; source = currently-live monitor rooms.
- 普通模式: featured list (prefer live), optionally gated by schedule.
"""
gid = str(group.get("id") or "")
if not gid or not group.get("enabled"):
return None
cfg = db.get_settings_map()
slot_mode = bool(cfg.get("youtube_relay_time_slot_mode")) if time_slot_mode is None else bool(time_slot_mode)
if slot_mode:
if respect_schedule and not _group_in_active_slot(gid, keyed_only=True):
return None
rooms = db.list_live_douyin_rooms_for_shorts(limit=40)
prefer_rid = str(prefer_room_id or "").strip()
prefer_url = str(prefer_source_url or "").strip()
def _row_to_src(row: dict[str, Any]) -> dict[str, str]:
url = str(row.get("url") or "").strip()
rid = str(row.get("room_id") or "").strip()
return {
"source_url": url,
"room_id": rid,
"anchor_name": str(row.get("last_anchor") or row.get("last_title") or rid).strip(),
}
if prefer_rid:
for row in rooms:
if str(row.get("room_id") or "").strip() == prefer_rid:
return _row_to_src(row)
# Monitor may briefly mark room offline while FFmpeg still has a valid pull.
if prefer_url:
return {
"source_url": prefer_url,
"room_id": prefer_rid,
"anchor_name": str(group.get("name") or prefer_rid).strip(),
}
for row in rooms:
url = str(row.get("url") or "").strip()
rid = str(row.get("room_id") or "").strip()
if not url or not rid:
continue
return _row_to_src(row)
return None
if respect_schedule:
sched = yt_assign_db.build_rotation_schedule(include_urls=False)
active_map = {
str(c.get("group_id") or ""): bool(c.get("active"))
for c in (sched.get("channels") or [])
}
if active_map and gid in active_map and not active_map[gid]:
if not _group_in_active_slot(gid, keyed_only=False):
return None
live_ids = _live_room_ids()
@ -70,38 +144,87 @@ class YoutubeRelayPipeline:
self._sessions: dict[str, RelayPushSession] = {}
# Manual Start holds the lane even outside schedule until Stop / auto window reclaim.
self._manual_hold: set[str] = set()
self._exclusive_winner: str | None = None
self._neko_paused_instances: set[int] = set()
# Serialize start/restart per group — prevents double FFmpeg on same stream key.
self._group_locks: dict[str, asyncio.Lock] = {}
self.last_error = ""
self.processed = 0
self._status_cache: dict[str, Any] | None = None
self._status_cache_at = 0.0
self._STATUS_CACHE_TTL_SEC = 1.0
def status(self) -> dict[str, Any]:
now = time.time()
cached = self._status_cache
if cached is not None and (now - self._status_cache_at) < self._STATUS_CACHE_TTL_SEC:
return cached
cfg = db.get_settings_map()
groups = yt_assign_db.list_groups(include_urls=False)
groups_full = {str(g.get("id") or ""): g for g in yt_assign_db.list_groups(include_urls=True)}
# featured_only: one DB pass with featured URLs (needed for url_count / misconfigured).
groups = yt_assign_db.list_groups(featured_only=True)
states = {str(s.get("group_id") or ""): s for s in youtube_relay_db.list_relay_states()}
relay_groups: list[dict[str, Any]] = []
entries: list[dict[str, Any]] = []
pushing = 0
pipeline_enabled = bool(cfg.get("youtube_relay_enabled"))
now = time.time()
# Batch Neko docker ps once per poll (read-only; no compose sync / no curl).
neko_by_id: dict[int, dict[str, Any]] = {}
try:
from . import youtube_neko
max_neko = max((int(g.get("neko_instance_id") or 0) for g in groups), default=0)
if max_neko > 0:
for inst in youtube_neko.list_instances(max_neko, check_http=False):
try:
neko_by_id[int(inst.get("id") or 0)] = inst
except (TypeError, ValueError):
continue
except Exception:
neko_by_id = {}
for g in groups:
gid = str(g.get("id") or "")
gf = groups_full.get(gid) or g
st = dict(states.get(gid) or {})
sess = self._sessions.get(gid)
running = bool(sess and sess.stats.running)
recent_log = list(
sess.stats.recent_log if sess else youtube_relay_db._parse_recent_log(st.get("recent_log"))
)
st["recent_log"] = recent_log
# Keep enough for progress parsing; wire payload trims further below.
st["recent_log"] = recent_log[-80:]
monitor = summarize_relay_group(
group=gf,
group=g,
st=st,
session_running=running,
pipeline_enabled=pipeline_enabled,
pipeline_enabled=pipeline_enabled or gid in self._manual_hold,
log_age_seconds=log_age_seconds(st, now),
lane_armed=gid in self._manual_hold or pipeline_enabled,
time_slot_mode=_time_slot_mode(cfg),
)
if monitor.get("is_pushing"):
pushing += 1
neko_id = int(g.get("neko_instance_id") or 0)
raw_neko = neko_by_id.get(neko_id) if neko_id > 0 else None
neko_state = None
if isinstance(raw_neko, dict):
neko_state = {
"id": raw_neko.get("id"),
"running": bool(raw_neko.get("running")),
"ready": bool(raw_neko.get("ready")),
"status": raw_neko.get("status"),
"studio_url": raw_neko.get("studio_url"),
"exists": bool(raw_neko.get("exists")),
}
# Trim log text for poll JSON (selected card still has enough to read).
rl = monitor.get("recent_log")
if isinstance(rl, str) and len(rl) > 3500:
monitor["recent_log"] = rl[-3500:]
elif isinstance(rl, list):
monitor["recent_log"] = rl[-40:]
re = monitor.get("recent_error")
if isinstance(re, str) and len(re) > 1200:
monitor["recent_error"] = re[-1200:]
row = {
"group_id": gid,
"name": g.get("name"),
@ -110,32 +233,58 @@ class YoutubeRelayPipeline:
"status": "pushing" if running else str(st.get("status") or "idle"),
"error": st.get("error") or "",
"manual_hold": gid in self._manual_hold,
"neko_instance_id": neko_id,
"neko_enabled": bool(g.get("neko_enabled")),
"neko": neko_state,
**monitor,
}
relay_groups.append(row)
entries.append({**monitor, "channel_pk": g.get("channel_pk"), "manual_hold": gid in self._manual_hold})
schedule = yt_assign_db.build_rotation_schedule(include_urls=True)
return {
# Light schedule — keyed-only when 时间段模式.
schedule = yt_assign_db.build_rotation_schedule(
include_urls=False,
groups=groups,
keyed_only=_time_slot_mode(cfg),
)
preset_id = str(cfg.get("youtube_relay_quality_preset") or "720p")
encoding = resolve_relay_encoding(cfg)
payload = {
"running": bool(self._task and not self._task.done()),
"enabled": pipeline_enabled,
"pushing_count": pushing,
"group_count": len(groups),
"enabled_groups": sum(1 for g in groups if g.get("enabled")),
"last_error": self.last_error,
"douyin_live_count": len(_live_room_ids()),
"douyin_live_count": _douyin_live_count_cached(),
"process_backend": "cloud_pipeline",
"family": "youtube",
"light": True,
"entries": entries,
"settings": {
"youtube_relay_enabled": pipeline_enabled,
"youtube_relay_bitrate": int(cfg.get("youtube_relay_bitrate") or 2500),
"youtube_relay_use_rtmps": bool(cfg.get("youtube_relay_use_rtmps", True)),
"youtube_relay_respect_schedule": bool(cfg.get("youtube_relay_respect_schedule", True)),
"youtube_relay_quality_preset": preset_id,
"youtube_relay_encoding": {
"preset_id": encoding.get("preset_id"),
"width": encoding.get("width"),
"height": encoding.get("height"),
"fps": encoding.get("fps"),
"x264_preset": encoding.get("x264_preset"),
"bitrate_kbps": encoding.get("bitrate_kbps"),
"audio_bitrate_kbps": encoding.get("audio_bitrate_kbps"),
},
"youtube_relay_quality_presets": list_relay_quality_presets(active_id=preset_id),
"youtube_relay_exclusive_live": bool(cfg.get("youtube_relay_exclusive_live", True)),
"youtube_relay_time_slot_mode": bool(cfg.get("youtube_relay_time_slot_mode")),
},
"groups": relay_groups,
"schedule": schedule,
"exclusive_winner_group_id": self._exclusive_winner,
"neko_paused_instances": sorted(self._neko_paused_instances),
}
self._status_cache = payload
self._status_cache_at = time.time()
return payload
async def start(self) -> None:
if self._task and not self._task.done():
@ -149,6 +298,8 @@ class YoutubeRelayPipeline:
await asyncio.to_thread(sess.stop)
self._sessions.clear()
self._manual_hold.clear()
self._exclusive_winner = None
self._neko_paused_instances.clear()
if self._task:
try:
await asyncio.wait_for(self._task, timeout=8)
@ -157,7 +308,11 @@ class YoutubeRelayPipeline:
self._task = None
async def start_group(self, group_id: str) -> dict[str, Any]:
"""Manual Start — always ignores schedule (like sh2 Pro Start)."""
"""Manual Start = arm monitor lane (sh2 Pro Start / start_record thread).
sh2 youtube.py: thread keeps polling forever; offline →「等待直播」+ continue;
only Stop / URL removed from active_monitor_urls exits. Never treat offline as fatal.
"""
gid = str(group_id or "").strip()
g = yt_assign_db.get_group(gid)
if not g:
@ -166,16 +321,30 @@ class YoutubeRelayPipeline:
raise ValueError("该组已停用")
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
raise ValueError("请先配置 YouTube 直播 KEY")
featured = [x for x in (g.get("featured") or []) if str(x.get("url") or "").strip() and not x.get("blacklisted")]
if not featured:
raise ValueError("直播地址列表(精选)为空,请先加入抖音房间")
# 时间段模式: sources come from currently-live monitor rooms (not 精选).
# 普通模式: still require 精选 list.
if not _time_slot_mode():
featured = [
x
for x in (g.get("featured") or [])
if str(x.get("url") or "").strip() and not x.get("blacklisted")
]
if not featured:
raise ValueError("直播地址列表(精选)为空,请先加入抖音房间")
# Ensure worker loop keeps polling this lane (even if auto relay is off).
# Exclusive FFmpeg/Neko lock applies only when push actually starts (see _ensure_group_relay).
await self.start()
self._manual_hold.add(gid)
result = await self._ensure_group_relay(g, force=True, respect_schedule=False)
if not result.get("ok"):
# Time-slot: keep schedule gate so only the active slot winner pushes.
# Normal mode: manual Start ignores schedule window (force lane).
respect = True if _time_slot_mode() else False
result = await self._ensure_group_relay(g, force=True, respect_schedule=respect)
# Fatal = missing key / empty source only. Offline/risk → waiting, hold stays.
if result.get("fatal"):
self._manual_hold.discard(gid)
raise ValueError(str(result.get("error") or "启动推流失败"))
return {"ok": True, "group_id": gid, **result}
raise ValueError(str(result.get("error") or "启动失败"))
return {"ok": True, "group_id": gid, "manual_hold": True, **result}
async def _halt_session(self, group_id: str, *, reason: str = "stopped") -> None:
"""Stop FFmpeg for a group without clearing manual_hold."""
@ -188,8 +357,11 @@ class YoutubeRelayPipeline:
async def stop_group(self, group_id: str) -> dict[str, Any]:
gid = str(group_id or "").strip()
was_exclusive = gid == self._exclusive_winner
self._manual_hold.discard(gid)
await self._halt_session(gid, reason="stopped")
if was_exclusive:
await self._release_exclusive_live()
return {"ok": True, "group_id": gid}
async def restart_group(self, group_id: str) -> dict[str, Any]:
@ -197,57 +369,234 @@ class YoutubeRelayPipeline:
await self.stop_group(gid)
return await self.start_group(gid)
async def apply_quality_preset(self, preset_id: str) -> dict[str, Any]:
from .youtube_relay_presets import RELAY_QUALITY_PRESETS
pid = str(preset_id or "").strip()
if pid not in RELAY_QUALITY_PRESETS:
raise ValueError(f"未知画质预设:{pid}")
db.update_settings_map({"youtube_relay_quality_preset": pid})
restarted: list[str] = []
for gid in list(self._sessions.keys()):
try:
if gid in self._manual_hold:
await self.restart_group(gid)
else:
g = yt_assign_db.get_group(gid)
await self._halt_session(gid, reason="quality_preset")
cfg = db.get_settings_map()
if g and g.get("enabled") and cfg.get("youtube_relay_enabled"):
src = pick_source_for_group(
g,
respect_schedule=bool(cfg.get("youtube_relay_respect_schedule", True)),
)
if src:
await self._ensure_group_relay(g, source=src, cfg=cfg)
restarted.append(gid)
except Exception:
continue
st = self.status()
return {"ok": True, "preset": pid, "restarted_groups": restarted, **st}
async def _loop(self) -> None:
"""sh2 outer monitor: forever poll armed lanes; offline never exits the lane."""
while not self._stop.is_set():
try:
cfg = db.get_settings_map()
if not cfg.get("youtube_relay_enabled"):
# Auto off: leave manual-hold sessions alone; stop orphan auto sessions.
for gid in list(self._sessions.keys()):
if gid not in self._manual_hold:
await self.stop_group(gid)
await asyncio.sleep(2.0)
continue
respect = bool(cfg.get("youtube_relay_respect_schedule", True))
auto_on = bool(cfg.get("youtube_relay_enabled"))
slot_mode = _time_slot_mode(cfg)
# 时间段模式始终尊重 24/N 轮播;普通模式可读原开关。
respect = True if slot_mode else bool(cfg.get("youtube_relay_respect_schedule", True))
groups = yt_assign_db.list_groups(include_urls=True)
by_id = {str(g.get("id") or ""): g for g in groups}
active_ids: set[str] = set()
for g in groups:
gid = str(g.get("id") or "")
if not gid or not g.get("enabled"):
if gid:
await self.stop_group(gid)
# 1) Always poll manual-hold lanes (sh2: start_record keeps waiting).
for gid in list(self._manual_hold):
g = by_id.get(gid)
if not g or not g.get("enabled"):
self._manual_hold.discard(gid)
await self._halt_session(gid, reason="disabled")
continue
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
await self.stop_group(gid)
continue
manual = gid in self._manual_hold
src = pick_source_for_group(g, respect_schedule=False if manual else respect)
if not src:
if manual and gid in self._sessions:
# Keep manual push; still tick stats.
active_ids.add(gid)
continue
await self.stop_group(gid)
continue
active_ids.add(gid)
await self._ensure_group_relay(
g,
source=src,
cfg=cfg,
respect_schedule=False if manual else respect,
g, force=False, respect_schedule=False, cfg=cfg
)
# 2) Auto relay: same poll for enabled groups (schedule optional).
if auto_on:
from . import youtube_neko
# Time-slot: identify current winner once per tick.
slot_winner_gid = ""
slot_winner_g: dict[str, Any] | None = None
if slot_mode and respect:
for g in groups:
gid0 = str(g.get("id") or "")
if not gid0 or not g.get("enabled"):
continue
if not (str(g.get("stream_key") or "").strip() or g.get("has_stream_key")):
continue
if _group_in_active_slot(gid0, keyed_only=True):
slot_winner_gid = gid0
slot_winner_g = g
break
for g in groups:
gid = str(g.get("id") or "")
if not gid or not g.get("enabled"):
continue
if gid in active_ids:
continue
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
continue
# 时间段模式:非当前时段 → 停推流 + 停 Neko。
if slot_mode and respect and gid != slot_winner_gid:
if gid in self._sessions:
await self._halt_session(gid, reason="outside_slot")
neko_id = int(g.get("neko_instance_id") or 0)
if neko_id > 0:
await asyncio.to_thread(youtube_neko.stop_instance, neko_id)
youtube_relay_db.upsert_relay_state(
gid,
status="idle",
error="非当前时段:已停推流并关闭 Neko",
recent_log=["[relay] outside_slot — ffmpeg+neko stopped"],
)
continue
src = pick_source_for_group(
g,
respect_schedule=respect,
time_slot_mode=slot_mode,
prefer_room_id=str((youtube_relay_db.get_relay_state(gid) or {}).get("source_room_id") or ""),
prefer_source_url=str((youtube_relay_db.get_relay_state(gid) or {}).get("source_url") or ""),
)
if not src:
sess = self._sessions.get(gid)
if sess and sess.stats.running:
active_ids.add(gid)
continue
# Outside schedule / empty list — idle, do not kill manual holds.
if slot_mode and gid in self._sessions and gid not in self._manual_hold:
await self._halt_session(gid, reason="no_live_source")
if slot_mode:
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error="时间段模式:等待在播抖音源",
recent_log=["[relay] waiting live Douyin source"],
)
# Keep winner Neko warm while waiting for a live room.
if slot_winner_g and gid == slot_winner_gid:
await self._enforce_exclusive_live(gid, slot_winner_g)
continue
active_ids.add(gid)
await self._ensure_group_relay(
g, source=src, cfg=cfg, respect_schedule=respect
)
else:
# Auto off: stop non-manual ffmpeg sessions only.
for gid in list(self._sessions.keys()):
if gid not in self._manual_hold:
await self._halt_session(gid, reason="auto_off")
for gid in list(self._sessions.keys()):
if gid not in active_ids and gid not in self._manual_hold:
await self.stop_group(gid)
await self._halt_session(gid, reason="inactive")
await self._tick_stats()
except Exception as exc:
self.last_error = str(exc)[:240]
await asyncio.sleep(4.0)
await asyncio.sleep(7.0)
async def _stop_all_sessions(self) -> None:
for gid in list(self._sessions.keys()):
await self.stop_group(gid)
async def set_exclusive_live(self, enabled: bool) -> dict[str, Any]:
db.update_settings_map({"youtube_relay_exclusive_live": bool(enabled)})
if not enabled and (self._exclusive_winner or self._neko_paused_instances):
# 时间段模式强制独占,不允许关掉独占。
if _time_slot_mode():
db.update_settings_map({"youtube_relay_exclusive_live": True})
st = await asyncio.to_thread(self.status)
st["note"] = "时间段模式已开启,单频道独占保持开启"
return st
await self._release_exclusive_live()
return await asyncio.to_thread(self.status)
async def set_time_slot_mode(self, enabled: bool) -> dict[str, Any]:
"""Enable 24/N keyed-channel slots + live Douyin sources + exclusive Neko/FFmpeg.
Does NOT turn on 自动推流 — operator must enable youtube_relay_enabled separately.
"""
on = bool(enabled)
patch: dict[str, Any] = {"youtube_relay_time_slot_mode": on}
if on:
patch["youtube_relay_exclusive_live"] = True
patch["youtube_relay_respect_schedule"] = True
db.update_settings_map(patch)
self._status_cache = None
self._status_cache_at = 0.0
return await asyncio.to_thread(self.status)
async def _enforce_exclusive_live(self, winner_gid: str, winner_group: dict[str, Any]) -> None:
"""When one channel actually pushes: stop other FFmpeg + Neko; keep winner Neko up."""
cfg = db.get_settings_map()
# 时间段模式始终独占;否则看开关。
if not (_time_slot_mode(cfg) or bool(cfg.get("youtube_relay_exclusive_live", True))):
return
winner_gid = str(winner_gid or "").strip()
if not winner_gid:
return
self._exclusive_winner = winner_gid
winner_neko = int(winner_group.get("neko_instance_id") or 0)
for g in yt_assign_db.list_groups(include_urls=False):
gid = str(g.get("id") or "")
if not gid or gid == winner_gid:
continue
self._manual_hold.discard(gid)
if gid in self._sessions:
await self._halt_session(gid, reason="exclusive_live")
youtube_relay_db.upsert_relay_state(
gid,
status="paused_exclusive",
error=f"单频道独占:当前仅允许 {winner_group.get('name') or winner_gid} 推流",
recent_log=[f"[relay] exclusive_live winner={winner_gid} — paused"],
)
from . import youtube_neko
paused = await asyncio.to_thread(youtube_neko.stop_instances_except, winner_neko)
self._neko_paused_instances |= set(paused)
if winner_neko > 0:
await asyncio.to_thread(youtube_neko.ensure_instance_running, winner_neko)
async def _release_exclusive_live(self) -> None:
if not self._exclusive_winner and not self._neko_paused_instances:
return
self._exclusive_winner = None
paused = set(self._neko_paused_instances)
self._neko_paused_instances.clear()
if not paused:
return
from . import youtube_neko
await asyncio.to_thread(youtube_neko.restore_enabled_instances)
async def _maybe_release_exclusive_live(self) -> None:
if not self._exclusive_winner:
return
gid = self._exclusive_winner
if gid in self._manual_hold:
return
sess = self._sessions.get(gid)
if sess and sess.stats.running:
return
await self._release_exclusive_live()
async def _ensure_group_relay(
self,
group: dict[str, Any],
@ -257,21 +606,73 @@ class YoutubeRelayPipeline:
force: bool = False,
respect_schedule: bool | None = None,
) -> dict[str, Any]:
cfg = cfg or db.get_settings_map()
gid = str(group.get("id") or "")
lock = self._group_locks.setdefault(gid, asyncio.Lock())
async with lock:
return await self._ensure_group_relay_locked(
group,
source=source,
cfg=cfg,
force=force,
respect_schedule=respect_schedule,
)
async def _ensure_group_relay_locked(
self,
group: dict[str, Any],
*,
source: dict[str, str] | None = None,
cfg: dict[str, Any] | None = None,
force: bool = False,
respect_schedule: bool | None = None,
) -> dict[str, Any]:
cfg = cfg or db.get_settings_map()
encoding = resolve_relay_encoding(cfg)
gid = str(group.get("id") or "")
slot_mode = _time_slot_mode(cfg)
if respect_schedule is None:
respect_schedule = bool(cfg.get("youtube_relay_respect_schedule", True))
respect_schedule = True if slot_mode else bool(cfg.get("youtube_relay_respect_schedule", True))
if force:
respect_schedule = False
src = source or pick_source_for_group(group, respect_schedule=respect_schedule)
relay_st = youtube_relay_db.get_relay_state(gid) or {}
existing = self._sessions.get(gid)
prefer_room = str(
(existing.room_id if existing else "")
or relay_st.get("source_room_id")
or ""
).strip()
prefer_url = str(
(existing.source_url if existing else "")
or relay_st.get("source_url")
or ""
).strip()
src = source or pick_source_for_group(
group,
respect_schedule=respect_schedule,
time_slot_mode=slot_mode,
prefer_room_id=prefer_room,
prefer_source_url=prefer_url,
)
if not src:
# Distinguish schedule block vs empty featured for diagnostics.
any_src = pick_source_for_group(group, respect_schedule=False)
any_src = pick_source_for_group(
group,
respect_schedule=False,
time_slot_mode=slot_mode,
prefer_room_id=prefer_room,
prefer_source_url=prefer_url,
)
if any_src and respect_schedule:
err = "当前不在分配时段,自动推流已跳过(手动「开始」可强制推流)"
err = "当前不在分配时段,自动推流已跳过(手动「开始」可强制监听)"
fatal = False
elif slot_mode:
err = "时间段模式:当前没有在播的抖音直播间可作为推流源"
fatal = False
else:
err = "直播地址列表为空或没有可用抖音源"
fatal = True
youtube_relay_db.upsert_relay_state(
gid,
status="idle",
@ -279,19 +680,27 @@ class YoutubeRelayPipeline:
recent_log=[f"[relay] skip: {err}"],
)
if force:
return {"ok": False, "error": err}
return {"ok": False, "fatal": fatal, "error": err}
# Auto path: stop if running.
if gid in self._sessions and gid not in self._manual_hold:
await self.stop_group(gid)
return {"ok": False, "error": err}
await self._halt_session(gid, reason="no_source")
return {"ok": False, "fatal": fatal, "error": err}
existing = self._sessions.get(gid)
if existing and existing.stats.running and not force:
if existing.source_url == src.get("source_url"):
return {"ok": True, "group_id": gid, "reused": True}
if existing and existing.stats.running:
same_url = existing.source_url == src.get("source_url")
same_room = (
str(existing.room_id or "").strip()
and str(existing.room_id or "").strip() == str(src.get("room_id") or "").strip()
)
if same_url or same_room:
if force:
self._manual_hold.add(gid)
return {"ok": True, "group_id": gid, "reused": True, "ffmpeg_pid": int(existing.stats.pid or 0)}
await self._halt_session(gid, reason="source_switch")
elif existing and force:
await self._halt_session(gid, reason="restart")
elif existing and (force or not existing.stats.running):
# Dead/stale session (CDN 404 etc.) → drop and re-resolve FLV URL.
await self._halt_session(gid, reason="restart" if force else "stream_refresh")
if force:
self._manual_hold.add(gid)
@ -303,7 +712,7 @@ class YoutubeRelayPipeline:
if not stream_key:
err = "缺少 stream key"
youtube_relay_db.upsert_relay_state(gid, status="error", error=err, recent_log=[f"[relay] {err}"])
return {"ok": False, "error": err}
return {"ok": False, "fatal": True, "error": err}
boot_log = [
f"[relay] resolve {src.get('source_url') or ''}",
@ -319,25 +728,91 @@ class YoutubeRelayPipeline:
recent_log=boot_log,
)
cookie = str(cfg.get("douyin_cookie") or "")
cands = await resolve_stream_candidates(
source_url=src["source_url"],
cookie=cookie,
prefer_fresh=True,
)
if not cands:
err = "无法解析抖音直播流(房间未开播或 Cookie 失效)"
boot_log.append(f"[relay] ERROR {err}")
# sh2: spider MUST use [Cookie]抖音cookie (= dy_cookie). FFmpeg itself does not send Cookie.
cookie = str(cfg.get("dy_cookie") or "").strip()
if not cookie:
# Keep lane armed — sh2 keeps polling even when fetch fails.
note = "缺少抖音 Cookie(dy_cookie / sh2 [Cookie]抖音cookie),轮询暂停推流但不会退出监听"
boot_log.append(f"[relay] 等待直播… {note}")
if gid in self._sessions:
await self._halt_session(gid, reason="wait_cookie")
youtube_relay_db.upsert_relay_state(
gid,
status="error",
error=err,
status="waiting",
error=note,
source_url=src.get("source_url") or "",
source_room_id=src.get("room_id") or "",
anchor_name=src.get("anchor_name") or "",
recent_log=boot_log,
ffmpeg_pid=0,
recent_log=boot_log[-40:],
)
return {"ok": False, "error": err}
return {"ok": True, "waiting": True, "group_id": gid, "note": note}
boot_log.append(f"[relay] dy_cookie len={len(cookie)} (sh2 spider path)")
# Probe first (same as sh2 spider.get_douyin_web_stream_data + get_douyin_stream_url).
probe = await check_room(src["source_url"], cookie=cookie)
if probe.get("anchor_name"):
src["anchor_name"] = str(probe.get("anchor_name") or src.get("anchor_name") or "")
boot_log.append(
f"[relay] probe ok={probe.get('ok')} live={probe.get('is_live')} "
f"status={probe.get('status_code')} risk={bool(probe.get('risk'))}"
)
cands: list[str] = []
if probe.get("ok") and probe.get("is_live"):
raw_cands = probe.get("stream_candidates") or []
if isinstance(raw_cands, list):
cands = [str(x).strip() for x in raw_cands if str(x or "").strip().startswith("http")]
fresh = str(probe.get("stream_url") or "").strip()
if fresh.startswith("http") and fresh not in cands:
cands.insert(0, fresh)
if not cands and probe.get("ok") and probe.get("is_live"):
cands = await resolve_stream_candidates(
source_url=src["source_url"],
cookie=cookie,
prefer_fresh=True,
)
# sh2 youtube.py L1213-1229: is_live False → print 等待直播 + continue (never exit lane).
if not cands:
live_sess = self._sessions.get(gid)
if live_sess and live_sess.stats.running:
# Probe flake must not kill an active FFmpeg pull.
return {
"ok": True,
"group_id": gid,
"reused": True,
"ffmpeg_pid": int(live_sess.stats.pid or 0),
"note": "probe_miss_keep_ffmpeg",
}
if gid in self._sessions:
await self._halt_session(gid, reason="wait_live")
anchor = str(src.get("anchor_name") or probe.get("anchor_name") or "").strip() or "-"
if probe.get("risk") or (probe.get("ok") is False):
note = str(probe.get("error") or "风控/接口失败,将继续轮询").strip()
line = f"[relay] 等待直播…(探测异常: {note})"
else:
note = f"status={probe.get('status_code')} 主播={anchor}"
line = f"[relay] 等待直播... ({note})"
boot_log.append(line)
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error="",
source_url=src.get("source_url") or "",
source_room_id=src.get("room_id") or "",
anchor_name=src.get("anchor_name") or probe.get("anchor_name") or "",
ffmpeg_pid=0,
speed=0,
frame=0,
recent_log=boot_log[-40:],
)
return {
"ok": True,
"waiting": True,
"group_id": gid,
"source_url": src.get("source_url") or "",
"note": line,
}
try:
rtmp = build_youtube_rtmp_url(
@ -351,7 +826,7 @@ class YoutubeRelayPipeline:
return {"ok": False, "error": err}
now = time.time()
boot_log.append(f"[relay] input {cands[0][:160]}")
boot_log.append(f"[relay] input {cands[0][:160]} (+{max(0, len(cands)-1)} fallbacks)")
boot_log.append(f"[relay] output {rtmp.split('/')[-1][:8]}… via {'rtmps' if 'rtmps' in rtmp else 'rtmp'}")
boot_log.append("[relay] starting ffmpeg…")
@ -370,14 +845,66 @@ class YoutubeRelayPipeline:
await asyncio.to_thread(old.stop)
await asyncio.to_thread(relay_sessions.end_session, gid, reason="restart")
boot_log.append(f"[relay] quality {encoding.get('preset_id')} {encoding.get('width')}x{encoding.get('height')}@{encoding.get('fps')}")
await self._enforce_exclusive_live(gid, group)
# VPS: wait until winner Neko is up and Studio Live page is open before FFmpeg.
neko_id = int(group.get("neko_instance_id") or 0)
if neko_id > 0 and (_time_slot_mode(cfg) or bool(cfg.get("youtube_relay_exclusive_live", True))):
from . import youtube_neko
skip_neko_wait = False
try:
inst = youtube_neko.list_instances(neko_id, check_http=False)
row = next((x for x in inst if int(x.get("id") or 0) == neko_id), None)
if isinstance(row, dict) and row.get("running") and (
row.get("ready") or youtube_neko.recent_live_studio_seen(max_age_sec=300.0)
):
skip_neko_wait = True
except Exception:
skip_neko_wait = False
if not skip_neko_wait:
boot_log.append(f"[relay] waiting neko-{neko_id} ready + YouTube Live…")
youtube_relay_db.upsert_relay_state(
gid,
status="starting",
error="",
recent_log=boot_log[-40:],
)
neko_wait = await asyncio.to_thread(
youtube_neko.wait_instance_ready_for_live,
neko_id,
timeout_sec=90.0,
require_live_page=True,
)
if not neko_wait.get("ok"):
err = str(neko_wait.get("error") or "Neko 未就绪,暂不推流")
boot_log.append(f"[relay] neko wait failed: {err}")
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error=err,
recent_log=boot_log[-40:],
)
return {"ok": True, "waiting": True, "group_id": gid, "note": err, "neko": neko_wait}
boot_log.append(
f"[relay] neko ready live_studio={bool(neko_wait.get('live_studio'))} "
f"timeout={bool(neko_wait.get('timeout'))} note={neko_wait.get('note') or '-'}"
)
else:
boot_log.append(f"[relay] neko-{neko_id} already ready — skip wait")
sess = RelayPushSession(
group_id=gid,
input_url=cands[0],
input_urls=cands,
youtube_rtmp=rtmp,
anchor_name=src.get("anchor_name") or "",
source_url=src.get("source_url") or "",
room_id=src.get("room_id") or "",
bitrate_kbps=int(cfg.get("youtube_relay_bitrate") or 4000),
bitrate_kbps=int(encoding.get("bitrate_kbps") or cfg.get("youtube_relay_bitrate") or 2500),
encoding=encoding,
on_stats=_on_stats,
)
# Seed in-memory log so UI sees lines before first ffmpeg frame
@ -432,15 +959,27 @@ class YoutubeRelayPipeline:
push_seconds=max(0.0, now - started),
recent_log=sess.stats.recent_log,
)
elif gid in self._sessions:
st = youtube_relay_db.get_relay_state(gid) or {}
if str(st.get("status") or "") == "pushing":
youtube_relay_db.upsert_relay_state(
gid,
status="reconnecting",
error=(sess.stats.last_line or "推流中断")[:500],
recent_log=sess.stats.recent_log,
)
else:
# Dead ffmpeg still registered — surface reconnecting, never leave "pushing".
last = (sess.stats.last_line or "").lower()
if "404" in last or "403" in last or "cdn 404" in "\n".join(sess.stats.recent_log[-8:]).lower():
err = "抖音 CDN 拉流地址失效(404),正在尝试换线重连;若主播已下播则需等开播后再开始"
else:
err = (sess.stats.last_line or "推流中断,等待重连")[:500]
youtube_relay_db.upsert_relay_state(
gid,
status="reconnecting",
ffmpeg_pid=0,
speed=0,
frame=0,
error=err,
recent_log=sess.stats.recent_log,
)
# Drop dead session object so next _ensure_group_relay always re-resolves.
# Keep manual_hold so user intent (开始) survives.
self._sessions.pop(gid, None)
await asyncio.to_thread(relay_sessions.end_session, gid, reason="stream_refresh")
await self._maybe_release_exclusive_live()
youtube_relay_pipeline = YoutubeRelayPipeline()

View File

@ -0,0 +1,86 @@
# -*- coding: utf-8 -*-
"""YouTube live relay encoding presets — switchable; 720p keeps the original profile."""
from __future__ import annotations
from typing import Any
DEFAULT_RELAY_QUALITY_PRESET = "vps_ultra"
VPS_4C_RELAY_QUALITY_PRESET = "vps_ultra"
# YouTube 侧更在意:稳定帧率、不卡顿、足够观看时长;分辨率低于 720p 仍可正常推荐,
# 但 speed<1 的「假 720p」比稳定的 480p/540p 更伤体验与留存。
RELAY_QUALITY_PRESETS: dict[str, dict[str, Any]] = {
"720p": {
"id": "720p",
"label": "720p 标准",
"description": "720×1280 · 30fps · veryfast · 码率跟随设置(默认 2500k)",
"width": 720,
"height": 1280,
"fps": 30,
"x264_preset": "veryfast",
"bitrate_kbps": None,
"audio_bitrate_kbps": 128,
"gop": 60,
"profile": "high",
"level": "4.0",
"x264_threads": 0,
"scale_flags": "bilinear",
"recommended_for_vps": False,
},
"vps_ultra": {
"id": "vps_ultra",
"label": "VPS Ultra(4核专供)",
"description": "480×854 · 24fps · ultrafast · 1500k · 限 2 线程(稳定优先,省 CPU)",
"width": 480,
"height": 854,
"fps": 24,
"x264_preset": "ultrafast",
"bitrate_kbps": 1500,
# YouTube Live Studio warns if audio < 128 Kbps (shows as 0 when under-delivered).
"audio_bitrate_kbps": 128,
"gop": 48,
"profile": "main",
"level": "3.1",
"x264_threads": 2,
"scale_flags": "fast_bilinear",
"recommended_for_vps": True,
},
}
def list_relay_quality_presets(*, active_id: str = "") -> list[dict[str, Any]]:
aid = str(active_id or DEFAULT_RELAY_QUALITY_PRESET).strip() or DEFAULT_RELAY_QUALITY_PRESET
out: list[dict[str, Any]] = []
for pid, row in RELAY_QUALITY_PRESETS.items():
out.append(
{
"id": pid,
"label": row["label"],
"description": row["description"],
"width": row["width"],
"height": row["height"],
"fps": row["fps"],
"x264_preset": row["x264_preset"],
"bitrate_kbps": row.get("bitrate_kbps"),
"audio_bitrate_kbps": row.get("audio_bitrate_kbps"),
"recommended_for_vps": bool(row.get("recommended_for_vps")),
"active": pid == aid,
}
)
return out
def resolve_relay_encoding(cfg: dict[str, Any]) -> dict[str, Any]:
"""Merge DB settings with the selected quality preset."""
preset_id = str(cfg.get("youtube_relay_quality_preset") or DEFAULT_RELAY_QUALITY_PRESET).strip()
if preset_id not in RELAY_QUALITY_PRESETS:
preset_id = DEFAULT_RELAY_QUALITY_PRESET
base = dict(RELAY_QUALITY_PRESETS[preset_id])
bitrate = base.get("bitrate_kbps")
if bitrate is None:
bitrate = int(cfg.get("youtube_relay_bitrate") or 2500)
base["preset_id"] = preset_id
base["bitrate_kbps"] = max(800, min(int(bitrate), 9000))
base["audio_bitrate_kbps"] = max(128, min(int(base.get("audio_bitrate_kbps") or 128), 192))
base["x264_threads"] = max(0, int(base.get("x264_threads") or 0))
return base

View File

@ -79,7 +79,7 @@ def _progress_stalled(samples: list[dict[str, float | int]]) -> bool:
return len(frames) == 1 and len(times) == 1
def _speed_low(samples: list[dict[str, float | int]], threshold: float = 0.98) -> bool:
def _speed_low(samples: list[dict[str, float | int]], threshold: float = 0.90) -> bool:
if len(samples) < 4:
return False
tail = samples[-4:]
@ -88,6 +88,19 @@ def _speed_low(samples: list[dict[str, float | int]], threshold: float = 0.98) -
return int(tail[-1]["frame"]) > int(tail[0]["frame"]) or float(tail[-1]["time"]) > float(tail[0]["time"])
def _speed_healthy(samples: list[dict[str, float | int]], st: dict[str, Any]) -> bool:
if samples:
try:
if float(samples[-1]["speed"]) >= 0.95:
return True
except (TypeError, ValueError, KeyError):
pass
try:
return float(st.get("speed") or 0) >= 0.95
except (TypeError, ValueError):
return False
def split_relay_logs(lines: list[str] | None) -> tuple[str, str]:
out: list[str] = []
err: list[str] = []
@ -107,6 +120,8 @@ def summarize_relay_group(
session_running: bool,
pipeline_enabled: bool,
log_age_seconds: float | None = None,
lane_armed: bool = False,
time_slot_mode: bool = False,
) -> dict[str, Any]:
"""Build process_monitor-style row for one assign group."""
gid = str(group.get("id") or st.get("group_id") or "")
@ -120,14 +135,19 @@ def summarize_relay_group(
if not recent_log_lines and isinstance(st.get("recent_log"), str):
recent_log_lines = [st["recent_log"]]
recent_log, recent_error = split_relay_logs(recent_log_lines)
tail = _norm_log(f"{recent_log}\n{recent_error}")[-8000:].lower()
# FFmpeg progress often uses \r — normalize before matching.
tail = _norm_log(f"{recent_log}\n{recent_error}")[-8000:].lower().replace("\r", "\n")
raw_status = str(st.get("status") or "idle").lower()
armed = bool(lane_armed or pipeline_enabled)
if session_running:
process_status = "online"
elif raw_status in {"waiting", "reconnecting", "starting"} and armed:
# sh2: monitor thread still online while「等待直播」
process_status = "online"
elif not enabled:
process_status = "stopped"
elif has_key and pipeline_enabled:
elif has_key and armed:
process_status = "configured" if raw_status in {"idle", "stopped"} else raw_status
elif has_key:
process_status = "configured"
@ -143,9 +163,11 @@ def summarize_relay_group(
latest = progress_samples[-1] if progress_samples else {}
progress_stalled = _progress_stalled(progress_samples)
speed_low = _speed_low(progress_samples)
has_progress = "frame=" in tail and "speed=" in tail
log_recent = log_age_seconds is None or log_age_seconds <= 20
has_progress = ("frame=" in tail and "speed=" in tail) or bool(progress_samples)
# Poll may be 3–10s; keep heartbeat window generous so UI doesn't flap.
log_recent = log_age_seconds is None or log_age_seconds <= 60
has_worker = bool(pids) or session_running
healthy_speed = _speed_healthy(progress_samples, st)
business_status = "inactive"
business_note = "未运行"
@ -155,42 +177,47 @@ def summarize_relay_group(
elif not enabled:
business_status = "inactive"
business_note = "频道已停用"
elif not featured_urls:
elif not featured_urls and not time_slot_mode:
business_status = "misconfigured"
business_note = "直播地址列表(精选)为空"
elif _looks_like_youtube_key_rejected(tail):
business_status = "youtube_key_rejected"
business_note = "YouTube 拒绝了 RTMPS 推流,请检查直播 KEY 或网络"
elif raw_status == "error" and st.get("error"):
business_status = "error"
business_note = str(st.get("error") or "")[:240]
elif session_running and has_progress and log_recent and progress_stalled:
business_status = "source_stalled"
business_note = "FFmpeg 在运行但帧/时间进度停滞"
elif session_running and has_progress and log_recent and speed_low:
elif session_running and has_progress and log_recent and speed_low and not healthy_speed:
business_status = "relay_slow"
business_note = "推流速度低于实时"
elif session_running and has_progress and log_recent:
elif session_running and (has_progress or healthy_speed) and (log_recent or healthy_speed):
business_status = "streaming"
business_note = "正在推流到 YouTube"
elif session_running and has_worker and log_recent and _has_any(tail, ("opening input", "opening output", "rtmps://")):
elif session_running and has_worker and log_recent and _has_any(tail, ("opening input", "opening output", "rtmps://", "starting ffmpeg", "quality=")):
business_status = "relay_starting"
business_note = "FFmpeg 已启动,等待进度上报"
elif pipeline_enabled and enabled and has_key and not session_running:
if raw_status == "reconnecting":
business_status = "relay_starting"
business_note = "推流中断,正在重连"
elif log_age_seconds is not None and log_age_seconds > 180 and has_worker:
elif session_running:
business_status = "relay_starting"
business_note = "推流进程运行中"
elif raw_status == "waiting" and armed:
# Exact sh2 wording path: offline → keep polling
business_status = "waiting_source"
business_note = str(st.get("error") or "等待直播...").strip() or "等待直播..."
elif raw_status == "starting" and armed:
business_status = "relay_starting"
business_note = str(st.get("error") or "正在启动推流(解析源 / Neko / FFmpeg)").strip()
elif raw_status == "error" and st.get("error") and not armed:
business_status = "error"
business_note = str(st.get("error") or "")[:240]
elif raw_status == "reconnecting" and armed:
business_status = "relay_starting"
business_note = "推流中断,正在重连"
elif armed and enabled and has_key and not session_running:
if log_age_seconds is not None and log_age_seconds > 180 and has_worker:
business_status = "stale"
business_note = "进程在线但日志心跳过期"
else:
live_ids_hint = bool(st.get("source_room_id"))
if live_ids_hint and not session_running:
business_status = "waiting_source"
business_note = "等待可用抖音源或 Worker 调度"
else:
business_status = "monitoring"
business_note = "Worker 运行中,等待推流"
business_status = "monitoring"
business_note = "监听中,等待开播后自动推流"
elif has_key and featured_urls and pipeline_enabled:
business_status = "ready"
business_note = "已配置,等待自动推流"
@ -216,6 +243,14 @@ def summarize_relay_group(
except (TypeError, ValueError):
frame = None
# Never leak live metrics when not actually pushing — UI must stay consistent.
if not is_pushing:
speed = None
frame = None
latest = {}
progress_stalled = False
speed_low = False
return {
"group_id": gid,
"label": group.get("name") or gid,
@ -223,16 +258,16 @@ def summarize_relay_group(
"business_status": business_status,
"business_note": business_note,
"is_pushing": is_pushing,
"ffmpeg_active": has_worker,
"ffmpeg_pids": pids,
"ffmpeg_pid": pids[0] if pids else 0,
"ffmpeg_speed": speed,
"ffmpeg_frame": frame,
"ffmpeg_fps": latest.get("fps"),
"ffmpeg_bitrate_kbps": latest.get("bitrate"),
"ffmpeg_time_seconds": latest.get("time"),
"ffmpeg_progress_stalled": progress_stalled,
"ffmpeg_speed_low": speed_low,
"ffmpeg_active": bool(is_pushing and has_worker),
"ffmpeg_pids": pids if is_pushing else [],
"ffmpeg_pid": (pids[0] if pids and is_pushing else 0),
"ffmpeg_speed": speed if is_pushing else None,
"ffmpeg_frame": frame if is_pushing else None,
"ffmpeg_fps": latest.get("fps") if is_pushing else None,
"ffmpeg_bitrate_kbps": latest.get("bitrate") if is_pushing else None,
"ffmpeg_time_seconds": latest.get("time") if is_pushing else None,
"ffmpeg_progress_stalled": progress_stalled if is_pushing else False,
"ffmpeg_speed_low": speed_low if is_pushing else False,
"log_age_seconds": log_age_seconds,
"recent_log": recent_log,
"recent_error": recent_error,
@ -244,7 +279,7 @@ def summarize_relay_group(
"douyin_count": douyin_count,
"has_stream_key": has_key,
"stream_key_suffix": _key_suffix(group),
"push_seconds": float(st.get("push_seconds") or 0),
"push_seconds": float(st.get("push_seconds") or 0) if is_pushing else 0.0,
"started_at": float(st.get("started_at") or 0),
"updated_at": float(st.get("updated_at") or 0),
}

View File

@ -14,6 +14,7 @@ from typing import Any, Optional
from .db import _connect, _lock, _row_to_dict
from .models import extract_room_id, normalize_room_url
from .config import settings
def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None:
@ -157,17 +158,25 @@ def _lookup_cover_and_anchor(conn: sqlite3.Connection, room_id: str) -> tuple[st
cover = ""
anchor = ""
try:
row = conn.execute(
"""
SELECT cover_path, anchor_name FROM sessions
WHERE room_id = ? AND cover_path IS NOT NULL AND TRIM(cover_path) != ''
ORDER BY started_at DESC LIMIT 1
""",
room = conn.execute(
"SELECT last_anchor, note, avatar_url FROM rooms WHERE room_id = ? LIMIT 1",
(rid,),
).fetchone()
if row:
cover = str(row["cover_path"] or "").strip()
anchor = str(row["anchor_name"] or "").strip()
if room:
anchor = str(room["last_anchor"] or "").strip() or str(room["note"] or "").strip()
cover = str(room["avatar_url"] or "").strip()
if not cover or not anchor:
row = conn.execute(
"""
SELECT cover_path, anchor_name FROM sessions
WHERE room_id = ? AND cover_path IS NOT NULL AND TRIM(cover_path) != ''
ORDER BY started_at DESC LIMIT 1
""",
(rid,),
).fetchone()
if row:
cover = cover or str(row["cover_path"] or "").strip()
anchor = anchor or str(row["anchor_name"] or "").strip()
if not cover or not anchor:
row2 = conn.execute(
"""
@ -180,12 +189,6 @@ def _lookup_cover_and_anchor(conn: sqlite3.Connection, room_id: str) -> tuple[st
if row2:
cover = cover or str(row2["cover_path"] or "").strip()
anchor = anchor or str(row2["anchor_name"] or "").strip()
room = conn.execute(
"SELECT last_anchor FROM rooms WHERE room_id = ? LIMIT 1",
(rid,),
).fetchone()
if room:
anchor = anchor or str(room["last_anchor"] or "").strip()
except Exception:
pass
if cover and not (cover.startswith("http") or cover.startswith("/api/") or cover.startswith("/covers/")):
@ -193,7 +196,12 @@ def _lookup_cover_and_anchor(conn: sqlite3.Connection, room_id: str) -> tuple[st
return cover, anchor
def _enrich_pool_row(conn: sqlite3.Connection, row: dict[str, Any]) -> dict[str, Any]:
def _enrich_pool_row(
conn: sqlite3.Connection,
row: dict[str, Any],
*,
mutate: bool = True,
) -> dict[str, Any]:
from .db import _is_blacklisted_conn
out = dict(row)
@ -208,6 +216,53 @@ def _enrich_pool_row(conn: sqlite3.Connection, row: dict[str, Any]) -> dict[str,
out["cover_url"] = found_cover
if not title and found_anchor:
out["title"] = found_anchor
if mutate:
# Persist so ordinary list stops showing「未命名主播」after refresh.
pool_pk = str(out.get("pool_url_id") or "").strip()
if not pool_pk:
# Pure pool row uses id; featured/slot rows use pool_url_id.
if "pool_url_id" not in row:
pool_pk = str(out.get("id") or "").strip()
try:
if pool_pk:
conn.execute(
"""
UPDATE yt_assign_pool_urls
SET title = ?, updated_at = ?
WHERE id = ? AND TRIM(COALESCE(title, '')) = ''
""",
(found_anchor[:120], time.time(), pool_pk),
)
else:
conn.execute(
"""
UPDATE yt_assign_pool_urls
SET title = ?, updated_at = ?
WHERE room_id = ? AND TRIM(COALESCE(title, '')) = ''
""",
(found_anchor[:120], time.time(), rid),
)
except Exception:
pass
# Backfill: pool URL missing from rooms → push into live pool (overview).
if mutate and rid and str(out.get("url") or "").strip():
try:
exists = conn.execute(
"SELECT 1 AS ok FROM rooms WHERE room_id = ? LIMIT 1",
(rid,),
).fetchone()
if not exists:
from .douyin_ingest import ensure_in_live_pool_conn
ensure_in_live_pool_conn(
conn,
str(out.get("url") or ""),
note=str(out.get("title") or ""),
title=str(out.get("title") or ""),
enabled=True,
)
except Exception:
pass
hit = _is_blacklisted_conn(conn, rid, str(out.get("url") or ""))
out["blacklisted"] = bool(hit)
out["blacklist_reason"] = str((hit or {}).get("reason") or (hit or {}).get("value") or "") if hit else ""
@ -243,7 +298,14 @@ def _beijing_hour_fraction(ts: float | None = None) -> float:
return dt.hour + dt.minute / 60.0 + dt.second / 3600.0
def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: list | None = None, slots: list | None = None) -> dict[str, Any]:
def _public_group(
row: dict[str, Any],
*,
pool: list | None = None,
featured: list | None = None,
slots: list | None = None,
include_secret: bool = True,
) -> dict[str, Any]:
out = dict(row)
out["enabled"] = bool(out.get("enabled"))
out["neko_enabled"] = bool(out.get("neko_enabled"))
@ -252,6 +314,10 @@ def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: li
sk = str(out.get("stream_key") or "")
out["has_stream_key"] = bool(sk.strip())
out["stream_key_masked"] = ("***" + sk[-4:]) if len(sk) > 6 else ("***" if sk else "")
if include_secret:
out["stream_key"] = sk
else:
out.pop("stream_key", None)
if pool is not None:
out["pool"] = pool
if featured is not None:
@ -290,7 +356,16 @@ def _feat_select_sql() -> str:
"""
def list_groups(*, include_urls: bool = True) -> list[dict[str, Any]]:
def list_groups(
*,
include_urls: bool = True,
include_secret: bool = False,
featured_only: bool = False,
) -> list[dict[str, Any]]:
"""List assign groups.
featured_only=True: load featured URLs only (no pool/slots/enrich) — for relay status polls.
"""
with _lock:
conn = _connect()
try:
@ -301,26 +376,46 @@ def list_groups(*, include_urls: bool = True) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for r in rows:
g = _row_to_dict(r) # type: ignore
if not include_urls:
out.append(_public_group(g, pool=[], featured=[], slots=[]))
if not include_urls and not featured_only:
out.append(_public_group(g, pool=[], featured=[], slots=[], include_secret=include_secret))
continue
gid = str(g.get("id") or "")
if featured_only:
feat_rows = conn.execute(_feat_select_sql(), (gid,)).fetchall()
featured = []
for x in feat_rows:
d = _row_to_dict(x) or {}
featured.append(
{
"url": str(d.get("url") or "").strip(),
"room_id": str(d.get("room_id") or "").strip(),
"title": str(d.get("title") or "").strip(),
"blacklisted": False,
}
)
out.append(
_public_group(g, pool=[], featured=featured, slots=[], include_secret=include_secret)
)
continue
pool_rows = conn.execute(
"SELECT * FROM yt_assign_pool_urls WHERE group_id = ? ORDER BY sort_order ASC, created_at ASC",
(gid,),
).fetchall()
pool = [_enrich_pool_row(conn, _row_to_dict(x) or {}) for x in pool_rows]
pool = [_enrich_pool_row(conn, _row_to_dict(x) or {}, mutate=False) for x in pool_rows]
feat_rows = conn.execute(_feat_select_sql(), (gid,)).fetchall()
featured = [_enrich_pool_row(conn, _row_to_dict(x) or {}) for x in feat_rows]
featured = [_enrich_pool_row(conn, _row_to_dict(x) or {}, mutate=False) for x in feat_rows]
slot_rows = conn.execute(_slot_select_sql(), (gid,)).fetchall()
slots = [_enrich_pool_row(conn, _row_to_dict(x) or {}) for x in slot_rows]
out.append(_public_group(g, pool=pool, featured=featured, slots=slots))
slots = [_enrich_pool_row(conn, _row_to_dict(x) or {}, mutate=False) for x in slot_rows]
out.append(
_public_group(g, pool=pool, featured=featured, slots=slots, include_secret=include_secret)
)
# Read path: no commit needed (enrich is non-mutating).
return out
finally:
conn.close()
def get_group(group_id: str) -> dict[str, Any] | None:
def get_group(group_id: str, *, include_secret: bool = True) -> dict[str, Any] | None:
with _lock:
conn = _connect()
try:
@ -345,11 +440,34 @@ def get_group(group_id: str) -> dict[str, Any] | None:
_enrich_pool_row(conn, _row_to_dict(x) or {})
for x in conn.execute(_slot_select_sql(), (gid,)).fetchall()
]
return _public_group(g, pool=pool, featured=featured, slots=slots) # type: ignore
conn.commit()
return _public_group(g, pool=pool, featured=featured, slots=slots, include_secret=include_secret) # type: ignore
finally:
conn.close()
def _sanitize_stream_key(raw: str) -> str:
"""Reject browser-autofilled site login passwords mistaken for YouTube stream keys."""
sk = str(raw or "").strip()
if not sk:
return ""
low = sk.lower()
banned = {
"hackrobot",
"douyinweb",
"xiao4669805@",
"xiao4669805",
str(getattr(settings, "admin_username", "") or "").strip().lower(),
str(getattr(settings, "admin_password", "") or "").strip().lower(),
str(getattr(settings, "neko_user_pass", "") or "").strip().lower(),
str(getattr(settings, "neko_admin_pass", "") or "").strip().lower(),
}
banned = {x for x in banned if x}
if low in banned:
raise ValueError("直播推流 KEY 不能使用站点登录密码;请粘贴 YouTube Studio 的 Stream key(留空可后填)")
return sk
def create_group(
*,
name: str = "",
@ -366,6 +484,7 @@ def create_group(
ch_pk = str(channel_pk or "").strip()
yt_id = str(youtube_channel_id or "").strip()
nm = str(name or "").strip()
stream_key = _sanitize_stream_key(stream_key)
if ch_pk:
ch = db.get_shorts_channel(ch_pk)
if ch:
@ -412,12 +531,35 @@ def create_group(
finally:
conn.close()
group = get_group(gid) or {"id": gid}
neko_sync: dict[str, Any] = {"ok": True, "skipped": True}
try:
from . import youtube_neko
youtube_neko.sync_for_groups(list_groups(include_urls=False))
except Exception:
pass
neko_sync = youtube_neko.sync_for_groups(list_groups(include_urls=False))
if not neko_sync.get("ok"):
db.add_event(
kind="ops",
level="warn",
message=f"Neko 容器创建失败:{neko_sync.get('error', 'unknown')[:160]}",
meta={"group_id": gid, "neko_instance_id": neko_instance_id},
)
except Exception as exc:
neko_sync = {"ok": False, "error": str(exc)[:300]}
try:
db.add_event(
kind="ops",
level="error",
message=f"Neko sync 异常:{str(exc)[:160]}",
meta={"group_id": gid},
)
except Exception:
pass
group["neko_sync"] = {
"ok": bool(neko_sync.get("ok")),
"neko_instance_id": neko_instance_id,
"error": neko_sync.get("error") or "",
"created": neko_sync.get("created"),
}
return group
@ -449,6 +591,8 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
continue
elif k in {"name", "note", "stream_key", "youtube_channel_id", "channel_pk"}:
patch[k] = str(v).strip()
if k == "stream_key":
patch[k] = _sanitize_stream_key(patch[k])
if k == "name":
patch[k] = patch[k][:120]
if k == "note":
@ -656,6 +800,15 @@ def add_pool_urls(
now,
),
)
# Unified live pool (rooms) — overview / monitor / live-map.
try:
from .douyin_ingest import ensure_in_live_pool_conn
ensure_in_live_pool_conn(
conn, url, note=title, title=title, enabled=True
)
except Exception:
pass
created.append({"id": uid, "url": url, "title": title, "cover_url": cover})
existing_keys.add(key)
conn.execute("UPDATE yt_assign_groups SET updated_at = ? WHERE id = ?", (now, group_id))
@ -1309,10 +1462,37 @@ def _rank_douyin_rooms_for_relay(*, limit: int = 40) -> list[dict[str, Any]]:
return ranked[: max(1, limit)]
def build_rotation_schedule(*, include_urls: bool = True) -> dict[str, Any]:
"""24h Beijing rotation: N channels → 24/N hours each, no overlap."""
groups = [g for g in list_groups(include_urls=include_urls) if g.get("enabled")]
n = len(groups)
def _group_has_stream_key(g: dict[str, Any]) -> bool:
if g.get("has_stream_key"):
return True
return bool(str(g.get("stream_key") or "").strip())
def build_rotation_schedule(
*,
include_urls: bool = True,
groups: list[dict[str, Any]] | None = None,
keyed_only: bool | None = None,
) -> dict[str, Any]:
"""24h Beijing rotation: N channels → 24/N hours each, no overlap.
keyed_only=True (时间段模式): only enabled groups that have a YouTube stream key.
"""
if groups is None:
raw = list_groups(include_urls=include_urls)
else:
raw = groups
if keyed_only is None:
try:
from . import db as _db
keyed_only = bool(_db.get_settings_map().get("youtube_relay_time_slot_mode"))
except Exception:
keyed_only = False
enabled = [g for g in raw if g.get("enabled")]
if keyed_only:
enabled = [g for g in enabled if _group_has_stream_key(g)]
n = len(enabled)
now_h = _beijing_hour_fraction()
if n == 0:
return {
@ -1321,11 +1501,13 @@ def build_rotation_schedule(*, include_urls: bool = True) -> dict[str, Any]:
"slot_hours": 0,
"now_hour": round(now_h, 3),
"now_label": _fmt_hour(now_h),
"keyed_only": bool(keyed_only),
"time_slot_mode": bool(keyed_only),
"channels": [],
}
slot_h = 24.0 / n
channels: list[dict[str, Any]] = []
for i, g in enumerate(groups):
for i, g in enumerate(enabled):
start_h = i * slot_h
end_h = (i + 1) * slot_h
active = start_h <= now_h < end_h if end_h <= 24 else (now_h >= start_h or now_h < (end_h % 24))
@ -1352,6 +1534,7 @@ def build_rotation_schedule(*, include_urls: bool = True) -> dict[str, Any]:
"name": g.get("name"),
"channel_pk": g.get("channel_pk"),
"youtube_channel_id": g.get("youtube_channel_id"),
"has_stream_key": _group_has_stream_key(g),
"start_hour": round(start_h, 3),
"end_hour": round(end_h, 3),
"start_label": _fmt_hour(start_h),
@ -1368,6 +1551,8 @@ def build_rotation_schedule(*, include_urls: bool = True) -> dict[str, Any]:
"slot_hours": round(slot_h, 2),
"now_hour": round(now_h, 3),
"now_label": _fmt_hour(now_h),
"keyed_only": bool(keyed_only),
"time_slot_mode": bool(keyed_only),
"channels": channels,
}

View File

@ -17,10 +17,10 @@ from .yt_long_db import YT_LONG_MAX_SEC, YT_LONG_MIN_SEC
def _portrait_vf() -> str:
"""Keep vertical 9:16 (1080x1920 center crop) — same as Shorts/TikTok/X."""
"""Vertical 9:16 at 720x1280 — matches Shorts CPU profile for 4c VPS."""
return (
"scale=1080:1920:force_original_aspect_ratio=increase,"
"crop=1080:1920,setsar=1"
"scale=720:1280:force_original_aspect_ratio=increase,"
"crop=720:1280,setsar=1"
)
@ -115,14 +115,16 @@ async def record_long_clip(
vf,
"-c:v",
"libx264",
"-threads",
"2",
"-preset",
"veryfast",
"ultrafast",
"-crf",
"23",
"26",
"-c:a",
"aac",
"-b:a",
"128k",
"96k",
"-movflags",
"+faststart",
"-avoid_negative_ts",

View File

@ -374,35 +374,38 @@ class YtLongPipeline:
self.last_error = ""
self._last_sample_at = 0.0
self._last_retention_at = 0.0
self._status_cache: dict[str, Any] | None = None
self._status_cache_at = 0.0
def status(self) -> dict[str, Any]:
now = time.time()
cached = self._status_cache
if cached is not None and (now - self._status_cache_at) < 2.0:
return cached
cfg = db.get_settings_map()
day = push_date_from_ts(time.time())
try:
yt_long_db.sync_channels_from_shorts()
except Exception:
pass
try:
yt_long_db.reconcile_yt_long_upload_caps(cfg)
cfg = db.get_settings_map()
except Exception:
pass
day = push_date_from_ts(now)
# Read-only: sync/reconcile/cascade mutations run in worker loop + start().
try:
board = yt_long_db.channel_board(day)
except Exception:
board = {"channels": [], "total_gap": 0, "push_date": day}
cascade_need: dict[str, Any] = {}
try:
from .clip_cascade import estimate_platform_daily_need, ensure_source_covers_platforms
from .clip_cascade import estimate_platform_daily_need
ensure_source_covers_platforms(cfg)
cfg = db.get_settings_map()
cascade_need = estimate_platform_daily_need(cfg)
except Exception:
cascade_need = {}
limited = yt_long_db.youtube_api_upload_limited(cfg)
effective_ch = yt_long_db.effective_yt_long_channel_daily_max(cfg)
return {
try:
from . import douyin_live
live_count = int(douyin_live.build_live_map().get("live_count") or 0)
except Exception:
live_count = 0
payload = {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
"enabled": bool(cfg.get("yt_long_enabled")),
@ -423,7 +426,7 @@ class YtLongPipeline:
"stats": yt_long_db.yt_long_stats(day),
"board": board,
"cascade_need": cascade_need,
"douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)),
"douyin_live_count": live_count,
"settings": {
"yt_long_enabled": bool(cfg.get("yt_long_enabled")),
"yt_long_with_shorts": bool(cfg.get("yt_long_with_shorts", True)),
@ -452,10 +455,68 @@ class YtLongPipeline:
"clips_min_free_gb": float(cfg.get("clips_min_free_gb") or 12),
},
}
self._status_cache = payload
self._status_cache_at = time.time()
return payload
def status_light(self) -> dict[str, Any]:
"""Poll-friendly counters without full board/settings blob."""
now = time.time()
cached = getattr(self, "_status_light_cache", None)
cache_at = float(getattr(self, "_status_light_cache_at", 0) or 0)
if cached is not None and (now - cache_at) < 1.5:
return cached
cfg = db.get_settings_map()
day = push_date_from_ts(now)
limited = yt_long_db.youtube_api_upload_limited(cfg)
effective_ch = yt_long_db.effective_yt_long_channel_daily_max(cfg)
try:
from . import douyin_live
live_count = int(douyin_live.build_live_map().get("live_count") or 0)
except Exception:
live_count = 0
payload = {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
"enabled": bool(cfg.get("yt_long_enabled")),
"processed": self.processed,
"sampled": self.sampled,
"quota_gap": yt_long_db.yt_long_upload_gap(day, cfg),
"quota_used": yt_long_db.yt_long_upload_used(day),
"upload_gap": yt_long_db.yt_long_upload_gap(day, cfg),
"upload_used": yt_long_db.yt_long_upload_used(day),
"source_gap": yt_long_db.yt_long_source_gap(day, cfg),
"source_used": yt_long_db.yt_long_source_used(day),
"api_quota_limited": limited,
"last_error": self.last_error,
"stats": yt_long_db.yt_long_stats(day),
"douyin_live_count": live_count,
"light": True,
}
full = self._status_cache
full_at = float(self._status_cache_at or 0)
if isinstance(full, dict) and (now - full_at) < 60:
for key in ("board", "cascade_need", "settings"):
if key in full:
payload[key] = full[key]
self._status_light_cache = payload
self._status_light_cache_at = time.time()
return payload
async def start(self) -> None:
if self._task and not self._task.done():
return
try:
cfg = db.get_settings_map()
yt_long_db.sync_channels_from_shorts()
yt_long_db.reconcile_yt_long_upload_caps(cfg)
from .clip_cascade import ensure_source_covers_platforms
ensure_source_covers_platforms(cfg)
except Exception:
pass
self._stop.clear()
self._task = asyncio.create_task(self._loop(), name="yt-long-pipeline")
@ -601,7 +662,7 @@ class YtLongPipeline:
asyncio.create_task(self._run_upload(job))
except Exception as exc:
self.last_error = str(exc)[:240]
await asyncio.sleep(3.0)
await asyncio.sleep(5.0)
async def _run_record(self, job: dict[str, Any]) -> None:
try:

View File

@ -0,0 +1,51 @@
from __future__ import annotations
from app.youtube_relay import build_ffmpeg_relay_cmd
from app.youtube_relay_presets import (
DEFAULT_RELAY_QUALITY_PRESET,
VPS_4C_RELAY_QUALITY_PRESET,
resolve_relay_encoding,
)
def test_default_preset_is_720p():
enc = resolve_relay_encoding({})
assert enc["preset_id"] == DEFAULT_RELAY_QUALITY_PRESET
assert enc["width"] == 720
assert enc["height"] == 1280
assert enc["fps"] == 30
assert enc["x264_preset"] == "veryfast"
def test_vps_ultra_preset_low_cpu():
enc = resolve_relay_encoding({"youtube_relay_quality_preset": VPS_4C_RELAY_QUALITY_PRESET})
assert enc["preset_id"] == "vps_ultra"
assert enc["width"] == 480
assert enc["height"] == 854
assert enc["fps"] == 24
assert enc["x264_preset"] == "ultrafast"
assert enc["bitrate_kbps"] == 1500
assert enc["x264_threads"] == 2
def test_ffmpeg_cmd_uses_preset_params():
cmd = build_ffmpeg_relay_cmd(
"http://example.com/a.flv",
"rtmps://a.rtmps.youtube.com/live2/key",
bitrate_kbps=1500,
width=480,
height=854,
fps=24,
x264_preset="ultrafast",
gop=48,
profile="main",
level="3.1",
audio_bitrate_kbps=96,
x264_threads=2,
scale_flags="fast_bilinear",
)
joined = " ".join(cmd)
assert "ultrafast" in joined
assert "-threads 2" in joined
assert "96k" in joined
assert "fps=24,scale=480:854" in joined

View File

@ -31,6 +31,11 @@ export function DouyinLiveBadge({
overlay = false,
showOffline = false,
}: Props) {
const rid = String(roomId || "").trim();
if (rid.startsWith("shorts:") || rid.startsWith("yt:")) {
return null;
}
const fromMap = useDouyinLiveEntry(roomId, entry ?? undefined);
const live = fromMap;
const { status, isLive } = resolveDouyinLive(live, lastStatus);

View File

@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { Loader2, Plus, Trash2 } from "lucide-react";
import { useConfirm } from "@/components/ConfirmDialog";

View File

@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { Loader2, Save, ShieldOff } from "lucide-react";
import { Shell } from "@/components/Shell";
@ -69,6 +69,7 @@ export default function SettingsPage() {
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_ntfy_on_douyin_live = Boolean(settings.notify_ntfy_on_douyin_live);
body.notify_on_risk = Boolean(settings.notify_on_risk);
body.notify_on_shorts_fail = settings.notify_on_shorts_fail !== false;
body.notify_on_shorts_ok = Boolean(settings.notify_on_shorts_ok);
@ -558,6 +559,7 @@ export default function SettingsPage() {
{[
["notify_on_live", "开播通知"],
["notify_on_offline", "停播通知"],
["notify_ntfy_on_douyin_live", "抖音直播 ntfy"],
["notify_on_risk", "风控通知"],
["notify_on_shorts_fail", "Shorts 失败"],
["notify_on_shorts_ok", "Shorts 成功"],

View File

@ -185,7 +185,7 @@ export default function AnchorsPage() {
<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>
<p className="text-sm text-slate-400">抖音直播主播汇总:场次、时长、开播作息与预计下次开播(不含 YouTube / Shorts)。</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" />}

View File

@ -3,7 +3,7 @@ import "./globals.css";
import { Providers } from "@/components/Providers";
export const metadata: Metadata = {
title: "直播监控中心",
title: "直播工作台",
description: "抖音 + YouTube 开播/停播/时长/截图监控与 Shorts、TikTok 分发",
applicationName: "LiveRadar",
manifest: "/manifest.webmanifest",

View File

@ -47,8 +47,18 @@ export default function OpsMobilePage() {
useEffect(() => {
void load();
const t = setInterval(() => void load(), 30000);
return () => clearInterval(t);
const t = setInterval(() => {
if (document.hidden) return;
void load();
}, 30000);
const onVis = () => {
if (!document.hidden) void load();
};
document.addEventListener("visibilitychange", onVis);
return () => {
clearInterval(t);
document.removeEventListener("visibilitychange", onVis);
};
}, [load]);
return (

View File

@ -4,19 +4,14 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Activity,
Bell,
BarChart3,
ExternalLink,
Eye,
Globe2,
Loader2,
MousePointerClick,
Radar,
RefreshCw,
Server,
ShieldCheck,
Users,
Wifi,
X,
} from "lucide-react";
import { Shell } from "@/components/Shell";
@ -49,46 +44,6 @@ type ServiceRow = {
ok: boolean;
};
type OverviewSite = {
domain: string;
role: string;
website_id: string;
ok: boolean;
active: number;
pageviews: number;
visitors: number;
visits: number;
bounces: number;
};
type AnalyticsDetail = {
domain?: string;
website_id?: string;
range?: string;
ok?: boolean;
active?: number;
stats?: {
pageviews?: number;
visitors?: number;
visits?: number;
bounces?: number;
bounce_rate?: number;
avg_visit_sec?: number;
totaltime?: number;
};
series?: { x: string; y: number }[];
top_paths?: { name: string; value: number }[];
top_referrers?: { name: string; value: number }[];
top_countries?: { name: string; value: number }[];
top_devices?: { name: string; value: number }[];
top_browsers?: { name: string; value: number }[];
top_os?: { name: string; value: number }[];
top_languages?: { name: string; value: number }[];
top_cities?: { name: string; value: number }[];
top_titles?: { name: string; value: number }[];
umami_url?: string;
};
type OpsSnapshot = {
generated_at?: number;
server_ip?: string;
@ -114,13 +69,6 @@ type OpsSnapshot = {
paths?: Record<string, string>;
};
const RANGES = [
{ id: "24h", label: "24小时" },
{ id: "7d", label: "7天" },
{ id: "30d", label: "30天" },
{ id: "90d", label: "90天" },
];
function StatusDot({ ok }: { ok?: boolean | null }) {
const color =
ok === true ? "bg-teal-400 shadow-[0_0_10px_rgba(45,212,191,0.55)]" : ok === false ? "bg-rose-400" : "bg-slate-500";
@ -139,243 +87,10 @@ function ProbeText({ p }: { p?: Probe }) {
return <span className="text-slate-500">n/a</span>;
}
function fmtNum(n?: number) {
const v = Number(n || 0);
if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`;
if (v >= 1_000) return `${(v / 1_000).toFixed(1)}k`;
return String(v);
}
function fmtDuration(sec?: number) {
const s = Math.max(0, Math.round(Number(sec || 0)));
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
const r = s % 60;
return `${m}m ${r}s`;
}
function Sparkline({ series }: { series?: { x: string; y: number }[] }) {
const pts = series || [];
if (pts.length < 2) {
return <div className="flex h-16 items-center text-xs text-slate-500">暂无趋势数据(站点刚接入时常见)</div>;
}
const ys = pts.map((p) => Number(p.y || 0));
const max = Math.max(...ys, 1);
const min = Math.min(...ys, 0);
const w = 320;
const h = 64;
const path = pts
.map((p, i) => {
const x = (i / (pts.length - 1)) * w;
const y = h - ((Number(p.y || 0) - min) / (max - min || 1)) * (h - 4) - 2;
return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
})
.join(" ");
return (
<svg viewBox={`0 0 ${w} ${h}`} className="h-16 w-full overflow-visible">
<path d={path} fill="none" stroke="rgba(45,212,191,0.9)" strokeWidth="2" />
</svg>
);
}
function MetricList({ title, rows }: { title: string; rows?: { name: string; value: number }[] }) {
const list = rows || [];
const max = Math.max(...list.map((r) => Number(r.value || 0)), 1);
return (
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-2 text-xs font-medium text-slate-300">{title}</div>
{!list.length && <div className="text-xs text-slate-500">暂无数据</div>}
<ul className="space-y-2">
{list.map((r) => (
<li key={`${title}-${r.name}`}>
<div className="mb-0.5 flex justify-between gap-2 text-[11px]">
<span className="truncate text-slate-200">{r.name || "(direct)"}</span>
<span className="shrink-0 text-slate-400">{fmtNum(r.value)}</span>
</div>
<div className="h-1 overflow-hidden rounded bg-white/5">
<div className="h-full rounded bg-gradient-to-r from-teal-400/80 to-sky-400/70" style={{ width: `${(Number(r.value) / max) * 100}%` }} />
</div>
</li>
))}
</ul>
</div>
);
}
function SiteDetailBody({
detail,
loading,
}: {
detail: AnalyticsDetail | null;
loading?: boolean;
}) {
const st = detail?.stats;
if (loading && !detail) {
return (
<div className="flex items-center justify-center gap-2 py-16 text-sm text-slate-400">
<Loader2 className="h-4 w-4 animate-spin" /> 加载访客详情…
</div>
);
}
if (!detail) {
return <div className="py-12 text-center text-sm text-slate-500">暂无该站点数据</div>;
}
return (
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
{[
{ label: "浏览量 PV", value: fmtNum(st?.pageviews), icon: Eye },
{ label: "独立访客", value: fmtNum(st?.visitors), icon: Users },
{ label: "访问次数", value: fmtNum(st?.visits), icon: MousePointerClick },
{ label: "跳出率", value: `${st?.bounce_rate ?? 0}%`, icon: Activity },
{ label: "平均停留", value: fmtDuration(st?.avg_visit_sec), icon: Radar },
].map((card) => (
<div key={card.label} className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="flex items-center gap-1.5 text-[11px] text-slate-400">
<card.icon className="h-3.5 w-3.5 text-teal-300" />
{card.label}
</div>
<div className="mt-1 text-xl font-semibold text-white">{card.value}</div>
</div>
))}
</div>
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-1 flex items-center justify-between text-xs text-slate-400">
<span>浏览量趋势</span>
<span className="text-teal-300">当前在线 {detail.active ?? 0}</span>
</div>
<Sparkline series={detail.series} />
</div>
<div className="grid gap-3 lg:grid-cols-2">
<MetricList title="热门页面" rows={detail.top_paths} />
<MetricList title="页面标题" rows={detail.top_titles} />
<MetricList title="来源 Referrer" rows={detail.top_referrers} />
<MetricList title="国家 / 地区" rows={detail.top_countries} />
<MetricList title="城市" rows={detail.top_cities} />
<MetricList title="语言" rows={detail.top_languages} />
<MetricList title="设备" rows={detail.top_devices} />
<MetricList title="操作系统" rows={detail.top_os} />
<MetricList title="浏览器" rows={detail.top_browsers} />
</div>
</div>
);
}
function SiteDetailModal({
open,
domain,
role,
range,
detail,
loading,
onClose,
onRange,
umamiUrl,
}: {
open: boolean;
domain: string;
role?: string;
range: string;
detail: AnalyticsDetail | null;
loading?: boolean;
onClose: () => void;
onRange: (id: string) => void;
umamiUrl?: string;
}) {
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
window.removeEventListener("keydown", onKey);
document.body.style.overflow = prev;
};
}, [open, onClose]);
if (!open) return null;
return (
<div
className="fixed inset-0 z-[80] flex items-end justify-center bg-black/70 p-0 backdrop-blur-sm sm:items-center sm:p-4"
onClick={onClose}
role="presentation"
>
<div
role="dialog"
aria-modal="true"
aria-label={`${domain} 访客详情`}
className="flex max-h-[92vh] w-full max-w-5xl flex-col overflow-hidden rounded-t-3xl border border-white/10 bg-[#0b1220] shadow-2xl sm:rounded-3xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex flex-wrap items-start justify-between gap-3 border-b border-white/10 px-4 py-3 sm:px-5">
<div className="min-w-0">
<div className="text-[11px] uppercase tracking-[0.16em] text-teal-200/70">站点访客详情</div>
<h2 className="truncate text-lg font-semibold text-white">{domain}</h2>
{role ? <p className="mt-0.5 text-[11px] text-slate-500">{role}</p> : null}
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap gap-1">
{RANGES.map((r) => (
<button
key={r.id}
type="button"
onClick={() => onRange(r.id)}
className={`rounded-lg px-2.5 py-1 text-[11px] ${
range === r.id ? "bg-sky-400/20 text-sky-200" : "bg-white/5 text-slate-400"
}`}
>
{r.label}
</button>
))}
</div>
<a
href={umamiUrl || "https://umami.nomadro.com"}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-200"
>
Umami <ExternalLink className="h-3 w-3" />
</a>
<button
type="button"
onClick={onClose}
className="rounded-lg border border-white/10 bg-white/5 p-1.5 text-slate-300 hover:bg-white/10"
aria-label="关闭"
>
<X className="h-4 w-4" />
</button>
</div>
</div>
<div className="relative flex-1 overflow-y-auto p-4 sm:p-5">
{loading ? (
<div className="pointer-events-none absolute right-4 top-3 inline-flex items-center gap-1 rounded-full bg-black/50 px-2 py-0.5 text-[10px] text-slate-300">
<Loader2 className="h-3 w-3 animate-spin" /> 刷新中
</div>
) : null}
<SiteDetailBody detail={detail} loading={loading} />
</div>
</div>
</div>
);
}
export default function OpsPage() {
const toast = useToast();
const now = useNow(1000);
const [tab, setTab] = useState<"analytics" | "monitor">("analytics");
const [data, setData] = useState<OpsSnapshot | null>(null);
const [overview, setOverview] = useState<OverviewSite[]>([]);
const [detail, setDetail] = useState<AnalyticsDetail | null>(null);
const [domain, setDomain] = useState("dylive.nomadro.com");
const [modalOpen, setModalOpen] = useState(false);
const [modalLoading, setModalLoading] = useState(false);
const [range, setRange] = useState("7d");
const [loading, setLoading] = useState(true);
const [syncing, setSyncing] = useState(false);
const [live, setLive] = useState(true);
@ -387,14 +102,6 @@ export default function OpsPage() {
const [priority, setPriority] = useState("default");
const [pageVisible, setPageVisible] = useState(true);
const inFlight = useRef(false);
const domainRef = useRef(domain);
const rangeRef = useRef(range);
const tabRef = useRef(tab);
const modalOpenRef = useRef(modalOpen);
domainRef.current = domain;
rangeRef.current = range;
tabRef.current = tab;
modalOpenRef.current = modalOpen;
useEffect(() => {
const onVis = () => setPageVisible(document.visibilityState === "visible");
@ -403,113 +110,45 @@ export default function OpsPage() {
return () => document.removeEventListener("visibilitychange", onVis);
}, []);
const loadSilent = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (inFlight.current) return;
inFlight.current = true;
if (!silent) setLoading(true);
else setSyncing(true);
try {
const tasks: Promise<void>[] = [];
tasks.push(
(async () => {
const ov = await fetchJson(`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}`);
setOverview(ov?.sites || []);
// Only pull heavy site detail while modal is open (or first paint needs it)
if (modalOpenRef.current && domainRef.current) {
setModalLoading(true);
try {
const d = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}&domain=${encodeURIComponent(domainRef.current)}`
);
setDetail(d);
} finally {
setModalLoading(false);
}
}
})()
);
tasks.push(
(async () => {
const r = await fetchJson("/api/ops");
setData(r);
})()
);
await Promise.all(tasks);
setLastOkAt(Date.now());
setLastErr("");
setLive(true);
} catch (e) {
setLive(false);
setLastErr((e as Error).message || "同步失败");
if (!silent) toast.push((e as Error).message, "err");
} finally {
inFlight.current = false;
setLoading(false);
setSyncing(false);
}
}, [toast]);
const openSiteModal = useCallback(
async (d: string) => {
setDomain(d);
setModalOpen(true);
setModalLoading(true);
const loadSilent = useCallback(
async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (inFlight.current) return;
inFlight.current = true;
if (!silent) setLoading(true);
else setSyncing(true);
try {
const detailRes = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}&domain=${encodeURIComponent(d)}`
);
setDetail(detailRes);
const r = await fetchJson("/api/ops");
setData(r);
setLastOkAt(Date.now());
setLastErr("");
setLive(true);
} catch (e) {
toast.push((e as Error).message || "加载详情失败", "err");
setLive(false);
setLastErr((e as Error).message || "同步失败");
if (!silent) toast.push((e as Error).message, "err");
} finally {
setModalLoading(false);
inFlight.current = false;
setLoading(false);
setSyncing(false);
}
},
[toast]
);
const closeSiteModal = useCallback(() => setModalOpen(false), []);
const onModalRange = useCallback(
async (id: string) => {
setRange(id);
if (!domainRef.current) return;
setModalLoading(true);
try {
const detailRes = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(id)}&domain=${encodeURIComponent(domainRef.current)}`
);
setDetail(detailRes);
} catch (e) {
toast.push((e as Error).message || "切换时间失败", "err");
} finally {
setModalLoading(false);
}
},
[toast]
);
// Poll server continuously while page is visible (no manual refresh required).
useAutoRefresh(loadSilent, {
intervalMs: tab === "analytics" ? 10000 : 12000,
intervalMs: 20000,
eventKinds: false,
enabled: pageVisible,
});
// When domain/range/tab changes, pull immediately (silent).
useEffect(() => {
if (!pageVisible) return;
void loadSilent({ silent: true });
}, [domain, range, tab, pageVisible, loadSilent]);
}, [pageVisible, loadSilent]);
const dnsOkCount = useMemo(() => (data?.sites || []).filter((s) => s.dns_ok).length, [data]);
const svcOkCount = useMemo(() => (data?.services || []).filter((s) => s.ok).length, [data]);
const modalRole = useMemo(
() => overview.find((s) => s.domain === domain)?.role || data?.sites?.find((s) => s.domain === domain)?.role,
[overview, data, domain]
);
const agoSec = lastOkAt ? Math.max(0, Math.floor((now - lastOkAt) / 1000)) : null;
async function sendNtfy() {
@ -546,10 +185,10 @@ export default function OpsPage() {
<div className="rounded-3xl border border-white/10 bg-black/30 p-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<div className="text-[11px] uppercase tracking-[0.18em] text-teal-200/70">Analytics + Ops</div>
<h1 className="font-display text-2xl font-semibold text-white">访问数据与运维</h1>
<div className="text-[11px] uppercase tracking-[0.18em] text-teal-200/70">Ops</div>
<h1 className="font-display text-2xl font-semibold text-white">监控 / DNS / ntfy</h1>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
页面打开时自动与服务器同步(访问数据约 10s、监控约 12s),无需手动刷新。切换标签页离开时暂停轮询。
页面打开时自动与服务器同步(约 12s)。站点访问数据已移至「Web」。
</p>
<div className="mt-2 flex flex-wrap items-center gap-2 text-[11px]">
<span
@ -583,265 +222,165 @@ export default function OpsPage() {
rel="noreferrer"
className="inline-flex items-center gap-1.5 rounded-xl bg-gradient-to-br from-teal-400 to-sky-500 px-3 py-2 text-xs font-semibold text-[#0b1220]"
>
打开 Umami 完整后台 <ExternalLink className="h-3.5 w-3.5" />
打开 Umami <ExternalLink className="h-3.5 w-3.5" />
</a>
</div>
</div>
</div>
<div className="mt-4 flex flex-wrap gap-2">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Radar className="h-3.5 w-3.5 text-teal-300" /> Umami
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.umami?.heartbeat?.ok} />
<ProbeText p={data?.umami?.heartbeat} />
</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Bell className="h-3.5 w-3.5 text-amber-300" /> ntfy
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.ntfy?.health?.ok} />
<ProbeText p={data?.ntfy?.health} />
</div>
<div className="mt-1 text-[11px] text-slate-500">topic {data?.ntfy?.topic}</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<ShieldCheck className="h-3.5 w-3.5 text-sky-300" /> DNS / 服务
</div>
<div className="mt-1 text-sm text-white">
DNS {dnsOkCount}/{data?.sites?.length ?? 0} · 服务 {svcOkCount}/{data?.services?.length ?? 0}
</div>
<button
type="button"
onClick={() => setTab("analytics")}
className={`rounded-xl px-3 py-1.5 text-xs ${tab === "analytics" ? "bg-teal-400/20 text-teal-200 ring-1 ring-teal-300/30" : "bg-white/5 text-slate-400"}`}
disabled={!!busy}
onClick={() => void runHealth()}
className="mt-2 inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-200"
>
<BarChart3 className="mr-1 inline h-3.5 w-3.5" />
访问数据
</button>
<button
type="button"
onClick={() => setTab("monitor")}
className={`rounded-xl px-3 py-1.5 text-xs ${tab === "monitor" ? "bg-amber-400/20 text-amber-100 ring-1 ring-amber-300/30" : "bg-white/5 text-slate-400"}`}
>
<ShieldCheck className="mr-1 inline h-3.5 w-3.5" />
监控 / DNS / ntfy
{busy === "health" ? <Loader2 className="h-3 w-3 animate-spin" /> : <Activity className="h-3 w-3" />}
跑健康检查
</button>
</div>
</div>
{tab === "analytics" && (
<>
<div className="grid gap-5 lg:grid-cols-5">
<div className="space-y-5 lg:col-span-3">
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<div className="text-sm font-medium text-white">各站点概览</div>
<div className="text-[11px] text-slate-500">点击卡片弹出访客详情(页面 / 来源 / 地区 / 设备等)</div>
</div>
<div className="flex flex-wrap gap-1.5">
{RANGES.map((r) => (
<button
key={r.id}
type="button"
onClick={() => setRange(r.id)}
className={`rounded-lg px-2.5 py-1 text-[11px] ${range === r.id ? "bg-sky-400/20 text-sky-200" : "bg-white/5 text-slate-400"}`}
>
{r.label}
</button>
))}
</div>
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Globe2 className="h-4 w-4 text-sky-300" />
域名 · DNS · 探测
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{overview.map((s) => (
<button
key={s.domain}
type="button"
onClick={() => void openSiteModal(s.domain)}
className="group rounded-2xl border border-white/10 bg-white/[0.03] p-3 text-left transition hover:border-teal-300/40 hover:bg-teal-400/10"
>
<div className="flex items-center justify-between gap-2">
<div className="truncate text-sm font-medium text-white">{s.domain}</div>
<span className="text-[10px] text-teal-300">在线 {s.active}</span>
</div>
<div className="mt-0.5 flex items-center justify-between gap-2">
<div className="truncate text-[11px] text-slate-500">{s.role}</div>
<div className="shrink-0 text-[10px] text-sky-300/80 opacity-0 transition group-hover:opacity-100">
查看详情 →
</div>
</div>
<div className="mt-3 grid grid-cols-3 gap-2 text-center">
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.pageviews)}</div>
<div className="text-[10px] text-slate-500">浏览量</div>
</div>
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.visitors)}</div>
<div className="text-[10px] text-slate-500">访客</div>
</div>
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.visits)}</div>
<div className="text-[10px] text-slate-500">访问</div>
</div>
</div>
</button>
))}
{!overview.length && (
<div className="col-span-full py-8 text-center text-sm text-slate-500">
{loading ? "加载访问数据…" : "暂无概览(确认 Umami 已采集到流量)"}
</div>
)}
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-left text-xs">
<thead className="text-slate-500">
<tr className="border-b border-white/10">
<th className="py-2 pr-2 font-medium">域名</th>
<th className="py-2 pr-2 font-medium">DNS</th>
<th className="py-2 pr-2 font-medium">健康</th>
<th className="py-2 font-medium">Umami ID</th>
</tr>
</thead>
<tbody>
{(data?.sites || []).map((s) => (
<tr key={s.domain} className="border-b border-white/5 align-top">
<td className="py-2.5 pr-2">
<div className="font-medium text-sky-200">{s.domain}</div>
<div className="mt-0.5 text-[11px] text-slate-500">{s.role}</div>
</td>
<td className="py-2.5 pr-2">
<div className="flex items-center gap-1.5">
<StatusDot ok={s.dns_ok} />
<span className={s.dns_ok ? "text-teal-300" : "text-rose-300"}>
{(s.ips || []).join(", ") || "—"}
</span>
</div>
</td>
<td className="py-2.5 pr-2">
<ProbeText p={s.health} />
</td>
<td className="py-2.5 font-mono text-[10px] text-slate-400">{s.umami_website_id || "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
<SiteDetailModal
open={modalOpen}
domain={domain}
role={modalRole}
range={range}
detail={detail?.domain === domain ? detail : detail}
loading={modalLoading}
onClose={closeSiteModal}
onRange={(id) => void onModalRange(id)}
umamiUrl={detail?.umami_url || data?.umami?.url}
/>
</>
)}
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Server className="h-4 w-4 text-amber-300" />
systemd 服务
</div>
<div className="grid gap-2 sm:grid-cols-2">
{(data?.services || []).map((s) => (
<div
key={s.unit}
className="flex items-center justify-between rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2"
>
<div>
<div className="text-sm text-slate-100">{s.label}</div>
<div className="font-mono text-[10px] text-slate-500">{s.unit}</div>
</div>
<div className="flex items-center gap-2 text-xs">
<StatusDot ok={s.ok} />
<span className={s.ok ? "text-teal-300" : "text-rose-300"}>{s.state}</span>
</div>
</div>
))}
</div>
</section>
</div>
{tab === "monitor" && (
<>
<div className="grid gap-3 sm:grid-cols-3">
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Radar className="h-3.5 w-3.5 text-teal-300" /> Umami
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.umami?.heartbeat?.ok} />
<ProbeText p={data?.umami?.heartbeat} />
</div>
<div className="space-y-5 lg:col-span-2">
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Bell className="h-4 w-4 text-amber-300" />
发送 ntfy
</div>
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Bell className="h-3.5 w-3.5 text-amber-300" /> ntfy
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.ntfy?.health?.ok} />
<ProbeText p={data?.ntfy?.health} />
</div>
<div className="mt-1 text-[11px] text-slate-500">topic {data?.ntfy?.topic}</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<ShieldCheck className="h-3.5 w-3.5 text-sky-300" /> DNS / 服务
</div>
<div className="mt-1 text-sm text-white">
DNS {dnsOkCount}/{data?.sites?.length ?? 0} · 服务 {svcOkCount}/{data?.services?.length ?? 0}
</div>
<div className="space-y-2">
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none"
placeholder="标题"
/>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={4}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none"
/>
<select
value={priority}
onChange={(e) => setPriority(e.target.value)}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
>
<option value="min">min</option>
<option value="low">low</option>
<option value="default">default</option>
<option value="high">high</option>
<option value="max">max</option>
</select>
<button
type="button"
disabled={!!busy}
onClick={() => void runHealth()}
className="mt-2 inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-200"
disabled={!!busy || !data?.ntfy?.configured}
onClick={() => void sendNtfy()}
className="inline-flex w-full items-center justify-center gap-1.5 rounded-xl bg-gradient-to-br from-amber-300 to-orange-500 px-3 py-2.5 text-sm font-semibold text-[#1a1208] disabled:opacity-50"
>
{busy === "health" ? <Loader2 className="h-3 w-3 animate-spin" /> : <Activity className="h-3 w-3" />}
跑健康检查
{busy === "ntfy" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bell className="h-4 w-4" />}
推送到 {data?.ntfy?.topic || "dylive"}
</button>
</div>
</div>
<div className="grid gap-5 lg:grid-cols-5">
<div className="space-y-5 lg:col-span-3">
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Globe2 className="h-4 w-4 text-sky-300" />
域名 · DNS · 探测
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-left text-xs">
<thead className="text-slate-500">
<tr className="border-b border-white/10">
<th className="py-2 pr-2 font-medium">域名</th>
<th className="py-2 pr-2 font-medium">DNS</th>
<th className="py-2 pr-2 font-medium">健康</th>
<th className="py-2 font-medium">Umami ID</th>
</tr>
</thead>
<tbody>
{(data?.sites || []).map((s) => (
<tr key={s.domain} className="border-b border-white/5 align-top">
<td className="py-2.5 pr-2">
<div className="font-medium text-sky-200">{s.domain}</div>
<div className="mt-0.5 text-[11px] text-slate-500">{s.role}</div>
</td>
<td className="py-2.5 pr-2">
<div className="flex items-center gap-1.5">
<StatusDot ok={s.dns_ok} />
<span className={s.dns_ok ? "text-teal-300" : "text-rose-300"}>
{(s.ips || []).join(", ") || "—"}
</span>
</div>
</td>
<td className="py-2.5 pr-2">
<ProbeText p={s.health} />
</td>
<td className="py-2.5 font-mono text-[10px] text-slate-400">{s.umami_website_id || "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Server className="h-4 w-4 text-amber-300" />
systemd 服务
</div>
<div className="grid gap-2 sm:grid-cols-2">
{(data?.services || []).map((s) => (
<div
key={s.unit}
className="flex items-center justify-between rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2"
>
<div>
<div className="text-sm text-slate-100">{s.label}</div>
<div className="font-mono text-[10px] text-slate-500">{s.unit}</div>
</div>
<div className="flex items-center gap-2 text-xs">
<StatusDot ok={s.ok} />
<span className={s.ok ? "text-teal-300" : "text-rose-300"}>{s.state}</span>
</div>
</div>
))}
</div>
</section>
<div className="mt-3 text-[11px] text-slate-500">
主机 {data?.host} · {data?.generated_at ? fmtTs(data.generated_at) : ""}
</div>
<div className="space-y-5 lg:col-span-2">
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Bell className="h-4 w-4 text-amber-300" />
发送 ntfy
</div>
<div className="space-y-2">
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none"
placeholder="标题"
/>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={4}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none"
/>
<select
value={priority}
onChange={(e) => setPriority(e.target.value)}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
>
<option value="min">min</option>
<option value="low">low</option>
<option value="default">default</option>
<option value="high">high</option>
<option value="max">max</option>
</select>
<button
type="button"
disabled={!!busy || !data?.ntfy?.configured}
onClick={() => void sendNtfy()}
className="inline-flex w-full items-center justify-center gap-1.5 rounded-xl bg-gradient-to-br from-amber-300 to-orange-500 px-3 py-2.5 text-sm font-semibold text-[#1a1208] disabled:opacity-50"
>
{busy === "ntfy" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bell className="h-4 w-4" />}
推送到 {data?.ntfy?.topic || "server-alerts"}
</button>
</div>
<div className="mt-3 text-[11px] text-slate-500">
主机 {data?.host} · {data?.generated_at ? fmtTs(data.generated_at) : ""}
</div>
</section>
</div>
</div>
</>
)}
</section>
</div>
</div>
</div>
</Shell>
);

View File

@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { Loader2, RefreshCw, ArrowRight, ShieldOff } from "lucide-react";
@ -112,6 +112,7 @@ export default function HomePage() {
const confirm = useConfirm();
const now = useNow(1000);
const { connected, last, tick } = useEventStream(true);
const silentTickRef = useRef(0);
const ytLiveCount = useYouTubeLiveCount();
const load = useCallback(async (opts?: RefreshOpts) => {
@ -122,6 +123,45 @@ export default function HomePage() {
}
try {
const iso = todayBeijingISO();
if (silent) {
silentTickRef.current += 1;
const everyThird = silentTickRef.current % 3 === 0;
// Silent poll: skip fat rooms/day-sessions/stats; SSE feeds events when connected.
const reqs: Promise<unknown>[] = [
fetchJson("/api/monitor/status?light=1"),
fetchJson("/api/sessions/active?platform=douyin"),
];
if (!connected) {
reqs.push(fetchJson("/api/events?limit=20&platform=douyin"));
}
if (everyThird) {
reqs.push(fetchJson("/api/anchors/upcoming?limit=12"));
}
const results = await Promise.all(reqs);
let i = 0;
const m = results[i++] as MonitorStatus;
setStatus((prev) => ({ ...(prev || {}), ...m } as MonitorStatus));
const a = results[i++] as { sessions?: ActiveSession[] };
if (!connected) {
const e = results[i++] as { events?: EventItem[] };
setEvents(e.events || []);
}
if (everyThird) {
const up = results[i++] as { items?: UpcomingItem[] };
setUpcoming(up.items || []);
}
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;
}),
);
return;
}
const [s, ytS, m, yt, r, e, a, daySessions, up] = await Promise.all([
fetchJson("/api/sessions/stats?platform=douyin&top_anchors=25"),
fetchJson("/api/sessions/stats?platform=youtube&top_anchors=10").catch(() => null),
@ -163,12 +203,22 @@ export default function HomePage() {
} finally {
if (!silent) setLoading(false);
}
}, []);
}, [connected]);
useEffect(() => {
void load({ silent: false });
const t = setInterval(() => void load({ silent: true }), 20000);
return () => clearInterval(t);
const t = setInterval(() => {
if (document.hidden) return;
void load({ silent: true });
}, 25000);
const onVis = () => {
if (!document.hidden) void load({ silent: true });
};
document.addEventListener("visibilitychange", onVis);
return () => {
clearInterval(t);
document.removeEventListener("visibilitychange", onVis);
};
}, [load]);
useEffect(() => {

View File

@ -189,7 +189,7 @@ export default function RoomsPage() {
}
}, [query]);
useAutoRefresh(load, { intervalMs: 15000 });
useAutoRefresh(load, { intervalMs: 30000 });
async function doAddRooms() {
setBusy("add");

View File

@ -178,7 +178,10 @@ export default function SettingsPage() {
const gSecret = String(settings.shorts_oauth_client_secret || "");
if (gSecret && !gSecret.startsWith("***")) body.shorts_oauth_client_secret = gSecret;
body.shorts_oauth_redirect_uri = String(
settings.shorts_oauth_redirect_uri || "https://dylive.nomadro.com/api/shorts/oauth/callback"
settings.shorts_oauth_redirect_uri ||
(typeof window !== "undefined"
? `${window.location.origin}/api/shorts/oauth/callback`
: "")
);
const profiles = Array.isArray(settings.shorts_oauth_profiles) ? settings.shorts_oauth_profiles : [];
body.shorts_upload_socks_enabled = Boolean(settings.shorts_upload_socks_enabled);
@ -191,6 +194,7 @@ export default function SettingsPage() {
label: String(p.label || ""),
client_id: String(p.client_id || ""),
client_secret: String(p.client_secret || ""),
email: String(p.email || ""),
}));
body.shorts_oauth_profiles = oauthProfiles;
const studioCookiesRaw =
@ -290,11 +294,7 @@ export default function SettingsPage() {
return (
<Shell>
<div className="mb-5 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">⚙️ 设置</h2>
<p className="mt-1 text-sm text-slate-400">按模块分组,改完记得点底部「保存设置」。</p>
</div>
<div className="mb-5 flex flex-wrap items-start justify-end gap-3">
<div className="hidden text-xs text-slate-500 sm:block">
{status?.running ? "抖音监控运行中" : "抖音监控已停"} ·{" "}
{ytStatus?.running ? "YouTube 轮询中" : "YouTube 已停"}
@ -847,6 +847,7 @@ export default function SettingsPage() {
<p className="mt-1 text-[11px] leading-relaxed text-slate-500">
每个谷歌 Cloud 项目填一套 Client,保存一次即可。Shorts 频道只需选择 A/B/C/D,不必再手填密钥。
各项目均须登记同一回调 URI。密钥留空或显示 *** 表示不修改已有值。
重授权后会自动读取并显示该谷歌账号的 Gmail。
<span className="block mt-1 text-amber-200/90">
长视频 YPP 自动开广告还需填写下方 Studio Cookie(与 OAuth 不同,从 studio.youtube.com 浏览器复制)。
</span>
@ -940,6 +941,15 @@ export default function SettingsPage() {
{ready ? "已配置" : "未配置"}
</span>
</div>
{String(row.email || "").trim() ? (
<p className="mb-2 text-[11px] text-teal-200/90">
Gmail:<span className="font-mono">{String(row.email)}</span>
</p>
) : (
<p className="mb-2 text-[10px] text-slate-500">
Gmail:重授权 Shorts 频道后自动写入(需同意查看邮箱)
</p>
)}
<div className="grid gap-2 md:grid-cols-2">
<label className="block text-[11px] text-slate-400">
Client ID
@ -1012,14 +1022,24 @@ export default function SettingsPage() {
);
})}
<label className="block text-xs text-slate-400">
授权回调 URI(所有 A/B/C/D 项目都须登记)
授权回调 URI(Google Console 须登记你实际访问的域名;授权时按发起域名自动选择)
<input
value={String(
settings.shorts_oauth_redirect_uri || "https://dylive.nomadro.com/api/shorts/oauth/callback"
settings.shorts_oauth_redirect_uri ||
(typeof window !== "undefined"
? `${window.location.origin}/api/shorts/oauth/callback`
: "")
)}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_oauth_redirect_uri: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm font-mono"
/>
<span className="mt-1 block text-[10px] text-slate-500">
当前站点会用:
{typeof window !== "undefined"
? `${window.location.origin}/api/shorts/oauth/callback`
: "(打开设置页后显示)"}
。勿再写死旧域名。
</span>
</label>
</div>
<p className="text-xs text-slate-500">

View File

@ -65,6 +65,7 @@ type Channel = {
type OauthProfile = {
id: string;
label?: string;
email?: string;
client_id?: string;
configured?: boolean;
};
@ -233,10 +234,38 @@ export default function ShortsPage() {
useEffect(() => {
void load();
let tick = 0;
const t = setInterval(() => {
if (pageTab === "ops") void load();
}, 10000);
return () => clearInterval(t);
if (pageTab !== "ops" || document.hidden) return;
tick += 1;
// Every poll: light status; channels+jobs every other tick (~40s).
if (tick % 2 === 0) {
void load();
} else {
void fetchJson("/api/shorts/status?light=1")
.then((st) =>
setStatus((prev) => ({
...(prev || {}),
...st,
board: st.board ?? prev?.board,
history: st.history ?? prev?.history,
failed_groups: st.failed_groups ?? prev?.failed_groups,
channel_perf: st.channel_perf ?? prev?.channel_perf,
heatmap: st.heatmap ?? prev?.heatmap,
oauth_profiles: st.oauth_profiles ?? prev?.oauth_profiles,
})),
)
.catch(() => undefined);
}
}, 20000);
const onVis = () => {
if (!document.hidden && pageTab === "ops") void load();
};
document.addEventListener("visibilitychange", onVis);
return () => {
clearInterval(t);
document.removeEventListener("visibilitychange", onVis);
};
}, [load, pageTab]);
// Sync right panel height to left panel
@ -257,7 +286,10 @@ export default function ShortsPage() {
useEffect(() => {
if (pageTab !== "live") return;
void loadLiveAnalytics();
const t = setInterval(() => void loadLiveAnalytics(), 20000);
const t = setInterval(() => {
if (document.hidden) return;
void loadLiveAnalytics();
}, 30000);
return () => clearInterval(t);
}, [pageTab, loadLiveAnalytics]);
@ -376,7 +408,10 @@ export default function ShortsPage() {
const profileLabelMap = useMemo(() => {
const m: Record<string, string> = {};
for (const p of (status?.oauth_profiles || []) as OauthProfile[]) {
m[normalizeOauthProfileId(p.id)] = String(p.label || `谷歌账号 ${p.id}`);
const pid = normalizeOauthProfileId(p.id);
const mail = String(p.email || "").trim();
const base = String(p.label || `谷歌账号 ${p.id}`);
m[pid] = mail ? `${base} · ${mail}` : base;
}
for (const c of channels) {
const pid = normalizeOauthProfileId(c.oauth_profile_id);
@ -442,33 +477,29 @@ export default function ShortsPage() {
}
}
function openOauthPopup(channelId: string, returnTo?: string) {
const q = new URLSearchParams({ channel_pk: channelId });
if (returnTo) q.set("return_to", returnTo);
const url = `/api/shorts/oauth/start?${q.toString()}`;
const w = window.open(url, "_blank", "noopener,noreferrer");
if (!w) {
setError("浏览器拦截了弹窗,请允许本站弹窗后重试;或改用当前页跳转");
window.location.href = url;
} else {
setMsg("已在新窗口打开 Google 授权,完成后关闭该窗口即可");
}
}
function goAuthorize(channelId: string) {
const full = channels.find((c) => c.id === channelId);
const board = boardChannels.find((c) => c.id === channelId);
// Stale state after create is fine — only block when we know this channel cannot auth
if (full && full.can_authorize === false) {
setShowWizard(true);
setError("请先在「设置」配置对应 OAuth 档(A/B/C/D),并在本频道选择该配置档");
return;
}
const needTitle = String(board?.yt_profile?.title || full?.name || board?.name || "").trim();
const needHandle = String(board?.yt_profile?.custom_url || "").trim();
const hasBound = Boolean(String(full?.youtube_channel_id || board?.youtube_channel_id || "").trim());
if (hasBound && needTitle) {
const hint = buildChannelMeta({
yt_profile: board?.yt_profile,
youtube_channel_id: full?.youtube_channel_id || board?.youtube_channel_id,
note: full?.note || board?.note,
brand_hint: board?.brand_hint,
}).brandHint;
const ok = window.confirm(
`本卡需要的 YouTube 频道:\n${needTitle}${needHandle ? ` ${needHandle}` : ""}\n\n` +
`Google 授权页请选品牌账号:${hint || "(见卡片 Google·… 提示)"}\n\n` +
`Google 品牌账号名可能和上面不一样;点错了页面会提示,不会写入。\n\n继续?`
);
if (!ok) return;
}
window.location.href = `/api/shorts/oauth/start?channel_pk=${encodeURIComponent(channelId)}`;
// 点哪张卡就写入哪张卡;不再弹品牌对照提示。
openOauthPopup(channelId);
}
async function saveChannel(andAuth: boolean) {
@ -510,7 +541,7 @@ export default function ShortsPage() {
setShowForm(false);
await load();
if (andAuth && id) {
window.location.href = `/api/shorts/oauth/start?channel_pk=${encodeURIComponent(id)}`;
openOauthPopup(id);
return;
}
} catch (e) {
@ -1198,6 +1229,11 @@ export default function ShortsPage() {
<OauthClientBadge
profileId={group.profileId}
label={profileLabelMap[group.profileId]}
email={
((status?.oauth_profiles || []) as OauthProfile[]).find(
(p) => normalizeOauthProfileId(p.id) === group.profileId
)?.email || ""
}
size="lg"
/>
<span className="text-xs text-slate-400">
@ -1455,6 +1491,7 @@ export default function ShortsPage() {
]).map((p) => (
<option key={p.id} value={String(p.id).toUpperCase()}>
{String(p.id).toUpperCase()} · {p.label || `谷歌账号 ${p.id}`}
{p.email ? ` · ${p.email}` : ""}
{p.configured ? "(已配置)" : "(未配置)"}
</option>
))}

View File

@ -181,8 +181,34 @@ export default function TikTokPage() {
useEffect(() => {
void load();
const t = setInterval(() => void load(), 12000);
return () => clearInterval(t);
let n = 0;
const t = setInterval(() => {
if (document.hidden) return;
n += 1;
if (n % 2 === 0) {
void load();
} else {
void fetchJson("/api/tiktok/status?light=1")
.then((st) => {
setStatus((prev: Record<string, unknown> | null) => ({
...(prev || {}),
...st,
channels: prev?.channels || st?.channels || [],
socks_profiles: prev?.socks_profiles || st?.socks_profiles || [],
setup: prev?.setup ?? st?.setup,
}));
})
.catch(() => undefined);
}
}, 20000);
const onVis = () => {
if (!document.hidden) void load();
};
document.addEventListener("visibilitychange", onVis);
return () => {
clearInterval(t);
document.removeEventListener("visibilitychange", onVis);
};
}, [load]);
useEffect(() => {

View File

@ -0,0 +1,534 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Activity,
ExternalLink,
Eye,
Loader2,
MousePointerClick,
Radar,
RefreshCw,
Users,
Wifi,
X,
} from "lucide-react";
import { Shell } from "@/components/Shell";
import { useToast } from "@/components/Toast";
import { fetchJson } from "@/lib/api";
import { useAutoRefresh, useNow, type RefreshOpts } from "@/lib/realtime";
type OverviewSite = {
domain: string;
role: string;
website_id: string;
ok: boolean;
active: number;
pageviews: number;
visitors: number;
visits: number;
bounces: number;
};
type AnalyticsDetail = {
domain?: string;
website_id?: string;
range?: string;
ok?: boolean;
active?: number;
stats?: {
pageviews?: number;
visitors?: number;
visits?: number;
bounces?: number;
bounce_rate?: number;
avg_visit_sec?: number;
totaltime?: number;
};
series?: { x: string; y: number }[];
top_paths?: { name: string; value: number }[];
top_referrers?: { name: string; value: number }[];
top_countries?: { name: string; value: number }[];
top_devices?: { name: string; value: number }[];
top_browsers?: { name: string; value: number }[];
top_os?: { name: string; value: number }[];
top_languages?: { name: string; value: number }[];
top_cities?: { name: string; value: number }[];
top_titles?: { name: string; value: number }[];
umami_url?: string;
};
const RANGES = [
{ id: "24h", label: "24小时" },
{ id: "7d", label: "7天" },
{ id: "30d", label: "30天" },
{ id: "90d", label: "90天" },
];
const HIDDEN_DOMAINS = new Set(["wx.nomadro.com", "x.nomadro.com", "portal.nomadro.com"]);
function fmtNum(n?: number) {
const v = Number(n || 0);
if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`;
if (v >= 1_000) return `${(v / 1_000).toFixed(1)}k`;
return String(v);
}
function fmtDuration(sec?: number) {
const s = Math.max(0, Math.round(Number(sec || 0)));
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
const r = s % 60;
return `${m}m ${r}s`;
}
function Sparkline({ series }: { series?: { x: string; y: number }[] }) {
const pts = series || [];
if (pts.length < 2) {
return <div className="flex h-16 items-center text-xs text-slate-500">暂无趋势数据(站点刚接入时常见)</div>;
}
const ys = pts.map((p) => Number(p.y || 0));
const max = Math.max(...ys, 1);
const min = Math.min(...ys, 0);
const w = 320;
const h = 64;
const path = pts
.map((p, i) => {
const x = (i / (pts.length - 1)) * w;
const y = h - ((Number(p.y || 0) - min) / (max - min || 1)) * (h - 4) - 2;
return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
})
.join(" ");
return (
<svg viewBox={`0 0 ${w} ${h}`} className="h-16 w-full overflow-visible">
<path d={path} fill="none" stroke="rgba(45,212,191,0.9)" strokeWidth="2" />
</svg>
);
}
function MetricList({ title, rows }: { title: string; rows?: { name: string; value: number }[] }) {
const list = rows || [];
const max = Math.max(...list.map((r) => Number(r.value || 0)), 1);
return (
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-2 text-xs font-medium text-slate-300">{title}</div>
{!list.length && <div className="text-xs text-slate-500">暂无数据</div>}
<ul className="space-y-2">
{list.map((r) => (
<li key={`${title}-${r.name}`}>
<div className="mb-0.5 flex justify-between gap-2 text-[11px]">
<span className="truncate text-slate-200">{r.name || "(direct)"}</span>
<span className="shrink-0 text-slate-400">{fmtNum(r.value)}</span>
</div>
<div className="h-1 overflow-hidden rounded bg-white/5">
<div
className="h-full rounded bg-gradient-to-r from-teal-400/80 to-sky-400/70"
style={{ width: `${(Number(r.value) / max) * 100}%` }}
/>
</div>
</li>
))}
</ul>
</div>
);
}
function SiteDetailBody({ detail, loading }: { detail: AnalyticsDetail | null; loading?: boolean }) {
const st = detail?.stats;
if (loading && !detail) {
return (
<div className="flex items-center justify-center gap-2 py-16 text-sm text-slate-400">
<Loader2 className="h-4 w-4 animate-spin" /> 加载访客详情…
</div>
);
}
if (!detail) {
return <div className="py-12 text-center text-sm text-slate-500">暂无该站点数据</div>;
}
return (
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
{[
{ label: "浏览量 PV", value: fmtNum(st?.pageviews), icon: Eye },
{ label: "独立访客", value: fmtNum(st?.visitors), icon: Users },
{ label: "访问次数", value: fmtNum(st?.visits), icon: MousePointerClick },
{ label: "跳出率", value: `${st?.bounce_rate ?? 0}%`, icon: Activity },
{ label: "平均停留", value: fmtDuration(st?.avg_visit_sec), icon: Radar },
].map((card) => (
<div key={card.label} className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="flex items-center gap-1.5 text-[11px] text-slate-400">
<card.icon className="h-3.5 w-3.5 text-teal-300" />
{card.label}
</div>
<div className="mt-1 text-xl font-semibold text-white">{card.value}</div>
</div>
))}
</div>
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-1 flex items-center justify-between text-xs text-slate-400">
<span>浏览量趋势</span>
<span className="text-teal-300">当前在线 {detail.active ?? 0}</span>
</div>
<Sparkline series={detail.series} />
</div>
<div className="grid gap-3 lg:grid-cols-2">
<MetricList title="热门页面" rows={detail.top_paths} />
<MetricList title="页面标题" rows={detail.top_titles} />
<MetricList title="来源 Referrer" rows={detail.top_referrers} />
<MetricList title="国家 / 地区" rows={detail.top_countries} />
<MetricList title="城市" rows={detail.top_cities} />
<MetricList title="语言" rows={detail.top_languages} />
<MetricList title="设备" rows={detail.top_devices} />
<MetricList title="操作系统" rows={detail.top_os} />
<MetricList title="浏览器" rows={detail.top_browsers} />
</div>
</div>
);
}
function SiteDetailModal({
open,
domain,
role,
range,
detail,
loading,
onClose,
onRange,
umamiUrl,
}: {
open: boolean;
domain: string;
role?: string;
range: string;
detail: AnalyticsDetail | null;
loading?: boolean;
onClose: () => void;
onRange: (id: string) => void;
umamiUrl?: string;
}) {
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
window.removeEventListener("keydown", onKey);
document.body.style.overflow = prev;
};
}, [open, onClose]);
if (!open) return null;
return (
<div
className="fixed inset-0 z-[80] flex items-end justify-center bg-black/70 p-0 backdrop-blur-sm sm:items-center sm:p-4"
onClick={onClose}
role="presentation"
>
<div
role="dialog"
aria-modal="true"
aria-label={`${domain} 访客详情`}
className="flex max-h-[92vh] w-full max-w-5xl flex-col overflow-hidden rounded-t-3xl border border-white/10 bg-[#0b1220] shadow-2xl sm:rounded-3xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex flex-wrap items-start justify-between gap-3 border-b border-white/10 px-4 py-3 sm:px-5">
<div className="min-w-0">
<div className="text-[11px] uppercase tracking-[0.16em] text-teal-200/70">站点访客详情</div>
<h2 className="truncate text-lg font-semibold text-white">{domain}</h2>
{role ? <p className="mt-0.5 text-[11px] text-slate-500">{role}</p> : null}
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap gap-1">
{RANGES.map((r) => (
<button
key={r.id}
type="button"
onClick={() => onRange(r.id)}
className={`rounded-lg px-2.5 py-1 text-[11px] ${
range === r.id ? "bg-sky-400/20 text-sky-200" : "bg-white/5 text-slate-400"
}`}
>
{r.label}
</button>
))}
</div>
<a
href={umamiUrl || "https://umami.nomadro.com"}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-200"
>
Umami <ExternalLink className="h-3 w-3" />
</a>
<button
type="button"
onClick={onClose}
className="rounded-lg border border-white/10 bg-white/5 p-1.5 text-slate-300 hover:bg-white/10"
aria-label="关闭"
>
<X className="h-4 w-4" />
</button>
</div>
</div>
<div className="relative flex-1 overflow-y-auto p-4 sm:p-5">
{loading ? (
<div className="pointer-events-none absolute right-4 top-3 inline-flex items-center gap-1 rounded-full bg-black/50 px-2 py-0.5 text-[10px] text-slate-300">
<Loader2 className="h-3 w-3 animate-spin" /> 刷新中
</div>
) : null}
<SiteDetailBody detail={detail} loading={loading} />
</div>
</div>
</div>
);
}
export default function WebPage() {
const toast = useToast();
const now = useNow(1000);
const [overview, setOverview] = useState<OverviewSite[]>([]);
const [umamiUrl, setUmamiUrl] = useState("https://umami.nomadro.com");
const [detail, setDetail] = useState<AnalyticsDetail | null>(null);
const [domain, setDomain] = useState("dylive.nomadro.com");
const [modalOpen, setModalOpen] = useState(false);
const [modalLoading, setModalLoading] = useState(false);
const [range, setRange] = useState("7d");
const [loading, setLoading] = useState(true);
const [syncing, setSyncing] = useState(false);
const [live, setLive] = useState(true);
const [lastOkAt, setLastOkAt] = useState(0);
const [lastErr, setLastErr] = useState("");
const [pageVisible, setPageVisible] = useState(true);
const inFlight = useRef(false);
const domainRef = useRef(domain);
const rangeRef = useRef(range);
const modalOpenRef = useRef(modalOpen);
domainRef.current = domain;
rangeRef.current = range;
modalOpenRef.current = modalOpen;
useEffect(() => {
const onVis = () => setPageVisible(document.visibilityState === "visible");
onVis();
document.addEventListener("visibilitychange", onVis);
return () => document.removeEventListener("visibilitychange", onVis);
}, []);
const visibleSites = useMemo(
() => overview.filter((s) => !HIDDEN_DOMAINS.has(String(s.domain || "").toLowerCase())),
[overview]
);
const loadSilent = useCallback(
async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (inFlight.current) return;
inFlight.current = true;
if (!silent) setLoading(true);
else setSyncing(true);
try {
const ov = await fetchJson(`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}`);
setOverview(ov?.sites || []);
if (ov?.umami_url) setUmamiUrl(String(ov.umami_url));
if (modalOpenRef.current && domainRef.current) {
setModalLoading(true);
try {
const d = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}&domain=${encodeURIComponent(domainRef.current)}`
);
setDetail(d);
if (d?.umami_url) setUmamiUrl(String(d.umami_url));
} finally {
setModalLoading(false);
}
}
setLastOkAt(Date.now());
setLastErr("");
setLive(true);
} catch (e) {
setLive(false);
setLastErr((e as Error).message || "同步失败");
if (!silent) toast.push((e as Error).message, "err");
} finally {
inFlight.current = false;
setLoading(false);
setSyncing(false);
}
},
[toast]
);
const openSiteModal = useCallback(
async (d: string) => {
setDomain(d);
setModalOpen(true);
setModalLoading(true);
try {
const detailRes = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}&domain=${encodeURIComponent(d)}`
);
setDetail(detailRes);
if (detailRes?.umami_url) setUmamiUrl(String(detailRes.umami_url));
} catch (e) {
toast.push((e as Error).message || "加载详情失败", "err");
} finally {
setModalLoading(false);
}
},
[toast]
);
const closeSiteModal = useCallback(() => setModalOpen(false), []);
const onModalRange = useCallback(
async (id: string) => {
setRange(id);
if (!domainRef.current) return;
setModalLoading(true);
try {
const detailRes = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(id)}&domain=${encodeURIComponent(domainRef.current)}`
);
setDetail(detailRes);
} catch (e) {
toast.push((e as Error).message || "切换时间失败", "err");
} finally {
setModalLoading(false);
}
},
[toast]
);
useAutoRefresh(loadSilent, {
intervalMs: 20000,
eventKinds: false,
enabled: pageVisible,
});
useEffect(() => {
if (!pageVisible) return;
void loadSilent({ silent: true });
}, [range, pageVisible, loadSilent]);
const modalRole = useMemo(() => visibleSites.find((s) => s.domain === domain)?.role, [visibleSites, domain]);
const agoSec = lastOkAt ? Math.max(0, Math.floor((now - lastOkAt) / 1000)) : null;
return (
<Shell>
<div className="mx-auto max-w-6xl space-y-4 pb-8">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-wrap items-center gap-2 text-[11px]">
<span
className={`inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 ${
live ? "bg-teal-400/15 text-teal-200" : "bg-rose-400/15 text-rose-200"
}`}
>
<Wifi className={`h-3 w-3 ${syncing ? "animate-pulse" : ""}`} />
{pageVisible ? (live ? "实时同步中" : "同步异常") : "已暂停"}
</span>
<span className="text-slate-500">
{syncing ? "拉取中…" : agoSec == null ? "等待首次同步" : `上次更新 ${agoSec}s 前`}
</span>
{lastErr ? <span className="truncate text-rose-300">{lastErr}</span> : null}
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap gap-1.5">
{RANGES.map((r) => (
<button
key={r.id}
type="button"
onClick={() => setRange(r.id)}
className={`rounded-lg px-2.5 py-1 text-[11px] ${
range === r.id ? "bg-sky-400/20 text-sky-200" : "bg-white/5 text-slate-400"
}`}
>
{r.label}
</button>
))}
</div>
<button
type="button"
disabled={syncing}
onClick={() => void loadSilent({ silent: false })}
className="inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200"
>
<RefreshCw className={`h-3.5 w-3.5 ${loading || syncing ? "animate-spin" : ""}`} />
同步
</button>
<a
href={umamiUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1.5 rounded-xl bg-gradient-to-br from-teal-400 to-sky-500 px-3 py-1.5 text-xs font-semibold text-[#0b1220]"
>
Umami <ExternalLink className="h-3.5 w-3.5" />
</a>
</div>
</div>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{visibleSites.map((s) => (
<button
key={s.domain}
type="button"
onClick={() => void openSiteModal(s.domain)}
className="group rounded-2xl border border-white/10 bg-white/[0.03] p-3 text-left transition hover:border-teal-300/40 hover:bg-teal-400/10"
>
<div className="flex items-center justify-between gap-2">
<div className="truncate text-sm font-medium text-white">{s.domain}</div>
<span className="text-[10px] text-teal-300">在线 {s.active}</span>
</div>
<div className="mt-0.5 flex items-center justify-between gap-2">
<div className="truncate text-[11px] text-slate-500">{s.role}</div>
<div className="shrink-0 text-[10px] text-sky-300/80 opacity-0 transition group-hover:opacity-100">
查看详情 →
</div>
</div>
<div className="mt-3 grid grid-cols-3 gap-2 text-center">
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.pageviews)}</div>
<div className="text-[10px] text-slate-500">浏览量</div>
</div>
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.visitors)}</div>
<div className="text-[10px] text-slate-500">访客</div>
</div>
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.visits)}</div>
<div className="text-[10px] text-slate-500">访问</div>
</div>
</div>
</button>
))}
{!visibleSites.length && (
<div className="col-span-full py-8 text-center text-sm text-slate-500">
{loading ? "加载访问数据…" : "暂无概览(确认 Umami 已采集到流量)"}
</div>
)}
</div>
</section>
<SiteDetailModal
open={modalOpen}
domain={domain}
role={modalRole}
range={range}
detail={detail}
loading={modalLoading}
onClose={closeSiteModal}
onRange={(id) => void onModalRange(id)}
umamiUrl={detail?.umami_url || umamiUrl}
/>
</div>
</Shell>
);
}

View File

@ -174,8 +174,18 @@ export default function XPage() {
useEffect(() => {
void load();
const t = setInterval(() => void load(), 3500);
return () => clearInterval(t);
const t = setInterval(() => {
if (document.hidden) return;
void load();
}, 15000);
const onVis = () => {
if (!document.hidden) void load();
};
document.addEventListener("visibilitychange", onVis);
return () => {
clearInterval(t);
document.removeEventListener("visibilitychange", onVis);
};
}, [load]);
const createJob = useCallback(

View File

@ -264,7 +264,7 @@ export default function YouTubePage() {
<p className="font-display text-xs uppercase tracking-[0.28em] text-rose-300/80">YouTube Studio Lite</p>
<h2 className="font-display text-3xl font-semibold">▶️ YouTube</h2>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
分配:频道 + 直播 KEY → 抖音 URL 池 → 精选转播。频道管理:片库 / 元数据 / 可见性。探测仍用 InnerTube。
分配:频道 + 直播 KEY → 抖音 URL 池 → 精选转播 / FFmpeg 推流。频道管理:片库 / 元数据 / 可见性。探测仍用 InnerTube。
</p>
</div>
<div className="flex flex-wrap gap-2">

View File

@ -245,8 +245,34 @@ export default function YtLongPage() {
useEffect(() => {
void load();
const t = setInterval(() => void load(), 10000);
return () => clearInterval(t);
let n = 0;
const t = setInterval(() => {
if (document.hidden) return;
n += 1;
if (n % 2 === 0) {
void load();
} else {
void fetchJson("/api/yt-long/status?light=1")
.then((st) =>
setStatus((prev) => ({
...(prev || {}),
...st,
board: st.board ?? prev?.board,
cascade_need: st.cascade_need ?? prev?.cascade_need,
settings: st.settings ?? prev?.settings,
})),
)
.catch(() => undefined);
}
}, 20000);
const onVis = () => {
if (!document.hidden) void load();
};
document.addEventListener("visibilitychange", onVis);
return () => {
clearInterval(t);
document.removeEventListener("visibilitychange", onVis);
};
}, [load]);
useEffect(() => {

View File

@ -35,6 +35,12 @@ export function DouyinLiveBadge({
overlay = false,
showOffline = false,
}: Props) {
// Never render Douyin badge for YouTube/Shorts synthetic ids.
const rid = String(roomId || "").trim();
if (rid.startsWith("shorts:") || rid.startsWith("yt:")) {
return null;
}
const fromMap = useDouyinLiveEntry(roomId, entry ?? undefined);
const live = fromMap;
const { status, isLive } = resolveDouyinLive(live, lastStatus);

View File

@ -47,7 +47,8 @@ export function GlobalEventAlerts() {
useEffect(() => {
const loadFlags = () => {
void fetchJson("/api/settings")
if (typeof document !== "undefined" && document.hidden) return;
void fetchJson("/api/settings/notify-flags")
.then((s) => {
flagsRef.current = applyFlags(s);
})
@ -56,10 +57,8 @@ export function GlobalEventAlerts() {
loadFlags();
const onChange = () => loadFlags();
window.addEventListener("dy-settings-changed", onChange);
const t = window.setInterval(loadFlags, 30000);
return () => {
window.removeEventListener("dy-settings-changed", onChange);
window.clearInterval(t);
};
}, []);

View File

@ -0,0 +1,96 @@
"use client";
import { useEffect, useState } from "react";
import { fetchJson } from "@/lib/api";
type HostMetrics = {
cpu_percent?: number;
memory_percent?: number;
memory_used_gb?: number;
memory_total_gb?: number;
load1?: number;
cpu_cores?: number;
};
function barColor(pct: number) {
if (pct >= 90) return "from-rose-500 to-orange-500";
if (pct >= 75) return "from-amber-400 to-orange-400";
return "from-teal-400 to-sky-400";
}
function MetricBar({ label, pct, hint }: { label: string; pct: number; hint: string }) {
const p = Math.max(0, Math.min(100, pct));
return (
<div className="min-w-[8.5rem] flex-1 sm:min-w-[10rem] sm:flex-none">
<div className="mb-0.5 flex items-center justify-between gap-2 text-[10px] text-slate-400 sm:text-[11px]">
<span>{label}</span>
<span className="font-mono text-slate-300">
{p.toFixed(1)}% <span className="text-slate-500">· {hint}</span>
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-white/10">
<div
className={`h-full rounded-full bg-gradient-to-r transition-[width] duration-500 ease-out ${barColor(p)}`}
style={{ width: `${p}%` }}
/>
</div>
</div>
);
}
export function HostResourceBar() {
const [m, setM] = useState<HostMetrics | null>(null);
const [err, setErr] = useState(false);
useEffect(() => {
let cancelled = false;
const load = async () => {
if (document.hidden) return;
try {
const d = (await fetchJson("/api/ops/host-metrics")) as HostMetrics;
if (!cancelled) {
setM(d);
setErr(false);
}
} catch {
if (!cancelled) setErr(true);
}
};
void load();
const t = setInterval(() => void load(), 20000);
const onVis = () => {
if (!document.hidden) void load();
};
document.addEventListener("visibilitychange", onVis);
return () => {
cancelled = true;
clearInterval(t);
document.removeEventListener("visibilitychange", onVis);
};
}, []);
if (err && !m) {
return <p className="mt-1 text-[10px] text-slate-600 sm:text-[11px]">主机指标暂不可用</p>;
}
const cpu = Number(m?.cpu_percent ?? 0);
const mem = Number(m?.memory_percent ?? 0);
const memHint =
m?.memory_used_gb != null && m?.memory_total_gb != null
? `${m.memory_used_gb}/${m.memory_total_gb}G`
: "—";
const loadHint =
m?.load1 != null && m?.cpu_cores
? `load ${m.load1}/${m.cpu_cores}`
: m?.load1 != null
? `load ${m.load1}`
: "";
return (
<div className="mt-1.5 flex flex-col gap-1.5 sm:mt-2 sm:flex-row sm:flex-wrap sm:items-center sm:gap-3">
<MetricBar label="CPU" pct={cpu} hint={loadHint || "实时"} />
<MetricBar label="内存" pct={mem} hint={memHint} />
</div>
);
}

View File

@ -16,11 +16,13 @@ export function normalizeOauthProfileId(raw?: string | null): string {
export function OauthClientBadge({
profileId,
label,
email,
size = "md",
className = "",
}: {
profileId?: string | null;
label?: string | null;
email?: string | null;
size?: "sm" | "md" | "lg";
className?: string;
}) {
@ -40,12 +42,15 @@ export function OauthClientBadge({
const style = PROFILE_STYLE[id] || "border-teal-400/40 bg-teal-500/20 text-teal-100";
const sizeCls =
size === "lg" ? "px-2.5 py-1 text-xs" : size === "sm" ? "px-1.5 py-0 text-[10px]" : "px-2 py-0.5 text-[11px]";
const mail = String(email || "").trim();
const tip = mail || label || `谷歌上传账号 ${id}`;
return (
<span
className={`inline-flex shrink-0 items-center rounded border font-bold tracking-wide ${style} ${sizeCls} ${className}`}
title={label || `谷歌上传账号 ${id}`}
title={tip}
>
账号 {id}
{mail && size === "lg" ? <span className="ml-1 font-mono font-normal opacity-90">{mail}</span> : null}
</span>
);
}

View File

@ -7,8 +7,11 @@ import { Menu, X as CloseIcon } from "lucide-react";
import { BrandMark, LivePulse } from "@/components/ui";
import { GlobalEventAlerts } from "@/components/GlobalEventAlerts";
import { HostResourceBar } from "@/components/HostResourceBar";
import { PwaInstallBanner } from "@/components/PwaInstallBanner";
import { ShellSubTabs } from "@/components/ShellSubTabs";
import { fetchJson } from "@/lib/api";
import { MAIN_NAV, MOBILE_PRIMARY, mainNavActive, sectionTabs, shellSection } from "@/lib/shellNav";
import {
DouyinLiveContextProvider,
useDouyinLiveCount,
@ -21,34 +24,6 @@ import {
useYouTubeLiveProviderValue,
} from "@/lib/youtubeLive";
const NAV = [
{ href: "/", label: "概览", emoji: "📡" },
{ href: "/slots", label: "时段", emoji: "🕐" },
{ href: "/sessions", label: "场次", emoji: "🎬" },
{ href: "/anchors", label: "主播", emoji: "👤" },
{ href: "/covers", label: "截图", emoji: "🖼️" },
{ href: "/events", label: "事件", emoji: "⚡" },
{ href: "/rooms", label: "直播间", emoji: "🏠" },
{ href: "/groups", label: "分组", emoji: "📺" },
{ href: "/youtube", label: "YouTube", emoji: "▶️" },
{ href: "/shorts", label: "Shorts", emoji: "📱" },
{ href: "/yt-long", label: "长视频", emoji: "🎞️" },
{ href: "/tiktok", label: "TikTok", emoji: "🎵" },
{ href: "/x", label: "X", emoji: "𝕏" },
{ href: "/clash", label: "Clash", emoji: "🧿" },
{ href: "/ops", label: "运维", emoji: "🛰️" },
{ href: "/downloads", label: "下载", emoji: "⬇️" },
{ href: "/blacklist", label: "黑名单", emoji: "🚫" },
{ href: "/settings", label: "设置", emoji: "⚙️" },
];
/** Bottom bar: 概览 / TikTok / X / Shorts + 更多(YouTube 仅在「更多」) */
const MOBILE_PRIMARY = ["/", "/tiktok", "/shorts"];
function navActive(pathname: string, href: string) {
return pathname === href || (href !== "/" && pathname.startsWith(href));
}
export function Shell({ children }: { children: React.ReactNode }) {
const ytCtx = useYouTubeLiveProviderValue();
const dyCtx = useDouyinLiveProviderValue();
@ -89,12 +64,15 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
};
}, [moreOpen]);
const section = shellSection(pathname);
const subTabs = sectionTabs(section);
const primaryNav = useMemo(
() => NAV.filter((n) => MOBILE_PRIMARY.includes(n.href)),
() => MAIN_NAV.filter((n) => MOBILE_PRIMARY.includes(n.href)),
[],
);
const moreActive = useMemo(
() => NAV.some((n) => !MOBILE_PRIMARY.includes(n.href) && navActive(pathname, n.href)),
() => MAIN_NAV.some((n) => !MOBILE_PRIMARY.includes(n.href) && mainNavActive(pathname, n.href)),
[pathname],
);
@ -125,11 +103,14 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
Live Radar
</p>
<h1 className="font-display text-xl font-bold tracking-tight text-white sm:text-3xl md:text-4xl">
直播监控中心
直播工作台
</h1>
<p className="mt-0.5 hidden max-w-2xl text-sm text-slate-400 sm:mt-1 sm:block">
抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证
</p>
<div className="mt-1 sm:mt-2">
<HostResourceBar />
</div>
{(dyLiveCount > 0 || ytLiveCount > 0) ? (
<div className="mt-1.5 flex flex-wrap items-center gap-2 sm:mt-2">
{dyLiveCount > 0 ? (
@ -138,7 +119,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
</Link>
) : null}
{ytLiveCount > 0 ? (
<Link href="/groups">
<Link href="/youtube">
<LivePulse label={`YouTube ${ytLiveCount} 路在播`} />
</Link>
) : null}
@ -180,8 +161,8 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
</div>
<nav className="mt-4 hidden max-w-full flex-wrap gap-2 md:flex">
{NAV.map((item) => {
const active = navActive(pathname, item.href);
{MAIN_NAV.map((item) => {
const active = mainNavActive(pathname, item.href);
return (
<Link
key={item.href}
@ -198,9 +179,17 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
);
})}
</nav>
{subTabs.length ? <ShellSubTabs tabs={subTabs} pathname={pathname} /> : null}
</header>
<main className="page-enter flex-1">{children}</main>
<main className="page-enter flex-1">
{subTabs.length ? (
<div className="mb-3 md:hidden">
<ShellSubTabs tabs={subTabs} pathname={pathname} />
</div>
) : null}
{children}
</main>
<footer className="hidden border-t border-white/5 py-4 text-center text-[11px] text-slate-600 md:block">
Douyin + YouTube Monitor · realtime radar
</footer>
@ -212,7 +201,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-white/10 bg-[#071018]/95 px-1 pt-1 backdrop-blur-md md:hidden pb-[env(safe-area-inset-bottom)]">
<div className="mx-auto flex max-w-lg items-stretch justify-between gap-0.5">
{primaryNav.map((item) => {
const active = navActive(pathname, item.href);
const active = mainNavActive(pathname, item.href);
return (
<Link
key={item.href}
@ -267,8 +256,8 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
<p className="mb-3 text-xs text-slate-400">当前账号:{username}</p>
) : null}
<div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
{NAV.map((item) => {
const active = navActive(pathname, item.href);
{MAIN_NAV.map((item) => {
const active = mainNavActive(pathname, item.href);
return (
<Link
key={item.href}

View File

@ -0,0 +1,30 @@
"use client";
import Link from "next/link";
import { navPathActive, type NavItem } from "@/lib/shellNav";
export function ShellSubTabs({ tabs, pathname }: { tabs: NavItem[]; pathname: string }) {
if (!tabs.length) return null;
return (
<nav className="mt-3 flex gap-1.5 overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{tabs.map((item) => {
const active = navPathActive(pathname, item.href);
return (
<Link
key={item.href}
href={item.href}
className={`shrink-0 rounded-lg px-2.5 py-1.5 text-xs sm:px-3 sm:text-sm ${
active
? "bg-teal-500/15 text-teal-100 ring-1 ring-teal-400/35"
: "bg-white/[0.04] text-slate-400 ring-1 ring-white/10 hover:bg-white/10 hover:text-slate-200"
}`}
>
<span className="mr-1">{item.emoji}</span>
{item.label}
</Link>
);
})}
</nav>
);
}

View File

@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import {
Ban,
@ -27,6 +27,7 @@ import { useToast } from "@/components/Toast";
import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet";
import { buildChannelMeta } from "@/lib/ytChannelMeta";
import { fetchJson } from "@/lib/api";
import { useDouyinLiveMap, useDouyinLiveEntry } from "@/lib/douyinLive";
type ManagedChannel = {
id: string;
@ -107,7 +108,10 @@ type ScheduleChannel = {
type RotationSchedule = {
channel_count?: number;
slot_hours?: number;
now_hour?: number;
now_label?: string;
keyed_only?: boolean;
time_slot_mode?: boolean;
channels?: ScheduleChannel[];
};
@ -128,14 +132,47 @@ type RelayGroup = {
enabled?: boolean;
};
type RelayQualityPreset = {
id: string;
label: string;
description?: string;
width?: number;
height?: number;
fps?: number;
x264_preset?: string;
bitrate_kbps?: number | null;
audio_bitrate_kbps?: number;
recommended_for_vps?: boolean;
active?: boolean;
};
type RelaySettings = {
youtube_relay_quality_preset?: string;
youtube_relay_exclusive_live?: boolean;
youtube_relay_time_slot_mode?: boolean;
youtube_relay_encoding?: {
preset_id?: string;
width?: number;
height?: number;
fps?: number;
x264_preset?: string;
bitrate_kbps?: number;
audio_bitrate_kbps?: number;
};
youtube_relay_quality_presets?: RelayQualityPreset[];
};
type RelayStatus = {
running?: boolean;
enabled?: boolean;
pushing_count?: number;
douyin_live_count?: number;
last_error?: string;
exclusive_winner_group_id?: string | null;
neko_paused_instances?: number[];
groups?: RelayGroup[];
entries?: RelayMonitorRow[];
settings?: RelaySettings;
};
function formatExportLine(url: string, title?: string): string {
@ -224,11 +261,12 @@ function CoverThumb({
roomId?: string;
onOpen: (src: string) => void;
}) {
const src = String(cover || "").trim();
const live = useDouyinLiveEntry(roomId);
const src = String(cover || live?.avatar_url || "").trim();
if (!src) {
return (
<div className="relative h-8 w-8 shrink-0">
<div className="h-8 w-8 rounded bg-white/10" title="无封面" />
<div className="h-8 w-8 rounded-full bg-white/10" title="无头像" />
{roomId ? (
<div className="absolute -right-0.5 -top-0.5">
<DouyinLiveBadge roomId={roomId} overlay showOffline />
@ -242,11 +280,11 @@ function CoverThumb({
<button
type="button"
onClick={() => onOpen(src)}
className="h-8 w-8 overflow-hidden rounded border border-white/10 bg-black/40 hover:ring-1 hover:ring-sky-400/40"
title="点击查看封面"
className="h-8 w-8 overflow-hidden rounded-full border border-white/10 bg-black/40 hover:ring-1 hover:ring-sky-400/40"
title="点击查看头像"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={src} alt={title || "cover"} className="h-full w-full object-cover" />
<img src={src} alt={title || "avatar"} className="h-full w-full object-cover" />
</button>
{roomId ? (
<div className="absolute -right-0.5 -top-0.5">
@ -265,7 +303,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
const [groupId, setGroupId] = useState("");
const [profiles, setProfiles] = useState<Record<string, YtProfileSnippet>>({});
const [busy, setBusy] = useState(false);
const [showKey, setShowKey] = useState(true);
const [showKey, setShowKey] = useState(false);
const [streamKeyDraft, setStreamKeyDraft] = useState("");
const [noteDraft, setNoteDraft] = useState("");
const [poolDraft, setPoolDraft] = useState("");
@ -277,7 +315,23 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
const [relayStatus, setRelayStatus] = useState<RelayStatus | null>(null);
const [relayBusy, setRelayBusy] = useState(false);
const [relayKickId, setRelayKickId] = useState("");
const relayStatusRef = useRef<RelayStatus | null>(null);
const { map: liveMap, refresh: refreshLiveMap } = useDouyinLiveMap();
useEffect(() => {
relayStatusRef.current = relayStatus;
}, [relayStatus]);
const displayAnchor = useCallback(
(row?: { title?: string; room_id?: string; url?: string } | null) => {
const title = String(row?.title || "").trim();
if (title) return title;
const rid = String(row?.room_id || "").trim();
const fromMap = rid ? String(liveMap?.entries?.[rid]?.anchor || "").trim() : "";
if (fromMap) return fromMap;
return "未命名主播";
},
[liveMap]
);
const selected = useMemo(() => groups.find((g) => g.id === groupId) || null, [groups, groupId]);
const featuredIds = useMemo(
() => new Set((selected?.featured || []).map((f) => String(f.pool_url_id))),
@ -322,8 +376,8 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
}, [relayStatus?.groups]);
const relayEntries = useMemo(
() => (relayStatus?.entries || relayStatus?.groups || []) as RelayMonitorRow[],
[relayStatus?.entries, relayStatus?.groups]
() => (relayStatus?.groups || relayStatus?.entries || []) as RelayMonitorRow[],
[relayStatus?.groups, relayStatus?.entries]
);
const selectedMonitor = useMemo(
@ -424,10 +478,45 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
void loadGroups();
void loadAllProfiles();
void loadRelay();
const t = setInterval(() => void loadRelay(), 3500);
return () => clearInterval(t);
let cancelled = false;
let t: number | undefined;
const tick = () => {
if (cancelled) return;
if (document.hidden) {
t = window.setTimeout(tick, 8000);
return;
}
void loadRelay().finally(() => {
if (cancelled) return;
const rows = (relayStatusRef.current?.groups ||
relayStatusRef.current?.entries ||
[]) as RelayMonitorRow[];
const pushing = rows.some((e) => isLivePushingRow(e));
// Pushing: 5s; idle: 15s — backend status also caches ~1s.
t = window.setTimeout(tick, pushing ? 5000 : 15000);
});
};
t = window.setTimeout(tick, 4000);
const onVis = () => {
if (!document.hidden && !cancelled) void loadRelay();
};
document.addEventListener("visibilitychange", onVis);
return () => {
cancelled = true;
if (t) window.clearTimeout(t);
document.removeEventListener("visibilitychange", onVis);
};
}, [loadGroups, loadAllProfiles, loadRelay]);
// Ordinary list titles + live badges: keep group payload in sync with live pool nicknames.
useEffect(() => {
const id = window.setInterval(() => {
if (document.hidden) return;
void loadGroups();
}, 45000);
return () => window.clearInterval(id);
}, [loadGroups]);
async function toggleRelayPipeline(on: boolean) {
if (!on) {
const ok = await confirm({
@ -450,6 +539,63 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
}
}
async function toggleExclusiveLive(on: boolean) {
setRelayBusy(true);
try {
await fetchJson("/api/youtube/relay/exclusive-live", {
method: "POST",
body: JSON.stringify({ enabled: on }),
});
toast.push(on ? "单频道独占已开启:开播时暂停其他频道" : "单频道独占已关闭", "ok");
await loadRelay();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setRelayBusy(false);
}
}
async function toggleTimeSlotMode(on: boolean) {
setRelayBusy(true);
try {
await fetchJson("/api/youtube/relay/time-slot-mode", {
method: "POST",
body: JSON.stringify({ enabled: on }),
});
toast.push(
on
? "时间段模式已开启:请再打开「自动推流」;有 KEY 频道按 24/N 轮播(源=在播抖音)"
: "时间段模式已关闭:恢复手动精选列表推流",
"ok",
);
await Promise.all([loadRelay(), loadSchedule()]);
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setRelayBusy(false);
}
}
async function setRelayQualityPreset(presetId: string) {
if (!presetId || presetId === relayStatus?.settings?.youtube_relay_quality_preset) return;
setRelayBusy(true);
try {
await fetchJson("/api/youtube/relay/quality-preset", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ preset: presetId }),
});
const label =
relayStatus?.settings?.youtube_relay_quality_presets?.find((p) => p.id === presetId)?.label || presetId;
toast.push(`已切换画质:${label}(推流将自动重启)`, "ok");
await loadRelay();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setRelayBusy(false);
}
}
async function kickRelayGroup(gid: string, action: "start" | "stop" | "restart") {
setRelayKickId(gid);
try {
@ -458,7 +604,10 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
? `/api/youtube/relay/groups/${gid}/restart`
: `/api/youtube/relay/groups/${gid}/${action}`;
await fetchJson(path, { method: "POST" });
toast.push(action === "start" ? "已触发推流" : action === "stop" ? "已停止推流" : "已重新开始", "ok");
toast.push(
action === "start" ? "已开始监听(开播后自动推流)" : action === "stop" ? "已停止监听/推流" : "已重新开始",
"ok",
);
await loadRelay();
} catch (e) {
toast.push((e as Error).message, "err");
@ -473,9 +622,24 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
setNoteDraft("");
return;
}
setStreamKeyDraft(String(selected.stream_key || ""));
setNoteDraft(String(selected.note || ""));
setShowKey(true);
setShowKey(false);
// List API omits stream_key — fetch full group for edit draft.
let cancelled = false;
void (async () => {
try {
const r = (await fetchJson(
`/api/youtube/assign/groups/${encodeURIComponent(selected.id)}`
)) as { group?: AssignGroup };
if (cancelled) return;
setStreamKeyDraft(String(r.group?.stream_key || ""));
} catch {
if (!cancelled) setStreamKeyDraft("");
}
})();
return () => {
cancelled = true;
};
}, [selected]);
async function createGroup() {
@ -485,15 +649,30 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
}
setBusy(true);
try {
const r = await fetchJson("/api/youtube/assign/groups", {
// Never send browser-autofilled site passwords as YouTube stream keys.
const key = String(newStreamKey || "").trim();
const banned = new Set(["hackrobot", "douyinweb", "xiao4669805@", "xiao4669805"]);
const streamKey = banned.has(key.toLowerCase()) ? "" : key;
const r = (await fetchJson("/api/youtube/assign/groups", {
method: "POST",
body: JSON.stringify({
channel_pk: newChannelPk,
stream_key: newStreamKey,
stream_key: streamKey,
enabled: true,
}),
});
toast.push("已新建分配分组", "ok");
})) as {
group?: AssignGroup;
neko_sync?: { ok?: boolean; neko_instance_id?: number; error?: string };
};
const nid = r.neko_sync?.neko_instance_id;
if (r.neko_sync && r.neko_sync.ok === false) {
toast.push(
`分组已建,但 Neko #${nid || "?"} 创建失败:${r.neko_sync.error || "unknown"}`,
"err"
);
} else {
toast.push(nid ? `已新建分组(Neko #${nid} 已创建,默认停止)` : "已新建分配分组", "ok");
}
setNewStreamKey("");
await loadGroups();
if (r?.group?.id) setGroupId(r.group.id);
@ -508,12 +687,12 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
if (!selected) return;
setBusy(true);
try {
const body: Record<string, string> = { note: noteDraft };
// Empty draft means "keep existing key" when list hid the secret.
if (streamKeyDraft.trim()) body.stream_key = streamKeyDraft.trim();
await fetchJson(`/api/youtube/assign/groups/${selected.id}`, {
method: "PATCH",
body: JSON.stringify({
stream_key: streamKeyDraft,
note: noteDraft,
}),
body: JSON.stringify(body),
});
toast.push("已保存直播 KEY / 备注", "ok");
await loadGroups();
@ -568,6 +747,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
if (bl) parts.push(`黑名单跳过 ${bl}`);
toast.push(parts.join(" · "), n || dup || bl ? "ok" : "err");
await loadGroups();
void refreshLiveMap();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
@ -791,6 +971,12 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
const usedChannelPks = useMemo(() => new Set(groups.map((g) => String(g.channel_pk || ""))), [groups]);
const availableChannels = channels.filter((c) => !usedChannelPks.has(c.id));
const exclusiveWinnerId = relayStatus?.exclusive_winner_group_id || "";
const exclusiveWinnerName =
groups.find((g) => g.id === exclusiveWinnerId)?.name || (exclusiveWinnerId ? "未知频道" : "");
const exclusiveLiveOn = relayStatus?.settings?.youtube_relay_exclusive_live !== false;
const timeSlotModeOn = Boolean(relayStatus?.settings?.youtube_relay_time_slot_mode);
const keyedCount = groups.filter((g) => g.enabled && g.has_stream_key).length;
return (
<div className="space-y-4">
@ -799,7 +985,10 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
<div>
<h3 className="text-sm font-medium text-slate-100">转播分配</h3>
<p className="mt-0.5 text-xs text-slate-500">
频道 + 直播 KEY → 抖音 URL 池 → 直播地址列表(精选)。开启自动推流后 FFmpeg 仅转播精选列表到 YouTube Live。
{timeSlotModeOn
? `时间段模式:有 KEY 的 ${keyedCount || "N"} 个频道平分 24 小时(北京时间),推流源=当前在播抖音;需同时打开「自动推流」才会轮询开播;开播前等待本频道 Neko 打开 YouTube Live。`
: "频道 + 直播 KEY → 抖音 URL 池 → 直播地址列表(精选)。开启自动推流后 FFmpeg 仅转播精选列表到 YouTube Live。"}
{exclusiveLiveOn ? " 单频道模式:某一频道开播时会暂停其他频道的 FFmpeg 与 Neko。" : ""}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
@ -811,6 +1000,22 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
label={relayStatus?.enabled ? "自动推流 开" : "自动推流 关"}
onChange={(v) => void toggleRelayPipeline(v)}
/>
<EnableSwitch
checked={timeSlotModeOn}
busy={relayBusy}
accent="teal"
size="md"
label={timeSlotModeOn ? "时间段模式 开" : "时间段模式 关"}
onChange={(v) => void toggleTimeSlotMode(v)}
/>
<EnableSwitch
checked={exclusiveLiveOn}
busy={relayBusy || timeSlotModeOn}
accent="amber"
size="md"
label={exclusiveLiveOn ? "单频道独占 开" : "单频道独占 关"}
onChange={(v) => void toggleExclusiveLive(v)}
/>
<button
type="button"
disabled={busy}
@ -835,6 +1040,34 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
</div>
</div>
{timeSlotModeOn ? (
<div className="mb-3 rounded-xl border border-violet-400/30 bg-violet-500/10 px-3 py-2 text-xs text-violet-100">
时间段模式:仅统计有直播 KEY 的频道(当前 {keyedCount} 个)
{keyedCount > 0 ? (
<span>
{" "}
· 每频道约 {(24 / keyedCount).toFixed(1)} 小时
</span>
) : (
<span> · 请先为频道配置 KEY</span>
)}
<span className="text-violet-200/70"> · 推流源取监控里正在播的抖音房间(非精选列表)</span>
</div>
) : null}
{exclusiveLiveOn && exclusiveWinnerId ? (
<div className="mb-3 rounded-xl border border-amber-400/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-100">
单频道独占中:<span className="font-medium">{exclusiveWinnerName}</span>
{(relayStatus?.neko_paused_instances?.length ?? 0) > 0 ? (
<span className="text-amber-200/80">
{" "}
· 已暂停 Neko {relayStatus?.neko_paused_instances?.join("、")}
</span>
) : null}
<span className="text-amber-200/70"> · 停止该频道后将恢复其他已启用的 Neko</span>
</div>
) : null}
<div className="mb-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
{[
{ label: "抖音在播", value: relayStatus?.douyin_live_count ?? "—" },
@ -848,15 +1081,61 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
</div>
))}
</div>
<div className="mb-3 rounded-xl border border-white/10 bg-black/30 px-3 py-3">
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
<div>
<div className="text-[10px] uppercase tracking-wider text-slate-500">转推画质预设</div>
<div className="mt-0.5 text-xs text-slate-400">
稳定推流优先于高分辨率;4 核 VPS 建议选 VPS Ultra,可随时切回 720p。
</div>
</div>
<select
value={relayStatus?.settings?.youtube_relay_quality_preset || "720p"}
disabled={relayBusy}
onChange={(e) => void setRelayQualityPreset(e.target.value)}
className="min-w-[12rem] rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm disabled:opacity-50"
>
{(relayStatus?.settings?.youtube_relay_quality_presets || []).map((p) => (
<option key={p.id} value={p.id}>
{p.label}
{p.recommended_for_vps ? " ★4核" : ""}
</option>
))}
</select>
</div>
{(() => {
const active =
relayStatus?.settings?.youtube_relay_quality_presets?.find((p) => p.active) ||
relayStatus?.settings?.youtube_relay_quality_presets?.find(
(p) => p.id === relayStatus?.settings?.youtube_relay_quality_preset
);
const enc = relayStatus?.settings?.youtube_relay_encoding;
if (!active && !enc) return null;
return (
<div className="text-[11px] text-slate-500">
{active?.description ||
`${enc?.width}×${enc?.height} · ${enc?.fps}fps · ${enc?.x264_preset} · ${enc?.bitrate_kbps}k`}
</div>
);
})()}
</div>
{relayStatus?.last_error ? (
<div className="mb-3 rounded-lg bg-rose-500/10 px-3 py-2 text-[11px] text-rose-200">{relayStatus.last_error}</div>
) : null}
<div className="grid gap-2 sm:grid-cols-[1.2fr_1fr_auto]">
<form
className="grid gap-2 sm:grid-cols-[1.2fr_1fr_auto]"
autoComplete="off"
onSubmit={(e) => {
e.preventDefault();
void createGroup();
}}
>
<select
value={newChannelPk}
onChange={(e) => setNewChannelPk(e.target.value)}
className="rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm"
autoComplete="off"
>
<option value="">选择已授权频道…</option>
{availableChannels.map((c) => (
@ -869,19 +1148,26 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
<input
value={newStreamKey}
onChange={(e) => setNewStreamKey(e.target.value)}
placeholder="直播推流 KEY(可后填)"
placeholder="直播推流 KEY(可后填,勿填登录密码)"
name="yt-live-stream-key-new"
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck={false}
data-lpignore="true"
data-1p-ignore="true"
data-form-type="other"
className="rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
<button
type="button"
type="submit"
disabled={busy || !newChannelPk}
onClick={() => void createGroup()}
className="inline-flex items-center justify-center gap-1 rounded-xl bg-[#ff2d55] px-4 py-2 text-sm text-white disabled:opacity-40"
>
<Plus className="h-4 w-4" />
新建分组
</button>
</div>
</form>
{channels.length === 0 ? (
<p className="mt-3 text-xs text-amber-200">
还没有已授权频道。请先到{" "}
@ -915,9 +1201,15 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
<section className="rounded-2xl border border-violet-500/25 bg-violet-500/5 p-4">
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
<div>
<h4 className="text-sm font-medium text-violet-100">24 小时频道轮播(北京时间)</h4>
<h4 className="text-sm font-medium text-violet-100">
{timeSlotModeOn || schedule.time_slot_mode
? "时间段模式 · 有 KEY 频道轮播(北京时间)"
: "24 小时频道轮播(北京时间)"}
</h4>
<p className="text-[11px] text-violet-200/70">
{schedule.channel_count} 个频道 · 每频道约 {schedule.slot_hours} 小时 · 当前 {schedule.now_label}
{schedule.channel_count} 个频道 · 每频道约 {schedule.slot_hours} 小时 · 当前{" "}
{schedule.now_label}
{timeSlotModeOn ? " · 源=在播抖音" : ""}
</p>
</div>
<button
@ -1052,7 +1344,11 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
onNekoChange={() => void loadGroups()}
/>
<YtRelayLiveLogCard row={selectedMonitor} onRefresh={() => void loadRelay()} />
<YtRelayLiveLogCard
row={selectedMonitor}
pollMs={isLivePushingRow(selectedMonitor) ? 5000 : 15000}
onRefresh={() => void loadRelay()}
/>
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
@ -1086,6 +1382,14 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
value={streamKeyDraft}
onChange={(e) => setStreamKeyDraft(e.target.value)}
placeholder="YouTube 直播推流密钥"
name="yt-live-stream-key"
autoComplete="new-password"
autoCorrect="off"
autoCapitalize="off"
spellCheck={false}
data-lpignore="true"
data-1p-ignore="true"
data-form-type="other"
className="w-full rounded-xl border border-white/10 bg-slate-900 px-3 py-2 pr-10 font-mono text-sm"
/>
<button
@ -1149,7 +1453,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
</div>
</div>
<p className="mb-3 text-[11px] text-slate-500">
支持:https://live.douyin.com/房间号,主播: 名称,
支持:https://live.douyin.com/房间号,主播: 名称, · 加入后同步写入直播池(概览/监控)
</p>
<textarea
value={poolDraft}
@ -1196,7 +1500,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
/>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-1.5">
<div className="truncate text-sm text-slate-100">{u.title || "未命名主播"}</div>
<div className="truncate text-sm text-slate-100">{displayAnchor(u)}</div>
{u.room_id ? <DouyinLiveBadge roomId={u.room_id} compact showOffline /> : null}
{banned ? (
<span className="rounded bg-fuchsia-500/25 px-1.5 text-[10px] text-fuchsia-100">
@ -1342,7 +1646,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
/>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-1.5">
<div className="truncate text-sm text-violet-50">{s.title || "未命名主播"}</div>
<div className="truncate text-sm text-violet-50">{displayAnchor(s)}</div>
{s.room_id ? <DouyinLiveBadge roomId={s.room_id} compact showOffline /> : null}
{timeLabel ? (
<span className="rounded bg-violet-500/25 px-1.5 text-[10px] text-violet-100">
@ -1464,7 +1768,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
/>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-1.5">
<div className="truncate text-sm text-amber-50">{f.title || "未命名主播"}</div>
<div className="truncate text-sm text-amber-50">{displayAnchor(f)}</div>
{f.room_id ? <DouyinLiveBadge roomId={f.room_id} compact showOffline /> : null}
{banned ? (
<span className="rounded bg-fuchsia-500/25 px-1.5 text-[10px] text-fuchsia-100">

View File

@ -3,7 +3,13 @@
import { AlertTriangle, Pause, Play, RefreshCw } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { isLivePushingRow, type RelayMonitorRow } from "@/lib/ytRelayStatus";
import {
businessStatusBadgeClass,
businessStatusLabel,
isLivePushingRow,
type RelayMonitorRow,
} from "@/lib/ytRelayStatus";
import { coerceLogText } from "@/lib/ffmpegMetrics";
type Props = {
row?: RelayMonitorRow;
@ -16,9 +22,10 @@ export function YtRelayLiveLogCard({ row, pollMs = 3500, onRefresh }: Props) {
const outRef = useRef<HTMLPreElement>(null);
const errRef = useRef<HTMLPreElement>(null);
const recentLog = row?.recent_log || "";
const recentError = row?.recent_error || "";
const recentLog = coerceLogText(row?.recent_log);
const recentError = coerceLogText(row?.recent_error);
const pushingNow = isLivePushingRow(row);
const statusLabel = businessStatusLabel(row);
const youtubeKeyRejected = row?.business_status === "youtube_key_rejected";
useEffect(() => {
@ -32,16 +39,20 @@ export function YtRelayLiveLogCard({ row, pollMs = 3500, onRefresh }: Props) {
pollMs >= 8000 ? "慢速刷新" : pollMs >= 4000 ? "常速刷新" : "快速刷新";
return (
<section className="rounded-2xl border border-emerald-500/20 bg-gradient-to-b from-emerald-500/[0.07] to-black/40 p-4 ring-1 ring-white/[0.04]">
<section
className={`rounded-2xl border p-4 ring-1 ring-white/[0.04] ${
pushingNow
? "border-emerald-500/20 bg-gradient-to-b from-emerald-500/[0.07] to-black/40"
: "border-white/10 bg-gradient-to-b from-white/[0.04] to-black/40"
}`}
>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-sm font-semibold text-white">当前直播日志</h3>
{pushingNow ? (
<span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-500/15 px-2.5 py-0.5 text-[10px] font-medium text-emerald-100 ring-1 ring-emerald-500/25">
<span className="live-dot" />
推流中
</span>
) : null}
<span className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[10px] font-medium ring-1 ${businessStatusBadgeClass(row)}`}>
{pushingNow ? <span className="live-dot" /> : null}
{statusLabel}
</span>
<span className="rounded-full bg-zinc-500/15 px-2 py-0.5 text-[10px] font-medium text-zinc-200 ring-1 ring-zinc-500/25">
{refreshBadge}
</span>
@ -70,6 +81,12 @@ export function YtRelayLiveLogCard({ row, pollMs = 3500, onRefresh }: Props) {
</div>
</div>
{!pushingNow ? (
<p className="mt-3 text-[11px] text-slate-500">
当前未在推流。下方为最近一次会话残留日志(非实时指标);状态变更后会同步刷新。
</p>
) : null}
{youtubeKeyRejected ? (
<div className="mt-4 rounded-lg border border-rose-500/30 bg-rose-500/[0.10] px-3 py-2.5 text-xs text-rose-100 ring-1 ring-rose-500/15">
<div className="flex gap-2">
@ -83,10 +100,20 @@ export function YtRelayLiveLogCard({ row, pollMs = 3500, onRefresh }: Props) {
<div className="mt-4 grid gap-4 lg:grid-cols-2">
<div>
<div className="text-[11px] font-semibold uppercase tracking-wider text-emerald-400/90">进程输出</div>
<div
className={`text-[11px] font-semibold uppercase tracking-wider ${
pushingNow ? "text-emerald-400/90" : "text-slate-500"
}`}
>
进程输出{pushingNow ? "" : " · 历史"}
</div>
<pre
ref={outRef}
className="mt-2 max-h-[min(22rem,42vh)] min-h-[12rem] overflow-auto whitespace-pre-wrap rounded-xl border border-emerald-500/20 bg-black/55 p-3 font-mono text-[10px] leading-relaxed text-emerald-100/95"
className={`mt-2 max-h-[min(22rem,42vh)] min-h-[12rem] overflow-auto whitespace-pre-wrap rounded-xl border bg-black/55 p-3 font-mono text-[10px] leading-relaxed ${
pushingNow
? "border-emerald-500/20 text-emerald-100/95"
: "border-white/10 text-slate-400"
}`}
>
{recentLog.trim() || "(暂无)"}
</pre>

View File

@ -19,6 +19,7 @@ import {
isLivePushingRow,
laneStatusEmoji,
procStartBlocked,
procStartBlockReason,
type RelayMonitorRow,
} from "@/lib/ytRelayStatus";
@ -38,6 +39,7 @@ type NekoState = {
ready?: boolean;
status?: string;
studio_url?: string;
detail?: string;
};
type Props = {
@ -50,11 +52,14 @@ type Props = {
onNekoChange?: () => void;
};
function nekoStatusLabel(st?: NekoState | null): string {
if (!st) return "未配置";
function nekoStatusLabel(st?: NekoState | null, instanceId?: number, pollErr?: string): string {
if (!instanceId || instanceId < 1) return "未配置";
if (pollErr) return "状态未知";
if (!st) return "检测中";
if (st.ready) return "运行中";
if (st.running) return "启动中";
return st.status === "missing" ? "未创建" : "已停止";
if (st.status === "missing") return "容器缺失";
return "已停止";
}
/** Single-channel Pro relay status + per-channel Neko studio — embedded in 分配. */
@ -75,37 +80,55 @@ export function YtRelayProStatusPanel({
const urlCount = row?.url_count ?? (group.featured || []).length;
const dyCount = row?.douyin_count ?? urlCount;
const blocked = procStartBlocked(row);
const metrics = mergeFfmpegMetrics(row, row?.recent_log || "");
const statsText = formatFfmpegStatsBrief(metrics, { live: metrics.live || isLivePushingRow(row) });
const blockReason = procStartBlockReason(row);
const pushing = isLivePushingRow(row);
const starting = row?.business_status === "relay_starting";
const logText = typeof row?.recent_log === "string" ? row.recent_log : Array.isArray(row?.recent_log) ? (row?.recent_log as string[]).join("\n") : "";
const metrics = mergeFfmpegMetrics(row, logText);
const statsText = formatFfmpegStatsBrief(metrics, { live: pushing });
const busy = relayKickId === group.id;
const instanceId = Number(group.neko_instance_id || 0);
const [nekoEnabled, setNekoEnabled] = useState(Boolean(group.neko_enabled));
const instanceId = Number(group.neko_instance_id || row?.neko_instance_id || 0);
const [nekoEnabled, setNekoEnabled] = useState(Boolean(group.neko_enabled ?? row?.neko_enabled));
const [nekoBusy, setNekoBusy] = useState(false);
const [nekoState, setNekoState] = useState<NekoState | null>(null);
const [nekoState, setNekoState] = useState<NekoState | null>((row?.neko as NekoState) || null);
const [nekoPollErr, setNekoPollErr] = useState("");
const studioUrl = String(nekoState?.studio_url || group.neko_studio_url || "").trim();
useEffect(() => {
setNekoEnabled(Boolean(group.neko_enabled));
}, [group.id, group.neko_enabled]);
setNekoEnabled(Boolean(group.neko_enabled ?? row?.neko_enabled));
}, [group.id, group.neko_enabled, row?.neko_enabled]);
// Prefer Neko snapshot from relay/status (3.5s) — avoids a second docker poll loop.
useEffect(() => {
if (row?.neko) {
setNekoState(row.neko as NekoState);
setNekoPollErr("");
}
}, [row?.neko, row?.neko?.status, row?.neko?.ready, row?.neko?.running, row?.neko?.studio_url]);
const refreshNeko = useCallback(async () => {
if (instanceId < 1) return;
try {
const st = (await fetchJson("/api/youtube/neko/status")) as { instances?: NekoState[] };
const st = (await fetchJson("/api/youtube/neko/status")) as { instances?: NekoState[]; available?: boolean };
if (st.available === false) {
setNekoPollErr("Docker 不可用");
return;
}
const inst = (st.instances || []).find((x) => Number((x as { id?: number }).id) === instanceId);
if (inst) setNekoState(inst);
} catch {
/* ignore poll errors */
setNekoPollErr("");
} catch (e) {
setNekoPollErr((e as Error).message || "状态查询失败");
}
}, [instanceId]);
// Fallback only when relay payload has no neko field yet (old API / cold start).
useEffect(() => {
void refreshNeko();
if (instanceId < 1) return;
const t = window.setInterval(() => void refreshNeko(), 12000);
return () => window.clearInterval(t);
}, [instanceId, refreshNeko]);
if (row?.neko) return;
void refreshNeko();
}, [instanceId, row?.neko, refreshNeko]);
async function postNeko(body: Record<string, unknown>) {
setNekoBusy(true);
@ -199,7 +222,15 @@ export function YtRelayProStatusPanel({
onClick={() => onStart(group.id)}
className="rounded-lg bg-emerald-500/20 px-2.5 py-1.5 text-[11px] text-emerald-100 ring-1 ring-emerald-500/30 disabled:opacity-40"
>
{busy ? <Loader2 className="h-3 w-3 animate-spin" /> : "开始"}
{busy ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : pushing ? (
"推流中"
) : starting ? (
"启动中…"
) : (
"开始"
)}
</button>
<button
type="button"
@ -221,6 +252,13 @@ export function YtRelayProStatusPanel({
</div>
</div>
{blockReason ? (
<p className="mt-2 text-[10px] text-amber-200/90">无法开始:{blockReason}</p>
) : null}
{!group.has_stream_key ? (
<p className="mt-2 text-[10px] text-rose-200/80">未配置推流密钥,无法启动 FFmpeg。</p>
) : null}
{instanceId > 0 ? (
<div className="mt-3 rounded-lg border border-violet-500/20 bg-violet-500/[0.06] px-3 py-2.5">
<div className="flex flex-wrap items-center justify-between gap-2">
@ -236,10 +274,12 @@ export function YtRelayProStatusPanel({
? "bg-emerald-500/20 text-emerald-200"
: nekoState?.running
? "bg-amber-500/20 text-amber-100"
: "bg-white/5 text-slate-400"
: nekoPollErr
? "bg-rose-500/15 text-rose-200"
: "bg-white/5 text-slate-400"
}`}
>
{nekoStatusLabel(nekoState)}
{nekoStatusLabel(nekoState, instanceId, nekoPollErr)}
</span>
</div>
<EnableSwitch
@ -250,7 +290,13 @@ export function YtRelayProStatusPanel({
/>
</div>
<p className="mt-1 text-[10px] text-slate-500">
新建分组时自动分配 Neko 实例(默认关闭)。用于 YouTube Studio 操作,不阻塞 FFmpeg 推流。美国 VPS 直连,不走 ShellClash。
新建分组自动创建 Docker 容器(默认停止)。美国 VPS 直连 YouTube Studio,不走 ShellClash;不阻塞 FFmpeg 推流。
</p>
<p className="mt-1 text-[10px] text-violet-200/80">
登录:用户名任意 · 普通密码 <span className="font-mono">douyinweb</span> · 管理员密码见服务器{" "}
<span className="font-mono">DY_NEKO_ADMIN_PASS</span>
。Neko 按 sh2:Tampermonkey 经 Chrome 策略安装,「YouTube Studio Auto Dismiss」由 provisioning 导入油猴(不走独立扩展)。
{nekoPollErr ? <span className="ml-2 text-rose-300">({nekoPollErr})</span> : null}
</p>
<div className="mt-2 flex flex-wrap gap-1.5">
{studioUrl ? (

View File

@ -40,7 +40,13 @@ export async function fetchJson(url, init) {
}
}
if (!res.ok) {
const detail = data?.detail || data?.message || text || res.statusText;
let detail = data?.detail || data?.message || text || res.statusText;
if (typeof detail === "string" && /<html[\s>]/i.test(detail)) {
if (res.status === 502) detail = "502 Bad Gateway(后端暂时不可用,请稍后刷新页面)";
else if (res.status === 503) detail = "503 Service Unavailable(服务维护中,请稍后刷新)";
else if (res.status === 504) detail = "504 Gateway Timeout(请求超时,请稍后重试)";
else detail = `${res.status} ${res.statusText || "请求失败"}(请刷新页面重试)`;
}
throw new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
}
return data;
@ -139,23 +145,25 @@ export function fmtClock(ts) {
}
}
/** Prefer public S3 URL (feiniu); proxy only as fallback. */
/** Prefer channel avatar, then public S3 cover, then API proxy. */
export function sessionCoverSrc(session, bust = true) {
if (!session) return "";
const avatarUrl = String(session.avatar_url || "").trim();
const publicUrl = String(session.cover_url || "").trim();
const proxyUrl = String(session.cover_proxy_url || "").trim();
const fallback = session.id ? `/api/sessions/${session.id}/cover` : "";
// Prefer absolute http(s) public object URL over API proxy hop.
// Channel avatar (S3) first — stream-frame covers are not profile faces.
const base =
(avatarUrl.startsWith("http://") || avatarUrl.startsWith("https://") ? avatarUrl : "") ||
(publicUrl.startsWith("http://") || publicUrl.startsWith("https://") ? publicUrl : "") ||
(proxyUrl.startsWith("http://") || proxyUrl.startsWith("https://") ? proxyUrl : "") ||
proxyUrl ||
fallback ||
publicUrl ||
avatarUrl ||
"";
if (!base) return "";
if (!bust) return base;
// Stable cache key from session identity (avoid Date.now() thrashing).
const ts = session.started_at || session.updated_at || session.id || "";
if (!ts) return base;
return base.includes("?") ? `${base}&v=${ts}` : `${base}?v=${ts}`;

View File

@ -10,6 +10,7 @@ export type DouyinLiveEntry = {
last_status?: string;
anchor?: string;
url?: string;
avatar_url?: string;
last_checked_at?: number;
active_session_id?: string;
};
@ -32,7 +33,7 @@ const DouyinLiveContext = createContext<{
refresh: async () => {},
});
export function useDouyinLiveProviderValue(intervalMs = 10000) {
export function useDouyinLiveProviderValue(intervalMs = 25000) {
const [map, setMap] = useState<DouyinLiveMap | null>(null);
const [loading, setLoading] = useState(false);
const { tick, last } = useEventStream(true);
@ -51,7 +52,10 @@ export function useDouyinLiveProviderValue(intervalMs = 10000) {
useEffect(() => {
void refresh(true);
const id = window.setInterval(() => void refresh(true), intervalMs);
const id = window.setInterval(() => {
if (document.hidden) return;
void refresh(true);
}, intervalMs);
const onVis = () => {
if (document.visibilityState === "visible") void refresh(true);
};
@ -65,6 +69,7 @@ export function useDouyinLiveProviderValue(intervalMs = 10000) {
useEffect(() => {
if (!last?.kind) return;
if (!["live", "offline", "risk"].includes(String(last.kind))) return;
if (document.hidden) return;
void refresh(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tick]);

View File

@ -14,6 +14,7 @@ type ProcessRowHint = {
ffmpeg_bitrate_kbps?: number | null;
ffmpeg_active?: boolean;
is_pushing?: boolean;
business_status?: string;
ffmpeg_speed_low?: boolean;
ffmpeg_progress_stalled?: boolean;
};
@ -28,9 +29,15 @@ function parseMetricNumber(value: string, asInt = false): number | undefined {
return Number.isFinite(parsed) ? parsed : undefined;
}
export function coerceLogText(log: unknown): string {
if (Array.isArray(log)) return log.map((x) => String(x ?? "")).join("\n");
return String(log || "");
}
export function latestFfmpegStatsLine(logText: string, lookback = 12): string {
const lines = logText
.split(/\r?\n/)
.replace(/\r/g, "\n")
.split(/\n/)
.map((line) => line.trim())
.filter(Boolean);
const tail = lines.slice(-lookback);
@ -69,12 +76,23 @@ function pickNumber(...values: Array<number | null | undefined>): number | undef
return undefined;
}
function rowIsLive(row?: ProcessRowHint): boolean {
if (!row) return false;
if (row.is_pushing) return true;
const b = String(row.business_status || "").toLowerCase();
return b === "streaming" || b === "relay_slow" || b === "source_stalled";
}
export function mergeFfmpegMetrics(
row?: ProcessRowHint,
logText = "",
logText: unknown = "",
): FfmpegMetrics & { speedLow?: boolean; progressStalled?: boolean; live: boolean } {
const fromLog = parseFfmpegMetricsFromLog(logText);
const live = !!row?.is_pushing;
const live = rowIsLive(row);
// Only surface live encode metrics while actively pushing — never ghost stale fps/speed.
if (!live) {
return { live: false, speedLow: false, progressStalled: false };
}
const fromLog = parseFfmpegMetricsFromLog(coerceLogText(logText));
return {
frame: pickNumber(row?.ffmpeg_frame, fromLog.frame),
fps: pickNumber(row?.ffmpeg_fps, fromLog.fps),
@ -84,7 +102,7 @@ export function mergeFfmpegMetrics(
dup: fromLog.dup,
speedLow: row?.ffmpeg_speed_low,
progressStalled: row?.ffmpeg_progress_stalled,
live,
live: true,
};
}
@ -101,6 +119,13 @@ export function formatFfmpegMetricValue(value: number | undefined, suffix = "",
}
export function formatFfmpegStatsBrief(metrics: FfmpegMetrics, opts?: { live?: boolean }): string {
if (!opts?.live) return "";
const hasAny =
typeof metrics.fps === "number" ||
typeof metrics.speed === "number" ||
typeof metrics.frame === "number" ||
typeof metrics.bitrate === "number";
if (!hasAny) return "";
const parts = [
`fps ${formatFfmpegMetricValue(metrics.fps)}`,
`speed ${formatFfmpegMetricValue(metrics.speed, "x")}`,
@ -108,7 +133,6 @@ export function formatFfmpegStatsBrief(metrics: FfmpegMetrics, opts?: { live?: b
];
const bitrate = formatBitrateLabel(metrics.bitrate);
if (bitrate) parts.push(bitrate);
if (!opts?.live && parts.every((part) => part.endsWith("—"))) return "";
return parts.join(" · ");
}

View File

@ -15,43 +15,93 @@ export type StreamEvent = {
export type RefreshOpts = { silent?: boolean };
/** One shared EventSource for the whole tab — avoids N sockets from Shell/home/alerts. */
type SharedBus = {
es: EventSource | null;
refs: number;
connected: boolean;
last: StreamEvent | null;
tick: number;
retryTimer: number;
listeners: Set<() => void>;
};
const bus: SharedBus = {
es: null,
refs: 0,
connected: false,
last: null,
tick: 0,
retryTimer: 0,
listeners: new Set(),
};
function notifyBus() {
for (const fn of bus.listeners) fn();
}
function openSharedStream() {
if (bus.es) return;
const es = new EventSource("/api/events/stream");
bus.es = es;
es.onopen = () => {
bus.connected = true;
notifyBus();
};
es.onerror = () => {
bus.connected = false;
es.close();
bus.es = null;
notifyBus();
if (bus.refs > 0 && !bus.retryTimer) {
bus.retryTimer = window.setTimeout(() => {
bus.retryTimer = 0;
if (bus.refs > 0) openSharedStream();
}, 2500);
}
};
es.onmessage = (msg) => {
try {
bus.last = JSON.parse(msg.data) as StreamEvent;
bus.tick += 1;
notifyBus();
} catch {
/* ignore */
}
};
}
function releaseSharedStream() {
bus.refs = Math.max(0, bus.refs - 1);
if (bus.refs > 0) return;
window.clearTimeout(bus.retryTimer);
bus.retryTimer = 0;
bus.es?.close();
bus.es = null;
bus.connected = false;
}
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);
const [connected, setConnected] = useState(bus.connected);
const [last, setLast] = useState<StreamEvent | null>(bus.last);
const [tick, setTick] = useState(bus.tick);
const enabledRef = useRef(enabled);
enabledRef.current = enabled;
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 */
}
};
bus.refs += 1;
openSharedStream();
const onChange = () => {
setConnected(bus.connected);
setLast(bus.last);
setTick(bus.tick);
};
connect();
bus.listeners.add(onChange);
onChange();
return () => {
closed = true;
window.clearTimeout(retryTimer);
esRef.current?.close();
bus.listeners.delete(onChange);
releaseSharedStream();
};
}, [enabled]);
@ -83,13 +133,25 @@ export function useAutoRefresh(
if (!enabled) return;
void loadRef.current({ silent: false });
if (!intervalMs || intervalMs <= 0) return;
const t = window.setInterval(() => void loadRef.current({ silent: true }), intervalMs);
return () => window.clearInterval(t);
const tickSilent = () => {
if (typeof document !== "undefined" && document.hidden) return;
void loadRef.current({ silent: true });
};
const t = window.setInterval(tickSilent, intervalMs);
const onVis = () => {
if (!document.hidden) void loadRef.current({ silent: true });
};
document.addEventListener("visibilitychange", onVis);
return () => {
window.clearInterval(t);
document.removeEventListener("visibilitychange", onVis);
};
}, [load, intervalMs, enabled]);
useEffect(() => {
if (!enabled || !eventKinds || !last?.kind) return;
if (!eventKinds.includes(String(last.kind))) return;
if (typeof document !== "undefined" && document.hidden) return;
void loadRef.current({ silent: true });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tick, enabled]);

View File

@ -0,0 +1,73 @@
export type NavItem = { href: string; label: string; emoji: string };
/** Top-level shell navigation */
export const MAIN_NAV: NavItem[] = [
{ href: "/", label: "抖音", emoji: "📡" },
{ href: "/youtube", label: "YouTube", emoji: "▶️" },
{ href: "/tiktok", label: "TikTok", emoji: "🎵" },
{ href: "/x", label: "X", emoji: "𝕏" },
{ href: "/web", label: "Web", emoji: "🌐" },
{ href: "/ops", label: "运维", emoji: "🛰️" },
{ href: "/settings", label: "设置", emoji: "⚙️" },
];
/** Sub-tabs under 抖音 */
export const OVERVIEW_TABS: NavItem[] = [
{ href: "/", label: "概览", emoji: "📡" },
{ href: "/rooms", label: "直播间", emoji: "🏠" },
{ href: "/slots", label: "时段", emoji: "🕐" },
{ href: "/sessions", label: "场次", emoji: "🎬" },
{ href: "/anchors", label: "主播", emoji: "👤" },
{ href: "/covers", label: "截图", emoji: "🖼️" },
{ href: "/events", label: "事件", emoji: "⚡" },
{ href: "/blacklist", label: "黑名单", emoji: "🚫" },
];
/** Sub-tabs under YouTube */
export const LIVE_TABS: NavItem[] = [
{ href: "/youtube", label: "直播Live", emoji: "▶️" },
{ href: "/shorts", label: "Shorts", emoji: "📱" },
{ href: "/yt-long", label: "长视频", emoji: "🎞️" },
];
/** Sub-tabs under 运维 */
export const OPS_TABS: NavItem[] = [
{ href: "/ops", label: "运维", emoji: "🛰️" },
{ href: "/clash", label: "Clash", emoji: "🧿" },
{ href: "/downloads", label: "下载", emoji: "⬇️" },
];
const OVERVIEW_PATHS = OVERVIEW_TABS.map((t) => t.href);
const LIVE_PATHS = ["/youtube", "/shorts", "/yt-long", "/youtube-relay-log", "/youtube/health"];
const OPS_PATHS = OPS_TABS.map((t) => t.href);
export type NavSection = "overview" | "live" | "ops";
export function navPathActive(pathname: string, href: string): boolean {
if (href === "/") return pathname === "/";
return pathname === href || pathname.startsWith(`${href}/`);
}
export function mainNavActive(pathname: string, href: string): boolean {
if (href === "/") return OVERVIEW_PATHS.some((p) => navPathActive(pathname, p));
if (href === "/youtube") return LIVE_PATHS.some((p) => navPathActive(pathname, p));
if (href === "/ops") return OPS_PATHS.some((p) => navPathActive(pathname, p));
return navPathActive(pathname, href);
}
export function shellSection(pathname: string): NavSection | null {
if (OVERVIEW_PATHS.some((p) => navPathActive(pathname, p))) return "overview";
if (LIVE_PATHS.some((p) => navPathActive(pathname, p))) return "live";
if (OPS_PATHS.some((p) => navPathActive(pathname, p))) return "ops";
return null;
}
export function sectionTabs(section: NavSection | null): NavItem[] {
if (section === "overview") return OVERVIEW_TABS;
if (section === "live") return LIVE_TABS;
if (section === "ops") return OPS_TABS;
return [];
}
/** Mobile bottom bar: 抖音 / YouTube / TikTok / X */
export const MOBILE_PRIMARY = ["/", "/youtube", "/tiktok", "/x"];

View File

@ -44,7 +44,7 @@ export function channelLiveRef(channelId: string) {
return `channel:${channelId}`;
}
export function useYouTubeLiveProviderValue(intervalMs = 15000) {
export function useYouTubeLiveProviderValue(intervalMs = 35000) {
const [map, setMap] = useState<YouTubeLiveMap | null>(null);
const [loading, setLoading] = useState(false);
@ -63,7 +63,10 @@ export function useYouTubeLiveProviderValue(intervalMs = 15000) {
useEffect(() => {
void refresh(true);
const id = window.setInterval(() => void refresh(true), intervalMs);
const id = window.setInterval(() => {
if (document.hidden) return;
void refresh(true);
}, intervalMs);
const onVis = () => {
if (document.visibilityState === "visible") void refresh(true);
};

View File

@ -27,6 +27,16 @@ export type RelayMonitorRow = {
douyin_count?: number;
has_stream_key?: boolean;
stream_key_suffix?: string;
neko_instance_id?: number;
neko_enabled?: boolean;
neko?: {
id?: number;
running?: boolean;
ready?: boolean;
status?: string;
studio_url?: string;
detail?: string;
} | null;
};
export function businessStatusLabel(row?: RelayMonitorRow): string {
@ -36,16 +46,16 @@ export function businessStatusLabel(row?: RelayMonitorRow): string {
if (business === "source_stalled") return "源卡住";
if (business === "relay_slow") return "低速推流";
if (business === "relay_starting") return "转推启动中";
if (business === "waiting_source") return "等待上游";
if (business === "waiting_source") return "等待直播";
if (business === "source_live") return "源已开播";
if (business === "monitoring") return "监控中";
if (business === "monitoring") return "监听中";
if (business === "misconfigured") return "密钥异常";
if (business === "youtube_key_rejected") return "密钥被拒";
if (business === "stale") return "心跳过期";
if (business === "error") return "异常";
if (business === "inactive") return "未运行";
const ps = (row?.process_status || "").trim().toLowerCase();
if (ps === "online" || ps === "running") return "运行中";
// Do NOT fall back to vague「运行中」while leaking live metrics — idle/unknown only.
if (row?.is_pushing) return "推流中";
return "空闲";
}
@ -62,12 +72,13 @@ export function businessStatusBadgeClass(row?: RelayMonitorRow): string {
if (business === "misconfigured" || business === "youtube_key_rejected" || business === "error" || business === "stale") {
return "bg-rose-500/15 text-rose-100 ring-rose-500/25";
}
if (row?.is_pushing) return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30";
return "bg-zinc-600/20 text-zinc-400 ring-zinc-500/25";
}
export function laneStatusEmoji(row?: RelayMonitorRow): string {
const business = (row?.business_status || "").trim().toLowerCase();
if (business === "streaming") return "🟢";
if (business === "streaming" || row?.is_pushing) return "🟢";
if (business === "relay_slow") return "🟡";
if (business === "source_stalled") return "🟠";
if (business === "relay_starting") return "🔵";
@ -78,9 +89,33 @@ export function laneStatusEmoji(row?: RelayMonitorRow): string {
}
export function isLivePushingRow(row?: RelayMonitorRow): boolean {
return !!row?.is_pushing || row?.business_status === "streaming" || row?.business_status === "relay_slow";
if (!row) return false;
if (row.is_pushing) return true;
const business = (row.business_status || "").trim().toLowerCase();
return business === "streaming" || business === "relay_slow" || business === "source_stalled";
}
export function procStartBlocked(row?: RelayMonitorRow): boolean {
return isLivePushingRow(row) || row?.process_status === "online";
if (isLivePushingRow(row)) return true;
if (row?.business_status === "relay_starting") return true;
return false;
}
/** Real failure text for「无法开始」— not success states like「正在推流」. */
export function procStartBlockReason(row?: RelayMonitorRow): string {
if (!row) return "";
if (isLivePushingRow(row) || row.business_status === "relay_starting") return "";
const err = String(row.recent_error || row.error || "").trim();
if (err) return err;
const business = String(row.business_status || "").trim().toLowerCase();
if (
business === "misconfigured" ||
business === "youtube_key_rejected" ||
business === "error" ||
business === "stale" ||
business === "source_stalled"
) {
return String(row.business_note || "").trim();
}
return "";
}

178
scripts/_deploy_netdata.py Normal file
View File

@ -0,0 +1,178 @@
# -*- coding: utf-8 -*-
"""Install Netdata + deploy host metrics UI to dy.nomadro.live (session-gated /netdata/)."""
from __future__ import annotations
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST = "108.174.50.68"
ROOT = Path(__file__).resolve().parents[1]
APP = "/opt/douyinWEB"
API_PORT = 8014
FILES = [
"backend/app/host_metrics.py",
"backend/app/main.py",
"backend/app/ops_panel.py",
"frontend/src/components/HostResourceBar.tsx",
"frontend/src/components/Shell.tsx",
"frontend/src/app/ops/page.tsx",
]
REMOTE = """#!/usr/bin/env bash
set -euo pipefail
API_PORT=__API_PORT__
echo "=== install netdata if missing ==="
if ! command -v netdata >/dev/null 2>&1 && [ ! -x /usr/sbin/netdata ]; then
curl -fsSL https://get.netdata.cloud/kickstart.sh -o /tmp/netdata-kickstart.sh
sh /tmp/netdata-kickstart.sh --non-interactive --stable-channel --disable-telemetry --dont-wait || true
fi
systemctl enable netdata 2>/dev/null || true
echo "=== netdata: localhost + subpath /netdata + disable cloud ==="
mkdir -p /etc/systemd/system/netdata.service.d
cat >/etc/systemd/system/netdata.service.d/web-path.conf <<'EOF'
[Service]
Environment=NETDATA_WEB_PATH=/netdata
EOF
if [ -f /etc/netdata/netdata.conf ]; then
if grep -q '^[[:space:]]*bind to' /etc/netdata/netdata.conf; then
sed -i 's/^[[:space:]]*bind to = .*/ bind to = 127.0.0.1/' /etc/netdata/netdata.conf || true
else
printf '\\n[web]\\n bind to = 127.0.0.1\\n' >>/etc/netdata/netdata.conf
fi
fi
mkdir -p /etc/netdata
touch /etc/netdata/netdata.conf
if grep -q '^\\[cloud\\]' /etc/netdata/netdata.conf; then
sed -i '/^\\[cloud\\]/,/^\\[/{{ /^[[:space:]]*enabled =/s/.*/ enabled = no/; }}' /etc/netdata/netdata.conf || true
else
printf '\\n[cloud]\\n enabled = no\\n' >>/etc/netdata/netdata.conf
fi
systemctl daemon-reload
systemctl restart netdata
sleep 3
systemctl is-active netdata
curl -sS -o /dev/null -w "netdata_subpath=%{{http_code}}\\n" http://127.0.0.1:19999/netdata/api/v1/info
echo "=== nginx /netdata/ (auth_request + websocket) ==="
CONF=/etc/nginx/conf.d/dy-nomadro-live.conf
python3 <<'PY'
import re
from pathlib import Path
API_PORT = "__API_PORT__"
conf = Path("/etc/nginx/conf.d/dy-nomadro-live.conf")
text = conf.read_text(encoding="utf-8")
bak = conf.with_suffix(".conf.bak.netdata-fix")
if not bak.exists():
bak.write_text(text, encoding="utf-8")
for pat in (
r"\\n location = /_douyinweb_netdata_auth \\{.*?\\n \\}\\n?",
r"\\n location @douyinweb_netdata_login \\{.*?\\n \\}\\n?",
r"\\n location \\^~ /netdata/ \\{.*?\\n \\}\\n?",
):
text = re.sub(pat, "\\n", text, flags=re.DOTALL)
block = f'''
location = /_douyinweb_netdata_auth {{
internal;
proxy_pass http://127.0.0.1:{API_PORT}/api/auth/netdata-gate;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header Cookie $http_cookie;
proxy_set_header Host $host;
}}
location @douyinweb_netdata_login {{
return 302 /login?next=/ops;
}}
location ^~ /netdata/ {{
auth_request /_douyinweb_netdata_auth;
error_page 401 = @douyinweb_netdata_login;
proxy_pass http://127.0.0.1:19999/netdata/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 600s;
proxy_buffering off;
proxy_hide_header X-Frame-Options;
add_header X-Frame-Options SAMEORIGIN always;
}}
'''
marker = " location ^~ /douyin-covers/"
if marker not in text:
marker = " location / {"
if "_douyinweb_netdata_auth" not in text:
text = text.replace(marker, block + marker, 1)
conf.write_text(text, encoding="utf-8")
print("nginx patched", conf)
PY
nginx -t
nginx -s reload
curl -sS -o /dev/null -w "netdata_nginx_no_cookie=%{{http_code}}\\n" -k https://127.0.0.1/netdata/ -H "Host: dy.nomadro.live" || true
echo "=== build web ==="
cd /opt/douyinWEB/frontend
npm run build 2>&1 | tail -8
systemctl restart douyinweb-web
sleep 3
systemctl is-active douyinweb-web
echo "=== restart api ==="
systemctl restart douyinweb-api
sleep 4
systemctl is-active douyinweb-api
curl -sS http://127.0.0.1:$API_PORT/api/ops/host-metrics | head -c 200
echo
echo DONE
""".replace("__API_PORT__", str(API_PORT))
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, "root", "Xiao4669805", timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel)
sftp.put(str(ROOT / rel), f"{APP}/{rel.replace(chr(92), '/')}")
with sftp.file("/tmp/deploy_netdata.sh", "w") as f:
f.write(REMOTE)
sftp.chmod("/tmp/deploy_netdata.sh", 0o755)
sftp.close()
chan = c.get_transport().open_session()
chan.settimeout(600)
chan.exec_command("bash /tmp/deploy_netdata.sh")
out = b""
deadline = time.time() + 580
while time.time() < deadline:
if chan.recv_ready():
out += chan.recv(8192)
elif chan.exit_status_ready():
while chan.recv_ready():
out += chan.recv(8192)
break
else:
time.sleep(0.5)
print(out.decode("utf-8", "replace")[-12000:])
if chan.exit_status_ready():
print("exit", chan.recv_exit_status())
c.close()
if __name__ == "__main__":
main()

View File

@ -29,24 +29,33 @@ source /etc/douyinweb.env
echo "=== docker ==="
if ! command -v docker >/dev/null 2>&1; then
apt-get update -y
apt-get install -y docker.io docker-compose-plugin || apt-get install -y docker.io
apt-get install -y docker.io curl
systemctl enable --now docker
fi
if ! docker compose version >/dev/null 2>&1 && ! command -v docker-compose >/dev/null 2>&1; then
echo "installing docker-compose standalone binary"
curl -fsSL https://github.com/docker/compose/releases/download/v2.29.7/docker-compose-linux-x86_64 \
-o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
fi
docker --version
docker compose version 2>/dev/null || docker-compose --version
echo "=== restart api ==="
systemctl restart douyinweb-api
sleep 5
systemctl is-active douyinweb-api
echo "=== migrate neko ids ==="
echo "=== migrate neko ids + provision containers ==="
cd /opt/douyinWEB/backend
.venv/bin/python - <<'PY'
from app import yt_assign_db
from app import yt_assign_db, youtube_neko
from app.db import init_db
init_db()
groups = yt_assign_db.list_groups(include_urls=False)
print("groups", len(groups), "neko_ids", [g.get("neko_instance_id") for g in groups])
result = youtube_neko.sync_for_groups(groups)
print("neko sync", result)
PY
echo "=== build web ==="

View File

@ -430,11 +430,7 @@ location ^~ /api/ {
proxy_read_timeout 3600s;
client_max_body_size 200m;
}
location ^~ /covers/ {
proxy_pass http://127.0.0.1:${API_PORT};
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-Proto \$scheme;
}
# /covers UI is Next.js (/covers page). Legacy local jpg only via Next rewrite → API.
location ^~ /_/ {
proxy_pass http://127.0.0.1:${PB_PORT};
proxy_set_header Host \$host;