diff --git a/README.md b/README.md
index 5ce6cc5..baba657 100644
--- a/README.md
+++ b/README.md
@@ -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 相同。
diff --git a/backend/app/auth.py b/backend/app/auth.py
index 44499de..a471cca 100644
--- a/backend/app/auth.py
+++ b/backend/app/auth.py
@@ -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",
}
diff --git a/backend/app/clip_cascade.py b/backend/app/clip_cascade.py
index b5bb1d0..e98d477 100644
--- a/backend/app/clip_cascade.py
+++ b/backend/app/clip_cascade.py
@@ -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:
diff --git a/backend/app/config.py b/backend/app/config.py
index 527966f..b7148ee 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -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_"
diff --git a/backend/app/cookie_loader.py b/backend/app/cookie_loader.py
index 7c32c45..0b64383 100644
--- a/backend/app/cookie_loader.py
+++ b/backend/app/cookie_loader.py
@@ -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"),
]
diff --git a/backend/app/cover.py b/backend/app/cover.py
index b5cd167..146a9f7 100644
--- a/backend/app/cover.py
+++ b/backend/app/cover.py
@@ -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,
*,
diff --git a/backend/app/db.py b/backend/app/db.py
index bacdd78..34dc9d5 100644
--- a/backend/app/db.py
+++ b/backend/app/db.py
@@ -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",
diff --git a/backend/app/douyin.py b/backend/app/douyin.py
index 660e859..44e1bba 100644
--- a/backend/app/douyin.py
+++ b/backend/app/douyin.py
@@ -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),
},
}
diff --git a/backend/app/douyin_live.py b/backend/app/douyin_live.py
index 716590d..99fab81 100644
--- a/backend/app/douyin_live.py
+++ b/backend/app/douyin_live.py
@@ -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 ""),
}
diff --git a/backend/app/host_metrics.py b/backend/app/host_metrics.py
new file mode 100644
index 0000000..fc8f4b7
--- /dev/null
+++ b/backend/app/host_metrics.py
@@ -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)
diff --git a/backend/app/main.py b/backend/app/main.py
index a9b252f..9ed0e2a 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -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)
diff --git a/backend/app/monitor.py b/backend/app/monitor.py
index fcaaba5..20c3b2e 100644
--- a/backend/app/monitor.py
+++ b/backend/app/monitor.py
@@ -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(
diff --git a/backend/app/ops_panel.py b/backend/app/ops_panel.py
index c50deb7..4610c07 100644
--- a/backend/app/ops_panel.py
+++ b/backend/app/ops_panel.py
@@ -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)
diff --git a/backend/app/s3_storage.py b/backend/app/s3_storage.py
index 0cf72c5..b2f80b4 100644
--- a/backend/app/s3_storage.py
+++ b/backend/app/s3_storage.py
@@ -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")
diff --git a/backend/app/session_auth.py b/backend/app/session_auth.py
index e5b7c05..d300afa 100644
--- a/backend/app/session_auth.py
+++ b/backend/app/session_auth.py
@@ -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 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)
diff --git a/backend/app/shorts_clip.py b/backend/app/shorts_clip.py
index 2bcba21..05e6262 100644
--- a/backend/app/shorts_clip.py
+++ b/backend/app/shorts_clip.py
@@ -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",
diff --git a/backend/app/shorts_oauth.py b/backend/app/shorts_oauth.py
index 938293a..8d39675 100644
--- a/backend/app/shorts_oauth.py
+++ b/backend/app/shorts_oauth.py
@@ -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)
diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py
index 8c5b1e0..810ae37 100644
--- a/backend/app/shorts_pipeline.py
+++ b/backend/app/shorts_pipeline.py
@@ -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:
diff --git a/backend/app/tiktok_oauth.py b/backend/app/tiktok_oauth.py
index 03461f0..af4b674 100644
--- a/backend/app/tiktok_oauth.py
+++ b/backend/app/tiktok_oauth.py
@@ -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]:
diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py
index 592ef1e..ae02268 100644
--- a/backend/app/tiktok_pipeline.py
+++ b/backend/app/tiktok_pipeline.py
@@ -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 "")
diff --git a/backend/app/x_clips_pipeline.py b/backend/app/x_clips_pipeline.py
index 0757a20..72ef712 100644
--- a/backend/app/x_clips_pipeline.py
+++ b/backend/app/x_clips_pipeline.py
@@ -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:
diff --git a/backend/app/youtube_live.py b/backend/app/youtube_live.py
index 808db86..1c8c331 100644
--- a/backend/app/youtube_live.py
+++ b/backend/app/youtube_live.py
@@ -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]]]] = {}
diff --git a/backend/app/youtube_manage.py b/backend/app/youtube_manage.py
index 3db9985..13b4e32 100644
--- a/backend/app/youtube_manage.py
+++ b/backend/app/youtube_manage.py
@@ -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 "")
diff --git a/backend/app/youtube_neko.py b/backend/app/youtube_neko.py
index b72f067..92afa06 100644
--- a/backend/app/youtube_neko.py
+++ b/backend/app/youtube_neko.py
@@ -1,11 +1,24 @@
# -*- coding: utf-8 -*-
-"""Per-channel Neko browser (Docker) for YouTube Studio — no ShellClash/WireGuard."""
+"""Per-channel Neko browser (Docker) for YouTube Studio on US VPS.
+
+Aligned with sh2/d2ypp2 lessons, adapted for cloud:
+- No ShellClash / WireGuard — browser egress is direct (US IP).
+- HTTP stays on 127.0.0.1 behind nginx HTTPS (/neko/{id}/ → :920x).
+- WebRTC UDP/TCP mux + EPR published on 0.0.0.0 (nginx cannot proxy WebRTC).
+- ICE Lite OFF (sh2 forces 0 for stable remote ICE).
+- NAT1TO1 = public VPS IP so clients get reachable ICE candidates.
+- Containers created by default; running only when neko_enabled.
+"""
from __future__ import annotations
import json
+import os
+import re
import shutil
+import socket
import subprocess
import threading
+import urllib.request
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
@@ -14,7 +27,14 @@ from .config import settings
_lock = threading.RLock()
MAX_INSTANCES = 32
-MIN_UDP_PORT = 52000
+_nat_ip_cache: str = ""
+_nat_ip_cached_at: float = 0.0
+_NAT_CACHE_TTL_SEC = 3600.0
+_list_cache_at: float = 0.0
+_list_cache_count: int = -1
+_list_cache_rows: list[dict[str, Any]] = []
+_LIST_CACHE_TTL_SEC = 5.0
+_list_cache_check_http: bool = False
def _neko_root() -> Path:
@@ -24,10 +44,28 @@ def _neko_root() -> Path:
return p
+def _asset_root() -> Path:
+ """Repo-bundled sh2 Neko assets: Tampermonkey seed, policies, browser-launch, live-ops."""
+ # backend/app/youtube_neko.py → backend/neko/
+ return Path(__file__).resolve().parent.parent / "neko"
+
+
def _compose_path() -> Path:
return _neko_root() / "docker-compose.yml"
+def _supervisor_conf_name() -> str:
+ image = str(getattr(settings, "neko_image", "") or "").lower()
+ if "google-chrome" in image or "chrome" in image:
+ return "google-chrome.conf"
+ return "chromium.conf"
+
+
+def _managed_policies_enabled() -> bool:
+ raw = str(getattr(settings, "neko_managed_policies", "") or os.environ.get("DY_NEKO_MANAGED_POLICIES") or "0")
+ return raw.strip().lower() in {"1", "true", "yes", "on"}
+
+
def _http_port(instance_id: int) -> int:
return int(getattr(settings, "neko_http_port_base", 9200) or 9200) + instance_id - 1
@@ -37,8 +75,16 @@ def _webrtc_mux(instance_id: int) -> int:
def _udp_range(instance_id: int) -> str:
- base = MIN_UDP_PORT + (instance_id - 1) * 100
- return f"{base}-{base + 98}"
+ """Match sh2 default_udp_range — avoid .99 collision patterns."""
+ idx = int(instance_id)
+ if idx == 1:
+ return "52000-52098"
+ if idx == 2:
+ return "52101-52199"
+ if idx == 3:
+ return "52201-52299"
+ start = 52400 + ((idx - 4) * 100)
+ return f"{start}-{start + 99}"
def _container_name(instance_id: int) -> str:
@@ -67,7 +113,89 @@ def _run(cmd: list[str], *, timeout: float = 120.0) -> tuple[int, str]:
def _public_base() -> str:
- return str(settings.public_base_url or "").strip().rstrip("/")
+ base = str(settings.public_base_url or "").strip().rstrip("/")
+ if base:
+ return base
+ for key in ("DY_PUBLIC_BASE_URL", "PUBLIC_BASE"):
+ alt = str(os.environ.get(key) or "").strip().rstrip("/")
+ if alt:
+ return alt
+ return ""
+
+
+def _detect_public_ip() -> str:
+ """Resolve reachable public IP for WebRTC ICE (NAT1TO1). Cached to avoid compose thrash."""
+ global _nat_ip_cache, _nat_ip_cached_at
+ import time as _time
+
+ configured = str(getattr(settings, "neko_nat1to1", "") or "").strip()
+ if configured:
+ return configured
+ env_ip = str(os.environ.get("DY_NEKO_NAT1TO1") or "").strip()
+ if env_ip:
+ return env_ip
+
+ now = _time.time()
+ if _nat_ip_cache and (now - _nat_ip_cached_at) < _NAT_CACHE_TTL_SEC:
+ return _nat_ip_cache
+
+ cache_file = _neko_root() / "nat1to1.txt"
+ if cache_file.is_file():
+ try:
+ cached = cache_file.read_text(encoding="utf-8").strip()
+ if re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}", cached):
+ _nat_ip_cache = cached
+ _nat_ip_cached_at = now
+ return cached
+ except OSError:
+ pass
+
+ ip = ""
+ for url in (
+ "https://checkip.amazonaws.com",
+ "https://api.ipify.org",
+ "https://ifconfig.me/ip",
+ ):
+ try:
+ with urllib.request.urlopen(url, timeout=4) as resp:
+ cand = (resp.read().decode("utf-8", "replace") or "").strip()
+ if re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}", cand):
+ ip = cand
+ break
+ except Exception:
+ continue
+ if not ip:
+ try:
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ s.settimeout(2)
+ s.connect(("8.8.8.8", 80))
+ cand = s.getsockname()[0]
+ s.close()
+ if cand and not cand.startswith("127."):
+ ip = cand
+ except OSError:
+ pass
+ if not ip:
+ ip = _nat_ip_cache or "108.174.50.68"
+ _nat_ip_cache = ip
+ _nat_ip_cached_at = now
+ try:
+ cache_file.write_text(ip + "\n", encoding="utf-8")
+ except OSError:
+ pass
+ return ip
+
+
+def _desired_from_db() -> int:
+ """Max assigned neko_instance_id across assign groups (never shrink on single-instance start)."""
+ try:
+ from . import yt_assign_db
+
+ groups = yt_assign_db.list_groups(include_urls=False)
+ ids = [int(g.get("neko_instance_id") or 0) for g in groups if int(g.get("neko_instance_id") or 0) > 0]
+ return max(ids) if ids else 0
+ except Exception:
+ return 0
def public_studio_url(instance_id: int) -> str:
@@ -77,71 +205,187 @@ def public_studio_url(instance_id: int) -> str:
return f"http://127.0.0.1:{_http_port(instance_id)}/"
+def _ensure_profile(instance_id: int) -> Path:
+ profile = _neko_root() / "profiles" / str(instance_id)
+ profile.mkdir(parents=True, exist_ok=True)
+ try:
+ os.chmod(profile, 0o777)
+ except OSError:
+ pass
+ # Tampermonkey/script seeding is sh2's job: browser-launch.sh + Chrome policies
+ # (NEKO_MANAGED_POLICIES=1 → ExtensionInstallForcelist + jsonImport from :18080).
+ return profile
+
+
+_TM_EXT_ID = "dhdgffkkebhmkfjojejmpbldmpobfkfo"
+
+def _q(value: str) -> str:
+ return json.dumps(str(value), ensure_ascii=False)
+
+
def _render_compose(count: int) -> str:
- image = str(getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/chromium:3.0.0")
+ # x86 US VPS → google-chrome (sh2); override via DY_NEKO_IMAGE.
+ image = str(
+ getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/google-chrome:3.0.0"
+ )
user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb")
- admin_pass = str(getattr(settings, "neko_admin_pass", "") or "douyinweb")
- nat1to1 = str(getattr(settings, "neko_nat1to1", "") or "").strip()
- start_url = "https://studio.youtube.com/"
- root = _neko_root()
- lines = ["# Generated by douyinWEB — do not edit", "services:"]
+ admin_pass = str(getattr(settings, "neko_admin_pass", "") or "Xiao4669805@")
+ nat1to1 = _detect_public_ip()
+ shm = str(getattr(settings, "neko_shm_size", "") or "512mb")
+ screen = str(getattr(settings, "neko_desktop_screen", "") or "1280x720@15")
+ max_fps = str(getattr(settings, "neko_max_fps", "") or "15")
+ bitrate = str(getattr(settings, "neko_video_bitrate", "") or "1200")
+ # sh2 forces ICE Lite OFF for remote clients unless explicitly overridden.
+ icelite = str(getattr(settings, "neko_webrtc_icelite", "") or "0")
+ start_url = str(
+ getattr(settings, "neko_start_url", "")
+ or "https://accounts.google.com/ServiceLogin?continue=https://studio.youtube.com/"
+ )
+ tz = "America/Chicago"
+ assets = _asset_root()
+ managed = _managed_policies_enabled()
+ policy_dir = assets / ("policies" if managed else "no-managed-policies")
+ seed_dir = assets / "tampermonkey-seed"
+ live_ops_dir = assets / "live-ops-extension"
+ provisioning_dir = assets / "provisioning"
+ browser_launch = assets / "browser-launch.sh"
+ supervisor = assets / _supervisor_conf_name()
+ # Fail loud in compose text if assets missing (ops can see in file).
+ for required in (seed_dir, live_ops_dir, provisioning_dir, browser_launch, supervisor, policy_dir):
+ if not required.exists():
+ raise RuntimeError(f"Neko sh2 asset missing: {required}")
+
+ lines = [
+ "# Generated by douyinWEB youtube_neko — sh2-aligned assets; do not edit",
+ "services:",
+ ]
for idx in range(1, count + 1):
http_port = _http_port(idx)
mux = _webrtc_mux(idx)
udp = _udp_range(idx)
- profile = root / "profiles" / str(idx)
- profile.mkdir(parents=True, exist_ok=True)
+ profile = _ensure_profile(idx)
lines.extend(
[
f" neko{idx}:",
- f" image: {image}",
- " restart: unless-stopped",
- " shm_size: 512mb",
+ f" image: {_q(image)}",
+ ' restart: "no"',
+ f" shm_size: {_q(shm)}",
" cap_add:",
" - SYS_ADMIN",
" security_opt:",
" - apparmor:unconfined",
+ " extra_hosts:",
+ ' - "host.docker.internal:host-gateway"',
f" container_name: {_container_name(idx)}",
" environment:",
- " TZ: America/Chicago",
+ f" TZ: {_q(tz)}",
+ ' DISPLAY: ":99.0"',
+ ' ENV_DISPLAY: ":99.0"',
+ ' ENV_USER: "neko"',
+ ' USER: "neko"',
+ ' HOME: "/home/neko"',
+ ' NEKO_CONTAINER_USER: "neko"',
+ ' NEKO_CONTAINER_HOME: "/home/neko"',
' NEKO_SERVER_BIND: ":8080"',
+ # Trust X-Forwarded-* from nginx; NO path prefix (nginx strips /neko/N/).
+ ' NEKO_SERVER_PROXY: "true"',
' NEKO_MEMBER_PROVIDER: "multiuser"',
- f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {user_pass}",
- f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {admin_pass}",
- " NEKO_DESKTOP_SCREEN: 1280x720@15",
- " NEKO_MAX_FPS: 15",
- " NEKO_VIDEO_BITRATE: 1200",
- " NEKO_WEBRTC_ICELITE: 1",
- f" NEKO_WEBRTC_NAT1TO1: {nat1to1}",
- f" NEKO_WEBRTC_TCPMUX: {mux}",
- f" NEKO_WEBRTC_UDPMUX: {mux}",
- f" NEKO_WEBRTC_EPR: {udp}",
- f" NEKO_START_URL: {start_url}",
- " NEKO_BROWSER_PROXY: ''",
+ f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {_q(user_pass)}",
+ f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {_q(admin_pass)}",
+ f" NEKO_DESKTOP_SCREEN: {_q(screen)}",
+ f" NEKO_MAX_FPS: {_q(max_fps)}",
+ f" NEKO_VIDEO_BITRATE: {_q(bitrate)}",
+ f" NEKO_WEBRTC_ICELITE: {_q(icelite)}",
+ f" NEKO_WEBRTC_NAT1TO1: {_q(nat1to1)}",
+ f" NEKO_WEBRTC_TCPMUX: {_q(str(mux))}",
+ f" NEKO_WEBRTC_UDPMUX: {_q(str(mux))}",
+ f" NEKO_WEBRTC_EPR: {_q(udp)}",
+ f" NEKO_START_URL: {_q(start_url)}",
+ # US VPS: direct egress, no ShellClash.
+ ' NEKO_BROWSER_PROXY: ""',
+ ' NEKO_BROWSER_RENDER_MODE: "auto"',
+ f" NEKO_MANAGED_POLICIES: {_q('1' if managed else '0')}",
+ ' NEKO_TAMPERMONKEY_REPAIR: "1"',
+ ' NEKO_LIVE_OPS_EXTENSION: "1"',
+ ' NEKO_LIVE_OPS_EXTENSION_DIR: "/etc/neko/live-ops-extension"',
+ ' NEKO_TAMPERMONKEY_SEED_DIR: "/etc/neko/tampermonkey-seed"',
" ports:",
+ # HTTP only localhost — HTTPS via nginx /neko/{id}/
f' - "127.0.0.1:{http_port}:8080"',
- f' - "127.0.0.1:{mux}:{mux}/tcp"',
- f' - "127.0.0.1:{mux}:{mux}/udp"',
- f' - "127.0.0.1:{udp}:{udp}/udp"',
+ # WebRTC must be public (cannot go through nginx).
+ f' - "{mux}:{mux}/tcp"',
+ f' - "{mux}:{mux}/udp"',
+ f' - "{udp}:{udp}/udp"',
" volumes:",
- f' - "{profile}:/home/neko/.config/chromium"',
- f' - "{profile}:/home/neko/.config/google-chrome"',
+ f" - {_q(f'{profile}:/home/neko/.config/chromium')}",
+ f" - {_q(f'{profile}:/home/neko/.config/google-chrome')}",
+ f" - {_q(f'{policy_dir}:/etc/chromium/policies/managed:ro')}",
+ f" - {_q(f'{policy_dir}:/etc/chromium-browser/policies/managed:ro')}",
+ f" - {_q(f'{policy_dir}:/etc/opt/chrome/policies/managed:ro')}",
+ f" - {_q(f'{seed_dir}:/etc/neko/tampermonkey-seed:ro')}",
+ f" - {_q(f'{live_ops_dir}:/etc/neko/live-ops-extension:ro')}",
+ f" - {_q(f'{provisioning_dir}:/var/www/provisioning:ro')}",
+ f" - {_q(f'{browser_launch}:/etc/neko/browser-launch.sh:ro')}",
+ f" - {_q(f'{supervisor}:/etc/neko/supervisord/{_supervisor_conf_name()}:ro')}",
]
)
return "\n".join(lines) + "\n"
def _compose_cmd(*args: str) -> list[str]:
- return ["docker", "compose", "-f", str(_compose_path()), *args]
+ path = str(_compose_path())
+ if shutil.which("docker-compose"):
+ return ["docker-compose", "-f", path, *args]
+ code, _ = _run(["docker", "compose", "version"], timeout=15)
+ if code == 0:
+ return ["docker", "compose", "-f", path, *args]
+ raise RuntimeError("未找到 docker-compose 或 docker compose,请安装 Docker Compose")
-def _container_state(instance_id: int) -> dict[str, Any]:
+def _compose_up(*, desired: int, start_instances: set[int]) -> tuple[int, str]:
+ """Create all containers stopped; start only requested instances.
+
+ Do NOT use --remove-orphans — starting a lower id must never wipe higher instances.
+ """
+ code, out = _run(_compose_cmd("up", "-d", "--no-start"), timeout=600)
+ if code != 0 and "--no-start" in out.lower():
+ code, out = _run(_compose_cmd("up", "-d"), timeout=600)
+ if code != 0:
+ return code, out
+ for idx in range(1, desired + 1):
+ if idx not in start_instances:
+ _run(["docker", "stop", "-t", "5", _container_name(idx)], timeout=30)
+ return code, out
+ if code != 0:
+ return code, out
+ for idx in sorted(start_instances):
+ if 1 <= idx <= desired:
+ _run(["docker", "start", _container_name(idx)], timeout=60)
+ return code, out
+
+
+def _open_firewall(desired: int) -> None:
+ """Best-effort UFW rules for WebRTC ports (HTTP stays nginx-only)."""
+ if not shutil.which("ufw"):
+ return
+ mux_lo = _webrtc_mux(1)
+ mux_hi = _webrtc_mux(max(1, desired))
+ _run(["ufw", "allow", f"{mux_lo}:{mux_hi}/tcp"], timeout=30)
+ _run(["ufw", "allow", f"{mux_lo}:{mux_hi}/udp"], timeout=30)
+ for idx in range(1, desired + 1):
+ udp = _udp_range(idx)
+ _run(["ufw", "allow", f"{udp}/udp"], timeout=30)
+
+
+def _container_state(instance_id: int, *, check_http: bool = False) -> dict[str, Any]:
name = _container_name(instance_id)
port = _http_port(instance_id)
out: dict[str, Any] = {
"id": instance_id,
"container": name,
"http_port": port,
+ "webrtc_mux": _webrtc_mux(instance_id),
+ "udp_range": _udp_range(instance_id),
"studio_url": public_studio_url(instance_id),
"exists": False,
"running": False,
@@ -168,74 +412,202 @@ def _container_state(instance_id: int) -> dict[str, Any]:
running = bool(state.get("Running"))
health = str((state.get("Health") or {}).get("Status") or "")
out["running"] = running
- out["status"] = health if health else ("running" if running else str(state.get("Status") or "stopped"))
+ if not running:
+ out["status"] = "stopped"
+ else:
+ out["status"] = health if health else "running"
if running:
- hc, _ = _run(["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"], timeout=8)
- out["ready"] = hc == 200
+ if check_http:
+ # Expensive: subprocess curl per instance — only for explicit readiness probes.
+ code, text = _run(
+ ["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"],
+ timeout=8,
+ )
+ out["ready"] = code == 0 and text.strip().endswith("200")
+ else:
+ # Hot path (relay status polls): docker health / running is enough.
+ out["ready"] = health in {"", "healthy", "starting"} or not health
+ if health == "unhealthy":
+ out["ready"] = False
return out
-def ensure_capacity(desired: int, *, start_instances: set[int] | None = None) -> dict[str, Any]:
- """Render compose for `desired` instances; create containers (optionally start subset)."""
+def _empty_instance_row(instance_id: int) -> dict[str, Any]:
+ return {
+ "id": instance_id,
+ "container": _container_name(instance_id),
+ "http_port": _http_port(instance_id),
+ "webrtc_mux": _webrtc_mux(instance_id),
+ "udp_range": _udp_range(instance_id),
+ "studio_url": public_studio_url(instance_id),
+ "exists": False,
+ "running": False,
+ "ready": False,
+ "status": "missing",
+ "detail": "",
+ }
+
+
+def _batch_container_states(count: int, *, check_http: bool = False) -> list[dict[str, Any]]:
+ """One `docker ps` for all neko containers — avoids N inspect + N curl on every poll."""
+ n = max(0, int(count))
+ rows = [_empty_instance_row(i) for i in range(1, n + 1)]
+ if n <= 0:
+ return rows
+ if not _docker_available():
+ for r in rows:
+ r["detail"] = "docker_unavailable"
+ return rows
+
+ code, text = _run(
+ [
+ "docker",
+ "ps",
+ "-a",
+ "--filter",
+ "name=douyinweb-neko-",
+ "--format",
+ "{{.Names}}\t{{.State}}\t{{.Status}}",
+ ],
+ timeout=12,
+ )
+ if code != 0:
+ # Fallback to per-instance inspect without HTTP.
+ return [_container_state(i, check_http=check_http) for i in range(1, n + 1)]
+
+ by_name: dict[str, tuple[str, str]] = {}
+ for line in (text or "").splitlines():
+ parts = line.split("\t")
+ if len(parts) < 2:
+ continue
+ name = parts[0].strip().lstrip("/")
+ state = parts[1].strip().lower()
+ status = parts[2].strip() if len(parts) > 2 else ""
+ by_name[name] = (state, status)
+
+ for i, row in enumerate(rows, start=1):
+ name = _container_name(i)
+ hit = by_name.get(name)
+ if not hit:
+ continue
+ state, status = hit
+ row["exists"] = True
+ running = state == "running"
+ row["running"] = running
+ status_l = status.lower()
+ if not running:
+ row["status"] = "stopped"
+ row["ready"] = False
+ elif "(healthy)" in status_l:
+ row["status"] = "healthy"
+ row["ready"] = True
+ elif "(unhealthy)" in status_l:
+ row["status"] = "unhealthy"
+ row["ready"] = False
+ elif "(health: starting)" in status_l:
+ row["status"] = "starting"
+ row["ready"] = True
+ else:
+ row["status"] = "running"
+ row["ready"] = True
+ if running and check_http:
+ port = int(row["http_port"])
+ c2, t2 = _run(
+ ["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"],
+ timeout=8,
+ )
+ row["ready"] = c2 == 0 and t2.strip().endswith("200")
+ return rows
+
+
+def ensure_capacity(
+ desired: int,
+ *,
+ start_instances: set[int] | None = None,
+ reconcile_running: bool = False,
+) -> dict[str, Any]:
+ """Render compose for `desired` instances; create all, start only requested.
+
+ reconcile_running=True (sync_for_groups): stop instances not in start_instances.
+ reconcile_running=False (single start/restart): never stop siblings.
+ """
desired = max(0, min(MAX_INSTANCES, int(desired or 0)))
+ # Never shrink below DB assignment (protects against start(#2) wiping #3+).
+ desired = max(desired, _desired_from_db())
if desired == 0:
return {"ok": True, "desired": 0, "changed": False, "message": "no_instances"}
if not _docker_available():
return {"ok": False, "desired": desired, "error": "Docker 不可用,请先在服务器安装 Docker"}
+ start_set = set(start_instances or ())
+
with _lock:
- compose = _compose_path()
- text = _render_compose(desired)
- changed = not compose.is_file() or compose.read_text(encoding="utf-8") != text
- if changed:
- compose.write_text(text, encoding="utf-8")
+ try:
+ compose = _compose_path()
+ text = _render_compose(desired)
+ changed = not compose.is_file() or compose.read_text(encoding="utf-8") != text
+ if changed:
+ compose.write_text(text, encoding="utf-8")
- code, out = _run(_compose_cmd("up", "-d", "--remove-orphans"), timeout=300)
- if code != 0:
- return {"ok": False, "desired": desired, "error": out[:500] or "compose up failed"}
-
- started: list[int] = []
- stopped: list[int] = []
- for idx in range(1, desired + 1):
- should_run = start_instances is None or idx in start_instances
- if should_run:
- c, _ = _run(["docker", "start", _container_name(idx)], timeout=45)
- if c == 0:
- started.append(idx)
+ missing = [i for i in range(1, desired + 1) if not _container_state(i).get("exists")]
+ need_up = changed or bool(missing)
+ out = ""
+ if need_up:
+ code, out = _compose_up(desired=desired, start_instances=start_set)
+ if code != 0:
+ return {"ok": False, "desired": desired, "error": out[:800] or "compose up failed"}
else:
- c, _ = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=30)
- if c == 0:
- stopped.append(idx)
+ for idx in sorted(start_set):
+ if 1 <= idx <= desired and not _container_state(idx).get("running"):
+ _run(["docker", "start", _container_name(idx)], timeout=60)
- sync_nginx_proxy(desired)
- return {
- "ok": True,
- "desired": desired,
- "changed": changed,
- "started": started,
- "stopped": stopped,
- "detail": out[:300],
- }
+ stopped: list[int] = []
+ if reconcile_running:
+ for idx in range(1, desired + 1):
+ st = _container_state(idx)
+ if st.get("running") and idx not in start_set:
+ _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=45)
+ stopped.append(idx)
+
+ if changed or need_up:
+ _open_firewall(desired)
+ sync_nginx_proxy(desired)
+ created = sum(1 for i in range(1, desired + 1) if _container_state(i).get("exists"))
+ return {
+ "ok": True,
+ "desired": desired,
+ "created": created,
+ "changed": changed,
+ "compose_up": need_up,
+ "started": sorted(start_set),
+ "stopped": stopped,
+ "nat1to1": _detect_public_ip(),
+ "detail": (out or "")[:300],
+ }
+ except RuntimeError as exc:
+ return {"ok": False, "desired": desired, "error": str(exc)}
def sync_nginx_proxy(count: int) -> dict[str, Any]:
- """Write nginx reverse-proxy snippets for /neko/{id}/ → local ports."""
+ """Nginx: /neko/{id}/ → http://127.0.0.1:920x/ (strip prefix; Neko has no path_prefix)."""
base = _public_base()
if not base:
return {"ok": False, "skipped": "no_public_base"}
host = urlparse(base).hostname or ""
if not host:
return {"ok": False, "skipped": "no_host"}
- conf_path = Path("/etc/nginx/conf.d/douyinweb-neko.conf")
- if not conf_path.parent.is_dir():
+ if not Path("/etc/nginx/conf.d").is_dir():
return {"ok": False, "skipped": "no_nginx"}
blocks: list[str] = []
for idx in range(1, max(0, int(count)) + 1):
port = _http_port(idx)
- mux = _webrtc_mux(idx)
+ # Trailing slash on proxy_pass strips /neko/{idx}/ → container /
blocks.append(
f"""
+ location = /neko/{idx} {{
+ return 301 /neko/{idx}/;
+ }}
location ^~ /neko/{idx}/ {{
proxy_pass http://127.0.0.1:{port}/;
proxy_http_version 1.1;
@@ -245,36 +617,20 @@ def sync_nginx_proxy(count: int) -> dict[str, Any]:
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
+ proxy_cache_bypass $http_upgrade;
proxy_read_timeout 3600s;
- }}
- location ^~ /neko/{idx}/ws {{
- proxy_pass http://127.0.0.1:{port}/ws;
- proxy_http_version 1.1;
- proxy_set_header Upgrade $http_upgrade;
- proxy_set_header Connection "upgrade";
- proxy_read_timeout 3600s;
- }}
- location ^~ /neko/{idx}/mux/ {{
- proxy_pass http://127.0.0.1:{mux}/;
- proxy_http_version 1.1;
- proxy_set_header Upgrade $http_upgrade;
- proxy_set_header Connection "upgrade";
+ proxy_send_timeout 3600s;
}}"""
)
- body = f"""# douyinWEB Neko reverse proxy — auto-generated
-server {{
- listen 80;
- server_name {host};
-{''.join(blocks)}
-}}
-"""
- # Merge into existing ssl server via include pattern
- include_path = Path("/etc/nginx/conf.d/douyinweb-neko-locations.conf")
- loc_body = "\n".join(blocks)
+
+ include_path = Path("/etc/nginx/conf.d/douyinweb-neko-locations.inc")
try:
- include_path.write_text(loc_body + "\n", encoding="utf-8")
- # Patch main vhost if snippet marker missing
- vhost = Path(f"/etc/nginx/conf.d/dy-nomadro-live.conf")
+ include_path.write_text("\n".join(blocks) + "\n", encoding="utf-8")
+ legacy = Path("/etc/nginx/conf.d/douyinweb-neko-locations.conf")
+ if legacy.is_file():
+ legacy.unlink()
+
+ vhost = Path("/etc/nginx/conf.d/dy-nomadro-live.conf")
if not vhost.is_file():
for p in Path("/etc/nginx/conf.d").glob("*.conf"):
if "nomadro" in p.name or "douyin" in p.name:
@@ -282,15 +638,21 @@ server {{
break
if vhost.is_file():
raw = vhost.read_text(encoding="utf-8")
- marker = "include /etc/nginx/conf.d/douyinweb-neko-locations.conf;"
- if marker not in raw and "douyinweb-neko-locations" not in raw:
+ marker = f"include {include_path};"
+ legacy_marker = "include /etc/nginx/conf.d/douyinweb-neko-locations.conf;"
+ if legacy_marker in raw:
+ raw = raw.replace(legacy_marker, marker)
+ elif marker not in raw and "douyinweb-neko-locations" not in raw:
raw = raw.replace(
"location / {",
f" {marker}\n\n location / {{",
1,
)
- vhost.write_text(raw, encoding="utf-8")
- _run(["nginx", "-t"], timeout=15)
+ vhost.write_text(raw, encoding="utf-8")
+
+ code, out = _run(["nginx", "-t"], timeout=15)
+ if code != 0:
+ return {"ok": False, "error": out[:400] or "nginx -t failed"}
_run(["systemctl", "reload", "nginx"], timeout=15)
return {"ok": True, "instances": count}
except OSError as exc:
@@ -306,12 +668,14 @@ def instance_action(instance_id: int, action: str) -> dict[str, Any]:
before = _container_state(instance_id)
message = f"Neko {instance_id}: {before.get('status')}"
+ # Always provision to max assigned id so --remove-orphans cannot wipe siblings.
+ desired = max(instance_id, _desired_from_db())
if action == "start":
- ensure_capacity(instance_id, start_instances={instance_id})
+ ensure_capacity(desired, start_instances={instance_id})
code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60)
- if code != 0 and not before.get("exists"):
- ensure_capacity(instance_id, start_instances={instance_id})
+ if code != 0:
+ ensure_capacity(desired, start_instances={instance_id})
code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60)
if code != 0:
raise RuntimeError(out or "启动失败")
@@ -323,8 +687,12 @@ def instance_action(instance_id: int, action: str) -> dict[str, Any]:
raise RuntimeError(out or "停止失败")
message = f"Neko {instance_id} 已停止"
elif action == "restart":
- ensure_capacity(instance_id, start_instances={instance_id})
+ ensure_capacity(desired, start_instances={instance_id})
code, out = _run(["docker", "restart", "-t", "8", _container_name(instance_id)], timeout=90)
+ if code != 0:
+ _run(["docker", "rm", "-f", _container_name(instance_id)], timeout=30)
+ ensure_capacity(desired, start_instances={instance_id})
+ code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60)
if code != 0:
raise RuntimeError(out or "重启失败")
message = f"Neko {instance_id} 已重启"
@@ -333,28 +701,68 @@ def instance_action(instance_id: int, action: str) -> dict[str, Any]:
after["action"] = action
after["message"] = message
after["available"] = _docker_available()
+ _invalidate_list_cache()
return after
-def list_instances(count: int) -> list[dict[str, Any]]:
- return [_container_state(i) for i in range(1, max(0, int(count)) + 1)]
+def list_instances(count: int, *, check_http: bool = False) -> list[dict[str, Any]]:
+ """Read container states; TTL cache for relay status polls (no HTTP curl by default)."""
+ global _list_cache_at, _list_cache_count, _list_cache_rows, _list_cache_check_http
+ import time as _time
+
+ n = max(0, int(count))
+ now = _time.time()
+ if (
+ _list_cache_rows
+ and _list_cache_count == n
+ and _list_cache_check_http == bool(check_http)
+ and (now - _list_cache_at) < _LIST_CACHE_TTL_SEC
+ ):
+ return list(_list_cache_rows)
+ rows = _batch_container_states(n, check_http=bool(check_http))
+ _list_cache_rows = rows
+ _list_cache_count = n
+ _list_cache_check_http = bool(check_http)
+ _list_cache_at = now
+ return list(rows)
+
+
+def _invalidate_list_cache() -> None:
+ global _list_cache_at
+ _list_cache_at = 0.0
def status_summary(*, desired: int) -> dict[str, Any]:
+ """Read-only status — does not run compose/nginx."""
desired = max(0, min(MAX_INSTANCES, int(desired or 0)))
+ if desired < 1:
+ desired = _desired_from_db()
instances = list_instances(desired)
running = sum(1 for x in instances if x.get("running"))
+ assets = _asset_root()
return {
"available": _docker_available(),
"desired": desired,
"running": running,
"instances": instances,
"enabled": bool(getattr(settings, "neko_enabled", True)),
+ "nat1to1": _detect_public_ip(),
+ # No plaintext passwords in API responses.
+ "login_hint": "用户名任意;普通密码见 DY_NEKO_USER_PASS;管理员密码见 DY_NEKO_ADMIN_PASS",
+ "assets": {
+ "root": str(assets),
+ "tampermonkey_seed": (assets / "tampermonkey-seed" / "Default" / "Extensions").is_dir(),
+ "userscript": (assets / "provisioning" / "youtube-studio-auto-dismiss.user.js").is_file(),
+ "browser_launch": (assets / "browser-launch.sh").is_file(),
+ "live_ops": (assets / "live-ops-extension" / "manifest.json").is_file(),
+ "managed_policies": _managed_policies_enabled(),
+ },
+ "studio_telemetry": latest_studio_telemetry(limit=8),
}
def sync_for_groups(groups: list[dict[str, Any]]) -> dict[str, Any]:
- """Ensure docker capacity matches assign groups; start only neko_enabled groups."""
+ """Ensure docker containers exist for all assign groups; start only neko_enabled."""
ids = [int(g.get("neko_instance_id") or 0) for g in groups if int(g.get("neko_instance_id") or 0) > 0]
desired = max(ids) if ids else 0
if desired == 0:
@@ -364,4 +772,198 @@ def sync_for_groups(groups: list[dict[str, Any]]) -> dict[str, Any]:
for g in groups
if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0) > 0
}
- return ensure_capacity(desired, start_instances=start_set)
+ return ensure_capacity(desired, start_instances=start_set, reconcile_running=True)
+
+
+def stop_instance(instance_id: int) -> dict[str, Any]:
+ """Stop one Neko container (time-slot off-duty). Does not change neko_enabled."""
+ idx = int(instance_id or 0)
+ if idx < 1:
+ return {"ok": False, "skipped": "no_instance"}
+ st = _container_state(idx)
+ if not st.get("running"):
+ return {"ok": True, "id": idx, "already_stopped": True}
+ code, out = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=45)
+ if code != 0:
+ return {"ok": False, "id": idx, "error": (out or "stop failed")[:300]}
+ return {"ok": True, "id": idx, "stopped": True}
+
+
+def stop_instances_except(keep_instance_id: int) -> list[int]:
+ """Stop running Neko containers except `keep_instance_id`. Does not change neko_enabled."""
+ keep = int(keep_instance_id or 0)
+ desired = max(_desired_from_db(), keep, 0)
+ stopped: list[int] = []
+ for idx in range(1, desired + 1):
+ if idx == keep:
+ continue
+ st = _container_state(idx)
+ if not st.get("running"):
+ continue
+ code, _ = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=45)
+ if code == 0:
+ stopped.append(idx)
+ return stopped
+
+
+def ensure_instance_running(instance_id: int) -> dict[str, Any]:
+ """Ensure one Neko container exists and is running (for exclusive-live winner)."""
+ idx = int(instance_id or 0)
+ if idx < 1:
+ return {"ok": False, "skipped": "no_instance"}
+ desired = max(_desired_from_db(), idx)
+ ensure_capacity(desired, start_instances={idx}, reconcile_running=False)
+ st = _container_state(idx)
+ if st.get("running"):
+ return {"ok": True, "id": idx, "already": True}
+ code, out = _run(["docker", "start", _container_name(idx)], timeout=60)
+ if code != 0:
+ return {"ok": False, "id": idx, "error": (out or "start failed")[:300]}
+ return {"ok": True, "id": idx, "started": True}
+
+
+def recent_live_studio_seen(*, max_age_sec: float = 120.0) -> bool:
+ """True if any recent studio telemetry URL is YouTube Live Control Room."""
+ import time as _time
+
+ now = _time.time()
+ for ev in _studio_events[:40]:
+ age = now - float(ev.get("received_at") or 0)
+ if age > max_age_sec:
+ continue
+ payload = ev.get("payload") or {}
+ url = str(payload.get("url") or "").lower()
+ path = str((payload.get("signals") or {}).get("path") or "").lower()
+ if "livestreaming" in url or "livestreaming" in path:
+ return True
+ return False
+
+
+def wait_instance_ready_for_live(
+ instance_id: int,
+ *,
+ timeout_sec: float = 90.0,
+ require_live_page: bool = True,
+) -> dict[str, Any]:
+ """Block until Neko is running/ready and (optionally) Studio livestreaming is open.
+
+ In exclusive mode only one Neko runs, so global livestreaming telemetry is enough.
+ """
+ import time as _time
+
+ idx = int(instance_id or 0)
+ if idx < 1:
+ return {"ok": True, "skipped": "no_instance"}
+ started = ensure_instance_running(idx)
+ if not started.get("ok") and not started.get("already"):
+ return {"ok": False, "id": idx, "error": started.get("error") or "neko_start_failed"}
+
+ deadline = _time.time() + max(15.0, float(timeout_sec))
+ ready_at = 0.0
+ last: dict[str, Any] = {}
+ while _time.time() < deadline:
+ last = _container_state(idx, check_http=False)
+ running = bool(last.get("running"))
+ ready = bool(last.get("ready")) or (running and str(last.get("status") or "") in {"running", "healthy", "starting"})
+ if running and ready:
+ if not ready_at:
+ ready_at = _time.time()
+ if not require_live_page:
+ return {"ok": True, "id": idx, "ready": True, "live_studio": False}
+ if recent_live_studio_seen(max_age_sec=180.0):
+ return {"ok": True, "id": idx, "ready": True, "live_studio": True}
+ # Give extension/browser time to land on livestreaming after container ready.
+ if ready_at and (_time.time() - ready_at) >= 25.0:
+ return {
+ "ok": True,
+ "id": idx,
+ "ready": True,
+ "live_studio": False,
+ "note": "neko_ready_waited_for_live_page",
+ }
+ _time.sleep(2.0)
+
+ if last.get("running"):
+ return {
+ "ok": True,
+ "id": idx,
+ "ready": bool(last.get("ready")),
+ "live_studio": recent_live_studio_seen(max_age_sec=180.0),
+ "timeout": True,
+ "note": "neko_running_after_timeout",
+ }
+ return {"ok": False, "id": idx, "error": "Neko 未在时限内启动成功", "state": last}
+
+
+def restore_enabled_instances() -> dict[str, Any]:
+ """Start all neko_enabled assign groups (after exclusive-live release)."""
+ from . import yt_assign_db
+
+ return sync_for_groups(yt_assign_db.list_groups(include_urls=False))
+
+
+def recreate_all_instances(*, start_enabled: bool = True) -> dict[str, Any]:
+ """Force-recreate every Neko container so bind-mounted assets (browser-launch.sh) refresh."""
+ desired = _desired_from_db()
+ if desired <= 0:
+ return {"ok": True, "desired": 0, "message": "no_instances"}
+ if not _docker_available():
+ return {"ok": False, "desired": desired, "error": "Docker 不可用"}
+ with _lock:
+ compose = _compose_path()
+ compose.write_text(_render_compose(desired), encoding="utf-8")
+ code, out = _run(_compose_cmd("up", "-d", "--force-recreate", "--no-start"), timeout=900)
+ if code != 0:
+ return {"ok": False, "desired": desired, "error": (out or "compose recreate failed")[:800]}
+ started: list[int] = []
+ if start_enabled:
+ from . import yt_assign_db
+
+ groups = yt_assign_db.list_groups(include_urls=False)
+ start_set = {
+ int(g.get("neko_instance_id") or 0)
+ for g in groups
+ if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0) > 0
+ }
+ for idx in sorted(start_set):
+ if 1 <= idx <= desired:
+ _run(["docker", "start", _container_name(idx)], timeout=60)
+ started.append(idx)
+ _open_firewall(desired)
+ sync_nginx_proxy(desired)
+ return {
+ "ok": True,
+ "desired": desired,
+ "started": started,
+ "detail": (out or "")[-400:],
+ }
+
+
+# --- Studio telemetry ingest (sh2 live-ops extension) ---
+_studio_events: list[dict[str, Any]] = []
+_STUDIO_EVENTS_MAX = 200
+
+
+def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]:
+ """Accept Studio telemetry from in-container Chrome extension."""
+ import time as _time
+ import uuid
+
+ body = dict(payload or {})
+ event = {
+ "id": str(uuid.uuid4()),
+ "received_at": float(body.get("received_at") or _time.time()),
+ "payload": body,
+ }
+ _studio_events.insert(0, event)
+ del _studio_events[_STUDIO_EVENTS_MAX:]
+ try:
+ path = _neko_root() / "studio_telemetry_latest.json"
+ path.write_text(json.dumps(event, ensure_ascii=False, indent=2), encoding="utf-8")
+ except OSError:
+ pass
+ return {"ok": True, "event": {"id": event["id"]}}
+
+
+def latest_studio_telemetry(*, limit: int = 20) -> list[dict[str, Any]]:
+ return list(_studio_events[: max(1, min(100, int(limit)))])
diff --git a/backend/app/youtube_relay.py b/backend/app/youtube_relay.py
index 1bba379..80f2775 100644
--- a/backend/app/youtube_relay.py
+++ b/backend/app/youtube_relay.py
@@ -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
diff --git a/backend/app/youtube_relay_pipeline.py b/backend/app/youtube_relay_pipeline.py
index 9a7723a..3bc1b5f 100644
--- a/backend/app/youtube_relay_pipeline.py
+++ b/backend/app/youtube_relay_pipeline.py
@@ -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()
diff --git a/backend/app/youtube_relay_presets.py b/backend/app/youtube_relay_presets.py
new file mode 100644
index 0000000..e2355f8
--- /dev/null
+++ b/backend/app/youtube_relay_presets.py
@@ -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
diff --git a/backend/app/youtube_relay_status.py b/backend/app/youtube_relay_status.py
index defa6f9..c190eb2 100644
--- a/backend/app/youtube_relay_status.py
+++ b/backend/app/youtube_relay_status.py
@@ -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),
}
diff --git a/backend/app/yt_assign_db.py b/backend/app/yt_assign_db.py
index 15d96cc..5f141f4 100644
--- a/backend/app/yt_assign_db.py
+++ b/backend/app/yt_assign_db.py
@@ -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,
}
diff --git a/backend/app/yt_long_clip.py b/backend/app/yt_long_clip.py
index 552d986..debafa1 100644
--- a/backend/app/yt_long_clip.py
+++ b/backend/app/yt_long_clip.py
@@ -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",
diff --git a/backend/app/yt_long_pipeline.py b/backend/app/yt_long_pipeline.py
index c75f1dd..e6b309c 100644
--- a/backend/app/yt_long_pipeline.py
+++ b/backend/app/yt_long_pipeline.py
@@ -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:
diff --git a/backend/tests/test_youtube_relay_presets.py b/backend/tests/test_youtube_relay_presets.py
new file mode 100644
index 0000000..1b5a091
--- /dev/null
+++ b/backend/tests/test_youtube_relay_presets.py
@@ -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
diff --git a/desktop/src/components/DouyinLiveBadge.tsx b/desktop/src/components/DouyinLiveBadge.tsx
index 5151d08..655e18b 100644
--- a/desktop/src/components/DouyinLiveBadge.tsx
+++ b/desktop/src/components/DouyinLiveBadge.tsx
@@ -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);
diff --git a/desktop/src/pages/BlacklistPage.tsx b/desktop/src/pages/BlacklistPage.tsx
index 80ff2a1..97f234b 100644
--- a/desktop/src/pages/BlacklistPage.tsx
+++ b/desktop/src/pages/BlacklistPage.tsx
@@ -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";
diff --git a/desktop/src/pages/SettingsPage.tsx b/desktop/src/pages/SettingsPage.tsx
index 8a1b5db..390c95e 100644
--- a/desktop/src/pages/SettingsPage.tsx
+++ b/desktop/src/pages/SettingsPage.tsx
@@ -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 成功"],
diff --git a/frontend/src/app/anchors/page.tsx b/frontend/src/app/anchors/page.tsx
index 796acc6..f9554a9 100644
--- a/frontend/src/app/anchors/page.tsx
+++ b/frontend/src/app/anchors/page.tsx
@@ -185,7 +185,7 @@ export default function AnchorsPage() {
按主播汇总场次、时长,并展示开播作息规律与预计下次开播。
+抖音直播主播汇总:场次、时长、开播作息与预计下次开播(不含 YouTube / Shorts)。