Document site auth, YT live-map/manage, and Shorts schedule UX; sync feature code to main.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
47d17aee3c
commit
b55f4b64df
105
README.md
105
README.md
@ -4,17 +4,20 @@
|
|||||||
|
|
||||||
可选旁路:**Shorts**(在播随机/开播入队 → 短成片 → YouTube Shorts 上传)。**默认关闭**,失败不影响监控 / 封面 / Webhook / 场次。
|
可选旁路:**Shorts**(在播随机/开播入队 → 短成片 → YouTube Shorts 上传)。**默认关闭**,失败不影响监控 / 封面 / Webhook / 场次。
|
||||||
|
|
||||||
|
控制台默认开启 **站点登录**(Cookie 会话);可选 `DY_API_KEY` 保护写操作。
|
||||||
|
|
||||||
## 线上地址
|
## 线上地址
|
||||||
|
|
||||||
| 用途 | URL |
|
| 用途 | URL |
|
||||||
|------|-----|
|
|------|-----|
|
||||||
| 控制台 | https://dylive.nomadro.com/ |
|
| 控制台 | https://dylive.nomadro.com/ |
|
||||||
|
| 登录 | https://dylive.nomadro.com/login |
|
||||||
| API Health | https://dylive.nomadro.com/api/health |
|
| API Health | https://dylive.nomadro.com/api/health |
|
||||||
| PocketBase | https://dylive.nomadro.com/_/ |
|
| PocketBase | https://dylive.nomadro.com/_/ |
|
||||||
| SeaweedFS S3 | https://feiniu.nomadro.com/ |
|
| SeaweedFS S3 | https://feiniu.nomadro.com/ |
|
||||||
| S3 别名 | https://s3.nomadro.com/ |
|
| S3 别名 | https://s3.nomadro.com/ |
|
||||||
| Shorts | https://dylive.nomadro.com/shorts |
|
| Shorts | https://dylive.nomadro.com/shorts |
|
||||||
| YouTube 探测 | https://dylive.nomadro.com/youtube |
|
| YouTube | https://dylive.nomadro.com/youtube |
|
||||||
|
|
||||||
HTTPS 由服务器 **Caddy** 自动签发。进程端口:
|
HTTPS 由服务器 **Caddy** 自动签发。进程端口:
|
||||||
|
|
||||||
@ -32,15 +35,25 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
|
|||||||
|
|
||||||
| 层 | 职责 |
|
| 层 | 职责 |
|
||||||
|----|------|
|
|----|------|
|
||||||
| **SQLite**(`backend/data/monitor.db`) | 监控热路径:轮询队列、场次、事件、Shorts 任务 |
|
| **SQLite**(`backend/data/monitor.db`) | 监控热路径:轮询队列、场次、事件、Shorts 任务、登录凭据哈希 |
|
||||||
| **PocketBase** | 业务元数据双写镜像(房间 / 场次 / 事件 / yt_groups) |
|
| **PocketBase** | 业务元数据双写镜像(房间 / 场次 / 事件 / yt_groups) |
|
||||||
| **SeaweedFS S3** | 封面媒体存储;UI 经 API 代理展示(私有桶可读) |
|
| **SeaweedFS S3** | 封面媒体存储;UI 经 API 代理展示(私有桶可读) |
|
||||||
| **Next.js 15** | 控制台 |
|
| **Next.js 15** | 控制台(中间件校验登录 Cookie) |
|
||||||
| **FastAPI** | 轮询、REST、SSE、封面补抓、Shorts worker |
|
| **FastAPI** | 轮询、REST、SSE、封面补抓、Shorts worker、YT live-map / manage |
|
||||||
| **youtube-svc** | YouTube.js / youtubei.js InnerTube 探测 |
|
| **youtube-svc** | YouTube.js / youtubei.js InnerTube 探测 |
|
||||||
|
|
||||||
## 功能一览
|
## 功能一览
|
||||||
|
|
||||||
|
### 站点登录
|
||||||
|
|
||||||
|
- Cookie 会话:`dy_session`(HttpOnly,约 7 天);HMAC 签名依赖 `DY_SESSION_SECRET`
|
||||||
|
- 首次启动用 `DY_ADMIN_USERNAME` / `DY_ADMIN_PASSWORD` 写入 SQLite(之后以库内哈希为准)
|
||||||
|
- `/login`;设置页改密;侧栏退出
|
||||||
|
- 未登录页面由 Next middleware 重定向;API `401` 时前端跳转登录
|
||||||
|
- `DY_AUTH_ENABLED=false` 时跳过会话校验(本地调试)
|
||||||
|
- 可选 `DY_API_KEY`:写操作需 `X-API-Key` / `Authorization`(GET 免检)
|
||||||
|
- 会话放行:`/api/auth/login`、`/api/auth/status`、`/api/shorts/oauth/callback`
|
||||||
|
|
||||||
### 监控核心
|
### 监控核心
|
||||||
|
|
||||||
- 直播间:单条 / 批量添加、标签(含「重点」「收藏」「shorts」)、启用停用、黑名单、CSV 导出
|
- 直播间:单条 / 批量添加、标签(含「重点」「收藏」「shorts」)、启用停用、黑名单、CSV 导出
|
||||||
@ -51,12 +64,25 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
|
|||||||
- 进行中实时计时;列表页静默自动刷新 + SSE 开播/停播提示
|
- 进行中实时计时;列表页静默自动刷新 + SSE 开播/停播提示
|
||||||
- UI 时间统一 **北京时间**
|
- UI 时间统一 **北京时间**
|
||||||
|
|
||||||
### YouTube 分组轮询
|
### YouTube 分组与在播地图
|
||||||
|
|
||||||
- `/groups`:添加频道 URL / @handle,独立轮询开播状态
|
- `/groups`:添加频道 URL / @handle,独立轮询开播状态;**分析**页签看 YT 场次统计
|
||||||
- `/youtube`:InnerTube 探测(频道 / 直播 / 视频 / 搜索),可一键加入分组
|
- `/youtube`:**管理**(OAuth 频道内容 CRUD)+ **探测**(InnerTube)
|
||||||
|
- **在播地图** `GET /api/youtube/live-map`:合并分组监控 + Shorts 频道;约 20s 后台刷新 / 15s 前端轮询
|
||||||
|
- 首页 `YouTubeLiveTicker`、导航 LIVE 角标、分组/Shorts/场次 `YouTubeLiveBadge`
|
||||||
|
- Shorts 频道开播可同步为场次(`source: shorts_live`)
|
||||||
- 设置页可启停 YouTube 轮询(与抖音监控开关分离)
|
- 设置页可启停 YouTube 轮询(与抖音监控开关分离)
|
||||||
|
|
||||||
|
### YouTube 频道管理
|
||||||
|
|
||||||
|
复用 Shorts OAuth refresh token(需含 manage / analytics 相关 scope):
|
||||||
|
|
||||||
|
| 能力 | API |
|
||||||
|
|------|-----|
|
||||||
|
| 频道列表 / 画像 / 看板 | `/api/youtube/manage/...` |
|
||||||
|
| 视频列表、改元数据、删视频 | GET / PATCH / DELETE `.../videos/{video_id}` |
|
||||||
|
| 播放列表 | `.../playlists` |
|
||||||
|
|
||||||
### Shorts 旁路(默认关)
|
### Shorts 旁路(默认关)
|
||||||
|
|
||||||
详见 [docs/SHORTS.md](docs/SHORTS.md)。摘要:
|
详见 [docs/SHORTS.md](docs/SHORTS.md)。摘要:
|
||||||
@ -64,7 +90,8 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
|
|||||||
- **隔离**:`shorts_enabled=false` 时仅空转;入队/录制/上传异常不进入监控主路径
|
- **隔离**:`shorts_enabled=false` 时仅空转;入队/录制/上传异常不进入监控主路径
|
||||||
- **入队**:开播边缘钩子 + **当前在播随机取样**(默认开启,同房北京日仅一次)
|
- **入队**:开播边缘钩子 + **当前在播随机取样**(默认开启,同房北京日仅一次)
|
||||||
- **成片**:默认 **15 秒**,设置可切换 15 / 30 / 60 / 90 秒
|
- **成片**:默认 **15 秒**,设置可切换 15 / 30 / 60 / 90 秒
|
||||||
- **上传**:每频道 Google OAuth 一键授权;按频道日配额 5–9 轮转
|
- **错峰上传**:录完 → `scheduled` + 抖动 `upload_at`;可「立即上传」绕过排程
|
||||||
|
- **上传**:每频道 Google OAuth 一键授权;每频道北京日配额固定 **9** 条
|
||||||
- **不复用** sh2 RTMP 转播通道
|
- **不复用** sh2 RTMP 转播通道
|
||||||
|
|
||||||
### 封面(S3)
|
### 封面(S3)
|
||||||
@ -78,17 +105,18 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
|
|||||||
|
|
||||||
| 路由 | 说明 |
|
| 路由 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `/` | 雷达台:健康条、重点看板、今日六段、预计开播、抖音/YT 在播 |
|
| `/login` | 站点登录 |
|
||||||
|
| `/` | 雷达台:健康条、重点看板、今日六段、预计开播、抖音/YT 在播 ticker |
|
||||||
| `/slots` | 开播时段规律:24h→6×4h,日/周热力 |
|
| `/slots` | 开播时段规律:24h→6×4h,日/周热力 |
|
||||||
| `/sessions` | 场次列表 + 图表;日期预设;标签筛选;CSV |
|
| `/sessions` | 场次列表 + 图表;`platform` 可筛抖音 / youtube / shorts |
|
||||||
| `/rooms` | 批量管理;预检;重检;批量标签;快捷收藏/拉黑 |
|
| `/rooms` | 批量管理;预检;重检;批量标签;快捷收藏/拉黑 |
|
||||||
| `/anchors` | 主播画像与下次开播启发式 |
|
| `/anchors` | 主播画像与下次开播启发式 |
|
||||||
| `/covers` | 截图库(有图墙 / 缺图表) |
|
| `/covers` | 截图库(有图墙 / 缺图表) |
|
||||||
| `/events` | SSE 时间线;场次详情;导出 |
|
| `/events` | SSE 时间线;场次详情;导出 |
|
||||||
| `/groups` | YouTube 频道分组监控 |
|
| `/groups` | YouTube 频道分组 + 分析页签 |
|
||||||
| `/youtube` | YouTube InnerTube 探测 |
|
| `/youtube` | 频道管理(默认)+ InnerTube 探测 |
|
||||||
| `/shorts` | Shorts 频道授权 / 任务队列 / 一键取样 |
|
| `/shorts` | 授权 / 任务 / 排程 / 立即上传 / 在播分析 |
|
||||||
| `/settings` | 防风控、通知、静默、YT/Shorts、PB/S3 运维 |
|
| `/settings` | 防风控、通知、静默、YT/Shorts、改密、PB/S3 运维 |
|
||||||
| `/blacklist` | 黑名单 |
|
| `/blacklist` | 黑名单 |
|
||||||
|
|
||||||
### 运维与通知
|
### 运维与通知
|
||||||
@ -103,13 +131,14 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
|
|||||||
|
|
||||||
```
|
```
|
||||||
douyinWEB/
|
douyinWEB/
|
||||||
backend/app/ FastAPI(monitor / cover / shorts_* / youtube_* / timeutil …)
|
backend/app/ FastAPI(auth / monitor / cover / shorts_* / youtube_* …)
|
||||||
|
backend/tests/ pytest(Shorts / live / reconcile 等)
|
||||||
backend/data/ SQLite、封面/成片缓存
|
backend/data/ SQLite、封面/成片缓存
|
||||||
frontend/src/ Next.js App Router
|
frontend/src/ Next.js App Router(含 middleware)
|
||||||
youtube-svc/ YouTube.js sidecar(InnerTube)
|
youtube-svc/ YouTube.js sidecar(InnerTube)
|
||||||
pb/ PocketBase 数据与 migrations
|
pb/ PocketBase 数据与 migrations
|
||||||
docs/ 专题文档(如 Shorts)
|
docs/ 专题文档(如 Shorts)
|
||||||
scripts/ 本地启动与 VPS 部署 / 探测脚本
|
scripts/ 本地启动与 VPS 增量部署
|
||||||
```
|
```
|
||||||
|
|
||||||
## 本地启动
|
## 本地启动
|
||||||
@ -131,7 +160,8 @@ cd frontend && npm run dev -- --port 3000 --hostname 127.0.0.1
|
|||||||
- API:http://127.0.0.1:8000/docs
|
- API:http://127.0.0.1:8000/docs
|
||||||
- PB:http://127.0.0.1:8090/_/
|
- PB:http://127.0.0.1:8090/_/
|
||||||
|
|
||||||
默认 PB:`admin@douyin.local` / `DouyinMonitor_Admin_2026`
|
默认 PB:`admin@douyin.local` / `DouyinMonitor_Admin_2026`
|
||||||
|
站点登录:见 `DY_ADMIN_*`(首次写入库后可在设置页改密)。
|
||||||
|
|
||||||
```bat
|
```bat
|
||||||
cd backend && pip install -r requirements.txt
|
cd backend && pip install -r requirements.txt
|
||||||
@ -143,9 +173,19 @@ cd youtube-svc && npm install
|
|||||||
|
|
||||||
| 方法 | 路径 | 说明 |
|
| 方法 | 路径 | 说明 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
|
| GET | `/api/auth/status` | 登录态(公开) |
|
||||||
|
| POST | `/api/auth/login` \| `/logout` | 登录 / 退出 |
|
||||||
|
| POST | `/api/auth/change-password` | 改密 |
|
||||||
| GET | `/api/monitor/status` | 抖音监控运行态 |
|
| GET | `/api/monitor/status` | 抖音监控运行态 |
|
||||||
| GET | `/api/youtube-monitor/status` | YouTube 分组轮询态 |
|
| GET | `/api/youtube-monitor/status` | YouTube 分组轮询态 |
|
||||||
|
| GET | `/api/youtube/live-map` | YT 分组 + Shorts 在播地图 |
|
||||||
|
| GET | `/api/youtube/manage/channels` | OAuth 频道管理入口 |
|
||||||
|
| GET | `/api/groups/analytics` | 分组场次分析 |
|
||||||
| GET | `/api/shorts/status` | Shorts worker / 配额 / OAuth |
|
| GET | `/api/shorts/status` | Shorts worker / 配额 / OAuth |
|
||||||
|
| GET | `/api/shorts/schedule` | 即将上传日程 |
|
||||||
|
| POST | `/api/shorts/jobs/{id}/upload-now` | 立即上传(绕过错峰) |
|
||||||
|
| POST | `/api/shorts/fill-quota` | 按配额补取样 |
|
||||||
|
| GET | `/api/shorts/live-analytics` | Shorts 频道在播/场次分析 |
|
||||||
| POST | `/api/shorts/start` \| `/stop` | 启停 Shorts(不影响监控) |
|
| POST | `/api/shorts/start` \| `/stop` | 启停 Shorts(不影响监控) |
|
||||||
| POST | `/api/shorts/sample-now` | 立即从在播房间随机入队 |
|
| POST | `/api/shorts/sample-now` | 立即从在播房间随机入队 |
|
||||||
| GET | `/api/shorts/oauth/start` | 跳转 Google 授权 |
|
| GET | `/api/shorts/oauth/start` | 跳转 Google 授权 |
|
||||||
@ -168,12 +208,22 @@ python scripts\sync_cookie_and_probe.py # 同步 Cookie 并抽样探测
|
|||||||
VPS(需 SSH):
|
VPS(需 SSH):
|
||||||
|
|
||||||
```bat
|
```bat
|
||||||
python scripts\deploy_ubuntu.py # 基础 Ubuntu 部署
|
python scripts\deploy_ubuntu.py # 基础 Ubuntu 部署
|
||||||
python scripts\deploy_seaweedfs.py # SeaweedFS + 封面能力
|
python scripts\deploy_seaweedfs.py # SeaweedFS + 封面能力
|
||||||
python scripts\setup_caddy_dylive.py # dylive / feiniu / s3 反代
|
python scripts\setup_caddy_dylive.py # dylive / feiniu / s3 反代
|
||||||
python scripts\deploy_shorts.py # Shorts 旁路增量部署
|
python scripts\deploy_shorts.py # Shorts 旁路增量
|
||||||
python scripts\deploy_dual_platform.py # 双平台 / 分组相关增量
|
python scripts\deploy_dual_platform.py # 双平台 / 分组相关增量
|
||||||
python scripts\restart_vps.py # 重启 douyinWEB 进程
|
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 进程
|
||||||
```
|
```
|
||||||
|
|
||||||
## 关键设置(防风控)
|
## 关键设置(防风控)
|
||||||
@ -192,6 +242,7 @@ python scripts\restart_vps.py # 重启 douyinWEB 进程
|
|||||||
| `shorts_live_sample` | 默认 `true`;在播随机取样 |
|
| `shorts_live_sample` | 默认 `true`;在播随机取样 |
|
||||||
| `shorts_sample_any_live` | 默认 `true`;取样不限标签 |
|
| `shorts_sample_any_live` | 默认 `true`;取样不限标签 |
|
||||||
| `shorts_dedupe_room_day` | 默认 `true`;同房北京日仅一次 |
|
| `shorts_dedupe_room_day` | 默认 `true`;同房北京日仅一次 |
|
||||||
|
| `shorts_upload_spread` | 默认 `true`;错峰排程 |
|
||||||
|
|
||||||
## 环境变量(`DY_` 前缀)
|
## 环境变量(`DY_` 前缀)
|
||||||
|
|
||||||
@ -206,6 +257,11 @@ DY_S3_ACCESS_KEY=douyin
|
|||||||
DY_S3_SECRET_KEY=…
|
DY_S3_SECRET_KEY=…
|
||||||
DY_S3_BUCKET=douyin-covers
|
DY_S3_BUCKET=douyin-covers
|
||||||
DY_YOUTUBE_SVC_URL=http://127.0.0.1:8020
|
DY_YOUTUBE_SVC_URL=http://127.0.0.1:8020
|
||||||
|
DY_AUTH_ENABLED=true
|
||||||
|
DY_ADMIN_USERNAME=…
|
||||||
|
DY_ADMIN_PASSWORD=…
|
||||||
|
DY_SESSION_SECRET=…
|
||||||
|
DY_API_KEY= # 可选;非空则写操作需密钥
|
||||||
TZ=Asia/Shanghai
|
TZ=Asia/Shanghai
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -219,5 +275,6 @@ https://gitea.dsx2020.com/eric/douyinWEB.git
|
|||||||
|
|
||||||
- 仓库含 `backend/data/` 与 `pb/pb_data/`,便于部署后带真实房间与 Cookie 开箱可用。
|
- 仓库含 `backend/data/` 与 `pb/pb_data/`,便于部署后带真实房间与 Cookie 开箱可用。
|
||||||
- Windows `pocketbase.exe` 不入库;Ubuntu 使用 Linux 版 `pocketbase`。
|
- Windows `pocketbase.exe` 不入库;Ubuntu 使用 Linux 版 `pocketbase`。
|
||||||
|
- **勿提交** Google `client_secret_*.json`;Client ID/Secret 走设置页或环境配置。
|
||||||
- **监控主路径**不含推流转播(推流仍在 sh2);**Shorts** 为可选短成片旁路,不占用 sh2 RTMP 车道。
|
- **监控主路径**不含推流转播(推流仍在 sh2);**Shorts** 为可选短成片旁路,不占用 sh2 RTMP 车道。
|
||||||
- 「无图」历史场次:停播后接口常无封面,多数无法回补;以在播补抓与后续开播为准。
|
- 「无图」历史场次:停播后接口常无封面,多数无法回补;以在播补抓与后续开播为准。
|
||||||
|
|||||||
38
backend/app/auth.py
Normal file
38
backend/app/auth.py
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Optional API key gate for mutating routes (DY_API_KEY)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
from starlette.requests import Request
|
||||||
|
from starlette.responses import JSONResponse
|
||||||
|
|
||||||
|
from .config import settings
|
||||||
|
|
||||||
|
# OAuth redirect + SSE + static covers — never block
|
||||||
|
_PUBLIC_PATHS = {
|
||||||
|
"/api/shorts/oauth/callback",
|
||||||
|
"/api/events/stream",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ApiKeyMiddleware(BaseHTTPMiddleware):
|
||||||
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
required = str(settings.api_key or "").strip()
|
||||||
|
if not required:
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
path = request.url.path
|
||||||
|
if path in _PUBLIC_PATHS or path.startswith("/covers/"):
|
||||||
|
return await call_next(request)
|
||||||
|
if request.method in {"GET", "HEAD", "OPTIONS"}:
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
provided = (
|
||||||
|
request.headers.get("X-API-Key")
|
||||||
|
or request.headers.get("x-api-key")
|
||||||
|
or request.query_params.get("api_key")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
if provided != required:
|
||||||
|
return JSONResponse({"detail": "需要 API Key(请求头 X-API-Key)"}, status_code=401)
|
||||||
|
return await call_next(request)
|
||||||
@ -47,6 +47,15 @@ class Settings(BaseSettings):
|
|||||||
# Node sidecar: youtubei.js (https://github.com/LuanRT/YouTube.js)
|
# Node sidecar: youtubei.js (https://github.com/LuanRT/YouTube.js)
|
||||||
youtube_svc_url: str = "http://127.0.0.1:8020"
|
youtube_svc_url: str = "http://127.0.0.1:8020"
|
||||||
|
|
||||||
|
# Optional: require X-API-Key on POST/PATCH/DELETE (leave empty to disable)
|
||||||
|
api_key: str = ""
|
||||||
|
|
||||||
|
# Site login (whole-site protection)
|
||||||
|
auth_enabled: bool = True
|
||||||
|
admin_username: str = "hackrobot"
|
||||||
|
admin_password: str = "Xiao4669805@!"
|
||||||
|
session_secret: str = "douyinweb-session-2026"
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
env_prefix = "DY_"
|
env_prefix = "DY_"
|
||||||
env_file = ".env"
|
env_file = ".env"
|
||||||
|
|||||||
1228
backend/app/db.py
1228
backend/app/db.py
File diff suppressed because it is too large
Load Diff
@ -10,11 +10,11 @@ from urllib.parse import quote
|
|||||||
|
|
||||||
from fastapi import FastAPI, HTTPException, Query, Request
|
from fastapi import FastAPI, HTTPException, Query, Request
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
|
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, StreamingResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from . import cookie_loader, db, pb_sync, shorts_oauth, youtube_client
|
from . import cookie_loader, db, pb_sync, shorts_oauth, youtube_client, youtube_manage
|
||||||
from .config import settings
|
from .config import settings
|
||||||
from .cover import cover_path_for, ensure_session_cover
|
from .cover import cover_path_for, ensure_session_cover
|
||||||
from .douyin import check_room
|
from .douyin import check_room
|
||||||
@ -33,10 +33,23 @@ from .models import (
|
|||||||
SettingsUpdate,
|
SettingsUpdate,
|
||||||
ShortsChannelCreate,
|
ShortsChannelCreate,
|
||||||
ShortsChannelUpdate,
|
ShortsChannelUpdate,
|
||||||
|
ShortsJobsBulkBody,
|
||||||
|
YouTubeVideoUpdate,
|
||||||
)
|
)
|
||||||
from .monitor import monitor
|
from .monitor import monitor
|
||||||
from .stats import summarize_anchor_schedule, summarize_sessions
|
from .stats import summarize_anchor_schedule, summarize_sessions
|
||||||
from .youtube_client import YouTubeSvcError
|
from .youtube_client import YouTubeSvcError
|
||||||
|
from . import youtube_live
|
||||||
|
from .auth import ApiKeyMiddleware
|
||||||
|
from .session_auth import (
|
||||||
|
SessionAuthMiddleware,
|
||||||
|
clear_session_cookie,
|
||||||
|
change_admin_password,
|
||||||
|
session_user_from_request,
|
||||||
|
set_session_cookie,
|
||||||
|
verify_admin,
|
||||||
|
_request_secure,
|
||||||
|
)
|
||||||
from .youtube_monitor import yt_monitor
|
from .youtube_monitor import yt_monitor
|
||||||
from .shorts_pipeline import shorts_pipeline
|
from .shorts_pipeline import shorts_pipeline
|
||||||
from .timeutil import stamp_beijing
|
from .timeutil import stamp_beijing
|
||||||
@ -57,6 +70,22 @@ async def lifespan(_: FastAPI):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
asyncio.create_task(_pb_boot())
|
asyncio.create_task(_pb_boot())
|
||||||
|
|
||||||
|
async def _live_map_refresh_loop() -> None:
|
||||||
|
# 启动立刻探测一次,之后每 20s 强制刷新缓存
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await youtube_live.build_live_map(force=True)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
await asyncio.sleep(20)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
raise
|
||||||
|
|
||||||
|
asyncio.create_task(_live_map_refresh_loop())
|
||||||
await monitor.start()
|
await monitor.start()
|
||||||
await yt_monitor.start()
|
await yt_monitor.start()
|
||||||
# Idle loop when disabled — does not affect monitor
|
# Idle loop when disabled — does not affect monitor
|
||||||
@ -74,13 +103,15 @@ async def lifespan(_: FastAPI):
|
|||||||
|
|
||||||
|
|
||||||
app = FastAPI(title="Douyin Live Monitor", version="0.2.0", lifespan=lifespan)
|
app = FastAPI(title="Douyin Live Monitor", version="0.2.0", lifespan=lifespan)
|
||||||
app.add_middleware(
|
app.add_middleware(ApiKeyMiddleware)
|
||||||
CORSMiddleware,
|
|
||||||
|
app.add_middleware(CORSMiddleware,
|
||||||
allow_origins=[o.strip() for o in settings.cors_origins.split(",") if o.strip()],
|
allow_origins=[o.strip() for o in settings.cors_origins.split(",") if o.strip()],
|
||||||
allow_credentials=True,
|
allow_credentials=True,
|
||||||
allow_methods=["*"],
|
allow_methods=["*"],
|
||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
)
|
)
|
||||||
|
app.add_middleware(SessionAuthMiddleware)
|
||||||
|
|
||||||
covers_dir = settings.covers_dir
|
covers_dir = settings.covers_dir
|
||||||
covers_dir.mkdir(parents=True, exist_ok=True)
|
covers_dir.mkdir(parents=True, exist_ok=True)
|
||||||
@ -115,9 +146,64 @@ async def health() -> dict[str, Any]:
|
|||||||
"youtube_monitor": yt_monitor.status(),
|
"youtube_monitor": yt_monitor.status(),
|
||||||
"monitor": monitor.status(),
|
"monitor": monitor.status(),
|
||||||
"shorts": shorts_pipeline.status(),
|
"shorts": shorts_pipeline.status(),
|
||||||
|
"api_key_required": bool(str(settings.api_key or "").strip()),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/auth/status")
|
||||||
|
async def auth_status(request: Request) -> dict[str, Any]:
|
||||||
|
user = session_user_from_request(request)
|
||||||
|
return {
|
||||||
|
"api_key_required": bool(str(settings.api_key or "").strip()),
|
||||||
|
"auth_enabled": bool(settings.auth_enabled),
|
||||||
|
"authenticated": bool(user),
|
||||||
|
"username": user or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/auth/me")
|
||||||
|
async def auth_me(request: Request) -> dict[str, Any]:
|
||||||
|
user = session_user_from_request(request)
|
||||||
|
if not user and settings.auth_enabled:
|
||||||
|
raise HTTPException(401, "未登录")
|
||||||
|
return {"ok": True, "username": user or settings.admin_username}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/auth/login")
|
||||||
|
async def auth_login(request: Request, body: dict[str, Any]) -> JSONResponse:
|
||||||
|
username = str(body.get("username") or body.get("user") or "").strip()
|
||||||
|
password = str(body.get("password") or "")
|
||||||
|
if not verify_admin(username, password):
|
||||||
|
raise HTTPException(401, "用户名或密码错误")
|
||||||
|
resp = JSONResponse({"ok": True, "username": username})
|
||||||
|
set_session_cookie(resp, username, secure=_request_secure(request))
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/auth/logout")
|
||||||
|
async def auth_logout() -> JSONResponse:
|
||||||
|
resp = JSONResponse({"ok": True})
|
||||||
|
clear_session_cookie(resp)
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/auth/change-password")
|
||||||
|
async def auth_change_password(request: Request, body: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
user = session_user_from_request(request)
|
||||||
|
if not user and settings.auth_enabled:
|
||||||
|
raise HTTPException(401, "未登录")
|
||||||
|
current = str(body.get("current_password") or body.get("current") or "")
|
||||||
|
new_pw = str(body.get("new_password") or body.get("new") or "")
|
||||||
|
confirm = str(body.get("confirm_password") or body.get("confirm") or "")
|
||||||
|
if new_pw != confirm:
|
||||||
|
raise HTTPException(400, "两次输入的新密码不一致")
|
||||||
|
try:
|
||||||
|
change_admin_password(username=str(user or ""), current_password=current, new_password=new_pw)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
return {"ok": True, "message": "密码已更新,请重新登录"}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/monitor/status")
|
@app.get("/api/monitor/status")
|
||||||
async def monitor_status() -> dict[str, Any]:
|
async def monitor_status() -> dict[str, Any]:
|
||||||
return monitor.status()
|
return monitor.status()
|
||||||
@ -185,6 +271,12 @@ def _public_shorts_channel(ch: dict[str, Any]) -> dict[str, Any]:
|
|||||||
out["authorized"] = bool(refresh.strip())
|
out["authorized"] = bool(refresh.strip())
|
||||||
out["client_secret"] = ("***" + secret[-4:]) if len(secret) > 4 else ("***" if secret else "")
|
out["client_secret"] = ("***" + secret[-4:]) if len(secret) > 4 else ("***" if secret else "")
|
||||||
out["refresh_token"] = ("***" + refresh[-4:]) if len(refresh) > 4 else ("***" if refresh else "")
|
out["refresh_token"] = ("***" + refresh[-4:]) if len(refresh) > 4 else ("***" if refresh else "")
|
||||||
|
try:
|
||||||
|
out["oauth_ok"] = int(out.get("oauth_ok") if out.get("oauth_ok") is not None else -1)
|
||||||
|
except Exception:
|
||||||
|
out["oauth_ok"] = -1
|
||||||
|
out["oauth_checked_at"] = float(out.get("oauth_checked_at") or 0)
|
||||||
|
out["oauth_error"] = str(out.get("oauth_error") or "")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
@ -197,16 +289,93 @@ def _request_public_base(request: Request) -> str:
|
|||||||
return "https://dylive.nomadro.com"
|
return "https://dylive.nomadro.com"
|
||||||
|
|
||||||
|
|
||||||
|
def _enrich_shorts_job(job: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||||
|
if not job:
|
||||||
|
return None
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
out = dict(job)
|
||||||
|
clip = str(out.get("clip_path") or "").strip()
|
||||||
|
out["clip_ready"] = bool(clip) and Path(clip).is_file()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _retry_shorts_job_record(job_id: str) -> dict[str, Any]:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
job = db.get_shorts_job(job_id)
|
||||||
|
if not job:
|
||||||
|
raise ValueError("任务不存在")
|
||||||
|
clip = str(job.get("clip_path") or "").strip()
|
||||||
|
if clip and Path(clip).is_file():
|
||||||
|
from .shorts_schedule import pick_upload_at
|
||||||
|
|
||||||
|
cfg = db.get_settings_map()
|
||||||
|
upload_at = pick_upload_at(
|
||||||
|
channel_pk=str(job.get("channel_pk") or ""),
|
||||||
|
push_date=str(job.get("push_date") or ""),
|
||||||
|
cfg=cfg,
|
||||||
|
)
|
||||||
|
return db.update_shorts_job(
|
||||||
|
job_id,
|
||||||
|
status="scheduled",
|
||||||
|
error="",
|
||||||
|
finished_at=0,
|
||||||
|
youtube_video_id="",
|
||||||
|
youtube_url="",
|
||||||
|
upload_at=upload_at,
|
||||||
|
)
|
||||||
|
return db.update_shorts_job(
|
||||||
|
job_id,
|
||||||
|
status="pending",
|
||||||
|
clip_path="",
|
||||||
|
clip_seconds=0,
|
||||||
|
error="成片已丢失,已重新排队录制" if clip else "",
|
||||||
|
finished_at=0,
|
||||||
|
youtube_video_id="",
|
||||||
|
youtube_url="",
|
||||||
|
upload_at=0,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/shorts/status")
|
@app.get("/api/shorts/status")
|
||||||
async def shorts_status() -> dict[str, Any]:
|
async def shorts_status() -> dict[str, Any]:
|
||||||
st = shorts_pipeline.status()
|
st = shorts_pipeline.status()
|
||||||
st["oauth_configured"] = shorts_oauth.oauth_client_configured()
|
st["oauth_configured"] = shorts_oauth.oauth_client_configured()
|
||||||
st["oauth_redirect_uri"] = shorts_oauth.resolve_redirect_uri("https://dylive.nomadro.com")
|
st["oauth_redirect_uri"] = shorts_oauth.resolve_redirect_uri("https://dylive.nomadro.com")
|
||||||
|
st["oauth_scopes"] = shorts_oauth.requested_scopes()
|
||||||
cfg = db.get_settings_map()
|
cfg = db.get_settings_map()
|
||||||
st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104")
|
st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104")
|
||||||
return st
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/shorts/live-analytics")
|
||||||
|
async def shorts_live_analytics(
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
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)
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/shorts/oauth/start")
|
@app.get("/api/shorts/oauth/start")
|
||||||
async def shorts_oauth_start(channel_pk: str, request: Request) -> RedirectResponse:
|
async def shorts_oauth_start(channel_pk: str, request: Request) -> RedirectResponse:
|
||||||
try:
|
try:
|
||||||
@ -263,14 +432,31 @@ async def shorts_stop() -> dict[str, Any]:
|
|||||||
@app.post("/api/shorts/sample-now")
|
@app.post("/api/shorts/sample-now")
|
||||||
async def shorts_sample_now() -> dict[str, Any]:
|
async def shorts_sample_now() -> dict[str, Any]:
|
||||||
"""Manually trigger one live-room sample tick (does not affect monitor)."""
|
"""Manually trigger one live-room sample tick (does not affect monitor)."""
|
||||||
from .shorts_pipeline import try_sample_live_rooms
|
from .shorts_pipeline import try_fill_daily_quota, try_sample_live_rooms
|
||||||
|
|
||||||
cfg = db.get_settings_map()
|
cfg = db.get_settings_map()
|
||||||
if not cfg.get("shorts_enabled"):
|
if not cfg.get("shorts_enabled"):
|
||||||
raise HTTPException(400, "请先启用 Shorts")
|
raise HTTPException(400, "请先启用 Shorts")
|
||||||
n = try_sample_live_rooms(cfg)
|
n = try_sample_live_rooms(cfg)
|
||||||
|
qn = try_fill_daily_quota(cfg)
|
||||||
st = shorts_pipeline.status()
|
st = shorts_pipeline.status()
|
||||||
st["just_enqueued"] = n
|
st["just_enqueued"] = n + qn
|
||||||
|
st["just_sampled"] = n
|
||||||
|
st["just_quota_filled"] = qn
|
||||||
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/shorts/fill-quota")
|
||||||
|
async def shorts_fill_quota() -> dict[str, Any]:
|
||||||
|
"""Manually trigger Beijing-day quota fill toward daily_max per channel."""
|
||||||
|
from .shorts_pipeline import try_fill_daily_quota
|
||||||
|
|
||||||
|
cfg = db.get_settings_map()
|
||||||
|
if not cfg.get("shorts_enabled"):
|
||||||
|
raise HTTPException(400, "请先启用 Shorts")
|
||||||
|
qn = try_fill_daily_quota(cfg)
|
||||||
|
st = shorts_pipeline.status()
|
||||||
|
st["just_quota_filled"] = qn
|
||||||
return st
|
return st
|
||||||
|
|
||||||
|
|
||||||
@ -316,27 +502,172 @@ async def shorts_jobs_list(
|
|||||||
limit: int = Query(100, ge=1, le=500),
|
limit: int = Query(100, ge=1, le=500),
|
||||||
offset: int = Query(0, ge=0),
|
offset: int = Query(0, ge=0),
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
return db.list_shorts_jobs(
|
data = db.list_shorts_jobs(
|
||||||
status=status, push_date=push_date, channel_pk=channel_pk, limit=limit, offset=offset
|
status=status, push_date=push_date, channel_pk=channel_pk, limit=limit, offset=offset
|
||||||
)
|
)
|
||||||
|
data["jobs"] = [_enrich_shorts_job(j) for j in data.get("jobs") or []]
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/shorts/jobs/{job_id}/retry")
|
@app.post("/api/shorts/jobs/{job_id}/retry")
|
||||||
async def shorts_job_retry(job_id: str) -> dict[str, Any]:
|
async def shorts_job_retry(job_id: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
updated = _retry_shorts_job_record(job_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(404, str(exc)) from exc
|
||||||
|
return {"job": _enrich_shorts_job(updated)}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/shorts/jobs/{job_id}")
|
||||||
|
async def shorts_job_get(job_id: str) -> dict[str, Any]:
|
||||||
|
job = _enrich_shorts_job(db.get_shorts_job(job_id))
|
||||||
|
if not job:
|
||||||
|
raise HTTPException(404, "任务不存在")
|
||||||
|
ch = db.get_shorts_channel(str(job.get("channel_pk") or ""))
|
||||||
|
if ch:
|
||||||
|
anchor = str(job.get("anchor_name") or job.get("room_id") or "live")
|
||||||
|
url = str(job.get("source_url") or "")
|
||||||
|
title_tpl = str(ch.get("title_template") or "{anchor} #Shorts")
|
||||||
|
desc_tpl = str(ch.get("description_template") or "")
|
||||||
|
job["preview_title"] = title_tpl.replace("{anchor}", anchor).replace("{url}", url)
|
||||||
|
job["preview_description"] = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
|
||||||
|
job["channel_name"] = ch.get("name") or ""
|
||||||
|
return {"job": job}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/shorts/jobs/{job_id}/clip")
|
||||||
|
async def shorts_job_clip(job_id: str):
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
job = db.get_shorts_job(job_id)
|
job = db.get_shorts_job(job_id)
|
||||||
if not job:
|
if not job:
|
||||||
raise HTTPException(404, "任务不存在")
|
raise HTTPException(404, "任务不存在")
|
||||||
clip = str(job.get("clip_path") or "").strip()
|
clip = str(job.get("clip_path") or "").strip()
|
||||||
next_status = "recorded" if clip else "pending"
|
if not clip:
|
||||||
updated = db.update_shorts_job(
|
raise HTTPException(404, "无成片")
|
||||||
job_id,
|
path = Path(clip).resolve()
|
||||||
status=next_status,
|
clips_root = settings.clips_dir.resolve()
|
||||||
error="",
|
try:
|
||||||
finished_at=0,
|
path.relative_to(clips_root)
|
||||||
youtube_video_id="",
|
except ValueError as exc:
|
||||||
youtube_url="",
|
raise HTTPException(403, "非法路径") from exc
|
||||||
|
if not path.is_file():
|
||||||
|
raise HTTPException(404, "成片文件不存在")
|
||||||
|
return FileResponse(
|
||||||
|
path,
|
||||||
|
media_type="video/mp4",
|
||||||
|
filename=f"{job_id}.mp4",
|
||||||
|
headers={"Cache-Control": "private, max-age=300"},
|
||||||
)
|
)
|
||||||
return {"job": updated}
|
|
||||||
|
|
||||||
|
@app.post("/api/shorts/jobs/bulk")
|
||||||
|
async def shorts_jobs_bulk(body: ShortsJobsBulkBody) -> dict[str, Any]:
|
||||||
|
action = (body.action or "retry").strip().lower()
|
||||||
|
if action not in {"retry", "upload_now"}:
|
||||||
|
raise HTTPException(400, "action 须为 retry 或 upload_now")
|
||||||
|
ids = [str(x).strip() for x in (body.job_ids or []) if str(x).strip()][:30]
|
||||||
|
if not ids:
|
||||||
|
raise HTTPException(400, "job_ids 为空")
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
ok = 0
|
||||||
|
for jid in ids:
|
||||||
|
try:
|
||||||
|
if action == "retry":
|
||||||
|
job = _enrich_shorts_job(_retry_shorts_job_record(jid))
|
||||||
|
results.append({"id": jid, "ok": True, "status": job.get("status") if job else ""})
|
||||||
|
ok += 1
|
||||||
|
else:
|
||||||
|
job = await shorts_pipeline.upload_job_now(jid)
|
||||||
|
results.append({"id": jid, "ok": True, "status": str(job.get("status") or "")})
|
||||||
|
ok += 1
|
||||||
|
except ValueError as exc:
|
||||||
|
results.append({"id": jid, "ok": False, "error": str(exc)[:200]})
|
||||||
|
except Exception as exc:
|
||||||
|
results.append({"id": jid, "ok": False, "error": str(exc)[:200]})
|
||||||
|
return {"ok_count": ok, "total": len(ids), "results": results}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/shorts/reconcile")
|
||||||
|
async def shorts_reconcile() -> dict[str, Any]:
|
||||||
|
missing = db.reconcile_missing_shorts_clips(limit=200)
|
||||||
|
healed = db.reconcile_false_failed_shorts(limit=200)
|
||||||
|
stale = db.reclaim_stale_shorts_uploads(max_age_sec=180)
|
||||||
|
return {"missing_clips": missing, "false_failed": healed, "stale_uploads": stale}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/shorts/stats/history")
|
||||||
|
async def shorts_stats_history(days: int = Query(7, ge=1, le=30)) -> dict[str, Any]:
|
||||||
|
return db.shorts_stats_history(days=days)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/shorts/failed-groups")
|
||||||
|
async def shorts_failed_groups(
|
||||||
|
push_date: str = "",
|
||||||
|
limit: int = Query(40, ge=1, le=200),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return db.shorts_failed_groups(push_date=push_date, limit=limit)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/shorts/stats/channels")
|
||||||
|
async def shorts_stats_channels(days: int = Query(7, ge=1, le=30)) -> dict[str, Any]:
|
||||||
|
return db.shorts_channel_performance(days=days)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/shorts/jobs/retry-all-failed")
|
||||||
|
async def shorts_retry_all_failed(
|
||||||
|
push_date: str = "",
|
||||||
|
limit: int = Query(50, ge=1, le=100),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Re-queue recent failed jobs (re-record if clip missing, else reschedule)."""
|
||||||
|
ids = db.list_failed_shorts_job_ids(push_date=push_date, limit=limit)
|
||||||
|
ok = 0
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
for jid in ids:
|
||||||
|
try:
|
||||||
|
job = _enrich_shorts_job(_retry_shorts_job_record(jid))
|
||||||
|
results.append({"id": jid, "ok": True, "status": job.get("status") if job else ""})
|
||||||
|
ok += 1
|
||||||
|
except ValueError as exc:
|
||||||
|
results.append({"id": jid, "ok": False, "error": str(exc)[:200]})
|
||||||
|
except Exception as exc:
|
||||||
|
results.append({"id": jid, "ok": False, "error": str(exc)[:200]})
|
||||||
|
return {"ok_count": ok, "total": len(ids), "results": results}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/shorts/stats/heatmap")
|
||||||
|
async def shorts_stats_heatmap(days: int = Query(1, ge=1, le=14)) -> dict[str, Any]:
|
||||||
|
return db.shorts_upload_heatmap(days=days)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/shorts/oauth/probe")
|
||||||
|
async def shorts_oauth_probe(channel_pk: str = "") -> dict[str, Any]:
|
||||||
|
"""Probe one channel or all enabled channels' refresh tokens."""
|
||||||
|
if channel_pk.strip():
|
||||||
|
ch = db.get_shorts_channel(channel_pk.strip())
|
||||||
|
if not ch:
|
||||||
|
raise HTTPException(404, "频道不存在")
|
||||||
|
result = await shorts_oauth.probe_channel_oauth(ch)
|
||||||
|
return {"ok": bool(result.get("ok")), **result, "channel": _public_shorts_channel(db.get_shorts_channel(channel_pk.strip()) or ch)}
|
||||||
|
data = await shorts_oauth.probe_all_enabled_channels()
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/shorts/jobs/{job_id}/upload-now")
|
||||||
|
async def shorts_job_upload_now(job_id: str) -> dict[str, Any]:
|
||||||
|
"""Upload a recorded/scheduled clip immediately (bypass staggered slot)."""
|
||||||
|
try:
|
||||||
|
job = await shorts_pipeline.upload_job_now(job_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
return {"ok": True, "job": _enrich_shorts_job(job)}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/shorts/schedule")
|
||||||
|
async def shorts_schedule() -> dict[str, Any]:
|
||||||
|
from .shorts_schedule import schedule_board
|
||||||
|
|
||||||
|
return schedule_board(limit=40)
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/monitor/check/{room_pk}")
|
@app.post("/api/monitor/check/{room_pk}")
|
||||||
@ -574,6 +905,32 @@ async def groups_list(
|
|||||||
return db.list_channel_groups(q=q, platform=platform, enabled=enabled, limit=limit, offset=offset)
|
return db.list_channel_groups(q=q, platform=platform, enabled=enabled, limit=limit, offset=offset)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/groups/analytics")
|
||||||
|
async def groups_analytics(
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
top_anchors: int = Query(25, ge=1, le=50),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""YouTube live-session analytics (same pipeline as Douyin /sessions/stats)."""
|
||||||
|
stats = summarize_sessions(
|
||||||
|
date_from=date_from,
|
||||||
|
date_to=date_to,
|
||||||
|
platform="youtube",
|
||||||
|
top_anchors=top_anchors,
|
||||||
|
)
|
||||||
|
channels = db.youtube_group_channel_stats(date_from=date_from, date_to=date_to)
|
||||||
|
recent = db.list_sessions(platform="youtube", limit=20, offset=0)
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"platform": "youtube",
|
||||||
|
"stats": stats,
|
||||||
|
"channels": channels,
|
||||||
|
"recent_sessions": recent.get("sessions") or [],
|
||||||
|
"recent_total": recent.get("total") or 0,
|
||||||
|
"monitor": yt_monitor.status(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/groups/export")
|
@app.get("/api/groups/export")
|
||||||
async def groups_export() -> StreamingResponse:
|
async def groups_export() -> StreamingResponse:
|
||||||
rows = db.export_channel_groups_rows()
|
rows = db.export_channel_groups_rows()
|
||||||
@ -713,6 +1070,81 @@ async def youtube_health() -> dict[str, Any]:
|
|||||||
return await youtube_client.health()
|
return await youtube_client.health()
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/manage/channels")
|
||||||
|
async def youtube_manage_channels() -> dict[str, Any]:
|
||||||
|
return {"channels": youtube_manage.list_managed_channels()}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/manage/{channel_pk}/profile")
|
||||||
|
async def youtube_manage_profile(channel_pk: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return await youtube_manage.fetch_channel_profile(channel_pk)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/manage/{channel_pk}/dashboard")
|
||||||
|
async def youtube_manage_dashboard(channel_pk: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return await youtube_manage.channel_dashboard(channel_pk)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/manage/{channel_pk}/videos")
|
||||||
|
async def youtube_manage_videos(
|
||||||
|
channel_pk: str,
|
||||||
|
max_results: int = Query(25, ge=1, le=50),
|
||||||
|
page_token: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return await youtube_manage.list_my_videos(channel_pk, max_results=max_results, page_token=page_token)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/manage/{channel_pk}/videos/{video_id}")
|
||||||
|
async def youtube_manage_video_get(channel_pk: str, video_id: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return await youtube_manage.get_video(channel_pk, video_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.patch("/api/youtube/manage/{channel_pk}/videos/{video_id}")
|
||||||
|
async def youtube_manage_video_update(channel_pk: str, video_id: str, body: YouTubeVideoUpdate) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return await youtube_manage.update_video(
|
||||||
|
channel_pk,
|
||||||
|
video_id,
|
||||||
|
title=body.title,
|
||||||
|
description=body.description,
|
||||||
|
tags=body.tags,
|
||||||
|
category_id=body.category_id,
|
||||||
|
privacy_status=body.privacy_status,
|
||||||
|
publish_at=body.publish_at,
|
||||||
|
embeddable=body.embeddable,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/youtube/manage/{channel_pk}/videos/{video_id}")
|
||||||
|
async def youtube_manage_video_delete(channel_pk: str, video_id: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return await youtube_manage.delete_video(channel_pk, video_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/manage/{channel_pk}/playlists")
|
||||||
|
async def youtube_manage_playlists(channel_pk: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return await youtube_manage.list_playlists(channel_pk)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/youtube/resolve")
|
@app.get("/api/youtube/resolve")
|
||||||
async def youtube_resolve(url: str = Query(..., min_length=1)) -> dict[str, Any]:
|
async def youtube_resolve(url: str = Query(..., min_length=1)) -> dict[str, Any]:
|
||||||
try:
|
try:
|
||||||
@ -771,6 +1203,15 @@ async def youtube_batch_live(body: dict[str, Any]) -> dict[str, Any]:
|
|||||||
raise HTTPException(exc.status_code or 400, str(exc)) from exc
|
raise HTTPException(exc.status_code or 400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/live-map")
|
||||||
|
async def youtube_live_map(force: bool = Query(False)) -> dict[str, Any]:
|
||||||
|
"""Unified live status for all YouTube groups + Shorts channels (InnerTube first)."""
|
||||||
|
try:
|
||||||
|
return await youtube_live.build_live_map(force=force)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(500, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/events")
|
@app.get("/api/events")
|
||||||
async def events_list(
|
async def events_list(
|
||||||
kind: str = "",
|
kind: str = "",
|
||||||
@ -1248,6 +1689,12 @@ async def sessions_recapture(session_id: str, body: dict[str, Any] | None = None
|
|||||||
return {"cover_url": f"/api/sessions/{session_id}/cover", **outcome}
|
return {"cover_url": f"/api/sessions/{session_id}/cover", **outcome}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/pb/health")
|
||||||
|
async def pb_sync_health() -> dict[str, Any]:
|
||||||
|
"""Compare SQLite vs PocketBase record counts + connection status."""
|
||||||
|
return await pb_sync.sync_health()
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/pb/bootstrap")
|
@app.post("/api/pb/bootstrap")
|
||||||
async def pb_bootstrap() -> dict[str, Any]:
|
async def pb_bootstrap() -> dict[str, Any]:
|
||||||
return await pb_sync.ensure_collections()
|
return await pb_sync.ensure_collections()
|
||||||
|
|||||||
@ -193,6 +193,9 @@ class SettingsUpdate(BaseModel):
|
|||||||
notify_on_live: Optional[bool] = None
|
notify_on_live: Optional[bool] = None
|
||||||
notify_on_offline: Optional[bool] = None
|
notify_on_offline: Optional[bool] = None
|
||||||
notify_on_risk: Optional[bool] = None
|
notify_on_risk: Optional[bool] = None
|
||||||
|
notify_on_shorts_fail: Optional[bool] = None
|
||||||
|
notify_on_shorts_ok: Optional[bool] = None
|
||||||
|
notify_on_shorts_quota: Optional[bool] = None
|
||||||
quiet_hours_enabled: Optional[bool] = None
|
quiet_hours_enabled: Optional[bool] = None
|
||||||
quiet_hours_start: Optional[int] = None
|
quiet_hours_start: Optional[int] = None
|
||||||
quiet_hours_end: Optional[int] = None
|
quiet_hours_end: Optional[int] = None
|
||||||
@ -214,6 +217,14 @@ class SettingsUpdate(BaseModel):
|
|||||||
shorts_live_sample_interval_sec: Optional[float] = None
|
shorts_live_sample_interval_sec: Optional[float] = None
|
||||||
shorts_live_sample_batch: Optional[int] = None
|
shorts_live_sample_batch: Optional[int] = None
|
||||||
shorts_sample_any_live: Optional[bool] = None
|
shorts_sample_any_live: Optional[bool] = None
|
||||||
|
shorts_upload_spread: Optional[bool] = None
|
||||||
|
shorts_upload_min_gap_sec: Optional[float] = None
|
||||||
|
shorts_channel_min_gap_sec: Optional[float] = None
|
||||||
|
shorts_delete_clip_after_upload: Optional[bool] = None
|
||||||
|
shorts_auto_retry_failed: Optional[bool] = None
|
||||||
|
shorts_auto_retry_max_attempts: Optional[int] = None
|
||||||
|
shorts_auto_retry_interval_sec: Optional[float] = None
|
||||||
|
shorts_oauth_check_interval_sec: Optional[float] = None
|
||||||
shorts_oauth_client_id: Optional[str] = None
|
shorts_oauth_client_id: Optional[str] = None
|
||||||
shorts_oauth_client_secret: Optional[str] = None
|
shorts_oauth_client_secret: Optional[str] = None
|
||||||
shorts_oauth_redirect_uri: Optional[str] = None
|
shorts_oauth_redirect_uri: Optional[str] = None
|
||||||
@ -227,7 +238,7 @@ class ShortsChannelCreate(BaseModel):
|
|||||||
client_secret: str = ""
|
client_secret: str = ""
|
||||||
refresh_token: str = ""
|
refresh_token: str = ""
|
||||||
enabled: bool = True
|
enabled: bool = True
|
||||||
daily_min: int = 5
|
daily_min: int = 9
|
||||||
daily_max: int = 9
|
daily_max: int = 9
|
||||||
title_template: str = "{anchor} 直播瞬间 #Shorts"
|
title_template: str = "{anchor} 直播瞬间 #Shorts"
|
||||||
description_template: str = "{anchor}\n{url}\n#Shorts #直播"
|
description_template: str = "{anchor}\n{url}\n#Shorts #直播"
|
||||||
@ -250,6 +261,21 @@ class ShortsChannelUpdate(BaseModel):
|
|||||||
note: Optional[str] = None
|
note: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ShortsJobsBulkBody(BaseModel):
|
||||||
|
job_ids: list[str]
|
||||||
|
action: str = "retry" # retry | upload_now
|
||||||
|
|
||||||
|
|
||||||
|
class YouTubeVideoUpdate(BaseModel):
|
||||||
|
title: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
tags: Optional[list[str]] = None
|
||||||
|
category_id: Optional[str] = None
|
||||||
|
privacy_status: Optional[str] = None
|
||||||
|
publish_at: Optional[str] = None
|
||||||
|
embeddable: Optional[bool] = None
|
||||||
|
|
||||||
|
|
||||||
class PurgeEventsBody(BaseModel):
|
class PurgeEventsBody(BaseModel):
|
||||||
older_than_days: float = 7
|
older_than_days: float = 7
|
||||||
kind: str = ""
|
kind: str = ""
|
||||||
|
|||||||
@ -19,6 +19,12 @@ async def send_webhook(event: str, payload: dict[str, Any]) -> None:
|
|||||||
return
|
return
|
||||||
if event == "risk" and not cfg.get("notify_on_risk", True):
|
if event == "risk" and not cfg.get("notify_on_risk", True):
|
||||||
return
|
return
|
||||||
|
if event == "shorts_fail" and not cfg.get("notify_on_shorts_fail", True):
|
||||||
|
return
|
||||||
|
if event == "shorts_ok" and not cfg.get("notify_on_shorts_ok", False):
|
||||||
|
return
|
||||||
|
if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True):
|
||||||
|
return
|
||||||
# allow ops/test always when URL configured
|
# allow ops/test always when URL configured
|
||||||
|
|
||||||
body = {
|
body = {
|
||||||
|
|||||||
@ -490,3 +490,69 @@ async def health() -> dict[str, Any]:
|
|||||||
return {"ok": ok, "status_code": resp.status_code, "body": body}
|
return {"ok": ok, "status_code": resp.status_code, "body": body}
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
return {"ok": False, "error": str(exc)}
|
return {"ok": False, "error": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
async def count_records(collection: str) -> int:
|
||||||
|
headers = await _auth_headers()
|
||||||
|
if not headers:
|
||||||
|
return -1
|
||||||
|
async with await _client() as client:
|
||||||
|
resp = await client.get(
|
||||||
|
f"/api/collections/{collection}/records",
|
||||||
|
headers=headers,
|
||||||
|
params={"perPage": 1, "page": 1},
|
||||||
|
)
|
||||||
|
if resp.status_code == 401:
|
||||||
|
headers = await _auth_headers(force=True)
|
||||||
|
if not headers:
|
||||||
|
return -1
|
||||||
|
resp = await client.get(
|
||||||
|
f"/api/collections/{collection}/records",
|
||||||
|
headers=headers,
|
||||||
|
params={"perPage": 1, "page": 1},
|
||||||
|
)
|
||||||
|
if resp.status_code != 200:
|
||||||
|
return -1
|
||||||
|
return int(resp.json().get("totalItems") or 0)
|
||||||
|
|
||||||
|
|
||||||
|
async def sync_health() -> dict[str, Any]:
|
||||||
|
from . import db
|
||||||
|
|
||||||
|
pb_conn = await health()
|
||||||
|
mapping = {
|
||||||
|
"rooms": "dy_rooms",
|
||||||
|
"sessions": "dy_sessions",
|
||||||
|
"groups": "yt_groups",
|
||||||
|
"events": "dy_events",
|
||||||
|
}
|
||||||
|
sqlite_counts = db.table_counts()
|
||||||
|
pb_counts: dict[str, int] = {}
|
||||||
|
drift: dict[str, dict[str, int]] = {}
|
||||||
|
for key, coll in mapping.items():
|
||||||
|
pb_n = await count_records(coll)
|
||||||
|
pb_counts[coll] = pb_n
|
||||||
|
sq_n = int(sqlite_counts.get(key) or 0)
|
||||||
|
drift[key] = {
|
||||||
|
"sqlite": sq_n,
|
||||||
|
"pocketbase": pb_n,
|
||||||
|
"delta": sq_n - pb_n if pb_n >= 0 else 0,
|
||||||
|
}
|
||||||
|
bl_sq = int(sqlite_counts.get("blacklist") or 0)
|
||||||
|
bl_pb = await count_records("dy_blacklist")
|
||||||
|
pb_counts["dy_blacklist"] = bl_pb
|
||||||
|
drift["blacklist"] = {
|
||||||
|
"sqlite": bl_sq,
|
||||||
|
"pocketbase": bl_pb,
|
||||||
|
"delta": bl_sq - bl_pb if bl_pb >= 0 else 0,
|
||||||
|
}
|
||||||
|
max_abs_delta = max(abs(d.get("delta") or 0) for d in drift.values()) if drift else 0
|
||||||
|
return {
|
||||||
|
"ok": bool(pb_conn.get("ok")),
|
||||||
|
"pocketbase": pb_conn,
|
||||||
|
"sqlite": sqlite_counts,
|
||||||
|
"pocketbase_counts": pb_counts,
|
||||||
|
"drift": drift,
|
||||||
|
"in_sync": max_abs_delta == 0 and bool(pb_conn.get("ok")),
|
||||||
|
"max_abs_delta": max_abs_delta,
|
||||||
|
}
|
||||||
|
|||||||
160
backend/app/session_auth.py
Normal file
160
backend/app/session_auth.py
Normal file
@ -0,0 +1,160 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Site-wide session login (cookie JWT)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
import time
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
from starlette.requests import Request
|
||||||
|
from starlette.responses import JSONResponse, Response
|
||||||
|
|
||||||
|
from .config import settings
|
||||||
|
|
||||||
|
SESSION_COOKIE = "dy_session"
|
||||||
|
SESSION_TTL_SEC = 7 * 86400
|
||||||
|
|
||||||
|
# Unauthenticated API paths (OAuth callback, login itself)
|
||||||
|
_PUBLIC_API_PREFIXES = (
|
||||||
|
"/api/auth/login",
|
||||||
|
"/api/auth/status",
|
||||||
|
)
|
||||||
|
_PUBLIC_API_EXACT = {
|
||||||
|
"/api/shorts/oauth/callback",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _secret() -> str:
|
||||||
|
s = str(settings.session_secret or "").strip()
|
||||||
|
if s:
|
||||||
|
return s
|
||||||
|
return "douyinweb-default-session-secret"
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
return hashlib.sha256(f"{_secret()}:{password}".encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def get_admin_credentials() -> tuple[str, str]:
|
||||||
|
"""Return (username, password_hash) from DB; seed from config on first use."""
|
||||||
|
from . import db
|
||||||
|
|
||||||
|
m = db.get_settings_map()
|
||||||
|
user = str(m.get("admin_username") or "").strip()
|
||||||
|
pw_hash = str(m.get("admin_password_hash") or "").strip()
|
||||||
|
if user and pw_hash:
|
||||||
|
return user, pw_hash
|
||||||
|
user = str(settings.admin_username or "hackrobot").strip()
|
||||||
|
pw_hash = hash_password(str(settings.admin_password or ""))
|
||||||
|
db.update_settings_map({"admin_username": user, "admin_password_hash": pw_hash})
|
||||||
|
return user, pw_hash
|
||||||
|
|
||||||
|
|
||||||
|
def verify_admin(username: str, password: str) -> bool:
|
||||||
|
user, pw_hash = get_admin_credentials()
|
||||||
|
if not secrets.compare_digest(str(username or ""), user):
|
||||||
|
return False
|
||||||
|
return secrets.compare_digest(hash_password(str(password or "")), pw_hash)
|
||||||
|
|
||||||
|
|
||||||
|
def change_admin_password(*, username: str, current_password: str, new_password: str) -> None:
|
||||||
|
from . import db
|
||||||
|
|
||||||
|
user, pw_hash = get_admin_credentials()
|
||||||
|
if not secrets.compare_digest(str(username or ""), user):
|
||||||
|
raise ValueError("无权限")
|
||||||
|
if not secrets.compare_digest(hash_password(str(current_password or "")), pw_hash):
|
||||||
|
raise ValueError("当前密码错误")
|
||||||
|
new_p = str(new_password or "")
|
||||||
|
if len(new_p) < 8:
|
||||||
|
raise ValueError("新密码至少 8 位")
|
||||||
|
db.update_settings_map({"admin_password_hash": hash_password(new_p)})
|
||||||
|
|
||||||
|
|
||||||
|
def create_session_token(username: str) -> str:
|
||||||
|
payload = {
|
||||||
|
"u": username,
|
||||||
|
"exp": int(time.time()) + SESSION_TTL_SEC,
|
||||||
|
}
|
||||||
|
body = base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode().rstrip("=")
|
||||||
|
sig = hmac.new(_secret().encode(), body.encode(), hashlib.sha256).hexdigest()
|
||||||
|
return f"{body}.{sig}"
|
||||||
|
|
||||||
|
|
||||||
|
def verify_session_token(token: str) -> Optional[str]:
|
||||||
|
if not token or "." not in token:
|
||||||
|
return None
|
||||||
|
body, sig = token.rsplit(".", 1)
|
||||||
|
expected = hmac.new(_secret().encode(), body.encode(), hashlib.sha256).hexdigest()
|
||||||
|
if not secrets.compare_digest(sig, expected):
|
||||||
|
return None
|
||||||
|
pad = "=" * (-len(body) % 4)
|
||||||
|
try:
|
||||||
|
payload = json.loads(base64.urlsafe_b64decode(body + pad).decode())
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
if int(payload.get("exp") or 0) < int(time.time()):
|
||||||
|
return None
|
||||||
|
user = str(payload.get("u") or "").strip()
|
||||||
|
return user or None
|
||||||
|
|
||||||
|
|
||||||
|
def session_user_from_request(request: Request) -> Optional[str]:
|
||||||
|
if not settings.auth_enabled:
|
||||||
|
return str(settings.admin_username or "admin")
|
||||||
|
token = (request.cookies.get(SESSION_COOKIE) or "").strip()
|
||||||
|
if not token:
|
||||||
|
auth = request.headers.get("Authorization") or ""
|
||||||
|
if auth.lower().startswith("bearer "):
|
||||||
|
token = auth[7:].strip()
|
||||||
|
return verify_session_token(token) if token else None
|
||||||
|
|
||||||
|
|
||||||
|
def set_session_cookie(response: Response, username: str, *, secure: bool) -> None:
|
||||||
|
token = create_session_token(username)
|
||||||
|
response.set_cookie(
|
||||||
|
key=SESSION_COOKIE,
|
||||||
|
value=token,
|
||||||
|
httponly=True,
|
||||||
|
secure=secure,
|
||||||
|
samesite="lax",
|
||||||
|
max_age=SESSION_TTL_SEC,
|
||||||
|
path="/",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_session_cookie(response: Response) -> None:
|
||||||
|
response.delete_cookie(key=SESSION_COOKIE, path="/")
|
||||||
|
|
||||||
|
|
||||||
|
def _request_secure(request: Request) -> bool:
|
||||||
|
proto = (request.headers.get("x-forwarded-proto") or request.url.scheme or "http").split(",")[0].strip()
|
||||||
|
return proto == "https"
|
||||||
|
|
||||||
|
|
||||||
|
class SessionAuthMiddleware(BaseHTTPMiddleware):
|
||||||
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
if not settings.auth_enabled:
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
path = request.url.path
|
||||||
|
if path.startswith("/covers/"):
|
||||||
|
if session_user_from_request(request):
|
||||||
|
return await call_next(request)
|
||||||
|
return JSONResponse({"detail": "未登录"}, status_code=401)
|
||||||
|
|
||||||
|
if not path.startswith("/api/"):
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
if path in _PUBLIC_API_EXACT or any(path.startswith(p) for p in _PUBLIC_API_PREFIXES):
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
if session_user_from_request(request):
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
return JSONResponse({"detail": "未登录,请先登录"}, status_code=401)
|
||||||
@ -13,8 +13,16 @@ from . import db
|
|||||||
|
|
||||||
YOUTUBE_SCOPES = " ".join(
|
YOUTUBE_SCOPES = " ".join(
|
||||||
[
|
[
|
||||||
|
# Full channel management (playlists, captions-ish surface, live bindings, etc.)
|
||||||
|
"https://www.googleapis.com/auth/youtube",
|
||||||
|
"https://www.googleapis.com/auth/youtube.force-ssl",
|
||||||
|
# Explicit upload + readonly (kept for clarity / older clients)
|
||||||
"https://www.googleapis.com/auth/youtube.upload",
|
"https://www.googleapis.com/auth/youtube.upload",
|
||||||
"https://www.googleapis.com/auth/youtube.readonly",
|
"https://www.googleapis.com/auth/youtube.readonly",
|
||||||
|
# Partner / brand-account surfaces when available
|
||||||
|
"https://www.googleapis.com/auth/youtubepartner",
|
||||||
|
# Channel analytics (non-monetary)
|
||||||
|
"https://www.googleapis.com/auth/yt-analytics.readonly",
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -69,6 +77,10 @@ def build_authorize_url(*, channel_pk: str, request_base: str = "") -> str:
|
|||||||
return "https://accounts.google.com/o/oauth2/v2/auth?" + urlencode(params)
|
return "https://accounts.google.com/o/oauth2/v2/auth?" + urlencode(params)
|
||||||
|
|
||||||
|
|
||||||
|
def requested_scopes() -> list[str]:
|
||||||
|
return [s for s in YOUTUBE_SCOPES.split() if s]
|
||||||
|
|
||||||
|
|
||||||
async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]:
|
async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]:
|
||||||
packed = _oauth_states.pop(state, None)
|
packed = _oauth_states.pop(state, None)
|
||||||
if not packed:
|
if not packed:
|
||||||
@ -147,3 +159,59 @@ def channel_oauth_creds(channel: dict[str, Any], cfg: dict[str, Any] | None = No
|
|||||||
"client_secret": str(channel.get("client_secret") or settings.get("shorts_oauth_client_secret") or "").strip(),
|
"client_secret": str(channel.get("client_secret") or settings.get("shorts_oauth_client_secret") or "").strip(),
|
||||||
"refresh_token": str(channel.get("refresh_token") or "").strip(),
|
"refresh_token": str(channel.get("refresh_token") or "").strip(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
"""Try refresh_token once; persist oauth_ok / oauth_error on the channel."""
|
||||||
|
from .shorts_upload import refresh_access_token
|
||||||
|
|
||||||
|
creds = channel_oauth_creds(channel, cfg)
|
||||||
|
cid = str(channel.get("id") or "")
|
||||||
|
now = time.time()
|
||||||
|
if not cid:
|
||||||
|
return {"ok": False, "error": "频道 ID 缺失"}
|
||||||
|
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
|
||||||
|
db.update_shorts_channel(
|
||||||
|
cid,
|
||||||
|
oauth_ok=0,
|
||||||
|
oauth_checked_at=now,
|
||||||
|
oauth_error="未授权或缺少 OAuth 凭证",
|
||||||
|
)
|
||||||
|
return {"ok": False, "error": "未授权或缺少 OAuth 凭证", "channel_id": cid}
|
||||||
|
try:
|
||||||
|
await refresh_access_token(
|
||||||
|
client_id=creds["client_id"],
|
||||||
|
client_secret=creds["client_secret"],
|
||||||
|
refresh_token=creds["refresh_token"],
|
||||||
|
)
|
||||||
|
db.update_shorts_channel(cid, oauth_ok=1, oauth_checked_at=now, oauth_error="")
|
||||||
|
return {"ok": True, "channel_id": cid}
|
||||||
|
except Exception as exc:
|
||||||
|
err = str(exc)[:240]
|
||||||
|
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)
|
||||||
|
return {"ok": False, "error": err, "channel_id": cid}
|
||||||
|
|
||||||
|
|
||||||
|
async def probe_all_enabled_channels(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
settings = cfg or _cfg()
|
||||||
|
rows = db.list_shorts_channels(enabled=True)
|
||||||
|
results = []
|
||||||
|
bad = 0
|
||||||
|
for ch in rows:
|
||||||
|
if not str(ch.get("refresh_token") or "").strip():
|
||||||
|
r = await probe_channel_oauth(ch, settings)
|
||||||
|
results.append(r)
|
||||||
|
if not r.get("ok"):
|
||||||
|
bad += 1
|
||||||
|
continue
|
||||||
|
# Skip recently healthy probes (< half interval)
|
||||||
|
checked = float(ch.get("oauth_checked_at") or 0)
|
||||||
|
ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1)
|
||||||
|
if ok_flag == 1 and checked and (time.time() - checked) < 1800:
|
||||||
|
results.append({"ok": True, "channel_id": ch.get("id"), "skipped": True})
|
||||||
|
continue
|
||||||
|
r = await probe_channel_oauth(ch, settings)
|
||||||
|
results.append(r)
|
||||||
|
if not r.get("ok"):
|
||||||
|
bad += 1
|
||||||
|
return {"checked": len(results), "failed": bad, "results": results}
|
||||||
|
|||||||
@ -44,6 +44,7 @@ def _enqueue_job(
|
|||||||
room: dict[str, Any],
|
room: dict[str, Any],
|
||||||
stream_url: str = "",
|
stream_url: str = "",
|
||||||
cfg: dict[str, Any] | None = None,
|
cfg: dict[str, Any] | None = None,
|
||||||
|
channel_pk: str = "",
|
||||||
) -> Optional[dict[str, Any]]:
|
) -> Optional[dict[str, Any]]:
|
||||||
"""Internal enqueue; never raises."""
|
"""Internal enqueue; never raises."""
|
||||||
try:
|
try:
|
||||||
@ -56,7 +57,16 @@ def _enqueue_job(
|
|||||||
day = push_date_from_ts(float((session or {}).get("started_at") or time.time()))
|
day = push_date_from_ts(float((session or {}).get("started_at") or time.time()))
|
||||||
if settings.get("shorts_dedupe_room_day", True) and room_id and db.has_shorts_job_for_room_day(room_id, day):
|
if settings.get("shorts_dedupe_room_day", True) and room_id and db.has_shorts_job_for_room_day(room_id, day):
|
||||||
return None
|
return None
|
||||||
channel = db.pick_shorts_channel(day)
|
channel: dict[str, Any] | None = None
|
||||||
|
if channel_pk:
|
||||||
|
ch = db.get_shorts_channel(channel_pk)
|
||||||
|
if ch and ch.get("enabled"):
|
||||||
|
used = db.shorts_channel_upload_count(channel_pk, day)
|
||||||
|
daily_max = db.SHORTS_DAILY_FORCE
|
||||||
|
if used < daily_max:
|
||||||
|
channel = ch
|
||||||
|
if not channel:
|
||||||
|
channel = db.pick_shorts_channel(day)
|
||||||
if not channel:
|
if not channel:
|
||||||
return None
|
return None
|
||||||
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
|
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
|
||||||
@ -151,17 +161,230 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
|
||||||
|
"""Enqueue live-room clips toward each channel's daily_max before Beijing midnight."""
|
||||||
|
try:
|
||||||
|
settings = cfg or db.get_settings_map()
|
||||||
|
if not settings.get("shorts_enabled"):
|
||||||
|
return 0
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
gap_total = db.shorts_total_quota_gap(day)
|
||||||
|
if gap_total <= 0:
|
||||||
|
return 0
|
||||||
|
if not db.pick_shorts_channel(day):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
from .timeutil import beijing_day_bounds
|
||||||
|
|
||||||
|
day_start, day_end = beijing_day_bounds(day)
|
||||||
|
now = time.time()
|
||||||
|
day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start)))
|
||||||
|
base_batch = max(1, min(int(settings.get("shorts_quota_fill_batch") or 3), 9))
|
||||||
|
if day_progress > 0.55:
|
||||||
|
base_batch = max(base_batch, min(gap_total, 6))
|
||||||
|
if day_progress > 0.75:
|
||||||
|
base_batch = max(base_batch, min(gap_total, 10))
|
||||||
|
if day_progress > 0.88:
|
||||||
|
base_batch = max(base_batch, min(gap_total, 16))
|
||||||
|
|
||||||
|
any_live = settings.get("shorts_sample_any_live", True)
|
||||||
|
used = db.room_ids_with_shorts_job_today(day)
|
||||||
|
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
|
||||||
|
candidates: list[dict[str, Any]] = []
|
||||||
|
for room in rooms:
|
||||||
|
rid = str(room.get("room_id") or "")
|
||||||
|
if not rid or rid in used:
|
||||||
|
continue
|
||||||
|
if not any_live and not _room_eligible(room, settings):
|
||||||
|
continue
|
||||||
|
if any_live or _room_eligible(room, settings):
|
||||||
|
candidates.append(room)
|
||||||
|
if not candidates:
|
||||||
|
return 0
|
||||||
|
random.shuffle(candidates)
|
||||||
|
|
||||||
|
enqueued = 0
|
||||||
|
for room in candidates:
|
||||||
|
if enqueued >= base_batch:
|
||||||
|
break
|
||||||
|
if not db.pick_shorts_channel(day):
|
||||||
|
break
|
||||||
|
sid = str(room.get("active_session_id") or "")
|
||||||
|
session = db.get_session(sid) if sid else None
|
||||||
|
job = _enqueue_job(session=session, room=room, stream_url="", cfg=settings)
|
||||||
|
if job:
|
||||||
|
enqueued += 1
|
||||||
|
used.add(str(room.get("room_id") or ""))
|
||||||
|
return enqueued
|
||||||
|
except Exception:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
class ShortsPipeline:
|
class ShortsPipeline:
|
||||||
"""Background worker; idle when shorts_enabled is false."""
|
"""Background worker; idle when shorts_enabled is false."""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self._task: asyncio.Task | None = None
|
self._task: asyncio.Task | None = None
|
||||||
self._stop = asyncio.Event()
|
self._stop = asyncio.Event()
|
||||||
self._busy = False
|
self._active_records = 0
|
||||||
|
self._active_uploads = 0
|
||||||
self._last_sample_at = 0.0
|
self._last_sample_at = 0.0
|
||||||
|
self._last_quota_fill_at = 0.0
|
||||||
|
self._last_quota_alert_at = 0.0
|
||||||
|
self._last_oauth_check_at = 0.0
|
||||||
|
self._last_auto_retry_at = 0.0
|
||||||
self.last_error = ""
|
self.last_error = ""
|
||||||
self.processed = 0
|
self.processed = 0
|
||||||
self.sampled = 0
|
self.sampled = 0
|
||||||
|
self.quota_filled = 0
|
||||||
|
self.auto_retried = 0
|
||||||
|
|
||||||
|
def reset_counters(self) -> None:
|
||||||
|
self.processed = 0
|
||||||
|
self.sampled = 0
|
||||||
|
self.quota_filled = 0
|
||||||
|
|
||||||
|
def _maybe_alert_quota_behind(self, cfg: dict[str, Any]) -> None:
|
||||||
|
"""Throttle alert when enabled channels fall behind Beijing-day pace."""
|
||||||
|
if not cfg.get("notify_on_shorts_quota", True):
|
||||||
|
return
|
||||||
|
interval = max(900.0, float(cfg.get("shorts_quota_alert_interval_sec") or 1800))
|
||||||
|
now = time.time()
|
||||||
|
if (now - self._last_quota_alert_at) < interval:
|
||||||
|
return
|
||||||
|
from .shorts_schedule import schedule_board
|
||||||
|
|
||||||
|
board = schedule_board(limit=10)
|
||||||
|
behind = [
|
||||||
|
c
|
||||||
|
for c in (board.get("channels") or [])
|
||||||
|
if c.get("enabled") and c.get("behind_pace") and not c.get("min_met")
|
||||||
|
]
|
||||||
|
if not behind:
|
||||||
|
return
|
||||||
|
# Only alert after ~20% of Beijing day has passed
|
||||||
|
if float(board.get("day_progress") or 0) < 0.2:
|
||||||
|
return
|
||||||
|
self._last_quota_alert_at = now
|
||||||
|
names = "、".join(str(c.get("name") or "频道") for c in behind[:4])
|
||||||
|
more = f" 等 {len(behind)} 个" if len(behind) > 4 else ""
|
||||||
|
msg = f"Shorts 配额落后:{names}{more}(北京日进度 {int(float(board.get('day_progress') or 0) * 100)}%)"
|
||||||
|
try:
|
||||||
|
db.add_event(
|
||||||
|
kind="shorts_quota",
|
||||||
|
level="warn",
|
||||||
|
message=msg,
|
||||||
|
meta={
|
||||||
|
"behind_count": len(behind),
|
||||||
|
"channel_ids": [str(c.get("id") or "") for c in behind],
|
||||||
|
"push_date": board.get("push_date"),
|
||||||
|
"day_progress": board.get("day_progress"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
from .notify import send_webhook
|
||||||
|
|
||||||
|
asyncio.create_task(
|
||||||
|
send_webhook(
|
||||||
|
"shorts_quota",
|
||||||
|
{
|
||||||
|
"message": msg,
|
||||||
|
"behind_count": len(behind),
|
||||||
|
"push_date": board.get("push_date"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def _probe_oauth(self, cfg: dict[str, Any]) -> None:
|
||||||
|
try:
|
||||||
|
from . import shorts_oauth
|
||||||
|
|
||||||
|
data = await shorts_oauth.probe_all_enabled_channels(cfg)
|
||||||
|
failed = int(data.get("failed") or 0)
|
||||||
|
if failed <= 0:
|
||||||
|
return
|
||||||
|
names = []
|
||||||
|
for r in data.get("results") or []:
|
||||||
|
if r.get("ok") or r.get("skipped"):
|
||||||
|
continue
|
||||||
|
ch = db.get_shorts_channel(str(r.get("channel_id") or ""))
|
||||||
|
names.append(str((ch or {}).get("name") or r.get("channel_id") or "频道"))
|
||||||
|
msg = f"Shorts OAuth 异常:{'、'.join(names[:4])}" + (f" 等 {failed} 个" if failed > 4 else "")
|
||||||
|
db.add_event(
|
||||||
|
kind="shorts_fail",
|
||||||
|
level="warn",
|
||||||
|
message=msg,
|
||||||
|
meta={"oauth_failed": failed, "channel_names": names},
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
from .notify import send_webhook
|
||||||
|
|
||||||
|
asyncio.create_task(send_webhook("shorts_fail", {"message": msg, "oauth_failed": failed}))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
except Exception as exc:
|
||||||
|
self.last_error = f"OAuth 探测失败: {exc}"[:300]
|
||||||
|
|
||||||
|
def _auto_retry_failed(self, cfg: dict[str, Any]) -> int:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .shorts_schedule import pick_upload_at
|
||||||
|
|
||||||
|
max_att = int(cfg.get("shorts_auto_retry_max_attempts") or 3)
|
||||||
|
jobs = db.list_auto_retry_failed_jobs(max_attempts=max_att, limit=5)
|
||||||
|
n = 0
|
||||||
|
for job in jobs:
|
||||||
|
jid = str(job.get("id") or "")
|
||||||
|
if not jid:
|
||||||
|
continue
|
||||||
|
clip = str(job.get("clip_path") or "").strip()
|
||||||
|
try:
|
||||||
|
if clip and Path(clip).is_file():
|
||||||
|
upload_at = pick_upload_at(
|
||||||
|
channel_pk=str(job.get("channel_pk") or ""),
|
||||||
|
push_date=str(job.get("push_date") or ""),
|
||||||
|
cfg=cfg,
|
||||||
|
)
|
||||||
|
db.update_shorts_job(
|
||||||
|
jid,
|
||||||
|
status="scheduled",
|
||||||
|
error="",
|
||||||
|
finished_at=0,
|
||||||
|
youtube_video_id="",
|
||||||
|
youtube_url="",
|
||||||
|
upload_at=upload_at,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
db.update_shorts_job(
|
||||||
|
jid,
|
||||||
|
status="pending",
|
||||||
|
clip_path="",
|
||||||
|
clip_seconds=0,
|
||||||
|
error="自动重试:重新排队录制",
|
||||||
|
finished_at=0,
|
||||||
|
youtube_video_id="",
|
||||||
|
youtube_url="",
|
||||||
|
upload_at=0,
|
||||||
|
)
|
||||||
|
n += 1
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
return n
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _upload_max(cfg: dict[str, Any]) -> int:
|
||||||
|
explicit = int(cfg.get("shorts_upload_max_concurrent") or 0)
|
||||||
|
if explicit > 0:
|
||||||
|
return max(1, min(explicit, 5))
|
||||||
|
return max(2, int(cfg.get("shorts_max_concurrent") or 1))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _record_max(cfg: dict[str, Any]) -> int:
|
||||||
|
return max(1, int(cfg.get("shorts_max_concurrent") or 1))
|
||||||
|
|
||||||
def status(self) -> dict[str, Any]:
|
def status(self) -> dict[str, Any]:
|
||||||
cfg = db.get_settings_map()
|
cfg = db.get_settings_map()
|
||||||
@ -169,17 +392,83 @@ class ShortsPipeline:
|
|||||||
stats = db.shorts_stats()
|
stats = db.shorts_stats()
|
||||||
except Exception:
|
except Exception:
|
||||||
stats = {}
|
stats = {}
|
||||||
|
try:
|
||||||
|
history = db.shorts_stats_history(days=7)
|
||||||
|
except Exception:
|
||||||
|
history = {}
|
||||||
|
try:
|
||||||
|
failed_groups = db.shorts_failed_groups(limit=40)
|
||||||
|
except Exception:
|
||||||
|
failed_groups = {}
|
||||||
|
try:
|
||||||
|
channel_perf = db.shorts_channel_performance(days=7)
|
||||||
|
except Exception:
|
||||||
|
channel_perf = {}
|
||||||
|
try:
|
||||||
|
heatmap = db.shorts_upload_heatmap(days=1)
|
||||||
|
except Exception:
|
||||||
|
heatmap = {}
|
||||||
|
try:
|
||||||
|
from .shorts_schedule import schedule_board
|
||||||
|
|
||||||
|
board = schedule_board(limit=30)
|
||||||
|
except Exception:
|
||||||
|
board = {}
|
||||||
|
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)
|
||||||
|
if ok_flag == 0 or not str(ch.get("refresh_token") or "").strip():
|
||||||
|
oauth_issues.append(
|
||||||
|
{
|
||||||
|
"id": ch.get("id"),
|
||||||
|
"name": ch.get("name"),
|
||||||
|
"oauth_ok": ok_flag,
|
||||||
|
"oauth_error": ch.get("oauth_error") or ("未授权" if not str(ch.get("refresh_token") or "").strip() else ""),
|
||||||
|
"oauth_checked_at": ch.get("oauth_checked_at") or 0,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
return {
|
return {
|
||||||
"running": bool(self._task and not self._task.done()),
|
"running": bool(self._task and not self._task.done()),
|
||||||
"busy": self._busy,
|
"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")),
|
"enabled": bool(cfg.get("shorts_enabled")),
|
||||||
"processed": self.processed,
|
"processed": self.processed,
|
||||||
"sampled": self.sampled,
|
"sampled": self.sampled,
|
||||||
|
"quota_filled": self.quota_filled,
|
||||||
|
"auto_retried": self.auto_retried,
|
||||||
|
"auto_retry_failed": bool(cfg.get("shorts_auto_retry_failed", True)),
|
||||||
|
"quota_gap": db.shorts_total_quota_gap(),
|
||||||
"last_error": self.last_error,
|
"last_error": self.last_error,
|
||||||
"clip_sec": int(cfg.get("shorts_clip_sec") or 15),
|
"clip_sec": int(cfg.get("shorts_clip_sec") or 15),
|
||||||
"live_sample": bool(cfg.get("shorts_live_sample", True)),
|
"live_sample": bool(cfg.get("shorts_live_sample", True)),
|
||||||
"sample_any_live": bool(cfg.get("shorts_sample_any_live", 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)
|
||||||
|
],
|
||||||
|
"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),
|
||||||
|
"max_concurrent": max(1, int(cfg.get("shorts_max_concurrent") or 1)),
|
||||||
|
"upload_max_concurrent": self._upload_max(cfg),
|
||||||
|
"delete_clip_after_upload": bool(cfg.get("shorts_delete_clip_after_upload", True)),
|
||||||
"stats": stats,
|
"stats": stats,
|
||||||
|
"board": board,
|
||||||
|
"history": history,
|
||||||
|
"failed_groups": failed_groups,
|
||||||
|
"channel_perf": channel_perf,
|
||||||
|
"heatmap": heatmap,
|
||||||
|
"oauth_issues": oauth_issues,
|
||||||
}
|
}
|
||||||
|
|
||||||
async def start(self) -> None:
|
async def start(self) -> None:
|
||||||
@ -205,6 +494,11 @@ class ShortsPipeline:
|
|||||||
await asyncio.sleep(5)
|
await asyncio.sleep(5)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.enforce_shorts_daily_force()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
# Random sample from currently-live rooms (does not touch monitor loop)
|
# Random sample from currently-live rooms (does not touch monitor loop)
|
||||||
interval = float(cfg.get("shorts_live_sample_interval_sec") or 180)
|
interval = float(cfg.get("shorts_live_sample_interval_sec") or 180)
|
||||||
interval = max(60.0, interval)
|
interval = max(60.0, interval)
|
||||||
@ -214,27 +508,346 @@ class ShortsPipeline:
|
|||||||
if n:
|
if n:
|
||||||
self.sampled += n
|
self.sampled += n
|
||||||
|
|
||||||
max_c = max(1, int(cfg.get("shorts_max_concurrent") or 1))
|
quota_interval = float(cfg.get("shorts_quota_fill_interval_sec") or 120)
|
||||||
if self._busy:
|
quota_interval = max(60.0, quota_interval)
|
||||||
await asyncio.sleep(1)
|
if (time.time() - self._last_quota_fill_at) >= quota_interval:
|
||||||
continue
|
self._last_quota_fill_at = time.time()
|
||||||
_ = max_c
|
qn = try_fill_daily_quota(cfg)
|
||||||
job = db.claim_next_shorts_job()
|
if qn:
|
||||||
|
self.quota_filled += qn
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._maybe_alert_quota_behind(cfg)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
oauth_interval = max(600.0, float(cfg.get("shorts_oauth_check_interval_sec") or 3600))
|
||||||
|
if (time.time() - self._last_oauth_check_at) >= oauth_interval:
|
||||||
|
self._last_oauth_check_at = time.time()
|
||||||
|
asyncio.create_task(self._probe_oauth(cfg))
|
||||||
|
|
||||||
|
retry_interval = max(120.0, float(cfg.get("shorts_auto_retry_interval_sec") or 300))
|
||||||
|
if cfg.get("shorts_auto_retry_failed", True) and (time.time() - self._last_auto_retry_at) >= retry_interval:
|
||||||
|
self._last_auto_retry_at = time.time()
|
||||||
|
try:
|
||||||
|
n = self._auto_retry_failed(cfg)
|
||||||
|
if n:
|
||||||
|
self.auto_retried += n
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Legacy recorded clips without upload_at → schedule irregularly
|
||||||
|
try:
|
||||||
|
self._backfill_schedules(cfg)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
n = db.reclaim_stale_shorts_uploads(max_age_sec=180)
|
||||||
|
if n:
|
||||||
|
self.last_error = ""
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
missing = db.reconcile_missing_shorts_clips(limit=80)
|
||||||
|
if missing:
|
||||||
|
self.last_error = ""
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
healed = db.reconcile_false_failed_shorts(limit=80)
|
||||||
|
if healed:
|
||||||
|
self.last_error = ""
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
record_max = self._record_max(cfg)
|
||||||
|
upload_max = self._upload_max(cfg)
|
||||||
|
job: dict[str, Any] | None = None
|
||||||
|
runner: str = ""
|
||||||
|
if self._active_uploads < upload_max:
|
||||||
|
job = db.claim_due_shorts_upload()
|
||||||
|
if job:
|
||||||
|
runner = "upload"
|
||||||
|
if not job and self._active_records < record_max:
|
||||||
|
job = db.claim_pending_shorts_record()
|
||||||
|
if job:
|
||||||
|
runner = "record"
|
||||||
if not job:
|
if not job:
|
||||||
await asyncio.sleep(2)
|
await asyncio.sleep(2)
|
||||||
continue
|
continue
|
||||||
self._busy = True
|
if runner == "upload":
|
||||||
try:
|
self._active_uploads += 1
|
||||||
await self._process(job, cfg)
|
asyncio.create_task(self._run_upload_only(job, cfg))
|
||||||
self.processed += 1
|
else:
|
||||||
finally:
|
self._active_records += 1
|
||||||
self._busy = False
|
asyncio.create_task(self._run_job(job, cfg))
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
break
|
break
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self.last_error = str(exc)[:300]
|
self.last_error = str(exc)[:300]
|
||||||
await asyncio.sleep(3)
|
await asyncio.sleep(3)
|
||||||
|
|
||||||
|
async def _run_job(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
||||||
|
try:
|
||||||
|
await self._process(job, cfg)
|
||||||
|
self.processed += 1
|
||||||
|
except Exception as exc:
|
||||||
|
if "成片文件不存在" in str(exc):
|
||||||
|
if str(job.get("youtube_video_id") or "").strip():
|
||||||
|
db.update_shorts_job(
|
||||||
|
str(job["id"]),
|
||||||
|
status="uploaded",
|
||||||
|
error="",
|
||||||
|
clip_path="",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
self._requeue_missing_clip(job)
|
||||||
|
return
|
||||||
|
self.last_error = str(exc)[:300]
|
||||||
|
finally:
|
||||||
|
self._active_records = max(0, self._active_records - 1)
|
||||||
|
|
||||||
|
def _backfill_schedules(self, cfg: dict[str, Any]) -> None:
|
||||||
|
"""Move recorded/clip-ready jobs without a slot onto staggered schedule."""
|
||||||
|
if not cfg.get("shorts_auto_upload", True):
|
||||||
|
return
|
||||||
|
from .shorts_schedule import pick_upload_at
|
||||||
|
from .timeutil import beijing_day_bounds
|
||||||
|
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
_, day_end = beijing_day_bounds(day)
|
||||||
|
data = db.list_shorts_jobs(push_date=day, status="recorded", limit=50, offset=0)
|
||||||
|
for job in data.get("jobs") or []:
|
||||||
|
if float(job.get("upload_at") or 0) > 0 and str(job.get("status")) == "scheduled":
|
||||||
|
continue
|
||||||
|
if not str(job.get("clip_path") or "").strip():
|
||||||
|
continue
|
||||||
|
upload_at = pick_upload_at(
|
||||||
|
channel_pk=str(job.get("channel_pk") or ""),
|
||||||
|
push_date=str(job.get("push_date") or day),
|
||||||
|
cfg=cfg,
|
||||||
|
)
|
||||||
|
db.update_shorts_job(
|
||||||
|
str(job["id"]),
|
||||||
|
status="scheduled",
|
||||||
|
upload_at=upload_at,
|
||||||
|
error="",
|
||||||
|
)
|
||||||
|
data2 = db.list_shorts_jobs(push_date=day, status="scheduled", limit=80, offset=0)
|
||||||
|
for job in data2.get("jobs") or []:
|
||||||
|
ch_pk = str(job.get("channel_pk") or "")
|
||||||
|
upload_at = float(job.get("upload_at") or 0)
|
||||||
|
if not str(job.get("clip_path") or "").strip():
|
||||||
|
continue
|
||||||
|
if upload_at <= 0:
|
||||||
|
upload_at = pick_upload_at(
|
||||||
|
channel_pk=ch_pk,
|
||||||
|
push_date=str(job.get("push_date") or day),
|
||||||
|
cfg=cfg,
|
||||||
|
)
|
||||||
|
db.update_shorts_job(str(job["id"]), upload_at=upload_at)
|
||||||
|
continue
|
||||||
|
if upload_at >= day_end - 30:
|
||||||
|
upload_at = pick_upload_at(
|
||||||
|
channel_pk=ch_pk,
|
||||||
|
push_date=str(job.get("push_date") or day),
|
||||||
|
cfg=cfg,
|
||||||
|
)
|
||||||
|
db.update_shorts_job(str(job["id"]), upload_at=upload_at)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _emit_shorts_event(
|
||||||
|
*,
|
||||||
|
kind: str,
|
||||||
|
level: str,
|
||||||
|
message: str,
|
||||||
|
job: dict[str, Any],
|
||||||
|
extra: dict[str, Any] | None = None,
|
||||||
|
) -> None:
|
||||||
|
try:
|
||||||
|
meta = {"shorts_job_id": str(job.get("id") or ""), **(extra or {})}
|
||||||
|
db.add_event(
|
||||||
|
kind=kind,
|
||||||
|
level=level,
|
||||||
|
message=message,
|
||||||
|
room_id=str(job.get("room_id") or ""),
|
||||||
|
session_id=str(job.get("session_id") or ""),
|
||||||
|
anchor_name=str(job.get("anchor_name") or job.get("room_id") or ""),
|
||||||
|
meta=meta,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
from .notify import send_webhook
|
||||||
|
|
||||||
|
asyncio.create_task(
|
||||||
|
send_webhook(
|
||||||
|
kind,
|
||||||
|
{
|
||||||
|
"message": message,
|
||||||
|
"job_id": str(job.get("id") or ""),
|
||||||
|
"anchor_name": str(job.get("anchor_name") or ""),
|
||||||
|
"room_id": str(job.get("room_id") or ""),
|
||||||
|
**(extra or {}),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _mark_failed(self, job: dict[str, Any], error: str) -> None:
|
||||||
|
jid = str(job["id"])
|
||||||
|
err = str(error or "失败")[:300]
|
||||||
|
self.last_error = err
|
||||||
|
db.update_shorts_job(jid, status="failed", error=err, finished_at=time.time())
|
||||||
|
anchor = str(job.get("anchor_name") or job.get("room_id") or "素材")
|
||||||
|
self._emit_shorts_event(
|
||||||
|
kind="shorts_fail",
|
||||||
|
level="error",
|
||||||
|
message=f"Shorts 失败:{anchor} — {err[:120]}",
|
||||||
|
job=job,
|
||||||
|
extra={"error": err},
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _requeue_missing_clip(job: dict[str, Any], *, manual: bool = False) -> None:
|
||||||
|
"""Clip file gone — reset to pending for re-record."""
|
||||||
|
jid = str(job["id"])
|
||||||
|
db.update_shorts_job(
|
||||||
|
jid,
|
||||||
|
status="pending",
|
||||||
|
clip_path="",
|
||||||
|
clip_seconds=0,
|
||||||
|
upload_at=0,
|
||||||
|
error="成片已丢失,已重新排队录制",
|
||||||
|
finished_at=0,
|
||||||
|
)
|
||||||
|
if manual:
|
||||||
|
raise ValueError("成片文件已丢失,已重新入队录制,请稍后刷新")
|
||||||
|
|
||||||
|
async def _wait_upload_done(self, job_id: str, *, timeout_sec: float = 120.0) -> dict[str, Any] | None:
|
||||||
|
"""Poll until job leaves uploading (uploaded/failed/requeued)."""
|
||||||
|
deadline = time.time() + max(10.0, float(timeout_sec))
|
||||||
|
while time.time() < deadline:
|
||||||
|
job = db.get_shorts_job(job_id)
|
||||||
|
if not job:
|
||||||
|
return None
|
||||||
|
st = str(job.get("status") or "")
|
||||||
|
if st in {"uploaded", "done", "failed", "pending"}:
|
||||||
|
return job
|
||||||
|
if st != "uploading":
|
||||||
|
return job
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
return db.get_shorts_job(job_id)
|
||||||
|
|
||||||
|
async def upload_job_now(self, job_id: str) -> dict[str, Any]:
|
||||||
|
"""Manually upload a recorded/scheduled clip immediately."""
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.reclaim_stale_shorts_uploads(max_age_sec=120)
|
||||||
|
db.reconcile_missing_shorts_clips(limit=50)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
job = db.get_shorts_job(job_id)
|
||||||
|
if not job:
|
||||||
|
raise ValueError("任务不存在")
|
||||||
|
clip = str(job.get("clip_path") or "").strip()
|
||||||
|
if not clip:
|
||||||
|
raise ValueError("尚未录制成片,无法上传")
|
||||||
|
if not Path(clip).is_file():
|
||||||
|
self._requeue_missing_clip(job, manual=True)
|
||||||
|
st = str(job.get("status") or "")
|
||||||
|
if st not in {"scheduled", "recorded", "uploading"}:
|
||||||
|
raise ValueError(f"状态 {st} 不可手动上传")
|
||||||
|
|
||||||
|
cfg = db.get_settings_map()
|
||||||
|
upload_max = self._upload_max(cfg)
|
||||||
|
if st == "uploading":
|
||||||
|
waited = await self._wait_upload_done(job_id, timeout_sec=120)
|
||||||
|
if waited:
|
||||||
|
wst = str(waited.get("status") or "")
|
||||||
|
if wst in {"uploaded", "done"}:
|
||||||
|
return waited
|
||||||
|
if wst == "failed":
|
||||||
|
raise ValueError(str(waited.get("error") or "上传失败"))
|
||||||
|
if wst == "pending":
|
||||||
|
raise ValueError(str(waited.get("error") or "成片已丢失,已重新排队录制"))
|
||||||
|
job = db.get_shorts_job(job_id) or job
|
||||||
|
st = str(job.get("status") or "")
|
||||||
|
|
||||||
|
if st == "uploaded":
|
||||||
|
return job
|
||||||
|
|
||||||
|
claimed = db.claim_shorts_job_manual_upload(job_id)
|
||||||
|
if not claimed:
|
||||||
|
if st == "uploading":
|
||||||
|
waited = await self._wait_upload_done(job_id, timeout_sec=90)
|
||||||
|
if waited and str(waited.get("status") or "") in {"uploaded", "done"}:
|
||||||
|
return waited
|
||||||
|
raise ValueError("任务已被其他进程占用或状态已变更")
|
||||||
|
|
||||||
|
if self._active_uploads >= upload_max:
|
||||||
|
wait_sec = 0
|
||||||
|
while self._active_uploads >= upload_max and wait_sec < 12:
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
wait_sec += 1
|
||||||
|
if self._active_uploads >= upload_max:
|
||||||
|
db.update_shorts_job(
|
||||||
|
job_id,
|
||||||
|
status="scheduled",
|
||||||
|
upload_at=time.time(),
|
||||||
|
error="",
|
||||||
|
)
|
||||||
|
raise ValueError("上传队列繁忙,请 5 秒后重试")
|
||||||
|
|
||||||
|
self._active_uploads += 1
|
||||||
|
try:
|
||||||
|
await self._do_upload(claimed, cfg)
|
||||||
|
self.processed += 1
|
||||||
|
done = db.get_shorts_job(job_id) or claimed
|
||||||
|
if str(done.get("status") or "") not in {"uploaded", "done"}:
|
||||||
|
waited = await self._wait_upload_done(job_id, timeout_sec=15)
|
||||||
|
if waited:
|
||||||
|
done = waited
|
||||||
|
return done
|
||||||
|
except Exception as exc:
|
||||||
|
if "成片文件不存在" in str(exc):
|
||||||
|
refreshed = db.get_shorts_job(job_id) or claimed
|
||||||
|
if str(refreshed.get("youtube_video_id") or "").strip():
|
||||||
|
db.update_shorts_job(job_id, status="uploaded", error="", clip_path="")
|
||||||
|
return refreshed
|
||||||
|
self._requeue_missing_clip(claimed, manual=True)
|
||||||
|
self.last_error = str(exc)[:300]
|
||||||
|
self._mark_failed(claimed, self.last_error)
|
||||||
|
raise ValueError(self.last_error) from exc
|
||||||
|
finally:
|
||||||
|
self._active_uploads = max(0, self._active_uploads - 1)
|
||||||
|
|
||||||
|
async def _run_upload_only(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
||||||
|
try:
|
||||||
|
await self._do_upload(job, cfg)
|
||||||
|
self.processed += 1
|
||||||
|
except Exception as exc:
|
||||||
|
if "成片文件不存在" in str(exc):
|
||||||
|
if str(job.get("youtube_video_id") or "").strip():
|
||||||
|
db.update_shorts_job(
|
||||||
|
str(job["id"]),
|
||||||
|
status="uploaded",
|
||||||
|
error="",
|
||||||
|
clip_path="",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
self._requeue_missing_clip(job)
|
||||||
|
return
|
||||||
|
self._mark_failed(job, str(exc)[:300])
|
||||||
|
finally:
|
||||||
|
self._active_uploads = max(0, self._active_uploads - 1)
|
||||||
|
|
||||||
async def _process(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
async def _process(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
||||||
jid = str(job["id"])
|
jid = str(job["id"])
|
||||||
status = str(job.get("status") or "")
|
status = str(job.get("status") or "")
|
||||||
@ -243,21 +856,22 @@ class ShortsPipeline:
|
|||||||
await self._do_record(job, cfg)
|
await self._do_record(job, cfg)
|
||||||
job = db.get_shorts_job(jid) or job
|
job = db.get_shorts_job(jid) or job
|
||||||
status = str(job.get("status") or "")
|
status = str(job.get("status") or "")
|
||||||
if status == "uploading" or (
|
# Only upload when claim already flipped to uploading (due slot)
|
||||||
status == "recorded" and cfg.get("shorts_auto_upload", True)
|
if status == "uploading":
|
||||||
):
|
|
||||||
if status == "recorded":
|
|
||||||
db.update_shorts_job(jid, status="uploading")
|
|
||||||
job = db.get_shorts_job(jid) or job
|
|
||||||
await self._do_upload(job, cfg)
|
await self._do_upload(job, cfg)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self.last_error = str(exc)[:300]
|
if "成片文件不存在" in str(exc):
|
||||||
db.update_shorts_job(
|
if str(job.get("youtube_video_id") or "").strip():
|
||||||
jid,
|
db.update_shorts_job(
|
||||||
status="failed",
|
str(job["id"]),
|
||||||
error=self.last_error,
|
status="uploaded",
|
||||||
finished_at=time.time(),
|
error="",
|
||||||
)
|
clip_path="",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
self._requeue_missing_clip(job)
|
||||||
|
return
|
||||||
|
self._mark_failed(job, str(exc)[:300])
|
||||||
|
|
||||||
async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
||||||
jid = str(job["id"])
|
jid = str(job["id"])
|
||||||
@ -268,43 +882,100 @@ class ShortsPipeline:
|
|||||||
cookie=cookie,
|
cookie=cookie,
|
||||||
)
|
)
|
||||||
if not stream:
|
if not stream:
|
||||||
|
err = str(job.get("error") or "")
|
||||||
|
if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900:
|
||||||
|
db.update_shorts_job(
|
||||||
|
jid,
|
||||||
|
status="pending",
|
||||||
|
error="stream_retry:1",
|
||||||
|
stream_url="",
|
||||||
|
)
|
||||||
|
return
|
||||||
db.update_shorts_job(
|
db.update_shorts_job(
|
||||||
jid,
|
jid,
|
||||||
status="failed",
|
status="failed",
|
||||||
error="无法获取直播流(可能已停播)",
|
error="无法获取直播流(可能已停播)",
|
||||||
finished_at=time.time(),
|
finished_at=time.time(),
|
||||||
)
|
)
|
||||||
|
self._emit_shorts_event(
|
||||||
|
kind="shorts_fail",
|
||||||
|
level="error",
|
||||||
|
message=f"Shorts 录制失败:{job.get('anchor_name') or job.get('room_id') or jid} — 无法获取直播流",
|
||||||
|
job=job,
|
||||||
|
extra={"error": "无法获取直播流(可能已停播)"},
|
||||||
|
)
|
||||||
return
|
return
|
||||||
sec = int(cfg.get("shorts_clip_sec") or 15)
|
sec = int(cfg.get("shorts_clip_sec") or 15)
|
||||||
outcome = await record_clip(job_id=jid, stream_url=stream, seconds=sec)
|
outcome = await record_clip(job_id=jid, stream_url=stream, seconds=sec)
|
||||||
if not outcome.get("ok"):
|
if not outcome.get("ok"):
|
||||||
|
err = str(outcome.get("error") or "录制失败")
|
||||||
db.update_shorts_job(
|
db.update_shorts_job(
|
||||||
jid,
|
jid,
|
||||||
status="failed",
|
status="failed",
|
||||||
error=str(outcome.get("error") or "录制失败"),
|
error=err,
|
||||||
stream_url=stream,
|
stream_url=stream,
|
||||||
finished_at=time.time(),
|
finished_at=time.time(),
|
||||||
)
|
)
|
||||||
|
self._emit_shorts_event(
|
||||||
|
kind="shorts_fail",
|
||||||
|
level="error",
|
||||||
|
message=f"Shorts 录制失败:{job.get('anchor_name') or job.get('room_id') or jid} — {err[:80]}",
|
||||||
|
job=job,
|
||||||
|
extra={"error": err},
|
||||||
|
)
|
||||||
return
|
return
|
||||||
next_status = "uploading" if cfg.get("shorts_auto_upload", True) else "recorded"
|
clip_path = str(outcome.get("path") or "")
|
||||||
|
if not cfg.get("shorts_auto_upload", True):
|
||||||
|
db.update_shorts_job(
|
||||||
|
jid,
|
||||||
|
status="recorded",
|
||||||
|
clip_path=clip_path,
|
||||||
|
clip_seconds=float(outcome.get("seconds") or sec),
|
||||||
|
stream_url=stream,
|
||||||
|
error="",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
# Stagger upload across the day (default) — never burst immediately
|
||||||
|
from .shorts_schedule import pick_upload_at
|
||||||
|
|
||||||
|
upload_at = pick_upload_at(
|
||||||
|
channel_pk=str(job.get("channel_pk") or ""),
|
||||||
|
push_date=str(job.get("push_date") or ""),
|
||||||
|
cfg=cfg,
|
||||||
|
)
|
||||||
db.update_shorts_job(
|
db.update_shorts_job(
|
||||||
jid,
|
jid,
|
||||||
status=next_status,
|
status="scheduled",
|
||||||
clip_path=str(outcome.get("path") or ""),
|
clip_path=clip_path,
|
||||||
clip_seconds=float(outcome.get("seconds") or sec),
|
clip_seconds=float(outcome.get("seconds") or sec),
|
||||||
stream_url=stream,
|
stream_url=stream,
|
||||||
|
upload_at=upload_at,
|
||||||
error="",
|
error="",
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _do_upload(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
async def _do_upload(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
jid = str(job["id"])
|
jid = str(job["id"])
|
||||||
|
yt_id = str(job.get("youtube_video_id") or "").strip()
|
||||||
|
if yt_id:
|
||||||
|
db.update_shorts_job(
|
||||||
|
jid,
|
||||||
|
status="uploaded",
|
||||||
|
error="",
|
||||||
|
clip_path="",
|
||||||
|
finished_at=float(job.get("finished_at") or 0) or time.time(),
|
||||||
|
)
|
||||||
|
return
|
||||||
clip = str(job.get("clip_path") or "")
|
clip = str(job.get("clip_path") or "")
|
||||||
if not clip:
|
if not clip:
|
||||||
db.update_shorts_job(jid, status="failed", error="无成片路径", finished_at=time.time())
|
self._mark_failed(job, "无成片路径")
|
||||||
return
|
return
|
||||||
|
if not Path(clip).is_file():
|
||||||
|
raise ValueError("成片文件不存在,已重新排队录制")
|
||||||
channel = db.get_shorts_channel(str(job.get("channel_pk") or ""))
|
channel = db.get_shorts_channel(str(job.get("channel_pk") or ""))
|
||||||
if not channel:
|
if not channel:
|
||||||
db.update_shorts_job(jid, status="failed", error="频道不存在", finished_at=time.time())
|
self._mark_failed(job, "频道不存在")
|
||||||
return
|
return
|
||||||
from .shorts_oauth import channel_oauth_creds
|
from .shorts_oauth import channel_oauth_creds
|
||||||
|
|
||||||
@ -312,7 +983,7 @@ class ShortsPipeline:
|
|||||||
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
|
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
|
||||||
db.update_shorts_job(
|
db.update_shorts_job(
|
||||||
jid,
|
jid,
|
||||||
status="recorded",
|
status="scheduled" if float(job.get("upload_at") or 0) else "recorded",
|
||||||
error="频道未授权 Google,已保留成片待上传",
|
error="频道未授权 Google,已保留成片待上传",
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
@ -340,17 +1011,27 @@ class ShortsPipeline:
|
|||||||
youtube_url=str(result.get("url") or ""),
|
youtube_url=str(result.get("url") or ""),
|
||||||
error="",
|
error="",
|
||||||
finished_at=time.time(),
|
finished_at=time.time(),
|
||||||
|
clip_path="",
|
||||||
)
|
)
|
||||||
|
if cfg.get("shorts_delete_clip_after_upload", True):
|
||||||
|
self._delete_clip(clip)
|
||||||
|
yt_url = str(result.get("url") or "")
|
||||||
|
self._emit_shorts_event(
|
||||||
|
kind="shorts_ok",
|
||||||
|
level="info",
|
||||||
|
message=f"Shorts 已上传:{yt_url or result.get('video_id')}",
|
||||||
|
job=job,
|
||||||
|
extra={"video_id": result.get("video_id"), "youtube_url": yt_url},
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _delete_clip(path: str) -> None:
|
||||||
try:
|
try:
|
||||||
db.add_event(
|
from pathlib import Path
|
||||||
kind="ops",
|
|
||||||
level="info",
|
p = Path(path)
|
||||||
message=f"Shorts 已上传:{result.get('url')}",
|
if p.is_file():
|
||||||
room_id=str(job.get("room_id") or ""),
|
p.unlink()
|
||||||
session_id=str(job.get("session_id") or ""),
|
|
||||||
anchor_name=anchor,
|
|
||||||
meta={"shorts_job_id": jid, "video_id": result.get("video_id")},
|
|
||||||
)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
242
backend/app/shorts_schedule.py
Normal file
242
backend/app/shorts_schedule.py
Normal file
@ -0,0 +1,242 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Irregular 24h upload scheduling — avoid dense / metronomic YouTube uploads."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import random
|
||||||
|
import time
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from . import db
|
||||||
|
from .timeutil import beijing_day_bounds, beijing_from_ts, beijing_now, push_date_from_ts
|
||||||
|
|
||||||
|
|
||||||
|
def _day_end_ts(push_date: str) -> float:
|
||||||
|
"""Exclusive end of Beijing calendar day for push_date (next midnight)."""
|
||||||
|
return beijing_day_bounds(push_date)[1]
|
||||||
|
|
||||||
|
|
||||||
|
def _occupied_slots(push_date: str) -> list[tuple[float, str]]:
|
||||||
|
"""(upload_at_or_finished, channel_pk) for jobs that already claim a slot today."""
|
||||||
|
data = db.list_shorts_jobs(push_date=push_date, limit=500, offset=0)
|
||||||
|
slots: list[tuple[float, str]] = []
|
||||||
|
for j in data.get("jobs") or []:
|
||||||
|
st = str(j.get("status") or "")
|
||||||
|
ch = str(j.get("channel_pk") or "")
|
||||||
|
if st in {"scheduled", "recorded", "uploading"}:
|
||||||
|
ts = float(j.get("upload_at") or 0) or float(j.get("updated_at") or 0)
|
||||||
|
if ts > 0:
|
||||||
|
slots.append((ts, ch))
|
||||||
|
elif st in {"uploaded", "done"}:
|
||||||
|
ts = float(j.get("finished_at") or j.get("updated_at") or 0)
|
||||||
|
if ts > 0:
|
||||||
|
slots.append((ts, ch))
|
||||||
|
return slots
|
||||||
|
|
||||||
|
|
||||||
|
def _quota_pressure(
|
||||||
|
*,
|
||||||
|
channel_pk: str,
|
||||||
|
push_date: str,
|
||||||
|
now: float,
|
||||||
|
) -> tuple[float, float, bool, bool]:
|
||||||
|
"""Return (global_min_scale, channel_min_scale, behind_min, must_compress)."""
|
||||||
|
ch = db.get_shorts_channel(channel_pk) if channel_pk else None
|
||||||
|
used = db.shorts_channel_upload_count(channel_pk, push_date) if channel_pk else 0
|
||||||
|
from .db import SHORTS_DAILY_FORCE
|
||||||
|
|
||||||
|
daily_max = SHORTS_DAILY_FORCE
|
||||||
|
daily_min = SHORTS_DAILY_FORCE
|
||||||
|
day_start, day_end = beijing_day_bounds(push_date)
|
||||||
|
span = max(1.0, day_end - day_start)
|
||||||
|
day_progress = max(0.0, min(1.0, (now - day_start) / span))
|
||||||
|
time_left = max(0.0, day_end - now)
|
||||||
|
remaining_slots = max(0, daily_max - used)
|
||||||
|
|
||||||
|
expected_min = daily_min * min(1.0, day_progress * 1.15 + 0.05)
|
||||||
|
behind_min = used < daily_min and used < expected_min
|
||||||
|
behind_max = remaining_slots > 0 and used < daily_max * day_progress * 0.9
|
||||||
|
must_compress = remaining_slots > 0 and time_left < 3600 * remaining_slots * 0.55
|
||||||
|
|
||||||
|
g_scale = 1.0
|
||||||
|
c_scale = 1.0
|
||||||
|
if behind_min:
|
||||||
|
g_scale = min(g_scale, 0.45)
|
||||||
|
c_scale = min(c_scale, 0.3)
|
||||||
|
elif behind_max and day_progress > 0.35:
|
||||||
|
g_scale = min(g_scale, 0.65)
|
||||||
|
c_scale = min(c_scale, 0.5)
|
||||||
|
if must_compress or (day_progress > 0.82 and remaining_slots > 0):
|
||||||
|
per_slot = time_left / max(1, remaining_slots)
|
||||||
|
c_scale = min(c_scale, max(0.15, per_slot / 2400.0))
|
||||||
|
g_scale = min(g_scale, max(0.2, c_scale * 0.75))
|
||||||
|
return g_scale, c_scale, behind_min, must_compress or (day_progress > 0.9 and remaining_slots > 0)
|
||||||
|
|
||||||
|
|
||||||
|
def pick_upload_at(
|
||||||
|
*,
|
||||||
|
channel_pk: str,
|
||||||
|
push_date: str = "",
|
||||||
|
cfg: dict[str, Any] | None = None,
|
||||||
|
) -> float:
|
||||||
|
"""Pick a jittered upload time within the Beijing day, avoiding clustering."""
|
||||||
|
settings = cfg or db.get_settings_map()
|
||||||
|
now = time.time()
|
||||||
|
day = push_date or push_date_from_ts(now)
|
||||||
|
day_end = _day_end_ts(day)
|
||||||
|
latest = day_end - 45
|
||||||
|
|
||||||
|
if not settings.get("shorts_upload_spread", True):
|
||||||
|
return min(now + random.uniform(20, 120), latest)
|
||||||
|
|
||||||
|
global_min = max(300.0, float(settings.get("shorts_upload_min_gap_sec") or 720))
|
||||||
|
channel_min = max(global_min, float(settings.get("shorts_channel_min_gap_sec") or 2400))
|
||||||
|
g_scale, c_scale, behind_min, urgent = _quota_pressure(
|
||||||
|
channel_pk=channel_pk, push_date=day, now=now
|
||||||
|
)
|
||||||
|
global_min *= g_scale
|
||||||
|
channel_min *= c_scale
|
||||||
|
|
||||||
|
if urgent or behind_min:
|
||||||
|
earliest = now + random.uniform(45, 240)
|
||||||
|
else:
|
||||||
|
earliest = now + random.uniform(180, 1500)
|
||||||
|
if earliest >= latest:
|
||||||
|
earliest = now + random.uniform(30, max(90.0, global_min * 0.4))
|
||||||
|
|
||||||
|
slots = _occupied_slots(day)
|
||||||
|
|
||||||
|
def conflicts(ts: float) -> bool:
|
||||||
|
for other_ts, other_ch in slots:
|
||||||
|
gap = abs(ts - other_ts)
|
||||||
|
if gap < global_min * random.uniform(0.85, 1.15):
|
||||||
|
return True
|
||||||
|
if other_ch == channel_pk and gap < channel_min * random.uniform(0.9, 1.2):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
window_end = max(earliest + 60, latest)
|
||||||
|
for _ in range(48):
|
||||||
|
if random.random() < 0.35:
|
||||||
|
span = max(600.0, (window_end - earliest) / 8)
|
||||||
|
cand = earliest + random.expovariate(1.0 / span)
|
||||||
|
cand = min(cand, window_end)
|
||||||
|
else:
|
||||||
|
cand = random.uniform(earliest, window_end)
|
||||||
|
if cand < earliest:
|
||||||
|
cand = earliest + random.uniform(0, 120)
|
||||||
|
if not conflicts(cand):
|
||||||
|
return float(min(cand, latest))
|
||||||
|
|
||||||
|
last_ts = max((s[0] for s in slots), default=now)
|
||||||
|
cand = max(earliest, last_ts + random.uniform(global_min, global_min * 2.8))
|
||||||
|
ch_last = max((s[0] for s in slots if s[1] == channel_pk), default=0.0)
|
||||||
|
if ch_last:
|
||||||
|
cand = max(cand, ch_last + random.uniform(channel_min, channel_min * 1.8))
|
||||||
|
return float(min(cand, latest))
|
||||||
|
|
||||||
|
|
||||||
|
def schedule_board(limit: int = 24) -> dict[str, Any]:
|
||||||
|
"""Upcoming scheduled uploads + per-channel today usage for UI."""
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
now = time.time()
|
||||||
|
day_start, day_end = beijing_day_bounds(day)
|
||||||
|
seconds_left = max(0, int(day_end - now))
|
||||||
|
data = db.list_shorts_jobs(push_date=day, limit=500, offset=0)
|
||||||
|
upcoming: list[dict[str, Any]] = []
|
||||||
|
by_ch: dict[str, dict[str, int]] = {}
|
||||||
|
for j in data.get("jobs") or []:
|
||||||
|
ch = str(j.get("channel_pk") or "")
|
||||||
|
st = str(j.get("status") or "")
|
||||||
|
bucket = by_ch.setdefault(ch, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0})
|
||||||
|
if st in db._SHORTS_QUOTA_STATUSES:
|
||||||
|
bucket["used"] += 1
|
||||||
|
if st == "uploaded" or st == "done":
|
||||||
|
bucket["uploaded"] += 1
|
||||||
|
if st == "scheduled":
|
||||||
|
bucket["scheduled"] += 1
|
||||||
|
if st in {"pending", "recording"}:
|
||||||
|
bucket["pending"] += 1
|
||||||
|
clip = str(j.get("clip_path") or "").strip()
|
||||||
|
clip_ready = bool(clip) and Path(clip).is_file()
|
||||||
|
if st == "scheduled" and clip_ready:
|
||||||
|
upcoming.append(j)
|
||||||
|
elif st == "recorded" and clip_ready:
|
||||||
|
upcoming.append(j)
|
||||||
|
upcoming.sort(
|
||||||
|
key=lambda x: (
|
||||||
|
float(x.get("upload_at") or 0) or float(x.get("updated_at") or 0),
|
||||||
|
float(x.get("created_at") or 0),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
channels = db.list_shorts_channels(enabled=None)
|
||||||
|
channel_map = {str(c["id"]): c for c in channels}
|
||||||
|
enriched = []
|
||||||
|
for j in upcoming[:limit]:
|
||||||
|
ch = channel_map.get(str(j.get("channel_pk") or ""), {})
|
||||||
|
clip = str(j.get("clip_path") or "").strip()
|
||||||
|
clip_ready = bool(clip) and Path(clip).is_file()
|
||||||
|
enriched.append(
|
||||||
|
{
|
||||||
|
"id": j.get("id"),
|
||||||
|
"upload_at": j.get("upload_at"),
|
||||||
|
"anchor_name": j.get("anchor_name"),
|
||||||
|
"room_id": j.get("room_id"),
|
||||||
|
"channel_pk": j.get("channel_pk"),
|
||||||
|
"channel_name": ch.get("name") or "",
|
||||||
|
"status": j.get("status"),
|
||||||
|
"clip_ready": clip_ready,
|
||||||
|
"can_upload_now": str(j.get("status") or "") in {"scheduled", "recorded"}
|
||||||
|
and clip_ready,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
channel_rows = []
|
||||||
|
day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start)))
|
||||||
|
total_gap = 0
|
||||||
|
min_unmet = 0
|
||||||
|
for c in channels:
|
||||||
|
cid = str(c["id"])
|
||||||
|
from .db import SHORTS_DAILY_FORCE
|
||||||
|
|
||||||
|
daily_min = SHORTS_DAILY_FORCE
|
||||||
|
daily_max = SHORTS_DAILY_FORCE
|
||||||
|
stats = by_ch.get(cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0})
|
||||||
|
used = int(stats["used"])
|
||||||
|
gap = max(0, daily_max - used)
|
||||||
|
min_met = used >= daily_min
|
||||||
|
if c.get("enabled") and not min_met:
|
||||||
|
min_unmet += 1
|
||||||
|
if c.get("enabled"):
|
||||||
|
total_gap += gap
|
||||||
|
expected_min = daily_min * min(1.0, day_progress * 1.15 + 0.05)
|
||||||
|
channel_rows.append(
|
||||||
|
{
|
||||||
|
"id": cid,
|
||||||
|
"name": c.get("name"),
|
||||||
|
"youtube_channel_id": c.get("youtube_channel_id"),
|
||||||
|
"enabled": bool(c.get("enabled")),
|
||||||
|
"daily_min": daily_min,
|
||||||
|
"daily_max": daily_max,
|
||||||
|
"authorized": bool(str(c.get("refresh_token") or "").strip()),
|
||||||
|
"gap": gap,
|
||||||
|
"min_met": min_met,
|
||||||
|
"max_met": used >= daily_max,
|
||||||
|
"behind_pace": bool(c.get("enabled") and used < expected_min and used < daily_min),
|
||||||
|
**stats,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"push_date": day,
|
||||||
|
"now": now,
|
||||||
|
"day_start": day_start,
|
||||||
|
"day_end": day_end,
|
||||||
|
"seconds_left": seconds_left,
|
||||||
|
"day_progress": round(day_progress, 4),
|
||||||
|
"total_gap": total_gap,
|
||||||
|
"min_unmet_channels": min_unmet,
|
||||||
|
"beijing_window": f"{day} 00:00–24:00",
|
||||||
|
"upcoming": enriched,
|
||||||
|
"channels": channel_rows,
|
||||||
|
"beijing_hint": beijing_from_ts(now).strftime("%Y-%m-%d %H:%M"),
|
||||||
|
}
|
||||||
@ -39,11 +39,15 @@ async def upload_shorts_mp4(
|
|||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
path = Path(file_path)
|
path = Path(file_path)
|
||||||
if not path.is_file():
|
if not path.is_file():
|
||||||
raise ValueError("成片文件不存在")
|
raise ValueError("成片文件不存在,已重新排队录制")
|
||||||
access = await refresh_access_token(
|
access = await refresh_access_token(
|
||||||
client_id=client_id, client_secret=client_secret, refresh_token=refresh_token
|
client_id=client_id, client_secret=client_secret, refresh_token=refresh_token
|
||||||
)
|
)
|
||||||
size = path.stat().st_size
|
try:
|
||||||
|
size = path.stat().st_size
|
||||||
|
raw = path.read_bytes()
|
||||||
|
except FileNotFoundError as exc:
|
||||||
|
raise ValueError("成片文件不存在,已重新排队录制") from exc
|
||||||
meta = {
|
meta = {
|
||||||
"snippet": {
|
"snippet": {
|
||||||
"title": (title or "Shorts")[:100],
|
"title": (title or "Shorts")[:100],
|
||||||
@ -59,7 +63,7 @@ async def upload_shorts_mp4(
|
|||||||
"https://www.googleapis.com/upload/youtube/v3/videos"
|
"https://www.googleapis.com/upload/youtube/v3/videos"
|
||||||
"?uploadType=resumable&part=snippet,status"
|
"?uploadType=resumable&part=snippet,status"
|
||||||
)
|
)
|
||||||
async with httpx.AsyncClient(timeout=120.0, trust_env=False) as client:
|
async with httpx.AsyncClient(timeout=180.0, trust_env=False) as client:
|
||||||
init = await client.post(
|
init = await client.post(
|
||||||
init_url,
|
init_url,
|
||||||
headers={
|
headers={
|
||||||
@ -73,7 +77,6 @@ async def upload_shorts_mp4(
|
|||||||
upload_url = init.headers.get("location") or init.headers.get("Location")
|
upload_url = init.headers.get("location") or init.headers.get("Location")
|
||||||
if init.status_code >= 400 or not upload_url:
|
if init.status_code >= 400 or not upload_url:
|
||||||
raise ValueError(f"初始化上传失败: {init.text[:400]}")
|
raise ValueError(f"初始化上传失败: {init.text[:400]}")
|
||||||
raw = path.read_bytes()
|
|
||||||
put = await client.put(
|
put = await client.put(
|
||||||
upload_url,
|
upload_url,
|
||||||
headers={
|
headers={
|
||||||
|
|||||||
@ -48,3 +48,12 @@ def next_hour_boundary_ts(ts: float) -> float:
|
|||||||
def beijing_today_at(hour: int, minute: int = 0) -> datetime:
|
def beijing_today_at(hour: int, minute: int = 0) -> datetime:
|
||||||
now = beijing_now()
|
now = beijing_now()
|
||||||
return now.replace(hour=int(hour) % 24, minute=int(minute) % 60, second=0, microsecond=0)
|
return now.replace(hour=int(hour) % 24, minute=int(minute) % 60, second=0, microsecond=0)
|
||||||
|
|
||||||
|
|
||||||
|
def beijing_day_bounds(push_date: str = "") -> tuple[float, float]:
|
||||||
|
"""Beijing calendar day [start, end) as Unix timestamps for push_date (default today)."""
|
||||||
|
day = push_date or push_date_from_ts(time.time())
|
||||||
|
y, m, d = [int(x) for x in day.split("-")]
|
||||||
|
start = datetime(y, m, d, 0, 0, 0, tzinfo=BJ)
|
||||||
|
end = start + timedelta(days=1)
|
||||||
|
return start.timestamp(), end.timestamp()
|
||||||
|
|||||||
366
backend/app/youtube_live.py
Normal file
366
backend/app/youtube_live.py
Normal file
@ -0,0 +1,366 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Unified YouTube live status: InnerTube (youtube-svc) first, OAuth / DB fallback."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import time
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from . import db, youtube_client
|
||||||
|
from .models import normalize_youtube_channel_url
|
||||||
|
from .youtube_client import YouTubeSvcError
|
||||||
|
|
||||||
|
_CACHE: dict[str, Any] = {"at": 0.0, "payload": None}
|
||||||
|
_CACHE_TTL_SEC = 15.0
|
||||||
|
_BATCH_SIZE = 20
|
||||||
|
_REFRESH_LOCK: Optional[asyncio.Lock] = None
|
||||||
|
_LAST_OAUTH_AT = 0.0
|
||||||
|
_OAUTH_MIN_INTERVAL_SEC = 45.0
|
||||||
|
|
||||||
|
|
||||||
|
def _refresh_lock() -> asyncio.Lock:
|
||||||
|
global _REFRESH_LOCK
|
||||||
|
if _REFRESH_LOCK is None:
|
||||||
|
_REFRESH_LOCK = asyncio.Lock()
|
||||||
|
return _REFRESH_LOCK
|
||||||
|
|
||||||
|
|
||||||
|
def _channel_url_for_group(group: dict[str, Any]) -> str:
|
||||||
|
cid = str(group.get("channel_id") or "").strip()
|
||||||
|
if cid:
|
||||||
|
return f"https://www.youtube.com/channel/{cid}"
|
||||||
|
url = str(group.get("channel_url") or "").strip()
|
||||||
|
if url:
|
||||||
|
return normalize_youtube_channel_url(url)
|
||||||
|
handle = str(group.get("handle") or "").strip()
|
||||||
|
if handle:
|
||||||
|
h = handle if handle.startswith("@") else f"@{handle}"
|
||||||
|
return f"https://www.youtube.com/{h}"
|
||||||
|
key = str(group.get("channel_key") or "").strip()
|
||||||
|
if key.startswith("UC"):
|
||||||
|
return f"https://www.youtube.com/channel/{key}"
|
||||||
|
if key.startswith("@"):
|
||||||
|
return f"https://www.youtube.com/{key}"
|
||||||
|
return url or key
|
||||||
|
|
||||||
|
|
||||||
|
def _channel_url_for_shorts(ch: dict[str, Any]) -> str:
|
||||||
|
cid = str(ch.get("youtube_channel_id") or "").strip()
|
||||||
|
if cid:
|
||||||
|
return f"https://www.youtube.com/channel/{cid}"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _live_entry(
|
||||||
|
*,
|
||||||
|
is_live: bool,
|
||||||
|
source: str,
|
||||||
|
live_url: str = "",
|
||||||
|
title: str = "",
|
||||||
|
channel_id: str = "",
|
||||||
|
error: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
out: dict[str, Any] = {"is_live": bool(is_live), "source": source}
|
||||||
|
if is_live:
|
||||||
|
if live_url:
|
||||||
|
out["live_url"] = live_url
|
||||||
|
if title:
|
||||||
|
out["title"] = title
|
||||||
|
if channel_id:
|
||||||
|
out["channel_id"] = channel_id
|
||||||
|
if error:
|
||||||
|
out["error"] = error
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_batch_result(row: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
if not row.get("ok"):
|
||||||
|
return _live_entry(is_live=False, source="youtubei", error=str(row.get("error") or "probe failed"))
|
||||||
|
live = row.get("live") if isinstance(row.get("live"), dict) else {}
|
||||||
|
live_url = str(live.get("url") or live.get("watch_url") or "").strip()
|
||||||
|
if not live_url:
|
||||||
|
vid = str(live.get("video_id") or live.get("id") or "").strip()
|
||||||
|
if vid:
|
||||||
|
live_url = f"https://www.youtube.com/watch?v={vid}"
|
||||||
|
title = str(live.get("title") or row.get("title") or "").strip()
|
||||||
|
cid = str(row.get("channel_id") or "").strip()
|
||||||
|
return _live_entry(
|
||||||
|
is_live=bool(row.get("is_live")),
|
||||||
|
source="youtubei",
|
||||||
|
live_url=live_url,
|
||||||
|
title=title,
|
||||||
|
channel_id=cid,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _oauth_live_for_shorts(channel_pk: str, youtube_channel_id: str) -> Optional[dict[str, Any]]:
|
||||||
|
"""Detect whether this OAuth-owned channel is currently live.
|
||||||
|
|
||||||
|
Prefer liveBroadcasts.list (mine + active) — 1 quota unit, no Search Queries pool.
|
||||||
|
Fall back to search.list only if broadcasts API is unavailable.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from . import youtube_manage
|
||||||
|
|
||||||
|
token, _ch = await youtube_manage._access_for_channel(channel_pk)
|
||||||
|
|
||||||
|
# 1) Own-channel liveBroadcasts (correct for Shorts upload channels)
|
||||||
|
# Note: broadcastStatus + mine can be rejected as incompatible; list mine then filter.
|
||||||
|
try:
|
||||||
|
data = await youtube_manage._get(
|
||||||
|
"liveBroadcasts",
|
||||||
|
token=token,
|
||||||
|
params={
|
||||||
|
"part": "id,snippet,status",
|
||||||
|
"mine": "true",
|
||||||
|
"maxResults": 25,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
items = data.get("items") or []
|
||||||
|
live_items = [
|
||||||
|
it
|
||||||
|
for it in items
|
||||||
|
if str(((it.get("status") or {}).get("lifeCycleStatus") or "")).lower() == "live"
|
||||||
|
]
|
||||||
|
if live_items:
|
||||||
|
item = live_items[0]
|
||||||
|
sn = item.get("snippet") or {}
|
||||||
|
vid = str(item.get("id") or "").strip()
|
||||||
|
title = str(sn.get("title") or "").strip()
|
||||||
|
live_url = f"https://www.youtube.com/watch?v={vid}" if vid else ""
|
||||||
|
return _live_entry(
|
||||||
|
is_live=True,
|
||||||
|
source="oauth-broadcast",
|
||||||
|
live_url=live_url,
|
||||||
|
title=title,
|
||||||
|
channel_id=youtube_channel_id,
|
||||||
|
)
|
||||||
|
return _live_entry(is_live=False, source="oauth-broadcast", channel_id=youtube_channel_id)
|
||||||
|
except Exception as broadcast_exc:
|
||||||
|
broadcast_err = str(broadcast_exc)
|
||||||
|
|
||||||
|
# 2) Fallback: search (expensive; may hit daily Search Queries quota)
|
||||||
|
try:
|
||||||
|
data = await youtube_manage._get(
|
||||||
|
"search",
|
||||||
|
token=token,
|
||||||
|
params={
|
||||||
|
"part": "snippet",
|
||||||
|
"channelId": youtube_channel_id,
|
||||||
|
"eventType": "live",
|
||||||
|
"type": "video",
|
||||||
|
"maxResults": 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
items = data.get("items") or []
|
||||||
|
if not items:
|
||||||
|
return _live_entry(
|
||||||
|
is_live=False,
|
||||||
|
source="oauth",
|
||||||
|
channel_id=youtube_channel_id,
|
||||||
|
error=broadcast_err[:120] if broadcast_err else "",
|
||||||
|
)
|
||||||
|
item = items[0]
|
||||||
|
vid = str((item.get("id") or {}).get("videoId") or "").strip()
|
||||||
|
title = str((item.get("snippet") or {}).get("title") or "").strip()
|
||||||
|
live_url = f"https://www.youtube.com/watch?v={vid}" if vid else ""
|
||||||
|
return _live_entry(
|
||||||
|
is_live=True,
|
||||||
|
source="oauth",
|
||||||
|
live_url=live_url,
|
||||||
|
title=title,
|
||||||
|
channel_id=youtube_channel_id,
|
||||||
|
)
|
||||||
|
except Exception as search_exc:
|
||||||
|
return _live_entry(
|
||||||
|
is_live=False,
|
||||||
|
source="oauth",
|
||||||
|
channel_id=youtube_channel_id,
|
||||||
|
error=f"{broadcast_err[:80]} | {str(search_exc)[:100]}",
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
return _live_entry(
|
||||||
|
is_live=False,
|
||||||
|
source="oauth",
|
||||||
|
channel_id=youtube_channel_id,
|
||||||
|
error=str(exc)[:200],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def build_live_map(*, force: bool = False) -> dict[str, Any]:
|
||||||
|
global _LAST_OAUTH_AT
|
||||||
|
now = time.time()
|
||||||
|
cached = _CACHE.get("payload")
|
||||||
|
if not force and cached and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC:
|
||||||
|
return cached
|
||||||
|
|
||||||
|
async with _refresh_lock():
|
||||||
|
now = time.time()
|
||||||
|
cached = _CACHE.get("payload")
|
||||||
|
if not force and cached and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC:
|
||||||
|
return cached
|
||||||
|
return await _build_live_map_unlocked(now=now)
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
targets: list[dict[str, Any]] = []
|
||||||
|
url_to_refs: dict[str, list[tuple[str, dict[str, Any]]]] = {}
|
||||||
|
cid_to_refs: dict[str, list[tuple[str, dict[str, Any]]]] = {}
|
||||||
|
|
||||||
|
for g in groups:
|
||||||
|
url = _channel_url_for_group(g)
|
||||||
|
ref = f"group:{g['id']}"
|
||||||
|
meta = {"kind": "group", "group": g, "url": url}
|
||||||
|
targets.append({"ref": ref, "url": url, **meta})
|
||||||
|
if url:
|
||||||
|
url_to_refs.setdefault(url, []).append((ref, meta))
|
||||||
|
cid = str(g.get("channel_id") or "").strip()
|
||||||
|
if cid:
|
||||||
|
cid_to_refs.setdefault(cid, []).append((ref, meta))
|
||||||
|
|
||||||
|
for ch in shorts:
|
||||||
|
url = _channel_url_for_shorts(ch)
|
||||||
|
ref = f"shorts:{ch['id']}"
|
||||||
|
meta = {"kind": "shorts", "channel_pk": ch["id"], "youtube_channel_id": ch.get("youtube_channel_id"), "url": url}
|
||||||
|
targets.append({"ref": ref, "url": url, **meta})
|
||||||
|
if url:
|
||||||
|
url_to_refs.setdefault(url, []).append((ref, meta))
|
||||||
|
cid = str(ch.get("youtube_channel_id") or "").strip()
|
||||||
|
if cid:
|
||||||
|
cid_to_refs.setdefault(cid, []).append((ref, meta))
|
||||||
|
targets.append({"ref": f"channel:{cid}", "url": url or f"https://www.youtube.com/channel/{cid}", **meta})
|
||||||
|
|
||||||
|
entries: dict[str, Any] = {}
|
||||||
|
unique_urls: list[str] = []
|
||||||
|
seen_urls: set[str] = set()
|
||||||
|
for t in targets:
|
||||||
|
url = str(t.get("url") or "").strip()
|
||||||
|
if not url or url in seen_urls:
|
||||||
|
continue
|
||||||
|
seen_urls.add(url)
|
||||||
|
unique_urls.append(url)
|
||||||
|
|
||||||
|
probe_by_url: dict[str, dict[str, Any]] = {}
|
||||||
|
svc_error = ""
|
||||||
|
if unique_urls:
|
||||||
|
try:
|
||||||
|
for i in range(0, len(unique_urls), _BATCH_SIZE):
|
||||||
|
chunk = unique_urls[i : i + _BATCH_SIZE]
|
||||||
|
data = await youtube_client.batch_live(chunk)
|
||||||
|
for row in data.get("results") or []:
|
||||||
|
if not isinstance(row, dict):
|
||||||
|
continue
|
||||||
|
key = str(row.get("input") or "").strip()
|
||||||
|
if key:
|
||||||
|
probe_by_url[key] = _parse_batch_result(row)
|
||||||
|
cid = str(row.get("channel_id") or "").strip()
|
||||||
|
if cid:
|
||||||
|
probe_by_url[f"cid:{cid}"] = _parse_batch_result(row)
|
||||||
|
except YouTubeSvcError as exc:
|
||||||
|
svc_error = str(exc)
|
||||||
|
|
||||||
|
for t in targets:
|
||||||
|
ref = str(t["ref"])
|
||||||
|
url = str(t.get("url") or "").strip()
|
||||||
|
entry = probe_by_url.get(url) if url else None
|
||||||
|
cid = str(t.get("youtube_channel_id") or (t.get("group") or {}).get("channel_id") or "").strip()
|
||||||
|
|
||||||
|
if entry is None and cid:
|
||||||
|
entry = probe_by_url.get(f"cid:{cid}")
|
||||||
|
|
||||||
|
if entry is None and svc_error:
|
||||||
|
entry = _live_entry(is_live=False, source="youtubei", error=svc_error)
|
||||||
|
|
||||||
|
if entry is None:
|
||||||
|
entry = _live_entry(is_live=False, source="unknown")
|
||||||
|
|
||||||
|
if t.get("kind") == "group" and not entry.get("is_live") and not svc_error:
|
||||||
|
g = t.get("group") or {}
|
||||||
|
if str(g.get("last_status") or "") == "live":
|
||||||
|
entry = _live_entry(
|
||||||
|
is_live=True,
|
||||||
|
source="monitor",
|
||||||
|
live_url=str(g.get("last_live_url") or ""),
|
||||||
|
title=str(g.get("last_title") or ""),
|
||||||
|
channel_id=str(g.get("channel_id") or ""),
|
||||||
|
)
|
||||||
|
|
||||||
|
entries[ref] = dict(entry)
|
||||||
|
if cid and entry.get("is_live"):
|
||||||
|
entries[f"channel:{cid}"] = dict(entry)
|
||||||
|
|
||||||
|
# OAuth 兜底限频,避免多标签 force/后台轮询打爆配额
|
||||||
|
run_oauth = (now - float(_LAST_OAUTH_AT or 0)) >= _OAUTH_MIN_INTERVAL_SEC
|
||||||
|
oauth_tasks: list[tuple[str, str, str]] = []
|
||||||
|
if run_oauth:
|
||||||
|
for ch in shorts:
|
||||||
|
cid = str(ch.get("youtube_channel_id") or "").strip()
|
||||||
|
pk = str(ch.get("id") or "")
|
||||||
|
if not cid or not pk:
|
||||||
|
continue
|
||||||
|
if not str(ch.get("refresh_token") or "").strip():
|
||||||
|
continue
|
||||||
|
ref = f"shorts:{pk}"
|
||||||
|
if entries.get(ref, {}).get("is_live"):
|
||||||
|
continue
|
||||||
|
oauth_tasks.append((ref, pk, cid))
|
||||||
|
|
||||||
|
if oauth_tasks:
|
||||||
|
_LAST_OAUTH_AT = now
|
||||||
|
oauth_results = await asyncio.gather(
|
||||||
|
*[_oauth_live_for_shorts(pk, cid) for _ref, pk, cid in oauth_tasks],
|
||||||
|
return_exceptions=True,
|
||||||
|
)
|
||||||
|
for (ref, _pk, cid), result in zip(oauth_tasks, oauth_results):
|
||||||
|
if isinstance(result, Exception):
|
||||||
|
continue
|
||||||
|
if isinstance(result, dict) and result.get("is_live"):
|
||||||
|
entries[ref] = result
|
||||||
|
entries[f"channel:{cid}"] = result
|
||||||
|
elif _CACHE.get("payload") and isinstance(_CACHE.get("payload"), dict):
|
||||||
|
# 沿用上一次 OAuth 检出的 live,避免限频窗口内把真直播刷成离线
|
||||||
|
prev = (_CACHE.get("payload") or {}).get("entries") or {}
|
||||||
|
for ref, old in prev.items():
|
||||||
|
if not str(ref).startswith("shorts:"):
|
||||||
|
continue
|
||||||
|
if not isinstance(old, dict) or not old.get("is_live"):
|
||||||
|
continue
|
||||||
|
if str(old.get("source") or "").startswith("oauth"):
|
||||||
|
cur = entries.get(ref) or {}
|
||||||
|
if not cur.get("is_live"):
|
||||||
|
entries[ref] = dict(old)
|
||||||
|
cid = str(old.get("channel_id") or "").strip()
|
||||||
|
if cid:
|
||||||
|
entries[f"channel:{cid}"] = dict(old)
|
||||||
|
|
||||||
|
live_count = sum(1 for k, v in entries.items() if k.startswith(("group:", "shorts:")) and v.get("is_live"))
|
||||||
|
sources = {str(v.get("source") or "") for v in entries.values() if v.get("is_live")}
|
||||||
|
primary_source = "youtubei" if "youtubei" in sources else (next(iter(sources)) if sources else "none")
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"ok": True,
|
||||||
|
"checked_at": int(now),
|
||||||
|
"live_count": live_count,
|
||||||
|
"source": primary_source,
|
||||||
|
"entries": entries,
|
||||||
|
"groups_total": len(groups),
|
||||||
|
"shorts_total": len(shorts),
|
||||||
|
"poll_sec": 20,
|
||||||
|
"cache_ttl_sec": _CACHE_TTL_SEC,
|
||||||
|
}
|
||||||
|
if svc_error:
|
||||||
|
payload["svc_error"] = svc_error
|
||||||
|
|
||||||
|
# Shorts 上传频道开播/停播 → sessions,供 /shorts 数据分析
|
||||||
|
try:
|
||||||
|
payload["shorts_live_sync"] = db.sync_shorts_channel_lives_from_map(entries)
|
||||||
|
except Exception as exc:
|
||||||
|
payload["shorts_live_sync"] = {"error": str(exc)[:160]}
|
||||||
|
|
||||||
|
_CACHE["at"] = now
|
||||||
|
_CACHE["payload"] = payload
|
||||||
|
return payload
|
||||||
377
backend/app/youtube_manage.py
Normal file
377
backend/app/youtube_manage.py
Normal file
@ -0,0 +1,377 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""YouTube Data API helpers using Shorts-channel OAuth (upload + readonly)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from . import db
|
||||||
|
from .shorts_oauth import channel_oauth_creds
|
||||||
|
from .shorts_upload import refresh_access_token
|
||||||
|
|
||||||
|
API = "https://www.googleapis.com/youtube/v3"
|
||||||
|
|
||||||
|
|
||||||
|
async def _access_for_channel(channel_pk: str) -> tuple[str, dict[str, Any]]:
|
||||||
|
ch = db.get_shorts_channel(channel_pk)
|
||||||
|
if not ch:
|
||||||
|
raise ValueError("频道不存在")
|
||||||
|
creds = channel_oauth_creds(ch)
|
||||||
|
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
|
||||||
|
raise ValueError("频道未授权 Google OAuth")
|
||||||
|
token = await refresh_access_token(
|
||||||
|
client_id=creds["client_id"],
|
||||||
|
client_secret=creds["client_secret"],
|
||||||
|
refresh_token=creds["refresh_token"],
|
||||||
|
)
|
||||||
|
return token, ch
|
||||||
|
|
||||||
|
|
||||||
|
async def _get(path: str, *, token: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
|
||||||
|
resp = await client.get(
|
||||||
|
f"{API}/{path}",
|
||||||
|
params=params,
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
data = resp.json() if resp.content else {}
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
err = (data.get("error") or {}).get("message") or data or resp.text
|
||||||
|
raise ValueError(f"YouTube API 错误: {err}")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
async def _post(path: str, *, token: str, params: dict[str, Any], json_body: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
|
||||||
|
resp = await client.post(
|
||||||
|
f"{API}/{path}",
|
||||||
|
params=params,
|
||||||
|
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||||
|
json=json_body,
|
||||||
|
)
|
||||||
|
data = resp.json() if resp.content else {}
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
err = (data.get("error") or {}).get("message") or data or resp.text
|
||||||
|
raise ValueError(f"YouTube API 错误: {err}")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
async def _put(path: str, *, token: str, params: dict[str, Any], json_body: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
|
||||||
|
resp = await client.put(
|
||||||
|
f"{API}/{path}",
|
||||||
|
params=params,
|
||||||
|
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||||
|
json=json_body,
|
||||||
|
)
|
||||||
|
data = resp.json() if resp.content else {}
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
err = (data.get("error") or {}).get("message") or data or resp.text
|
||||||
|
raise ValueError(f"YouTube API 错误: {err}")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
async def _delete(path: str, *, token: str, params: dict[str, Any]) -> None:
|
||||||
|
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
|
||||||
|
resp = await client.delete(
|
||||||
|
f"{API}/{path}",
|
||||||
|
params=params,
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
data = resp.json() if resp.content else {}
|
||||||
|
err = (data.get("error") or {}).get("message") or data or resp.text
|
||||||
|
raise ValueError(f"YouTube API 错误: {err}")
|
||||||
|
|
||||||
|
|
||||||
|
def list_managed_channels() -> list[dict[str, Any]]:
|
||||||
|
rows = db.list_shorts_channels()
|
||||||
|
out = []
|
||||||
|
for ch in rows:
|
||||||
|
out.append(
|
||||||
|
{
|
||||||
|
"id": ch.get("id"),
|
||||||
|
"name": ch.get("name"),
|
||||||
|
"youtube_channel_id": ch.get("youtube_channel_id"),
|
||||||
|
"enabled": bool(ch.get("enabled")),
|
||||||
|
"authorized": bool(str(ch.get("refresh_token") or "").strip()),
|
||||||
|
"daily_min": ch.get("daily_min"),
|
||||||
|
"daily_max": ch.get("daily_max"),
|
||||||
|
"privacy": ch.get("privacy"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
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"},
|
||||||
|
)
|
||||||
|
items = data.get("items") or []
|
||||||
|
if not items:
|
||||||
|
raise ValueError("未拿到频道资料(请确认授权账号下有频道)")
|
||||||
|
item = items[0]
|
||||||
|
# If stored youtube_channel_id differs, still return mine (Brand account caveat)
|
||||||
|
yt_id = str(item.get("id") or "")
|
||||||
|
if yt_id and yt_id != str(ch.get("youtube_channel_id") or ""):
|
||||||
|
try:
|
||||||
|
db.update_shorts_channel(channel_pk, youtube_channel_id=yt_id, name=str((item.get("snippet") or {}).get("title") or ch.get("name")))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
uploads = ((item.get("contentDetails") or {}).get("relatedPlaylists") or {}).get("uploads") or ""
|
||||||
|
sn = item.get("snippet") or {}
|
||||||
|
st = item.get("statistics") or {}
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"channel_pk": channel_pk,
|
||||||
|
"youtube_channel_id": yt_id,
|
||||||
|
"title": sn.get("title"),
|
||||||
|
"description": sn.get("description"),
|
||||||
|
"custom_url": sn.get("customUrl"),
|
||||||
|
"thumbnails": sn.get("thumbnails"),
|
||||||
|
"uploads_playlist_id": uploads,
|
||||||
|
"statistics": {
|
||||||
|
"viewCount": st.get("viewCount"),
|
||||||
|
"subscriberCount": st.get("subscriberCount"),
|
||||||
|
"videoCount": st.get("videoCount"),
|
||||||
|
"hiddenSubscriberCount": st.get("hiddenSubscriberCount"),
|
||||||
|
},
|
||||||
|
"raw": item,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def list_my_videos(channel_pk: str, *, max_results: int = 25, page_token: str = "") -> dict[str, Any]:
|
||||||
|
profile = await fetch_channel_profile(channel_pk)
|
||||||
|
uploads = str(profile.get("uploads_playlist_id") or "")
|
||||||
|
if not uploads:
|
||||||
|
return {"ok": True, "videos": [], "profile": profile}
|
||||||
|
token, _ch = await _access_for_channel(channel_pk)
|
||||||
|
params: dict[str, Any] = {
|
||||||
|
"part": "snippet,contentDetails,status",
|
||||||
|
"playlistId": uploads,
|
||||||
|
"maxResults": max(1, min(int(max_results), 50)),
|
||||||
|
}
|
||||||
|
if page_token:
|
||||||
|
params["pageToken"] = page_token
|
||||||
|
pl = await _get("playlistItems", token=token, params=params)
|
||||||
|
ids = []
|
||||||
|
order_meta = []
|
||||||
|
for it in pl.get("items") or []:
|
||||||
|
vid = ((it.get("contentDetails") or {}).get("videoId")) or ((it.get("snippet") or {}).get("resourceId") or {}).get("videoId")
|
||||||
|
if vid:
|
||||||
|
ids.append(vid)
|
||||||
|
order_meta.append(it)
|
||||||
|
videos: list[dict[str, Any]] = []
|
||||||
|
if ids:
|
||||||
|
detail = await _get(
|
||||||
|
"videos",
|
||||||
|
token=token,
|
||||||
|
params={"part": "snippet,status,statistics,contentDetails", "id": ",".join(ids)},
|
||||||
|
)
|
||||||
|
by_id = {str(v.get("id")): v for v in (detail.get("items") or [])}
|
||||||
|
for vid in ids:
|
||||||
|
v = by_id.get(vid)
|
||||||
|
if not v:
|
||||||
|
continue
|
||||||
|
sn = v.get("snippet") or {}
|
||||||
|
st = v.get("status") or {}
|
||||||
|
stats = v.get("statistics") or {}
|
||||||
|
videos.append(
|
||||||
|
{
|
||||||
|
"id": vid,
|
||||||
|
"title": sn.get("title"),
|
||||||
|
"description": sn.get("description"),
|
||||||
|
"published_at": sn.get("publishedAt"),
|
||||||
|
"thumbnails": sn.get("thumbnails"),
|
||||||
|
"tags": sn.get("tags") or [],
|
||||||
|
"categoryId": sn.get("categoryId"),
|
||||||
|
"privacyStatus": st.get("privacyStatus"),
|
||||||
|
"publishAt": st.get("publishAt"),
|
||||||
|
"madeForKids": st.get("madeForKids"),
|
||||||
|
"duration": (v.get("contentDetails") or {}).get("duration"),
|
||||||
|
"statistics": {
|
||||||
|
"viewCount": stats.get("viewCount"),
|
||||||
|
"likeCount": stats.get("likeCount"),
|
||||||
|
"commentCount": stats.get("commentCount"),
|
||||||
|
},
|
||||||
|
"url": f"https://www.youtube.com/watch?v={vid}",
|
||||||
|
"shorts_url": f"https://www.youtube.com/shorts/{vid}",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"profile": profile,
|
||||||
|
"videos": videos,
|
||||||
|
"next_page_token": pl.get("nextPageToken") or "",
|
||||||
|
"prev_page_token": pl.get("prevPageToken") or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def get_video(channel_pk: str, video_id: str) -> dict[str, Any]:
|
||||||
|
token, _ch = await _access_for_channel(channel_pk)
|
||||||
|
data = await _get(
|
||||||
|
"videos",
|
||||||
|
token=token,
|
||||||
|
params={"part": "snippet,status,statistics,contentDetails", "id": video_id},
|
||||||
|
)
|
||||||
|
items = data.get("items") or []
|
||||||
|
if not items:
|
||||||
|
raise ValueError("视频不存在或无权访问")
|
||||||
|
v = items[0]
|
||||||
|
sn = v.get("snippet") or {}
|
||||||
|
st = v.get("status") or {}
|
||||||
|
stats = v.get("statistics") or {}
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"video": {
|
||||||
|
"id": v.get("id"),
|
||||||
|
"title": sn.get("title"),
|
||||||
|
"description": sn.get("description"),
|
||||||
|
"tags": sn.get("tags") or [],
|
||||||
|
"categoryId": sn.get("categoryId") or "22",
|
||||||
|
"published_at": sn.get("publishedAt"),
|
||||||
|
"thumbnails": sn.get("thumbnails"),
|
||||||
|
"privacyStatus": st.get("privacyStatus"),
|
||||||
|
"publishAt": st.get("publishAt"),
|
||||||
|
"embeddable": st.get("embeddable"),
|
||||||
|
"selfDeclaredMadeForKids": st.get("selfDeclaredMadeForKids"),
|
||||||
|
"duration": (v.get("contentDetails") or {}).get("duration"),
|
||||||
|
"statistics": stats,
|
||||||
|
"url": f"https://www.youtube.com/watch?v={v.get('id')}",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def update_video(
|
||||||
|
channel_pk: str,
|
||||||
|
video_id: str,
|
||||||
|
*,
|
||||||
|
title: Optional[str] = None,
|
||||||
|
description: Optional[str] = None,
|
||||||
|
tags: Optional[list[str]] = None,
|
||||||
|
category_id: Optional[str] = None,
|
||||||
|
privacy_status: Optional[str] = None,
|
||||||
|
publish_at: Optional[str] = None,
|
||||||
|
embeddable: Optional[bool] = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
token, _ch = await _access_for_channel(channel_pk)
|
||||||
|
current = await get_video(channel_pk, video_id)
|
||||||
|
cur = current["video"]
|
||||||
|
snippet: dict[str, Any] = {
|
||||||
|
"title": (title if title is not None else cur.get("title")) or "Untitled",
|
||||||
|
"categoryId": (category_id if category_id is not None else cur.get("categoryId")) or "22",
|
||||||
|
}
|
||||||
|
if description is not None:
|
||||||
|
snippet["description"] = description
|
||||||
|
else:
|
||||||
|
snippet["description"] = cur.get("description") or ""
|
||||||
|
if tags is not None:
|
||||||
|
snippet["tags"] = tags
|
||||||
|
elif cur.get("tags"):
|
||||||
|
snippet["tags"] = cur.get("tags")
|
||||||
|
|
||||||
|
status: dict[str, Any] = {}
|
||||||
|
priv = privacy_status if privacy_status is not None else cur.get("privacyStatus")
|
||||||
|
if priv:
|
||||||
|
status["privacyStatus"] = priv
|
||||||
|
if publish_at is not None:
|
||||||
|
# Scheduled publish requires private until publishAt
|
||||||
|
if publish_at.strip():
|
||||||
|
status["privacyStatus"] = "private"
|
||||||
|
status["publishAt"] = publish_at.strip()
|
||||||
|
else:
|
||||||
|
# clear schedule — omit publishAt by updating without it (API keeps if not sent carefully)
|
||||||
|
pass
|
||||||
|
if embeddable is not None:
|
||||||
|
status["embeddable"] = embeddable
|
||||||
|
|
||||||
|
body: dict[str, Any] = {"id": video_id, "snippet": snippet}
|
||||||
|
parts = ["snippet"]
|
||||||
|
if status:
|
||||||
|
body["status"] = status
|
||||||
|
parts.append("status")
|
||||||
|
|
||||||
|
data = await _put(
|
||||||
|
"videos",
|
||||||
|
token=token,
|
||||||
|
params={"part": ",".join(parts)},
|
||||||
|
json_body=body,
|
||||||
|
)
|
||||||
|
return {"ok": True, "video": data}
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_video(channel_pk: str, video_id: str) -> dict[str, Any]:
|
||||||
|
token, _ch = await _access_for_channel(channel_pk)
|
||||||
|
await _delete("videos", token=token, params={"id": video_id})
|
||||||
|
return {"ok": True, "deleted": video_id}
|
||||||
|
|
||||||
|
|
||||||
|
async def list_playlists(channel_pk: str, *, max_results: int = 25) -> dict[str, Any]:
|
||||||
|
token, _ch = await _access_for_channel(channel_pk)
|
||||||
|
data = await _get(
|
||||||
|
"playlists",
|
||||||
|
token=token,
|
||||||
|
params={"part": "snippet,contentDetails,status", "mine": "true", "maxResults": max(1, min(max_results, 50))},
|
||||||
|
)
|
||||||
|
items = []
|
||||||
|
for it in data.get("items") or []:
|
||||||
|
sn = it.get("snippet") or {}
|
||||||
|
items.append(
|
||||||
|
{
|
||||||
|
"id": it.get("id"),
|
||||||
|
"title": sn.get("title"),
|
||||||
|
"description": sn.get("description"),
|
||||||
|
"itemCount": (it.get("contentDetails") or {}).get("itemCount"),
|
||||||
|
"privacyStatus": (it.get("status") or {}).get("privacyStatus"),
|
||||||
|
"thumbnails": sn.get("thumbnails"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {"ok": True, "playlists": items}
|
||||||
|
|
||||||
|
|
||||||
|
async def set_thumbnail_from_path(channel_pk: str, video_id: str, file_path: str) -> dict[str, Any]:
|
||||||
|
token, _ch = await _access_for_channel(channel_pk)
|
||||||
|
path = Path(file_path)
|
||||||
|
if not path.is_file():
|
||||||
|
raise ValueError("缩略图文件不存在")
|
||||||
|
raw = path.read_bytes()
|
||||||
|
ctype = "image/jpeg"
|
||||||
|
if path.suffix.lower() == ".png":
|
||||||
|
ctype = "image/png"
|
||||||
|
async with httpx.AsyncClient(timeout=60.0, trust_env=False) as client:
|
||||||
|
resp = await client.post(
|
||||||
|
"https://www.googleapis.com/upload/youtube/v3/thumbnails/set",
|
||||||
|
params={"videoId": video_id},
|
||||||
|
headers={"Authorization": f"Bearer {token}", "Content-Type": ctype},
|
||||||
|
content=raw,
|
||||||
|
)
|
||||||
|
data = resp.json() if resp.content else {}
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
err = (data.get("error") or {}).get("message") or data or resp.text
|
||||||
|
raise ValueError(f"设置缩略图失败: {err}")
|
||||||
|
return {"ok": True, "thumbnails": data}
|
||||||
|
|
||||||
|
|
||||||
|
async def channel_dashboard(channel_pk: str) -> dict[str, Any]:
|
||||||
|
"""Combine YT profile + recent videos + local Shorts job stats."""
|
||||||
|
listing = await list_my_videos(channel_pk, max_results=15)
|
||||||
|
from .timeutil import push_date_from_ts
|
||||||
|
import time
|
||||||
|
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
local = db.list_shorts_jobs(push_date=day, channel_pk=channel_pk, limit=100, offset=0)
|
||||||
|
by_status: dict[str, int] = {}
|
||||||
|
for j in local.get("jobs") or []:
|
||||||
|
st = str(j.get("status") or "")
|
||||||
|
by_status[st] = by_status.get(st, 0) + 1
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"profile": listing.get("profile"),
|
||||||
|
"recent_videos": listing.get("videos") or [],
|
||||||
|
"shorts_today": {"push_date": day, "by_status": by_status, "total": local.get("total") or 0},
|
||||||
|
}
|
||||||
@ -182,6 +182,38 @@ class YouTubeMonitorService:
|
|||||||
item = {"ok": False, "error": str(exc), "input": key}
|
item = {"ok": False, "error": str(exc), "input": key}
|
||||||
return await self._apply_result(group, item, cfg)
|
return await self._apply_result(group, item, cfg)
|
||||||
|
|
||||||
|
async def _probe_group_url_list(self, group: dict[str, Any], cfg: dict[str, Any]) -> dict[str, Any] | None:
|
||||||
|
"""When channel tab says offline, scan group reference URLs for active streams."""
|
||||||
|
raw = group.get("urls") or []
|
||||||
|
if isinstance(raw, str):
|
||||||
|
lines = [ln.strip() for ln in raw.replace("\r\n", "\n").split("\n")]
|
||||||
|
elif isinstance(raw, list):
|
||||||
|
lines = [str(x).strip() for x in raw]
|
||||||
|
else:
|
||||||
|
lines = []
|
||||||
|
urls = [u for u in lines if u and not u.startswith("#")][:6]
|
||||||
|
if not urls:
|
||||||
|
return None
|
||||||
|
for url in urls:
|
||||||
|
try:
|
||||||
|
await self._throttle(cfg)
|
||||||
|
data = await youtube_client.channel_live(url)
|
||||||
|
if data.get("is_live"):
|
||||||
|
live = data.get("live") or {}
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"input": url,
|
||||||
|
"is_live": True,
|
||||||
|
"channel_id": data.get("channel_id") or group.get("channel_id") or "",
|
||||||
|
"title": data.get("title") or group.get("name") or "",
|
||||||
|
"handle": data.get("handle") or group.get("handle") or "",
|
||||||
|
"live": live if isinstance(live, dict) else {"url": url, "title": data.get("title") or ""},
|
||||||
|
"source": "url_list",
|
||||||
|
}
|
||||||
|
except YouTubeSvcError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
async def _apply_result(self, group: dict[str, Any], item: dict[str, Any], cfg: dict[str, Any]) -> dict[str, Any]:
|
async def _apply_result(self, group: dict[str, Any], item: dict[str, Any], cfg: dict[str, Any]) -> dict[str, Any]:
|
||||||
self.checked_total += 1
|
self.checked_total += 1
|
||||||
self.last_check_at = time.time()
|
self.last_check_at = time.time()
|
||||||
@ -217,6 +249,11 @@ class YouTubeMonitorService:
|
|||||||
return item
|
return item
|
||||||
|
|
||||||
is_live = bool(item.get("is_live"))
|
is_live = bool(item.get("is_live"))
|
||||||
|
if not is_live:
|
||||||
|
alt = await self._probe_group_url_list(group, cfg)
|
||||||
|
if alt:
|
||||||
|
item = alt
|
||||||
|
is_live = True
|
||||||
live = item.get("live") or {}
|
live = item.get("live") or {}
|
||||||
title = str(live.get("title") or item.get("title") or group.get("last_title") or "")
|
title = str(live.get("title") or item.get("title") or group.get("last_title") or "")
|
||||||
live_url = str(live.get("url") or "")
|
live_url = str(live.get("url") or "")
|
||||||
|
|||||||
Binary file not shown.
@ -6,3 +6,5 @@ pydantic-settings==2.7.0
|
|||||||
python-multipart==0.0.20
|
python-multipart==0.0.20
|
||||||
aiofiles==24.1.0
|
aiofiles==24.1.0
|
||||||
boto3==1.35.99
|
boto3==1.35.99
|
||||||
|
pytest==8.3.4
|
||||||
|
|
||||||
|
|||||||
60
backend/tests/conftest.py
Normal file
60
backend/tests/conftest.py
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def temp_db(monkeypatch):
|
||||||
|
td = tempfile.mkdtemp()
|
||||||
|
db_path = Path(td) / "test.db"
|
||||||
|
monkeypatch.setattr("app.config.settings.sqlite_path", db_path)
|
||||||
|
monkeypatch.setattr("app.config.settings.data_dir", Path(td))
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
db.init_db()
|
||||||
|
return db
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def yt_group(temp_db):
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
return db.create_channel_group(
|
||||||
|
name="Test YT",
|
||||||
|
platform="youtube",
|
||||||
|
channel_url="https://www.youtube.com/channel/UCtest123456789012345678",
|
||||||
|
urls=["https://www.youtube.com/watch?v=extra1"],
|
||||||
|
enabled=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def douyin_room(temp_db):
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
return db.create_room("https://live.douyin.com/999888777666", note="test", enabled=True)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def active_yt_session(temp_db, yt_group):
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
sess = db.start_session(
|
||||||
|
room_pk=yt_group["id"],
|
||||||
|
room_id="yt:UCtest123456789012345678",
|
||||||
|
source_url="https://www.youtube.com/watch?v=live1",
|
||||||
|
anchor_name="Test YT",
|
||||||
|
metadata={"platform": "youtube"},
|
||||||
|
)
|
||||||
|
db.touch_channel_group(
|
||||||
|
yt_group["id"],
|
||||||
|
last_status="live",
|
||||||
|
next_check_at=0,
|
||||||
|
active_session_id=sess["id"],
|
||||||
|
channel_id="UCtest123456789012345678",
|
||||||
|
)
|
||||||
|
return sess
|
||||||
64
backend/tests/test_reconcile_yt.py
Normal file
64
backend/tests/test_reconcile_yt.py
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
def test_yt_session_not_killed_when_group_live(temp_db, yt_group, active_yt_session):
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
result = db.reconcile_stale_active_sessions()
|
||||||
|
assert result["closed"] == 0
|
||||||
|
assert result["kept"] == 1
|
||||||
|
row = db.get_session(active_yt_session["id"])
|
||||||
|
assert row
|
||||||
|
assert row["status"] == "active"
|
||||||
|
assert row["ended_at"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_yt_session_closed_when_group_offline(temp_db, yt_group, active_yt_session):
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
db.touch_channel_group(
|
||||||
|
yt_group["id"],
|
||||||
|
last_status="offline",
|
||||||
|
next_check_at=0,
|
||||||
|
active_session_id=active_yt_session["id"],
|
||||||
|
)
|
||||||
|
result = db.reconcile_stale_active_sessions()
|
||||||
|
assert result["closed"] == 1
|
||||||
|
row = db.get_session(active_yt_session["id"])
|
||||||
|
assert row
|
||||||
|
assert row["status"] == "ended"
|
||||||
|
|
||||||
|
|
||||||
|
def test_start_session_updates_channel_group(temp_db, yt_group):
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
sess = db.start_session(
|
||||||
|
room_pk=yt_group["id"],
|
||||||
|
room_id="yt:UCtest123456789012345678",
|
||||||
|
source_url="https://youtube.com/watch?v=x",
|
||||||
|
anchor_name="Anchor",
|
||||||
|
)
|
||||||
|
group = db.get_channel_group(yt_group["id"])
|
||||||
|
assert group["active_session_id"] == sess["id"]
|
||||||
|
assert group["last_status"] == "live"
|
||||||
|
|
||||||
|
|
||||||
|
def test_douyin_reconcile_unchanged(temp_db, douyin_room):
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
sess = db.start_session(
|
||||||
|
room_pk=douyin_room["id"],
|
||||||
|
room_id=douyin_room["room_id"],
|
||||||
|
source_url=douyin_room["url"],
|
||||||
|
anchor_name="Douyin Anchor",
|
||||||
|
)
|
||||||
|
db.touch_room(
|
||||||
|
douyin_room["id"],
|
||||||
|
last_status="live",
|
||||||
|
next_check_at=0,
|
||||||
|
active_session_id=sess["id"],
|
||||||
|
)
|
||||||
|
result = db.reconcile_stale_active_sessions()
|
||||||
|
assert result["kept"] == 1
|
||||||
|
assert result["closed"] == 0
|
||||||
53
backend/tests/test_shorts_missing_clip.py
Normal file
53
backend/tests/test_shorts_missing_clip.py
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from app.timeutil import push_date_from_ts
|
||||||
|
|
||||||
|
|
||||||
|
def test_reconcile_false_failed_shorts(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="F", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
job = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="r-false-fail",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
temp_db.update_shorts_job(
|
||||||
|
job["id"],
|
||||||
|
status="failed",
|
||||||
|
youtube_video_id="abc123",
|
||||||
|
youtube_url="https://www.youtube.com/shorts/abc123",
|
||||||
|
error="[Errno 2] No such file",
|
||||||
|
finished_at=time.time(),
|
||||||
|
)
|
||||||
|
fixed = temp_db.reconcile_false_failed_shorts()
|
||||||
|
assert fixed == 1
|
||||||
|
updated = temp_db.get_shorts_job(job["id"])
|
||||||
|
assert updated["status"] == "uploaded"
|
||||||
|
assert updated["error"] == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_reconcile_missing_shorts_clips(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="M", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
job = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="r-miss",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
temp_db.update_shorts_job(
|
||||||
|
job["id"],
|
||||||
|
status="scheduled",
|
||||||
|
clip_path="/tmp/does-not-exist-clip.mp4",
|
||||||
|
upload_at=time.time() + 60,
|
||||||
|
)
|
||||||
|
fixed = temp_db.reconcile_missing_shorts_clips()
|
||||||
|
assert fixed == 1
|
||||||
|
updated = temp_db.get_shorts_job(job["id"])
|
||||||
|
assert updated["status"] == "pending"
|
||||||
|
assert updated["clip_path"] == ""
|
||||||
|
assert "丢失" in str(updated["error"])
|
||||||
49
backend/tests/test_shorts_ops.py
Normal file
49
backend/tests/test_shorts_ops.py
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.timeutil import push_date_from_ts
|
||||||
|
|
||||||
|
|
||||||
|
def test_clip_ready_enrichment_via_path(temp_db, tmp_path):
|
||||||
|
ch = temp_db.create_shorts_channel(name="P", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
job = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="r-prev",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
clip = tmp_path / f"{job['id']}.mp4"
|
||||||
|
clip.write_bytes(b"0" * 60_000)
|
||||||
|
temp_db.update_shorts_job(job["id"], status="scheduled", clip_path=str(clip), upload_at=time.time() + 60)
|
||||||
|
updated = temp_db.get_shorts_job(job["id"])
|
||||||
|
assert Path(updated["clip_path"]).is_file()
|
||||||
|
|
||||||
|
missing = temp_db.reconcile_missing_shorts_clips()
|
||||||
|
assert missing == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_bulk_retry_requeues_failed(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="B", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
job = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="r-bulk",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
temp_db.update_shorts_job(job["id"], status="failed", error="boom", finished_at=time.time())
|
||||||
|
# Simulate retry helper path: no clip → pending
|
||||||
|
temp_db.update_shorts_job(
|
||||||
|
job["id"],
|
||||||
|
status="pending",
|
||||||
|
clip_path="",
|
||||||
|
error="",
|
||||||
|
finished_at=0,
|
||||||
|
upload_at=0,
|
||||||
|
)
|
||||||
|
updated = temp_db.get_shorts_job(job["id"])
|
||||||
|
assert updated["status"] == "pending"
|
||||||
55
backend/tests/test_shorts_quota.py
Normal file
55
backend/tests/test_shorts_quota.py
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from app.timeutil import beijing_day_bounds, push_date_from_ts
|
||||||
|
|
||||||
|
|
||||||
|
def test_shorts_quota_counts_scheduled(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="Q", daily_min=5, daily_max=9, enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="r1",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
job = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="r2",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
temp_db.update_shorts_job(job["id"], status="scheduled", upload_at=time.time() + 3600)
|
||||||
|
assert temp_db.shorts_channel_upload_count(ch["id"], day) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_pick_shorts_channel_prefers_under_min(temp_db):
|
||||||
|
ch1 = temp_db.create_shorts_channel(name="A", daily_min=5, daily_max=9, enabled=True)
|
||||||
|
ch2 = temp_db.create_shorts_channel(name="B", daily_min=5, daily_max=9, enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
for i in range(5):
|
||||||
|
temp_db.create_shorts_job(session_id="", room_id=f"a{i}", channel_pk=ch1["id"], push_date=day)
|
||||||
|
picked = temp_db.pick_shorts_channel(day)
|
||||||
|
assert picked is not None
|
||||||
|
assert picked["id"] == ch2["id"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_quota_gap_and_summary(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="G", daily_min=5, daily_max=9, enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
for i in range(3):
|
||||||
|
temp_db.create_shorts_job(session_id="", room_id=f"g{i}", channel_pk=ch["id"], push_date=day)
|
||||||
|
summary = temp_db.shorts_channels_quota_summary(day)
|
||||||
|
assert len(summary) == 1
|
||||||
|
assert summary[0]["used"] == 3
|
||||||
|
assert summary[0]["gap"] == 6
|
||||||
|
assert summary[0]["min_met"] is False
|
||||||
|
assert temp_db.shorts_total_quota_gap(day) == 6
|
||||||
|
|
||||||
|
|
||||||
|
def test_beijing_day_bounds():
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
start, end = beijing_day_bounds(day)
|
||||||
|
assert end - start == 86400
|
||||||
93
backend/tests/test_shorts_stats.py
Normal file
93
backend/tests/test_shorts_stats.py
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from app.timeutil import push_date_from_ts
|
||||||
|
|
||||||
|
|
||||||
|
def test_shorts_stats_history(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="H", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
j1 = temp_db.create_shorts_job(session_id="", room_id="h1", channel_pk=ch["id"], push_date=day)
|
||||||
|
j2 = temp_db.create_shorts_job(session_id="", room_id="h2", channel_pk=ch["id"], push_date=day)
|
||||||
|
temp_db.update_shorts_job(j1["id"], status="uploaded", youtube_video_id="v1")
|
||||||
|
temp_db.update_shorts_job(j2["id"], status="failed", error="OAuth refresh failed")
|
||||||
|
hist = temp_db.shorts_stats_history(days=7)
|
||||||
|
assert hist["days"] == 7
|
||||||
|
assert len(hist["series"]) == 7
|
||||||
|
today = next(x for x in hist["series"] if x["push_date"] == day)
|
||||||
|
assert today["uploaded"] == 1
|
||||||
|
assert today["failed"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_shorts_failed_groups(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="G", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
a = temp_db.create_shorts_job(session_id="", room_id="g1", channel_pk=ch["id"], push_date=day)
|
||||||
|
b = temp_db.create_shorts_job(session_id="", room_id="g2", channel_pk=ch["id"], push_date=day)
|
||||||
|
c = temp_db.create_shorts_job(session_id="", room_id="g3", channel_pk=ch["id"], push_date=day)
|
||||||
|
temp_db.update_shorts_job(a["id"], status="failed", error="OAuth 刷新失败: invalid_grant")
|
||||||
|
temp_db.update_shorts_job(b["id"], status="failed", error="成片已丢失,已重新排队录制")
|
||||||
|
temp_db.update_shorts_job(c["id"], status="failed", error="ffmpeg 录制超时")
|
||||||
|
data = temp_db.shorts_failed_groups(push_date=day)
|
||||||
|
assert data["total"] == 3
|
||||||
|
cats = {g["category"]: g["count"] for g in data["groups"]}
|
||||||
|
assert cats.get("oauth") == 1
|
||||||
|
assert cats.get("missing_clip") == 1
|
||||||
|
assert cats.get("record") == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_shorts_channel_performance(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="Perf", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
a = temp_db.create_shorts_job(session_id="", room_id="p1", channel_pk=ch["id"], push_date=day)
|
||||||
|
b = temp_db.create_shorts_job(session_id="", room_id="p2", channel_pk=ch["id"], push_date=day)
|
||||||
|
temp_db.update_shorts_job(a["id"], status="uploaded", youtube_video_id="x")
|
||||||
|
temp_db.update_shorts_job(b["id"], status="failed", error="boom")
|
||||||
|
data = temp_db.shorts_channel_performance(days=7)
|
||||||
|
row = next(c for c in data["channels"] if c["id"] == ch["id"])
|
||||||
|
assert row["uploaded"] == 1
|
||||||
|
assert row["failed"] == 1
|
||||||
|
assert row["success_rate"] == 0.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_failed_shorts_job_ids(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="FailList", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
a = temp_db.create_shorts_job(session_id="", room_id="f1", channel_pk=ch["id"], push_date=day)
|
||||||
|
b = temp_db.create_shorts_job(session_id="", room_id="f2", channel_pk=ch["id"], push_date=day)
|
||||||
|
temp_db.update_shorts_job(a["id"], status="failed", error="x")
|
||||||
|
temp_db.update_shorts_job(b["id"], status="uploaded", youtube_video_id="y")
|
||||||
|
ids = temp_db.list_failed_shorts_job_ids(push_date=day)
|
||||||
|
assert a["id"] in ids
|
||||||
|
assert b["id"] not in ids
|
||||||
|
|
||||||
|
|
||||||
|
def test_shorts_upload_heatmap(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="Heat", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
job = temp_db.create_shorts_job(session_id="", room_id="ht1", channel_pk=ch["id"], push_date=day)
|
||||||
|
now = time.time()
|
||||||
|
temp_db.update_shorts_job(job["id"], status="uploaded", youtube_video_id="z", finished_at=now)
|
||||||
|
heat = temp_db.shorts_upload_heatmap(days=1)
|
||||||
|
assert heat["days"] == 1
|
||||||
|
assert len(heat["uploaded"]) == 24
|
||||||
|
assert sum(heat["uploaded"]) == 1
|
||||||
|
assert heat["peak_hour"] is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_auto_retry_skips_oauth(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="AR", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
a = temp_db.create_shorts_job(session_id="", room_id="ar1", channel_pk=ch["id"], push_date=day)
|
||||||
|
b = temp_db.create_shorts_job(session_id="", room_id="ar2", channel_pk=ch["id"], push_date=day)
|
||||||
|
now = time.time() - 120
|
||||||
|
temp_db.update_shorts_job(a["id"], status="failed", error="ffmpeg 录制超时", attempts=1, finished_at=now)
|
||||||
|
temp_db.update_shorts_job(
|
||||||
|
b["id"], status="failed", error="OAuth 刷新失败: invalid_grant", attempts=1, finished_at=now
|
||||||
|
)
|
||||||
|
rows = temp_db.list_auto_retry_failed_jobs(max_attempts=3, limit=10)
|
||||||
|
ids = {r["id"] for r in rows}
|
||||||
|
assert a["id"] in ids
|
||||||
|
assert b["id"] not in ids
|
||||||
39
backend/tests/test_shorts_upload_now.py
Normal file
39
backend/tests/test_shorts_upload_now.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from app.timeutil import push_date_from_ts
|
||||||
|
|
||||||
|
|
||||||
|
def test_claim_manual_upload_from_scheduled(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="U", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
job = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="r1",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
temp_db.update_shorts_job(
|
||||||
|
job["id"],
|
||||||
|
status="scheduled",
|
||||||
|
clip_path="/tmp/fake.mp4",
|
||||||
|
upload_at=time.time() + 3600,
|
||||||
|
)
|
||||||
|
claimed = temp_db.claim_shorts_job_manual_upload(job["id"])
|
||||||
|
assert claimed is not None
|
||||||
|
assert claimed["status"] == "uploading"
|
||||||
|
assert float(claimed["upload_at"]) <= time.time() + 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_claim_manual_upload_rejects_pending(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="U", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
job = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="r1",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
assert temp_db.claim_shorts_job_manual_upload(job["id"]) is None
|
||||||
58
backend/tests/test_shorts_worker.py
Normal file
58
backend/tests/test_shorts_worker.py
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from app.timeutil import push_date_from_ts
|
||||||
|
|
||||||
|
|
||||||
|
def test_claim_upload_before_pending_record(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="P", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
pending = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="pending1",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
due = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="due1",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
temp_db.update_shorts_job(
|
||||||
|
due["id"],
|
||||||
|
status="scheduled",
|
||||||
|
clip_path="/tmp/x.mp4",
|
||||||
|
upload_at=time.time() - 10,
|
||||||
|
)
|
||||||
|
claimed = temp_db.claim_due_shorts_upload()
|
||||||
|
assert claimed is not None
|
||||||
|
assert claimed["id"] == due["id"]
|
||||||
|
assert claimed["status"] == "uploading"
|
||||||
|
# pending still pending
|
||||||
|
row = temp_db.get_shorts_job(pending["id"])
|
||||||
|
assert row["status"] == "pending"
|
||||||
|
|
||||||
|
|
||||||
|
def test_reclaim_stale_uploading(temp_db):
|
||||||
|
ch = temp_db.create_shorts_channel(name="S", enabled=True)
|
||||||
|
day = push_date_from_ts(time.time())
|
||||||
|
job = temp_db.create_shorts_job(
|
||||||
|
session_id="",
|
||||||
|
room_id="stale1",
|
||||||
|
channel_pk=ch["id"],
|
||||||
|
push_date=day,
|
||||||
|
)
|
||||||
|
temp_db.update_shorts_job(
|
||||||
|
job["id"],
|
||||||
|
status="uploading",
|
||||||
|
clip_path="/tmp/x.mp4",
|
||||||
|
upload_at=time.time(),
|
||||||
|
started_at=time.time() - 500,
|
||||||
|
)
|
||||||
|
n = temp_db.reclaim_stale_shorts_uploads(max_age_sec=120)
|
||||||
|
assert n == 1
|
||||||
|
row = temp_db.get_shorts_job(job["id"])
|
||||||
|
assert row["status"] == "scheduled"
|
||||||
47
backend/tests/test_youtube_live.py
Normal file
47
backend/tests/test_youtube_live.py
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.youtube_live import _live_entry, _parse_batch_result
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_batch_live():
|
||||||
|
row = {
|
||||||
|
"ok": True,
|
||||||
|
"is_live": True,
|
||||||
|
"channel_id": "UCabc",
|
||||||
|
"title": "Channel",
|
||||||
|
"live": {"id": "vid123456789", "title": "Stream Title", "url": "https://www.youtube.com/watch?v=vid123456789"},
|
||||||
|
}
|
||||||
|
entry = _parse_batch_result(row)
|
||||||
|
assert entry["is_live"] is True
|
||||||
|
assert entry["source"] == "youtubei"
|
||||||
|
assert "watch?v=vid123456789" in entry["live_url"]
|
||||||
|
assert entry["title"] == "Stream Title"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_batch_offline():
|
||||||
|
row = {"ok": True, "is_live": False, "channel_id": "UCabc"}
|
||||||
|
entry = _parse_batch_result(row)
|
||||||
|
assert entry["is_live"] is False
|
||||||
|
assert "live_url" not in entry
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_batch_error():
|
||||||
|
row = {"ok": False, "error": "timeout"}
|
||||||
|
entry = _parse_batch_result(row)
|
||||||
|
assert entry["is_live"] is False
|
||||||
|
assert entry.get("error")
|
||||||
|
|
||||||
|
|
||||||
|
def test_live_entry_minimal():
|
||||||
|
entry = _live_entry(is_live=True, source="oauth", live_url="https://youtube.com/watch?v=x", title="T")
|
||||||
|
assert entry["is_live"]
|
||||||
|
assert entry["source"] == "oauth"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_broadcast_shaped_as_search_not_required():
|
||||||
|
"""Regression: offline oauth entry keeps channel_id."""
|
||||||
|
entry = _live_entry(is_live=False, source="oauth-broadcast", channel_id="UCabc")
|
||||||
|
assert entry["is_live"] is False
|
||||||
|
assert entry["channel_id"] == "UCabc"
|
||||||
|
assert entry["source"] == "oauth-broadcast"
|
||||||
100
docs/SHORTS.md
100
docs/SHORTS.md
@ -4,7 +4,8 @@
|
|||||||
**独立可选路径**:默认关闭;异常不影响抖音监控、封面、Webhook、场次。
|
**独立可选路径**:默认关闭;异常不影响抖音监控、封面、Webhook、场次。
|
||||||
|
|
||||||
线上:https://dylive.nomadro.com/shorts
|
线上:https://dylive.nomadro.com/shorts
|
||||||
OAuth 回调:`https://dylive.nomadro.com/api/shorts/oauth/callback`
|
OAuth 回调:`https://dylive.nomadro.com/api/shorts/oauth/callback`
|
||||||
|
(站点登录开启时,回调路径仍公开;其余 Shorts API 需会话。)
|
||||||
|
|
||||||
## 隔离规则
|
## 隔离规则
|
||||||
|
|
||||||
@ -20,7 +21,13 @@ OAuth 回调:`https://dylive.nomadro.com/api/shorts/oauth/callback`
|
|||||||
1. **开播边缘**:监控检测到新开播且房间匹配触发规则时入队
|
1. **开播边缘**:监控检测到新开播且房间匹配触发规则时入队
|
||||||
2. **在播随机取样**(默认开):从 SQLite 中 `last_status=live` 的抖音房随机抽,默认不限标签(`shorts_sample_any_live`)
|
2. **在播随机取样**(默认开):从 SQLite 中 `last_status=live` 的抖音房随机抽,默认不限标签(`shorts_sample_any_live`)
|
||||||
|
|
||||||
手动:`POST /api/shorts/sample-now` 或 Shorts 页「立即随机取样」。
|
手动:
|
||||||
|
|
||||||
|
| 操作 | API / UI |
|
||||||
|
|------|----------|
|
||||||
|
| 立即随机取样 | `POST /api/shorts/sample-now` / Shorts 页 |
|
||||||
|
| 按配额补取样 | `POST /api/shorts/fill-quota` |
|
||||||
|
| 批量建任务 | `POST /api/shorts/jobs/bulk` |
|
||||||
|
|
||||||
## 成片时长
|
## 成片时长
|
||||||
|
|
||||||
@ -28,24 +35,67 @@ OAuth 回调:`https://dylive.nomadro.com/api/shorts/oauth/callback`
|
|||||||
|------|----|
|
|------|----|
|
||||||
| `shorts_clip_sec` | 默认 **15**;可选 30 / 60 / 90 |
|
| `shorts_clip_sec` | 默认 **15**;可选 30 / 60 / 90 |
|
||||||
|
|
||||||
设置页「Shorts → 成片时长」下拉切换,保存后对新任务生效。
|
设置页「Shorts → 成片时长」下拉切换,保存后对新任务生效。
|
||||||
|
预览成片:`GET /api/shorts/jobs/{id}/clip`。
|
||||||
|
|
||||||
|
## 错峰上传(防降权)
|
||||||
|
|
||||||
|
录制完成后状态为 `scheduled`,写入 `upload_at`(北京日剩余时段内随机 + 抖动):
|
||||||
|
|
||||||
|
| 配置 | 默认 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `shorts_upload_spread` | `true` | 开启 24h 不定时排程 |
|
||||||
|
| `shorts_upload_min_gap_sec` | `720` | 任意两次上传全局最小间隔(约 12 分,实际会再抖动) |
|
||||||
|
| `shorts_channel_min_gap_sec` | `2400` | 同一频道最小间隔(约 40 分) |
|
||||||
|
| `shorts_delete_clip_after_upload` | `true` | 上传成功后删除服务器本地 mp4 |
|
||||||
|
|
||||||
|
日程看板:`GET /api/shorts/schedule`(Shorts 页「即将上传」)。
|
||||||
|
配额压力大或临近日末时,调度会压缩间隔以尽量凑满日配额。
|
||||||
|
|
||||||
|
### 立即上传
|
||||||
|
|
||||||
|
`POST /api/shorts/jobs/{job_id}/upload-now`:绕过错峰,立刻进入上传。
|
||||||
|
UI(`ShortsUploadUx`)会弹出确认(展示原定 `upload_at` + 成片预览),并轮询进度。
|
||||||
|
|
||||||
## Google OAuth(一键授权)
|
## Google OAuth(一键授权)
|
||||||
|
|
||||||
1. Google Cloud 启用 **YouTube Data API v3**
|
授权时请求的 scope(尽量完整,便于后续能力):
|
||||||
2. OAuth 同意屏幕(External)+ Test users
|
|
||||||
|
- `youtube` / `youtube.force-ssl`:频道与内容完整管理(含播放列表写入、评论等)
|
||||||
|
- `youtube.upload` / `youtube.readonly`:上传与只读
|
||||||
|
- `youtubepartner`:品牌账号 / Partner 相关表面
|
||||||
|
- `yt-analytics.readonly`:频道分析只读
|
||||||
|
|
||||||
|
1. Google Cloud 启用 **YouTube Data API v3**(建议再启 **YouTube Analytics API**)
|
||||||
|
2. OAuth 同意屏幕(External)+ Test users,并在 Scopes 中加上面这些
|
||||||
3. 创建 **Web application** 客户端:
|
3. 创建 **Web application** 客户端:
|
||||||
- JavaScript origins:`https://dylive.nomadro.com`(不要带路径)
|
- JavaScript origins:`https://dylive.nomadro.com`(不要带路径)
|
||||||
- Redirect URI:`https://dylive.nomadro.com/api/shorts/oauth/callback`
|
- Redirect URI:`https://dylive.nomadro.com/api/shorts/oauth/callback`
|
||||||
4. 在 Shorts 页「一键打开」引导中粘贴 Client ID / Secret 并保存
|
4. 在 Shorts 页「一键打开」引导中粘贴 Client ID / Secret 并保存
|
||||||
5. 每个上传频道点 **Google 授权**(多品牌频道各授权一次)
|
5. 每个上传频道点 **Google 授权**(多品牌频道各授权一次)
|
||||||
|
6. **以后若扩大了 scope,必须对每个频道再点一次「重新授权」**,旧 token 不会自动升级
|
||||||
|
|
||||||
未验证应用:授权页点 **Advanced → Go to dylive (unsafe)**。
|
探测 token:`POST /api/shorts/oauth/probe`。
|
||||||
|
|
||||||
|
未验证应用:授权页点 **Advanced → Go to dylive (unsafe)**。
|
||||||
|
**勿把** `client_secret_*.json` 提交进仓库。
|
||||||
|
|
||||||
|
同一 OAuth 也可驱动控制台 **YouTube 频道管理**(`/youtube` 管理模式)与在播地图中的 Shorts 频道 live 探测。
|
||||||
|
|
||||||
## 频道配额
|
## 频道配额
|
||||||
|
|
||||||
每个 Shorts 频道配置 `daily_min` / `daily_max`(如 5–9)。
|
每个 Shorts 频道强制 `daily_min` = `daily_max` = **9**(北京日,`SHORTS_DAILY_FORCE`)。
|
||||||
调度优先未达下限、再选当日任务更少的频道。单频道时自然全部进该频道,且同房当天不重复。
|
调度优先未达 9 条、再选当日任务更少的频道。单频道时自然全部进该频道,且同房当天不重复。
|
||||||
|
|
||||||
|
## 在播与场次分析
|
||||||
|
|
||||||
|
| 能力 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 在播地图 | Shorts 频道并入 `GET /api/youtube/live-map`;UI LIVE 角标 |
|
||||||
|
| 场次同步 | 开播可写入 `source: shorts_live` 场次 |
|
||||||
|
| 分析 | `GET /api/shorts/live-analytics`(Shorts 页在播分析区) |
|
||||||
|
|
||||||
|
其它运维:`POST /api/shorts/reconcile`、失败重试 / 热力 / 频道统计等见 `/api/shorts/*`。
|
||||||
|
|
||||||
## 关键设置键
|
## 关键设置键
|
||||||
|
|
||||||
@ -60,7 +110,11 @@ OAuth 回调:`https://dylive.nomadro.com/api/shorts/oauth/callback`
|
|||||||
| `shorts_trigger` | `tagged` | 开播钩子触发:tagged / favorite / all |
|
| `shorts_trigger` | `tagged` | 开播钩子触发:tagged / favorite / all |
|
||||||
| `shorts_tag` | `shorts` | tagged 模式标签名 |
|
| `shorts_tag` | `shorts` | tagged 模式标签名 |
|
||||||
| `shorts_dedupe_room_day` | `true` | 同房日去重 |
|
| `shorts_dedupe_room_day` | `true` | 同房日去重 |
|
||||||
| `shorts_auto_upload` | `true` | 录完自动上传 |
|
| `shorts_auto_upload` | `true` | 录完自动上传(进排程) |
|
||||||
|
| `shorts_upload_spread` | `true` | 错峰排程 |
|
||||||
|
| `shorts_upload_min_gap_sec` | `720` | 全局最小上传间隔 |
|
||||||
|
| `shorts_channel_min_gap_sec` | `2400` | 同频道最小间隔 |
|
||||||
|
| `shorts_delete_clip_after_upload` | `true` | 上传后删本地成片 |
|
||||||
| `shorts_oauth_client_*` | 空 | 全局 OAuth Client |
|
| `shorts_oauth_client_*` | 空 | 全局 OAuth Client |
|
||||||
|
|
||||||
## 主要代码
|
## 主要代码
|
||||||
@ -68,11 +122,30 @@ OAuth 回调:`https://dylive.nomadro.com/api/shorts/oauth/callback`
|
|||||||
| 文件 | 职责 |
|
| 文件 | 职责 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `backend/app/shorts_pipeline.py` | worker、取样、入队、录制/上传编排 |
|
| `backend/app/shorts_pipeline.py` | worker、取样、入队、录制/上传编排 |
|
||||||
|
| `backend/app/shorts_schedule.py` | 错峰 `upload_at`、日程看板 |
|
||||||
| `backend/app/shorts_clip.py` | ffmpeg 成片 |
|
| `backend/app/shorts_clip.py` | ffmpeg 成片 |
|
||||||
| `backend/app/shorts_upload.py` | YouTube resumable upload |
|
| `backend/app/shorts_upload.py` | YouTube resumable upload |
|
||||||
| `backend/app/shorts_oauth.py` | OAuth start / callback |
|
| `backend/app/shorts_oauth.py` | OAuth start / callback / probe |
|
||||||
|
| `backend/app/youtube_live.py` | 在播地图(含 Shorts 频道) |
|
||||||
|
| `backend/app/youtube_manage.py` | OAuth 频道内容管理 |
|
||||||
| `frontend/src/app/shorts/page.tsx` | 管理页 |
|
| `frontend/src/app/shorts/page.tsx` | 管理页 |
|
||||||
| `scripts/deploy_shorts.py` | VPS 增量部署 |
|
| `frontend/src/components/ShortsUploadUx.tsx` | 立即上传确认与进度 |
|
||||||
|
| `frontend/src/components/ShortsJobDetailModal.tsx` | 任务详情 |
|
||||||
|
| `scripts/deploy_shorts.py` | VPS Shorts 增量部署 |
|
||||||
|
|
||||||
|
## 主要 API
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| GET | `/api/shorts/status` | worker / 配额 / OAuth 摘要 |
|
||||||
|
| GET | `/api/shorts/schedule` | 即将上传 + 频道用量 |
|
||||||
|
| POST | `/api/shorts/sample-now` | 随机取样入队 |
|
||||||
|
| POST | `/api/shorts/fill-quota` | 按日配额补取样 |
|
||||||
|
| POST | `/api/shorts/jobs/{id}/upload-now` | 立即上传 |
|
||||||
|
| GET | `/api/shorts/jobs/{id}/clip` | 成片文件 |
|
||||||
|
| GET | `/api/shorts/live-analytics` | Shorts 在播/场次分析 |
|
||||||
|
| POST | `/api/shorts/oauth/probe` | 探测授权是否可用 |
|
||||||
|
| POST | `/api/shorts/start` \| `/stop` | 启停 worker |
|
||||||
|
|
||||||
## 部署
|
## 部署
|
||||||
|
|
||||||
@ -80,10 +153,13 @@ OAuth 回调:`https://dylive.nomadro.com/api/shorts/oauth/callback`
|
|||||||
python scripts\deploy_shorts.py
|
python scripts\deploy_shorts.py
|
||||||
```
|
```
|
||||||
|
|
||||||
|
相关增量:`deploy_oauth_scopes.py`、`deploy_shorts_live_analytics.py`、`deploy_ux.py`、`deploy_youtube_live.py`。
|
||||||
|
|
||||||
验证:
|
验证:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -sS http://127.0.0.1:8014/api/shorts/status
|
curl -sS http://127.0.0.1:8014/api/shorts/status
|
||||||
|
curl -sS http://127.0.0.1:8014/api/shorts/schedule
|
||||||
curl -sS http://127.0.0.1:8014/api/monitor/status
|
curl -sS http://127.0.0.1:8014/api/monitor/status
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@ -1,14 +1,16 @@
|
|||||||
/** @type {import('next').NextConfig} */
|
/** @type {import('next').NextConfig} */
|
||||||
|
const apiBase = process.env.DY_INTERNAL_API_URL || "http://127.0.0.1:8014";
|
||||||
|
|
||||||
const nextConfig = {
|
const nextConfig = {
|
||||||
async rewrites() {
|
async rewrites() {
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
source: "/api/:path*",
|
source: "/api/:path*",
|
||||||
destination: "http://127.0.0.1:8000/api/:path*",
|
destination: `${apiBase}/api/:path*`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
source: "/covers/:path*",
|
source: "/covers/:path*",
|
||||||
destination: "http://127.0.0.1:8000/covers/:path*",
|
destination: `${apiBase}/covers/:path*`,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
},
|
},
|
||||||
|
|||||||
@ -3,7 +3,10 @@
|
|||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { Loader2, Plus, Trash2 } from "lucide-react";
|
import { Loader2, Plus, Trash2 } from "lucide-react";
|
||||||
|
|
||||||
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
import { Shell } from "@/components/Shell";
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
|
import { EmptyState, PageLoader } from "@/components/ui";
|
||||||
import { fetchJson, fmtTs } from "@/lib/api";
|
import { fetchJson, fmtTs } from "@/lib/api";
|
||||||
|
|
||||||
type Item = {
|
type Item = {
|
||||||
@ -15,10 +18,14 @@ type Item = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function BlacklistPage() {
|
export default function BlacklistPage() {
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const toast = useToast();
|
||||||
const [items, setItems] = useState<Item[]>([]);
|
const [items, setItems] = useState<Item[]>([]);
|
||||||
const [value, setValue] = useState("");
|
const [value, setValue] = useState("");
|
||||||
const [reason, setReason] = useState("");
|
const [reason, setReason] = useState("");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [adding, setAdding] = useState(false);
|
||||||
|
const [deletingId, setDeletingId] = useState("");
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
@ -39,6 +46,8 @@ export default function BlacklistPage() {
|
|||||||
}, [load]);
|
}, [load]);
|
||||||
|
|
||||||
async function add() {
|
async function add() {
|
||||||
|
setAdding(true);
|
||||||
|
setError("");
|
||||||
try {
|
try {
|
||||||
await fetchJson("/api/blacklist", {
|
await fetchJson("/api/blacklist", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@ -46,15 +55,35 @@ export default function BlacklistPage() {
|
|||||||
});
|
});
|
||||||
setValue("");
|
setValue("");
|
||||||
setReason("");
|
setReason("");
|
||||||
|
toast.push("已加入黑名单", "ok");
|
||||||
await load();
|
await load();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError((e as Error).message);
|
const msg = (e as Error).message;
|
||||||
|
setError(msg);
|
||||||
|
toast.push(msg, "err");
|
||||||
|
} finally {
|
||||||
|
setAdding(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function remove(id: string) {
|
async function remove(item: Item) {
|
||||||
await fetchJson(`/api/blacklist/${id}`, { method: "DELETE" });
|
const ok = await confirm({
|
||||||
await load();
|
title: "移出黑名单",
|
||||||
|
message: `确定移除「${item.value}」?相关房间将恢复可监控状态。`,
|
||||||
|
confirmLabel: "移除",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
setDeletingId(item.id);
|
||||||
|
try {
|
||||||
|
await fetchJson(`/api/blacklist/${item.id}`, { method: "DELETE" });
|
||||||
|
toast.push("已从黑名单移除", "ok");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setDeletingId("");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -67,20 +96,28 @@ export default function BlacklistPage() {
|
|||||||
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-[1fr_1fr_auto]">
|
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-[1fr_1fr_auto]">
|
||||||
<label className="block text-xs text-slate-400">
|
<label className="block text-xs text-slate-400">
|
||||||
房间号 / URL / 关键词
|
房间号 / URL / 关键词
|
||||||
<input value={value} onChange={(e) => setValue(e.target.value)} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
|
<input
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => setValue(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label className="block text-xs text-slate-400">
|
<label className="block text-xs text-slate-400">
|
||||||
原因
|
原因
|
||||||
<input value={reason} onChange={(e) => setReason(e.target.value)} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
|
<input
|
||||||
|
value={reason}
|
||||||
|
onChange={(e) => setReason(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
</label>
|
</label>
|
||||||
<div className="flex items-end">
|
<div className="flex items-end">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={!value.trim()}
|
disabled={!value.trim() || adding}
|
||||||
onClick={() => void add()}
|
onClick={() => void add()}
|
||||||
className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-white/10 px-4 py-2 text-sm hover:bg-white/15 disabled:opacity-50"
|
className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-white/10 px-4 py-2 text-sm hover:bg-white/15 disabled:opacity-50"
|
||||||
>
|
>
|
||||||
<Plus className="h-4 w-4" />
|
{adding ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
|
||||||
加入黑名单
|
加入黑名单
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@ -88,40 +125,46 @@ export default function BlacklistPage() {
|
|||||||
|
|
||||||
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
|
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
|
||||||
|
|
||||||
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
|
{loading ? (
|
||||||
<table className="min-w-full text-left text-sm">
|
<PageLoader />
|
||||||
<thead className="bg-white/5 text-xs uppercase text-slate-400">
|
) : items.length === 0 ? (
|
||||||
<tr>
|
<EmptyState emoji="🚫" title="黑名单为空" desc="添加房间号、URL 或关键词后,命中项将自动停用并不再轮询。" />
|
||||||
<th className="px-3 py-3">内容</th>
|
) : (
|
||||||
<th className="px-3 py-3">房间号</th>
|
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
|
||||||
<th className="px-3 py-3">原因</th>
|
<table className="min-w-full text-left text-sm">
|
||||||
<th className="px-3 py-3">时间</th>
|
<thead className="bg-white/5 text-xs uppercase text-slate-400">
|
||||||
<th className="px-3 py-3">操作</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{items.map((item) => (
|
|
||||||
<tr key={item.id} className="border-t border-white/5">
|
|
||||||
<td className="px-3 py-3 font-mono text-xs">{item.value}</td>
|
|
||||||
<td className="px-3 py-3">{item.room_id || "—"}</td>
|
|
||||||
<td className="px-3 py-3 text-slate-400">{item.reason || "—"}</td>
|
|
||||||
<td className="px-3 py-3 text-slate-400">{fmtTs(item.created_at)}</td>
|
|
||||||
<td className="px-3 py-3">
|
|
||||||
<button type="button" onClick={() => void remove(item.id)} className="inline-flex items-center gap-1 rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200">
|
|
||||||
{loading ? <Loader2 className="h-3 w-3 animate-spin" /> : <Trash2 className="h-3 w-3" />}
|
|
||||||
移除
|
|
||||||
</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
{items.length === 0 ? (
|
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={5} className="px-3 py-10 text-center text-slate-500">黑名单为空</td>
|
<th className="px-3 py-3">内容</th>
|
||||||
|
<th className="px-3 py-3">房间号</th>
|
||||||
|
<th className="px-3 py-3">原因</th>
|
||||||
|
<th className="px-3 py-3">时间</th>
|
||||||
|
<th className="px-3 py-3">操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
) : null}
|
</thead>
|
||||||
</tbody>
|
<tbody>
|
||||||
</table>
|
{items.map((item) => (
|
||||||
</div>
|
<tr key={item.id} className="border-t border-white/5">
|
||||||
|
<td className="px-3 py-3 font-mono text-xs">{item.value}</td>
|
||||||
|
<td className="px-3 py-3">{item.room_id || "—"}</td>
|
||||||
|
<td className="px-3 py-3 text-slate-400">{item.reason || "—"}</td>
|
||||||
|
<td className="px-3 py-3 text-slate-400">{fmtTs(item.created_at)}</td>
|
||||||
|
<td className="px-3 py-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={deletingId === item.id}
|
||||||
|
onClick={() => void remove(item)}
|
||||||
|
className="inline-flex items-center gap-1 rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200 hover:bg-rose-500/10 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{deletingId === item.id ? <Loader2 className="h-3 w-3 animate-spin" /> : <Trash2 className="h-3 w-3" />}
|
||||||
|
移除
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</Shell>
|
</Shell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,6 +4,8 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
|||||||
import { Loader2, RefreshCw } from "lucide-react";
|
import { Loader2, RefreshCw } from "lucide-react";
|
||||||
|
|
||||||
import { Shell } from "@/components/Shell";
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
import { EmptyState, PlatformBadge } from "@/components/ui";
|
import { EmptyState, PlatformBadge } from "@/components/ui";
|
||||||
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
|
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
|
||||||
import { fetchJson, fmtTs, detectPlatform } from "@/lib/api";
|
import { fetchJson, fmtTs, detectPlatform } from "@/lib/api";
|
||||||
@ -31,13 +33,18 @@ const KIND_META: Record<string, { emoji: string; color: string; label: string }>
|
|||||||
demo: { emoji: "✨", color: "text-teal-200 border-teal-500/30 bg-teal-500/10", label: "演示" },
|
demo: { emoji: "✨", color: "text-teal-200 border-teal-500/30 bg-teal-500/10", label: "演示" },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const PAGE_SIZE = 50;
|
||||||
|
|
||||||
export default function EventsPage() {
|
export default function EventsPage() {
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const toast = useToast();
|
||||||
const [events, setEvents] = useState<EventItem[]>([]);
|
const [events, setEvents] = useState<EventItem[]>([]);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
const [kind, setKind] = useState("");
|
const [kind, setKind] = useState("");
|
||||||
const [platform, setPlatform] = useState("");
|
const [platform, setPlatform] = useState("");
|
||||||
const [q, setQ] = useState("");
|
const [q, setQ] = useState("");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [loadingMore, setLoadingMore] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [detail, setDetail] = useState<SessionDetail | null>(null);
|
const [detail, setDetail] = useState<SessionDetail | null>(null);
|
||||||
const [detailBusy, setDetailBusy] = useState(false);
|
const [detailBusy, setDetailBusy] = useState(false);
|
||||||
@ -54,24 +61,32 @@ export default function EventsPage() {
|
|||||||
if (qq) setQ(qq);
|
if (qq) setQ(qq);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(
|
||||||
setLoading(true);
|
async (opts?: { append?: boolean; offset?: number }) => {
|
||||||
setError("");
|
const append = Boolean(opts?.append);
|
||||||
try {
|
if (append) setLoadingMore(true);
|
||||||
const params = new URLSearchParams();
|
else setLoading(true);
|
||||||
if (kind) params.set("kind", kind);
|
setError("");
|
||||||
if (platform) params.set("platform", platform);
|
try {
|
||||||
if (q.trim()) params.set("q", q.trim());
|
const params = new URLSearchParams();
|
||||||
params.set("limit", "150");
|
if (kind) params.set("kind", kind);
|
||||||
const data = await fetchJson(`/api/events?${params}`);
|
if (platform) params.set("platform", platform);
|
||||||
setEvents(data.events || []);
|
if (q.trim()) params.set("q", q.trim());
|
||||||
setTotal(Number(data.total) || 0);
|
params.set("limit", String(PAGE_SIZE));
|
||||||
} catch (e) {
|
params.set("offset", String(append ? opts?.offset ?? 0 : 0));
|
||||||
setError((e as Error).message);
|
const data = await fetchJson(`/api/events?${params}`);
|
||||||
} finally {
|
const rows = data.events || [];
|
||||||
setLoading(false);
|
setEvents((prev) => (append ? [...prev, ...rows] : rows));
|
||||||
}
|
setTotal(Number(data.total) || 0);
|
||||||
}, [kind, platform, q]);
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
setLoadingMore(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[kind, platform, q],
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load();
|
void load();
|
||||||
@ -196,12 +211,23 @@ export default function EventsPage() {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (!confirm("清理 7 天前的事件?")) return;
|
const ok = await confirm({
|
||||||
await fetchJson("/api/events/purge", {
|
title: "清理历史事件",
|
||||||
method: "POST",
|
message: "确定清理 7 天前的事件?此操作不可撤销。",
|
||||||
body: JSON.stringify({ older_than_days: 7 }),
|
confirmLabel: "清理",
|
||||||
|
destructive: true,
|
||||||
});
|
});
|
||||||
await load();
|
if (!ok) return;
|
||||||
|
try {
|
||||||
|
await fetchJson("/api/events/purge", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ older_than_days: 7 }),
|
||||||
|
});
|
||||||
|
toast.push("已清理 7 天前的事件", "ok");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-sm text-amber-100"
|
className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-sm text-amber-100"
|
||||||
>
|
>
|
||||||
@ -263,6 +289,20 @@ export default function EventsPage() {
|
|||||||
<EmptyState emoji="🛰️" title="雷达静默中" desc="还没有事件。开播、停播或风控触发后会出现在这条时间线上。" />
|
<EmptyState emoji="🛰️" title="雷达静默中" desc="还没有事件。开播、停播或风控触发后会出现在这条时间线上。" />
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{!loading && events.length > 0 && events.length < total ? (
|
||||||
|
<div className="mt-6 flex justify-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={loadingMore}
|
||||||
|
onClick={() => void load({ append: true, offset: events.length })}
|
||||||
|
className="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-5 py-2.5 text-sm text-slate-200 hover:bg-white/10 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{loadingMore ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
||||||
|
加载更多({events.length}/{total})
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{detail ? <SessionDetailModal session={detail} onClose={() => setDetail(null)} /> : null}
|
{detail ? <SessionDetailModal session={detail} onClose={() => setDetail(null)} /> : null}
|
||||||
</Shell>
|
</Shell>
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,11 +1,17 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
import { Loader2, Pencil, Plus, Trash2, Download, Zap } from "lucide-react";
|
import { Loader2, Pencil, Plus, Trash2, Download, Zap } from "lucide-react";
|
||||||
|
|
||||||
import { Shell } from "@/components/Shell";
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
import { Modal } from "@/components/Modal";
|
import { Modal } from "@/components/Modal";
|
||||||
import { fetchJson, fmtTs } from "@/lib/api";
|
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
||||||
|
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
|
||||||
|
import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api";
|
||||||
|
import { groupLiveRef } from "@/lib/youtubeLive";
|
||||||
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
|
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
|
||||||
|
|
||||||
type Group = {
|
type Group = {
|
||||||
@ -28,6 +34,35 @@ type Group = {
|
|||||||
updated_at?: number;
|
updated_at?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type ChannelStat = {
|
||||||
|
group_id?: string | null;
|
||||||
|
name?: string;
|
||||||
|
channel_id?: string;
|
||||||
|
channel_url?: string;
|
||||||
|
handle?: string;
|
||||||
|
enabled?: boolean | null;
|
||||||
|
last_status?: string;
|
||||||
|
last_title?: string;
|
||||||
|
last_live_url?: string;
|
||||||
|
sessions?: number;
|
||||||
|
hours_total?: number;
|
||||||
|
last_started_at?: number | null;
|
||||||
|
active?: number;
|
||||||
|
room_id?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type RecentSession = {
|
||||||
|
id: string;
|
||||||
|
anchor_name?: string;
|
||||||
|
title?: string;
|
||||||
|
room_id?: string;
|
||||||
|
started_at?: number;
|
||||||
|
ended_at?: number | null;
|
||||||
|
duration_seconds?: number;
|
||||||
|
status?: string;
|
||||||
|
source_url?: string;
|
||||||
|
};
|
||||||
|
|
||||||
const emptyForm = {
|
const emptyForm = {
|
||||||
name: "",
|
name: "",
|
||||||
channel_url: "",
|
channel_url: "",
|
||||||
@ -37,6 +72,9 @@ const emptyForm = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function GroupsPage() {
|
export default function GroupsPage() {
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const toast = useToast();
|
||||||
|
const [tab, setTab] = useState<"monitor" | "analytics">("monitor");
|
||||||
const [groups, setGroups] = useState<Group[]>([]);
|
const [groups, setGroups] = useState<Group[]>([]);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
const [q, setQ] = useState("");
|
const [q, setQ] = useState("");
|
||||||
@ -55,6 +93,13 @@ export default function GroupsPage() {
|
|||||||
const [probeInfo, setProbeInfo] = useState<Record<string, any>>({});
|
const [probeInfo, setProbeInfo] = useState<Record<string, any>>({});
|
||||||
const [monStatus, setMonStatus] = useState<any>(null);
|
const [monStatus, setMonStatus] = useState<any>(null);
|
||||||
|
|
||||||
|
const [ytStats, setYtStats] = useState<RelayStats | null>(null);
|
||||||
|
const [channelStats, setChannelStats] = useState<ChannelStat[]>([]);
|
||||||
|
const [recentSessions, setRecentSessions] = useState<RecentSession[]>([]);
|
||||||
|
const [analyticsBusy, setAnalyticsBusy] = useState(false);
|
||||||
|
const [dateFrom, setDateFrom] = useState(() => shiftBeijingISO(todayBeijingISO(), -29));
|
||||||
|
const [dateTo, setDateTo] = useState(() => todayBeijingISO());
|
||||||
|
|
||||||
const query = useMemo(() => {
|
const query = useMemo(() => {
|
||||||
const p = new URLSearchParams();
|
const p = new URLSearchParams();
|
||||||
p.set("platform", "youtube");
|
p.set("platform", "youtube");
|
||||||
@ -87,13 +132,36 @@ export default function GroupsPage() {
|
|||||||
}
|
}
|
||||||
}, [query]);
|
}, [query]);
|
||||||
|
|
||||||
useAutoRefresh(load, { intervalMs: 20000 });
|
const loadAnalytics = useCallback(async (opts?: RefreshOpts) => {
|
||||||
|
const silent = Boolean(opts?.silent);
|
||||||
|
if (!silent) setAnalyticsBusy(true);
|
||||||
|
try {
|
||||||
|
const p = new URLSearchParams();
|
||||||
|
if (dateFrom) p.set("date_from", dateFrom);
|
||||||
|
if (dateTo) p.set("date_to", dateTo);
|
||||||
|
p.set("top_anchors", "25");
|
||||||
|
const data = await fetchJson(`/api/groups/analytics?${p}`);
|
||||||
|
setYtStats((data.stats || null) as RelayStats | null);
|
||||||
|
setChannelStats((data.channels || []) as ChannelStat[]);
|
||||||
|
setRecentSessions((data.recent_sessions || []) as RecentSession[]);
|
||||||
|
if (data.monitor) setMonStatus(data.monitor);
|
||||||
|
} catch (e) {
|
||||||
|
if (!silent) setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
if (!silent) setAnalyticsBusy(false);
|
||||||
|
}
|
||||||
|
}, [dateFrom, dateTo]);
|
||||||
|
|
||||||
|
useAutoRefresh(load, { intervalMs: 20000, enabled: tab === "monitor" });
|
||||||
|
useAutoRefresh(loadAnalytics, { intervalMs: 30000, enabled: tab === "analytics" });
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (typeof window === "undefined") return;
|
if (typeof window === "undefined") return;
|
||||||
const p = new URLSearchParams(window.location.search);
|
const p = new URLSearchParams(window.location.search);
|
||||||
const channel = p.get("channel") || p.get("url") || "";
|
const channel = p.get("channel") || p.get("url") || "";
|
||||||
const name = p.get("name") || "";
|
const name = p.get("name") || "";
|
||||||
|
const t = p.get("tab");
|
||||||
|
if (t === "analytics") setTab("analytics");
|
||||||
if (channel || name) {
|
if (channel || name) {
|
||||||
setForm((f) => ({
|
setForm((f) => ({
|
||||||
...f,
|
...f,
|
||||||
@ -103,6 +171,10 @@ export default function GroupsPage() {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (tab === "analytics") void loadAnalytics();
|
||||||
|
}, [tab, loadAnalytics]);
|
||||||
|
|
||||||
const urlLineCount = form.urls
|
const urlLineCount = form.urls
|
||||||
.split(/\r?\n/)
|
.split(/\r?\n/)
|
||||||
.map((l) => l.trim())
|
.map((l) => l.trim())
|
||||||
@ -171,14 +243,21 @@ export default function GroupsPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function removeOne(id: string) {
|
async function removeOne(id: string) {
|
||||||
if (!confirm("确定删除该分组?")) return;
|
const ok = await confirm({
|
||||||
|
title: "删除分组",
|
||||||
|
message: "确定删除该 YouTube 分组?关联监控将停止。",
|
||||||
|
confirmLabel: "删除",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
setBusy(id);
|
setBusy(id);
|
||||||
try {
|
try {
|
||||||
await fetchJson(`/api/groups/${id}`, { method: "DELETE" });
|
await fetchJson(`/api/groups/${id}`, { method: "DELETE" });
|
||||||
setMsg("已删除");
|
toast.push("分组已删除", "ok");
|
||||||
await load();
|
await load();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError((e as Error).message);
|
setError((e as Error).message);
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
} finally {
|
} finally {
|
||||||
setBusy("");
|
setBusy("");
|
||||||
}
|
}
|
||||||
@ -225,7 +304,15 @@ export default function GroupsPage() {
|
|||||||
setMsg("请先勾选分组");
|
setMsg("请先勾选分组");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (action === "delete" && !confirm(`确定删除选中的 ${ids.length} 个分组?`)) return;
|
if (action === "delete") {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: "批量删除分组",
|
||||||
|
message: `确定删除选中的 ${ids.length} 个分组?`,
|
||||||
|
confirmLabel: "删除",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
setBusy(action);
|
setBusy(action);
|
||||||
setError("");
|
setError("");
|
||||||
try {
|
try {
|
||||||
@ -261,10 +348,22 @@ export default function GroupsPage() {
|
|||||||
<div>
|
<div>
|
||||||
<h2 className="font-display text-2xl font-semibold">📺 YouTube 频道分组</h2>
|
<h2 className="font-display text-2xl font-semibold">📺 YouTube 频道分组</h2>
|
||||||
<p className="text-sm text-slate-400">
|
<p className="text-sm text-slate-400">
|
||||||
每个分组对应一个 YouTube 频道;启用后自动轮询开播,Toast / 浏览器通知 / Webhook 提醒。
|
开播轮询入库场次,与抖音共用同一套时长 / 时段 / 排行分析。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Link
|
||||||
|
href="/sessions?platform=youtube"
|
||||||
|
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
|
||||||
|
>
|
||||||
|
场次明细
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
href="/slots?platform=youtube"
|
||||||
|
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
|
||||||
|
>
|
||||||
|
时段分析
|
||||||
|
</Link>
|
||||||
<a
|
<a
|
||||||
href="/api/groups/export"
|
href="/api/groups/export"
|
||||||
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
|
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
|
||||||
@ -275,6 +374,41 @@ export default function GroupsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4 flex flex-wrap gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setTab("monitor");
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
const u = new URL(window.location.href);
|
||||||
|
u.searchParams.delete("tab");
|
||||||
|
window.history.replaceState({}, "", u.pathname + u.search);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`rounded-xl px-4 py-2 text-sm ${
|
||||||
|
tab === "monitor" ? "bg-teal-500/20 text-teal-50 ring-1 ring-teal-400/30" : "bg-white/5 text-slate-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
监控
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setTab("analytics");
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
const u = new URL(window.location.href);
|
||||||
|
u.searchParams.set("tab", "analytics");
|
||||||
|
window.history.replaceState({}, "", u.pathname + u.search);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`rounded-xl px-4 py-2 text-sm ${
|
||||||
|
tab === "analytics" ? "bg-amber-500/20 text-amber-50 ring-1 ring-amber-400/30" : "bg-white/5 text-slate-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
数据分析
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-white/10 bg-black/25 px-4 py-3 text-sm">
|
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-white/10 bg-black/25 px-4 py-3 text-sm">
|
||||||
<span className={monStatus?.yt_monitor_enabled ? "text-teal-300" : "text-slate-500"}>
|
<span className={monStatus?.yt_monitor_enabled ? "text-teal-300" : "text-slate-500"}>
|
||||||
轮询:{monStatus?.yt_monitor_enabled ? "运行中" : "已暂停"}
|
轮询:{monStatus?.yt_monitor_enabled ? "运行中" : "已暂停"}
|
||||||
@ -306,6 +440,149 @@ export default function GroupsPage() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
|
||||||
|
{msg ? <div className="mb-4 rounded-lg border border-teal-500/30 bg-teal-500/10 px-4 py-3 text-sm">{msg}</div> : null}
|
||||||
|
|
||||||
|
{tab === "analytics" ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex flex-wrap items-end gap-2 rounded-xl border border-white/10 bg-black/25 p-3">
|
||||||
|
<label className="text-xs text-slate-400">
|
||||||
|
起
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={dateFrom}
|
||||||
|
onChange={(e) => setDateFrom(e.target.value)}
|
||||||
|
className="mt-1 block rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="text-xs text-slate-400">
|
||||||
|
止
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={dateTo}
|
||||||
|
onChange={(e) => setDateTo(e.target.value)}
|
||||||
|
className="mt-1 block rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void loadAnalytics()}
|
||||||
|
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
|
||||||
|
>
|
||||||
|
{analyticsBusy ? <Loader2 className="inline h-3.5 w-3.5 animate-spin" /> : null} 刷新分析
|
||||||
|
</button>
|
||||||
|
<span className="text-xs text-slate-500">北京日 · 与抖音场次统计同一口径</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
{[
|
||||||
|
["场次", String(ytStats?.overview?.sessions ?? 0), "YouTube 开播记录"],
|
||||||
|
["在播", String(ytStats?.overview?.active_sessions ?? 0), "当前未结场"],
|
||||||
|
["累计小时", Number(ytStats?.overview?.total_hours || 0).toFixed(1), "含进行中时长"],
|
||||||
|
["频道数", String(ytStats?.overview?.unique_anchors ?? channelStats.length), "有场次的频道"],
|
||||||
|
].map(([label, value, hint]) => (
|
||||||
|
<div key={label as string} className="rounded-2xl border border-white/10 bg-black/30 px-4 py-3">
|
||||||
|
<div className="text-xs text-slate-500">{label}</div>
|
||||||
|
<div className="mt-1 font-display text-2xl text-white">{value}</div>
|
||||||
|
<div className="mt-1 text-[11px] text-slate-500">{hint}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||||
|
<h3 className="mb-3 font-display text-sm font-medium text-slate-100">可视化分析</h3>
|
||||||
|
<SessionCharts stats={ytStats} />
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="overflow-hidden rounded-2xl border border-white/10 bg-black/25">
|
||||||
|
<div className="border-b border-white/5 px-4 py-3 text-sm font-medium text-slate-100">频道排行</div>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="min-w-full text-left text-sm">
|
||||||
|
<thead className="bg-white/5 text-xs uppercase text-slate-400">
|
||||||
|
<tr>
|
||||||
|
<th className="px-3 py-2">频道</th>
|
||||||
|
<th className="px-3 py-2">状态</th>
|
||||||
|
<th className="px-3 py-2">场次</th>
|
||||||
|
<th className="px-3 py-2">小时</th>
|
||||||
|
<th className="px-3 py-2">最近开播</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{channelStats.map((ch) => (
|
||||||
|
<tr key={String(ch.group_id || ch.room_id || ch.name)} className="border-t border-white/5">
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="font-medium text-slate-100">{ch.name || "—"}</span>
|
||||||
|
{ch.group_id ? <YouTubeLiveBadge refKey={groupLiveRef(ch.group_id)} compact showOffline /> : null}
|
||||||
|
</div>
|
||||||
|
<div className="font-mono text-[10px] text-slate-500">{ch.channel_id || ch.room_id || "—"}</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<span className={Number(ch.active) > 0 || ch.last_status === "live" ? "text-rose-300" : "text-slate-500"}>
|
||||||
|
{Number(ch.active) > 0 || ch.last_status === "live" ? "LIVE" : ch.last_status || "offline"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2 tabular-nums">{ch.sessions ?? 0}</td>
|
||||||
|
<td className="px-3 py-2 tabular-nums">{Number(ch.hours_total || 0).toFixed(1)}</td>
|
||||||
|
<td className="px-3 py-2 text-slate-400">{ch.last_started_at ? fmtTs(ch.last_started_at) : "—"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{!channelStats.length ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} className="px-3 py-8 text-center text-slate-500">
|
||||||
|
暂无 YouTube 场次。开启分组轮询并等频道开播后会出现在这里。
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="overflow-hidden rounded-2xl border border-white/10 bg-black/25">
|
||||||
|
<div className="flex items-center justify-between border-b border-white/5 px-4 py-3">
|
||||||
|
<span className="text-sm font-medium text-slate-100">最近场次</span>
|
||||||
|
<Link href="/sessions?platform=youtube" className="text-xs text-teal-300 hover:underline">
|
||||||
|
全部 →
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="min-w-full text-left text-sm">
|
||||||
|
<thead className="bg-white/5 text-xs uppercase text-slate-400">
|
||||||
|
<tr>
|
||||||
|
<th className="px-3 py-2">频道</th>
|
||||||
|
<th className="px-3 py-2">标题</th>
|
||||||
|
<th className="px-3 py-2">开始</th>
|
||||||
|
<th className="px-3 py-2">时长</th>
|
||||||
|
<th className="px-3 py-2">状态</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{recentSessions.map((s) => (
|
||||||
|
<tr key={s.id} className="border-t border-white/5">
|
||||||
|
<td className="px-3 py-2 text-slate-100">{s.anchor_name || s.room_id || "—"}</td>
|
||||||
|
<td className="max-w-[240px] truncate px-3 py-2 text-slate-400">{s.title || "—"}</td>
|
||||||
|
<td className="px-3 py-2 text-slate-400">{fmtTs(s.started_at)}</td>
|
||||||
|
<td className="px-3 py-2 tabular-nums text-slate-300">{fmtDuration(s.duration_seconds)}</td>
|
||||||
|
<td className="px-3 py-2">{s.ended_at ? "已结束" : <span className="text-rose-300">在播</span>}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{!recentSessions.length ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} className="px-3 py-8 text-center text-slate-500">
|
||||||
|
暂无场次
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{tab === "monitor" ? (
|
||||||
|
<>
|
||||||
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2">
|
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2">
|
||||||
<label className="block text-xs text-slate-400">
|
<label className="block text-xs text-slate-400">
|
||||||
分组名称
|
分组名称
|
||||||
@ -326,7 +603,7 @@ export default function GroupsPage() {
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label className="block text-xs text-slate-400 md:col-span-2">
|
<label className="block text-xs text-slate-400 md:col-span-2">
|
||||||
分组内 URL(每行一条,共 {urlLineCount})
|
分组内 URL(频道未播时也会探测,每行一条,最多 6 条,共 {urlLineCount})
|
||||||
<textarea
|
<textarea
|
||||||
value={form.urls}
|
value={form.urls}
|
||||||
onChange={(e) => setForm((f) => ({ ...f, urls: e.target.value }))}
|
onChange={(e) => setForm((f) => ({ ...f, urls: e.target.value }))}
|
||||||
@ -403,9 +680,6 @@ export default function GroupsPage() {
|
|||||||
<span className="text-xs text-slate-500">共 {total} · 已选 {selected.size}</span>
|
<span className="text-xs text-slate-500">共 {total} · 已选 {selected.size}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
|
|
||||||
{msg ? <div className="mb-4 rounded-lg border border-teal-500/30 bg-teal-500/10 px-4 py-3 text-sm">{msg}</div> : null}
|
|
||||||
|
|
||||||
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
|
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
|
||||||
<table className="min-w-full text-left text-sm">
|
<table className="min-w-full text-left text-sm">
|
||||||
<thead className="bg-white/5 text-xs uppercase text-slate-400">
|
<thead className="bg-white/5 text-xs uppercase text-slate-400">
|
||||||
@ -437,7 +711,10 @@ export default function GroupsPage() {
|
|||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-3">
|
<td className="px-3 py-3">
|
||||||
<div className="font-medium text-white">{g.name}</div>
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<div className="font-medium text-white">{g.name}</div>
|
||||||
|
<YouTubeLiveBadge refKey={groupLiveRef(g.id)} compact />
|
||||||
|
</div>
|
||||||
{g.note ? <div className="mt-1 text-xs text-slate-500">{g.note}</div> : null}
|
{g.note ? <div className="mt-1 text-xs text-slate-500">{g.note}</div> : null}
|
||||||
{g.last_title || probeInfo[g.id]?.live?.title ? (
|
{g.last_title || probeInfo[g.id]?.live?.title ? (
|
||||||
<div className="mt-1 max-w-[220px] truncate text-xs text-slate-500">
|
<div className="mt-1 max-w-[220px] truncate text-xs text-slate-500">
|
||||||
@ -468,29 +745,12 @@ export default function GroupsPage() {
|
|||||||
) : null}
|
) : null}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-3">
|
<td className="px-3 py-3">
|
||||||
{g.last_status === "live" ? (
|
<YouTubeLiveBadge refKey={groupLiveRef(g.id)} showTitle />
|
||||||
<div>
|
{g.last_status === "error" ? (
|
||||||
<span className="text-rose-300">LIVE</span>
|
<span className="mt-1 block text-amber-300" title={g.last_error || ""}>
|
||||||
{g.last_live_url ? (
|
|
||||||
<a
|
|
||||||
href={g.last_live_url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noreferrer"
|
|
||||||
className="mt-1 block text-[11px] text-teal-300 hover:underline"
|
|
||||||
>
|
|
||||||
打开直播
|
|
||||||
</a>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
) : g.last_status === "error" ? (
|
|
||||||
<span className="text-amber-300" title={g.last_error || ""}>
|
|
||||||
错误
|
错误
|
||||||
</span>
|
</span>
|
||||||
) : g.last_status === "offline" ? (
|
) : null}
|
||||||
<span className="text-slate-400">离线</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-slate-600">{g.last_status || "—"}</span>
|
|
||||||
)}
|
|
||||||
{g.last_checked_at ? (
|
{g.last_checked_at ? (
|
||||||
<div className="mt-1 text-[11px] text-slate-600">{fmtTs(g.last_checked_at)}</div>
|
<div className="mt-1 text-[11px] text-slate-600">{fmtTs(g.last_checked_at)}</div>
|
||||||
) : null}
|
) : null}
|
||||||
@ -529,7 +789,7 @@ export default function GroupsPage() {
|
|||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{groups.length === 0 ? (
|
{groups.length === 0 && !loading ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={8} className="px-3 py-10 text-center text-slate-500">
|
<td colSpan={8} className="px-3 py-10 text-center text-slate-500">
|
||||||
暂无 YouTube 分组
|
暂无 YouTube 分组
|
||||||
@ -539,6 +799,8 @@ export default function GroupsPage() {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<Modal open={!!edit} onClose={() => setEdit(null)}>
|
<Modal open={!!edit} onClose={() => setEdit(null)}>
|
||||||
{edit ? (
|
{edit ? (
|
||||||
|
|||||||
104
frontend/src/app/login/page.tsx
Normal file
104
frontend/src/app/login/page.tsx
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Suspense } from "react";
|
||||||
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
|
import { FormEvent, useEffect, useState } from "react";
|
||||||
|
import { Loader2, LockKeyhole } from "lucide-react";
|
||||||
|
|
||||||
|
import { BrandMark } from "@/components/ui";
|
||||||
|
import { clearAuthRedirect, fetchJson } from "@/lib/api";
|
||||||
|
|
||||||
|
function LoginForm() {
|
||||||
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const next = searchParams.get("next") || "/";
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void fetchJson("/api/auth/status")
|
||||||
|
.then((d) => {
|
||||||
|
if (d.authenticated) router.replace(next);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}, [next, router]);
|
||||||
|
|
||||||
|
async function onSubmit(e: FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await fetchJson("/api/auth/login", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ username, password }),
|
||||||
|
});
|
||||||
|
clearAuthRedirect();
|
||||||
|
router.replace(next);
|
||||||
|
router.refresh();
|
||||||
|
} catch (err) {
|
||||||
|
setError((err as Error).message || "登录失败");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative flex min-h-screen items-center justify-center px-4">
|
||||||
|
<div className="ambient-orb a" />
|
||||||
|
<div className="ambient-orb b" />
|
||||||
|
<div className="relative z-10 w-full max-w-md animate-fade-up rounded-2xl border border-white/10 bg-black/40 p-8 shadow-2xl backdrop-blur-md">
|
||||||
|
<div className="mb-6 flex flex-col items-center text-center">
|
||||||
|
<BrandMark className="mb-4 h-14 w-14" />
|
||||||
|
<p className="font-display text-xs uppercase tracking-[0.28em] text-teal-300/90">Live Radar</p>
|
||||||
|
<h1 className="mt-2 font-display text-2xl font-bold text-white">登录监控中心</h1>
|
||||||
|
<p className="mt-2 text-sm text-slate-500">抖音 + YouTube 直播监控 · 请登录后继续</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={(e) => void onSubmit(e)} className="space-y-4">
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
用户名
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
autoComplete="username"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
placeholder="用户名"
|
||||||
|
className="mt-1 w-full rounded-xl border border-white/10 bg-slate-950 px-3 py-2.5 text-sm text-white outline-none ring-teal-400/30 focus:ring-2"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
密码
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-xl border border-white/10 bg-slate-950 px-3 py-2.5 text-sm text-white outline-none ring-teal-400/30 focus:ring-2"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{error ? <div className="text-sm text-rose-300">{error}</div> : null}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={busy}
|
||||||
|
className="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-[#ff2d55] px-4 py-2.5 text-sm font-medium text-white hover:bg-[#ff4d6d] disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <LockKeyhole className="h-4 w-4" />}
|
||||||
|
登录
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={<div className="flex min-h-screen items-center justify-center text-slate-500">加载中…</div>}>
|
||||||
|
<LoginForm />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -8,11 +8,15 @@ import { Shell } from "@/components/Shell";
|
|||||||
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
||||||
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
|
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
|
||||||
import { AnimatedNumber, LivePulse, StatTile, PlatformBadge } from "@/components/ui";
|
import { AnimatedNumber, LivePulse, StatTile, PlatformBadge } from "@/components/ui";
|
||||||
|
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
|
||||||
|
import { YouTubeLiveTicker } from "@/components/YouTubeLiveTicker";
|
||||||
import { useToast } from "@/components/Toast";
|
import { useToast } from "@/components/Toast";
|
||||||
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||||
import { RoomQuickActions, isFavorited } from "@/components/RoomQuickActions";
|
import { RoomQuickActions, isFavorited } from "@/components/RoomQuickActions";
|
||||||
import { fetchJson, fmtTs, sessionCoverSrc, todayBeijingISO, beijingHourFromTs, beijingParts, detectPlatform } from "@/lib/api";
|
import { fetchJson, fmtTs, sessionCoverSrc, todayBeijingISO, beijingHourFromTs, beijingParts, detectPlatform } from "@/lib/api";
|
||||||
import { liveElapsed, useEventStream, useNow, type RefreshOpts } from "@/lib/realtime";
|
import { liveElapsed, useEventStream, useNow, type RefreshOpts } from "@/lib/realtime";
|
||||||
|
import { channelLiveRef, useYouTubeLiveCount } from "@/lib/youtubeLive";
|
||||||
|
|
||||||
type MonitorStatus = {
|
type MonitorStatus = {
|
||||||
running: boolean;
|
running: boolean;
|
||||||
@ -89,6 +93,7 @@ type ActiveSession = {
|
|||||||
|
|
||||||
export default function HomePage() {
|
export default function HomePage() {
|
||||||
const [stats, setStats] = useState<RelayStats | null>(null);
|
const [stats, setStats] = useState<RelayStats | null>(null);
|
||||||
|
const [ytStats, setYtStats] = useState<RelayStats | null>(null);
|
||||||
const [status, setStatus] = useState<MonitorStatus | null>(null);
|
const [status, setStatus] = useState<MonitorStatus | null>(null);
|
||||||
const [ytStatus, setYtStatus] = useState<Record<string, any> | null>(null);
|
const [ytStatus, setYtStatus] = useState<Record<string, any> | null>(null);
|
||||||
const [rooms, setRooms] = useState<Room[]>([]);
|
const [rooms, setRooms] = useState<Room[]>([]);
|
||||||
@ -103,8 +108,10 @@ export default function HomePage() {
|
|||||||
const [detail, setDetail] = useState<SessionDetail | null>(null);
|
const [detail, setDetail] = useState<SessionDetail | null>(null);
|
||||||
const [opsBusy, setOpsBusy] = useState("");
|
const [opsBusy, setOpsBusy] = useState("");
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
|
const confirm = useConfirm();
|
||||||
const now = useNow(1000);
|
const now = useNow(1000);
|
||||||
const { connected, last, tick } = useEventStream(true);
|
const { connected, last, tick } = useEventStream(true);
|
||||||
|
const ytLiveCount = useYouTubeLiveCount();
|
||||||
|
|
||||||
const load = useCallback(async (opts?: RefreshOpts) => {
|
const load = useCallback(async (opts?: RefreshOpts) => {
|
||||||
const silent = Boolean(opts?.silent);
|
const silent = Boolean(opts?.silent);
|
||||||
@ -114,8 +121,9 @@ export default function HomePage() {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const iso = todayBeijingISO();
|
const iso = todayBeijingISO();
|
||||||
const [s, m, yt, r, e, a, daySessions, up] = await Promise.all([
|
const [s, ytS, m, yt, r, e, a, daySessions, up] = await Promise.all([
|
||||||
fetchJson("/api/sessions/stats?top_anchors=25"),
|
fetchJson("/api/sessions/stats?top_anchors=25"),
|
||||||
|
fetchJson("/api/sessions/stats?platform=youtube&top_anchors=10").catch(() => null),
|
||||||
fetchJson("/api/monitor/status"),
|
fetchJson("/api/monitor/status"),
|
||||||
fetchJson("/api/youtube-monitor/status").catch(() => null),
|
fetchJson("/api/youtube-monitor/status").catch(() => null),
|
||||||
fetchJson("/api/rooms?limit=500"),
|
fetchJson("/api/rooms?limit=500"),
|
||||||
@ -125,6 +133,7 @@ export default function HomePage() {
|
|||||||
fetchJson("/api/anchors/upcoming?limit=12"),
|
fetchJson("/api/anchors/upcoming?limit=12"),
|
||||||
]);
|
]);
|
||||||
setStats(s);
|
setStats(s);
|
||||||
|
setYtStats(ytS);
|
||||||
setStatus(m);
|
setStatus(m);
|
||||||
setYtStatus(yt);
|
setYtStatus(yt);
|
||||||
setRooms(r.rooms || []);
|
setRooms(r.rooms || []);
|
||||||
@ -186,7 +195,6 @@ export default function HomePage() {
|
|||||||
.map((r) => r.room_id),
|
.map((r) => r.room_id),
|
||||||
);
|
);
|
||||||
const liveRooms = rooms.filter((r) => r.last_status === "live" && (!focusOnly || priorityRoomIds.has(r.room_id)));
|
const liveRooms = rooms.filter((r) => r.last_status === "live" && (!focusOnly || priorityRoomIds.has(r.room_id)));
|
||||||
const ytLiveCount = Number(ytStatus?.groups?.live || 0);
|
|
||||||
const focusLive = active.filter((s) => {
|
const focusLive = active.filter((s) => {
|
||||||
const isYt = detectPlatform(s) === "youtube";
|
const isYt = detectPlatform(s) === "youtube";
|
||||||
if (focusOnly && isYt) return false;
|
if (focusOnly && isYt) return false;
|
||||||
@ -273,7 +281,10 @@ export default function HomePage() {
|
|||||||
{liveRooms.length > 0 ? <LivePulse label={`抖音 ${liveRooms.length} 路`} /> : null}
|
{liveRooms.length > 0 ? <LivePulse label={`抖音 ${liveRooms.length} 路`} /> : null}
|
||||||
{ytLiveCount > 0 ? (
|
{ytLiveCount > 0 ? (
|
||||||
<Link href="/groups" className="rounded-md border border-red-500/30 bg-red-500/10 px-2 py-1 text-[11px] text-red-100">
|
<Link href="/groups" className="rounded-md border border-red-500/30 bg-red-500/10 px-2 py-1 text-[11px] text-red-100">
|
||||||
▶ YT 在播 {ytLiveCount}
|
<span className="inline-flex items-center gap-1.5">
|
||||||
|
<span className="live-dot" />
|
||||||
|
YT 在播 {ytLiveCount}
|
||||||
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
) : ytStatus?.yt_monitor_enabled !== false && ytStatus?.running ? (
|
) : ytStatus?.yt_monitor_enabled !== false && ytStatus?.running ? (
|
||||||
<Link href="/groups" className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-400">
|
<Link href="/groups" className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-400">
|
||||||
@ -452,11 +463,24 @@ export default function HomePage() {
|
|||||||
</section>
|
</section>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<div className="stagger mb-6 grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
|
<div className="stagger mb-6 grid gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-6">
|
||||||
<StatTile emoji="🏠" label="抖音直播间" value={<AnimatedNumber value={status?.room_count || 0} />} hint="已纳入监控队列" accent="sky" />
|
<StatTile emoji="🏠" label="抖音直播间" value={<AnimatedNumber value={status?.room_count || 0} />} hint="已纳入监控队列" accent="sky" />
|
||||||
<StatTile emoji="🔴" label="抖音在播" value={<AnimatedNumber value={status?.live_count || 0} />} hint="正在直播中的房间" accent="rose" />
|
<StatTile emoji="🔴" label="抖音在播" value={<AnimatedNumber value={status?.live_count || 0} />} hint="正在直播中的房间" accent="rose" />
|
||||||
<StatTile emoji="▶️" label="YT 在播" value={<AnimatedNumber value={ytLiveCount} />} hint={`启用分组 ${String(ytStatus?.groups?.enabled ?? "—")}`} accent="amber" />
|
<StatTile emoji="▶️" label="YT 在播" value={<AnimatedNumber value={ytLiveCount} />} hint={`启用分组 ${String(ytStatus?.groups?.enabled ?? "—")}`} accent="amber" />
|
||||||
<StatTile emoji="⏱️" label="累计时长" value={<AnimatedNumber value={Number(stats?.overview?.total_hours || 0)} decimals={1} suffix="h" />} hint="历史场次合计" accent="teal" />
|
<StatTile
|
||||||
|
emoji="📺"
|
||||||
|
label="YT 场次/时长"
|
||||||
|
value={
|
||||||
|
<span className="tabular-nums">
|
||||||
|
<AnimatedNumber value={Number(ytStats?.overview?.sessions || 0)} />
|
||||||
|
<span className="mx-1 text-base text-slate-500">/</span>
|
||||||
|
<AnimatedNumber value={Number(ytStats?.overview?.total_hours || 0)} decimals={1} suffix="h" />
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
hint="YouTube 历史场次合计"
|
||||||
|
accent="teal"
|
||||||
|
/>
|
||||||
|
<StatTile emoji="⏱️" label="全平台时长" value={<AnimatedNumber value={Number(stats?.overview?.total_hours || 0)} decimals={1} suffix="h" />} hint="抖音+YouTube" accent="teal" />
|
||||||
<StatTile emoji="🎯" label="检查次数" value={<AnimatedNumber value={status?.checked_total || 0} />} hint={`上次 ${fmtTs(status?.last_check_at)}`} accent="amber" />
|
<StatTile emoji="🎯" label="检查次数" value={<AnimatedNumber value={status?.checked_total || 0} />} hint={`上次 ${fmtTs(status?.last_check_at)}`} accent="amber" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -565,13 +589,24 @@ export default function HomePage() {
|
|||||||
<PlatformBadge platform={detectPlatform(s)} />
|
<PlatformBadge platform={detectPlatform(s)} />
|
||||||
</span>
|
</span>
|
||||||
{s.anchor_name || s.room_id}
|
{s.anchor_name || s.room_id}
|
||||||
|
{detectPlatform(s) === "youtube" && s.room_id?.startsWith("yt:UC") ? (
|
||||||
|
<span className="ml-1.5 inline-block align-middle">
|
||||||
|
<YouTubeLiveBadge refKey={channelLiveRef(s.room_id.slice(3))} compact />
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="font-mono text-xs text-rose-200">{liveElapsed(s.started_at, now)}</div>
|
<div className="font-mono text-xs text-rose-200">{liveElapsed(s.started_at, now)}</div>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (!confirm(`结束「${s.anchor_name || s.room_id}」这场?`)) return;
|
const ok = await confirm({
|
||||||
|
title: "结束场次",
|
||||||
|
message: `结束「${s.anchor_name || s.room_id}」这场?`,
|
||||||
|
confirmLabel: "结束",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
try {
|
try {
|
||||||
await fetchJson(`/api/sessions/${s.id}/end`, { method: "POST" });
|
await fetchJson(`/api/sessions/${s.id}/end`, { method: "POST" });
|
||||||
toast.push("已结束场次", "ok");
|
toast.push("已结束场次", "ok");
|
||||||
@ -666,13 +701,27 @@ export default function HomePage() {
|
|||||||
|
|
||||||
<div className="mb-6 grid gap-4 lg:grid-cols-[1.4fr_1fr]">
|
<div className="mb-6 grid gap-4 lg:grid-cols-[1.4fr_1fr]">
|
||||||
<section className="glass-panel rounded-2xl p-4">
|
<section className="glass-panel rounded-2xl p-4">
|
||||||
<div className="mb-3 flex items-center justify-between">
|
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||||
<h3 className="font-display text-sm font-medium text-slate-100">📊 可视化分析</h3>
|
<h3 className="font-display text-sm font-medium text-slate-100">📊 可视化分析(全平台)</h3>
|
||||||
<Link href="/sessions" className="inline-flex items-center gap-1 text-xs text-teal-300 hover:underline">
|
<div className="flex flex-wrap gap-3 text-xs">
|
||||||
场次明细 <ArrowRight className="h-3 w-3" />
|
<Link href="/sessions" className="inline-flex items-center gap-1 text-teal-300 hover:underline">
|
||||||
</Link>
|
场次明细 <ArrowRight className="h-3 w-3" />
|
||||||
|
</Link>
|
||||||
|
<Link href="/groups?tab=analytics" className="inline-flex items-center gap-1 text-amber-300 hover:underline">
|
||||||
|
YouTube 分析 <ArrowRight className="h-3 w-3" />
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<SessionCharts stats={stats} />
|
<SessionCharts stats={stats} />
|
||||||
|
{ytStats?.overview ? (
|
||||||
|
<div className="mt-4 rounded-xl border border-amber-500/20 bg-amber-500/5 px-3 py-2 text-xs text-amber-100/90">
|
||||||
|
YouTube 单独:场次 {ytStats.overview.sessions ?? 0} · 在播 {ytStats.overview.active_sessions ?? 0} · 累计{" "}
|
||||||
|
{Number(ytStats.overview.total_hours || 0).toFixed(1)}h · 频道 {ytStats.overview.unique_anchors ?? 0}
|
||||||
|
<Link href="/groups?tab=analytics" className="ml-2 text-teal-300 hover:underline">
|
||||||
|
打开图表 →
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="glass-panel rounded-2xl p-4">
|
<section className="glass-panel rounded-2xl p-4">
|
||||||
|
|||||||
@ -4,6 +4,8 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
|||||||
import { Loader2, Plus, RefreshCw, Trash2, Zap } from "lucide-react";
|
import { Loader2, Plus, RefreshCw, Trash2, Zap } from "lucide-react";
|
||||||
|
|
||||||
import { Shell } from "@/components/Shell";
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
import { Modal } from "@/components/Modal";
|
import { Modal } from "@/components/Modal";
|
||||||
import { RoomQuickActions, isFavorited } from "@/components/RoomQuickActions";
|
import { RoomQuickActions, isFavorited } from "@/components/RoomQuickActions";
|
||||||
import { fetchJson, fmtTs } from "@/lib/api";
|
import { fetchJson, fmtTs } from "@/lib/api";
|
||||||
@ -26,6 +28,8 @@ type Room = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function RoomsPage() {
|
export default function RoomsPage() {
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const toast = useToast();
|
||||||
const [rooms, setRooms] = useState<Room[]>([]);
|
const [rooms, setRooms] = useState<Room[]>([]);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
const [allTags, setAllTags] = useState<string[]>([]);
|
const [allTags, setAllTags] = useState<string[]>([]);
|
||||||
@ -196,7 +200,15 @@ export default function RoomsPage() {
|
|||||||
async function bulk(action: string) {
|
async function bulk(action: string) {
|
||||||
const ids = Array.from(selected);
|
const ids = Array.from(selected);
|
||||||
if (!ids.length) return;
|
if (!ids.length) return;
|
||||||
if (action === "delete" && !confirm(`删除选中的 ${ids.length} 个直播间?`)) return;
|
if (action === "delete") {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: "批量删除直播间",
|
||||||
|
message: `确定删除选中的 ${ids.length} 个直播间?`,
|
||||||
|
confirmLabel: "删除",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
setBusy(action);
|
setBusy(action);
|
||||||
setError("");
|
setError("");
|
||||||
try {
|
try {
|
||||||
@ -229,10 +241,17 @@ export default function RoomsPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function remove(room: Room) {
|
async function remove(room: Room) {
|
||||||
if (!confirm(`删除直播间 ${room.room_id}?`)) return;
|
const ok = await confirm({
|
||||||
|
title: "删除直播间",
|
||||||
|
message: `确定删除 ${room.room_id}?`,
|
||||||
|
confirmLabel: "删除",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
setBusy(room.id);
|
setBusy(room.id);
|
||||||
try {
|
try {
|
||||||
await fetchJson(`/api/rooms/${room.id}`, { method: "DELETE" });
|
await fetchJson(`/api/rooms/${room.id}`, { method: "DELETE" });
|
||||||
|
toast.push("直播间已删除", "ok");
|
||||||
await load();
|
await load();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError((e as Error).message);
|
setError((e as Error).message);
|
||||||
|
|||||||
@ -4,11 +4,15 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
|||||||
import { Loader2, RefreshCw, Search } from "lucide-react";
|
import { Loader2, RefreshCw, Search } from "lucide-react";
|
||||||
|
|
||||||
import { Shell } from "@/components/Shell";
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
||||||
import { SessionDetailModal } from "@/components/SessionDetailModal";
|
import { SessionDetailModal } from "@/components/SessionDetailModal";
|
||||||
import { RoomQuickActions } from "@/components/RoomQuickActions";
|
import { RoomQuickActions } from "@/components/RoomQuickActions";
|
||||||
import { PlatformBadge } from "@/components/ui";
|
import { PlatformBadge } from "@/components/ui";
|
||||||
|
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
|
||||||
import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc, todayBeijingISO, shiftBeijingISO, detectPlatform } from "@/lib/api";
|
import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc, todayBeijingISO, shiftBeijingISO, detectPlatform } from "@/lib/api";
|
||||||
|
import { channelLiveRef } from "@/lib/youtubeLive";
|
||||||
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
|
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
|
||||||
|
|
||||||
type Session = {
|
type Session = {
|
||||||
@ -28,6 +32,8 @@ type Session = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function SessionsPage() {
|
export default function SessionsPage() {
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const toast = useToast();
|
||||||
const [tab, setTab] = useState<"charts" | "list">("list");
|
const [tab, setTab] = useState<"charts" | "list">("list");
|
||||||
const [q, setQ] = useState("");
|
const [q, setQ] = useState("");
|
||||||
const [dateFrom, setDateFrom] = useState("");
|
const [dateFrom, setDateFrom] = useState("");
|
||||||
@ -170,14 +176,21 @@ export default function SessionsPage() {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (!confirm("确认结束全部进行中的场次?")) return;
|
const ok = await confirm({
|
||||||
|
title: "结束全部进行中场次",
|
||||||
|
message: "确定结束所有当前进行中的场次?",
|
||||||
|
confirmLabel: "全部结束",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
try {
|
try {
|
||||||
const data = await fetchJson("/api/sessions/end-all-active", { method: "POST" });
|
const data = await fetchJson("/api/sessions/end-all-active", { method: "POST" });
|
||||||
setError("");
|
setError("");
|
||||||
alert(`已结束 ${data.ended || 0} 场`);
|
toast.push(`已结束 ${data.ended || 0} 场`, "ok");
|
||||||
await load();
|
await load();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError((e as Error).message);
|
setError((e as Error).message);
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100 hover:bg-amber-500/20"
|
className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100 hover:bg-amber-500/20"
|
||||||
@ -225,6 +238,7 @@ export default function SessionsPage() {
|
|||||||
<option value="">全部平台</option>
|
<option value="">全部平台</option>
|
||||||
<option value="douyin">抖音</option>
|
<option value="douyin">抖音</option>
|
||||||
<option value="youtube">YouTube</option>
|
<option value="youtube">YouTube</option>
|
||||||
|
<option value="shorts">Shorts 频道开播</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label className="block text-xs text-slate-400">
|
<label className="block text-xs text-slate-400">
|
||||||
@ -325,7 +339,16 @@ export default function SessionsPage() {
|
|||||||
<td className="px-3 py-3">
|
<td className="px-3 py-3">
|
||||||
<PlatformBadge platform={detectPlatform(session)} />
|
<PlatformBadge platform={detectPlatform(session)} />
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-3 font-medium">{session.anchor_name || "—"}</td>
|
<td className="px-3 py-3 font-medium">
|
||||||
|
<span className="inline-flex items-center gap-2">
|
||||||
|
{session.anchor_name || "—"}
|
||||||
|
{detectPlatform(session) === "youtube" &&
|
||||||
|
!session.ended_at &&
|
||||||
|
session.room_id?.startsWith("yt:UC") ? (
|
||||||
|
<YouTubeLiveBadge refKey={channelLiveRef(session.room_id.slice(3))} compact />
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
<td className="max-w-[14rem] truncate px-3 py-3 font-mono text-xs text-cyan-300/90">
|
<td className="max-w-[14rem] truncate px-3 py-3 font-mono text-xs text-cyan-300/90">
|
||||||
{session.source_url ? (
|
{session.source_url ? (
|
||||||
<a href={session.source_url} target="_blank" rel="noreferrer" className="hover:underline" onClick={(e) => e.stopPropagation()}>
|
<a href={session.source_url} target="_blank" rel="noreferrer" className="hover:underline" onClick={(e) => e.stopPropagation()}>
|
||||||
@ -354,12 +377,20 @@ export default function SessionsPage() {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (!confirm(`结束「${session.anchor_name || session.room_id}」?`)) return;
|
const ok = await confirm({
|
||||||
|
title: "结束场次",
|
||||||
|
message: `确定结束「${session.anchor_name || session.room_id}」这场?`,
|
||||||
|
confirmLabel: "结束",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
try {
|
try {
|
||||||
await fetchJson(`/api/sessions/${session.id}/end`, { method: "POST" });
|
await fetchJson(`/api/sessions/${session.id}/end`, { method: "POST" });
|
||||||
|
toast.push("已结束场次", "ok");
|
||||||
await load();
|
await load();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError((e as Error).message);
|
setError((e as Error).message);
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
className="rounded border border-amber-500/30 px-2 py-1 text-xs text-amber-100 hover:bg-amber-500/10"
|
className="rounded border border-amber-500/30 px-2 py-1 text-xs text-amber-100 hover:bg-amber-500/10"
|
||||||
|
|||||||
@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { Loader2, Save, ShieldOff } from "lucide-react";
|
import { Loader2, Save, ShieldOff } from "lucide-react";
|
||||||
|
|
||||||
import { Shell } from "@/components/Shell";
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
import { fetchJson, fmtTs } from "@/lib/api";
|
import { fetchJson, fmtTs } from "@/lib/api";
|
||||||
|
|
||||||
type Settings = Record<string, number | boolean | string>;
|
type Settings = Record<string, number | boolean | string>;
|
||||||
@ -20,6 +21,7 @@ const FIELDS: Array<{ key: string; label: string; hint: string; step?: number }>
|
|||||||
];
|
];
|
||||||
|
|
||||||
export default function SettingsPage() {
|
export default function SettingsPage() {
|
||||||
|
const toast = useToast();
|
||||||
const [settings, setSettings] = useState<Settings>({});
|
const [settings, setSettings] = useState<Settings>({});
|
||||||
const [status, setStatus] = useState<Record<string, unknown> | null>(null);
|
const [status, setStatus] = useState<Record<string, unknown> | null>(null);
|
||||||
const [ytStatus, setYtStatus] = useState<Record<string, unknown> | null>(null);
|
const [ytStatus, setYtStatus] = useState<Record<string, unknown> | null>(null);
|
||||||
@ -70,6 +72,9 @@ export default function SettingsPage() {
|
|||||||
body.notify_on_live = Boolean(settings.notify_on_live);
|
body.notify_on_live = Boolean(settings.notify_on_live);
|
||||||
body.notify_on_offline = Boolean(settings.notify_on_offline);
|
body.notify_on_offline = Boolean(settings.notify_on_offline);
|
||||||
body.notify_on_risk = Boolean(settings.notify_on_risk);
|
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);
|
||||||
|
body.notify_on_shorts_quota = settings.notify_on_shorts_quota !== false;
|
||||||
body.quiet_hours_enabled = Boolean(settings.quiet_hours_enabled);
|
body.quiet_hours_enabled = Boolean(settings.quiet_hours_enabled);
|
||||||
body.quiet_hours_start = Number(settings.quiet_hours_start ?? 2);
|
body.quiet_hours_start = Number(settings.quiet_hours_start ?? 2);
|
||||||
body.quiet_hours_end = Number(settings.quiet_hours_end ?? 7);
|
body.quiet_hours_end = Number(settings.quiet_hours_end ?? 7);
|
||||||
@ -91,6 +96,14 @@ export default function SettingsPage() {
|
|||||||
body.shorts_live_sample_interval_sec = Number(settings.shorts_live_sample_interval_sec ?? 180);
|
body.shorts_live_sample_interval_sec = Number(settings.shorts_live_sample_interval_sec ?? 180);
|
||||||
body.shorts_live_sample_batch = Number(settings.shorts_live_sample_batch ?? 1);
|
body.shorts_live_sample_batch = Number(settings.shorts_live_sample_batch ?? 1);
|
||||||
body.shorts_sample_any_live = settings.shorts_sample_any_live !== false;
|
body.shorts_sample_any_live = settings.shorts_sample_any_live !== false;
|
||||||
|
body.shorts_upload_spread = settings.shorts_upload_spread !== false;
|
||||||
|
body.shorts_upload_min_gap_sec = Number(settings.shorts_upload_min_gap_sec ?? 720);
|
||||||
|
body.shorts_channel_min_gap_sec = Number(settings.shorts_channel_min_gap_sec ?? 2400);
|
||||||
|
body.shorts_delete_clip_after_upload = settings.shorts_delete_clip_after_upload !== false;
|
||||||
|
body.shorts_auto_retry_failed = settings.shorts_auto_retry_failed !== false;
|
||||||
|
body.shorts_auto_retry_max_attempts = Number(settings.shorts_auto_retry_max_attempts ?? 3);
|
||||||
|
body.shorts_auto_retry_interval_sec = Number(settings.shorts_auto_retry_interval_sec ?? 300);
|
||||||
|
body.shorts_oauth_check_interval_sec = Number(settings.shorts_oauth_check_interval_sec ?? 3600);
|
||||||
body.shorts_oauth_client_id = String(settings.shorts_oauth_client_id || "");
|
body.shorts_oauth_client_id = String(settings.shorts_oauth_client_id || "");
|
||||||
body.shorts_oauth_client_secret = String(settings.shorts_oauth_client_secret || "");
|
body.shorts_oauth_client_secret = String(settings.shorts_oauth_client_secret || "");
|
||||||
body.shorts_oauth_redirect_uri = String(
|
body.shorts_oauth_redirect_uri = String(
|
||||||
@ -109,24 +122,44 @@ export default function SettingsPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function toggleMonitor(enabled: boolean) {
|
async function toggleMonitor(enabled: boolean) {
|
||||||
await fetchJson(enabled ? "/api/monitor/start" : "/api/monitor/stop", { method: "POST" });
|
try {
|
||||||
await load();
|
await fetchJson(enabled ? "/api/monitor/start" : "/api/monitor/stop", { method: "POST" });
|
||||||
|
toast.push(enabled ? "抖音监控已启用" : "抖音监控已暂停", "ok");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function toggleYtMonitor(enabled: boolean) {
|
async function toggleYtMonitor(enabled: boolean) {
|
||||||
await fetchJson(enabled ? "/api/youtube-monitor/start" : "/api/youtube-monitor/stop", { method: "POST" });
|
try {
|
||||||
await load();
|
await fetchJson(enabled ? "/api/youtube-monitor/start" : "/api/youtube-monitor/stop", { method: "POST" });
|
||||||
|
toast.push(enabled ? "YouTube 分组轮询已开启" : "YouTube 分组轮询已暂停", "ok");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function toggleShorts(enabled: boolean) {
|
async function toggleShorts(enabled: boolean) {
|
||||||
await fetchJson(enabled ? "/api/shorts/start" : "/api/shorts/stop", { method: "POST" });
|
try {
|
||||||
await load();
|
await fetchJson(enabled ? "/api/shorts/start" : "/api/shorts/stop", { method: "POST" });
|
||||||
|
toast.push(enabled ? "Shorts 旁路已启用" : "Shorts 旁路已关闭", "ok");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function clearRisk() {
|
async function clearRisk() {
|
||||||
await fetchJson("/api/monitor/clear-risk", { method: "POST" });
|
try {
|
||||||
setMsg("已清除风控暂停");
|
await fetchJson("/api/monitor/clear-risk", { method: "POST" });
|
||||||
await load();
|
setMsg("已清除风控暂停");
|
||||||
|
toast.push("已清除风控暂停", "ok");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -279,7 +312,31 @@ export default function SettingsPage() {
|
|||||||
checked={settings.shorts_auto_upload !== false}
|
checked={settings.shorts_auto_upload !== false}
|
||||||
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_auto_upload: e.target.checked }))}
|
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_auto_upload: e.target.checked }))}
|
||||||
/>
|
/>
|
||||||
录完自动上传
|
录完自动进入上传排程
|
||||||
|
</label>
|
||||||
|
<label className="inline-flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={settings.shorts_upload_spread !== false}
|
||||||
|
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_upload_spread: e.target.checked }))}
|
||||||
|
/>
|
||||||
|
24h 不定时错峰上传(防规律/密集)
|
||||||
|
</label>
|
||||||
|
<label className="inline-flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={settings.shorts_delete_clip_after_upload !== false}
|
||||||
|
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_delete_clip_after_upload: e.target.checked }))}
|
||||||
|
/>
|
||||||
|
上传成功后删除本地成片
|
||||||
|
</label>
|
||||||
|
<label className="inline-flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={settings.shorts_auto_retry_failed !== false}
|
||||||
|
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_auto_retry_failed: e.target.checked }))}
|
||||||
|
/>
|
||||||
|
失败任务自动重试(跳过 OAuth 永久错误)
|
||||||
</label>
|
</label>
|
||||||
<label className="inline-flex items-center gap-2">
|
<label className="inline-flex items-center gap-2">
|
||||||
<input
|
<input
|
||||||
@ -319,6 +376,46 @@ export default function SettingsPage() {
|
|||||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
全局最小上传间隔(秒)
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={Number(settings.shorts_upload_min_gap_sec ?? 720)}
|
||||||
|
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_upload_min_gap_sec: Number(e.target.value) }))}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
同频道最小间隔(秒)
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={Number(settings.shorts_channel_min_gap_sec ?? 2400)}
|
||||||
|
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_channel_min_gap_sec: Number(e.target.value) }))}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
自动重试最大次数
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={Number(settings.shorts_auto_retry_max_attempts ?? 3)}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSettings((prev) => ({ ...prev, shorts_auto_retry_max_attempts: Number(e.target.value) }))
|
||||||
|
}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
自动重试扫描间隔(秒)
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={Number(settings.shorts_auto_retry_interval_sec ?? 300)}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSettings((prev) => ({ ...prev, shorts_auto_retry_interval_sec: Number(e.target.value) }))
|
||||||
|
}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-3 md:grid-cols-2">
|
<div className="grid gap-3 md:grid-cols-2">
|
||||||
<label className="block text-xs text-slate-400 md:col-span-2">
|
<label className="block text-xs text-slate-400 md:col-span-2">
|
||||||
@ -464,6 +561,9 @@ export default function SettingsPage() {
|
|||||||
["notify_on_live", "开播通知"],
|
["notify_on_live", "开播通知"],
|
||||||
["notify_on_offline", "停播通知"],
|
["notify_on_offline", "停播通知"],
|
||||||
["notify_on_risk", "风控通知"],
|
["notify_on_risk", "风控通知"],
|
||||||
|
["notify_on_shorts_fail", "Shorts 失败"],
|
||||||
|
["notify_on_shorts_ok", "Shorts 成功"],
|
||||||
|
["notify_on_shorts_quota", "Shorts 配额落后"],
|
||||||
["capture_cover_on_start", "开播截图"],
|
["capture_cover_on_start", "开播截图"],
|
||||||
].map(([key, label]) => (
|
].map(([key, label]) => (
|
||||||
<label key={key} className="inline-flex items-center gap-2">
|
<label key={key} className="inline-flex items-center gap-2">
|
||||||
@ -522,6 +622,10 @@ export default function SettingsPage() {
|
|||||||
|
|
||||||
<OpsPanel />
|
<OpsPanel />
|
||||||
|
|
||||||
|
<ApiKeyPanel />
|
||||||
|
|
||||||
|
<ChangePasswordPanel />
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<button type="button" onClick={() => void save()} className="inline-flex items-center gap-2 rounded-lg bg-[#ff2d55] px-4 py-2 text-sm font-medium text-white hover:bg-[#ff4d6d]">
|
<button type="button" onClick={() => void save()} className="inline-flex items-center gap-2 rounded-lg bg-[#ff2d55] px-4 py-2 text-sm font-medium text-white hover:bg-[#ff4d6d]">
|
||||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
|
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
|
||||||
@ -534,14 +638,156 @@ export default function SettingsPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ChangePasswordPanel() {
|
||||||
|
const [current, setCurrent] = useState("");
|
||||||
|
const [newPw, setNewPw] = useState("");
|
||||||
|
const [confirm, setConfirm] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [msg, setMsg] = useState("");
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
setBusy(true);
|
||||||
|
setMsg("");
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const data = await fetchJson("/api/auth/change-password", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
current_password: current,
|
||||||
|
new_password: newPw,
|
||||||
|
confirm_password: confirm,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
setMsg(data.message || "密码已更新");
|
||||||
|
setCurrent("");
|
||||||
|
setNewPw("");
|
||||||
|
setConfirm("");
|
||||||
|
await fetchJson("/api/auth/logout", { method: "POST" });
|
||||||
|
window.location.href = "/login";
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mb-6 rounded-xl border border-white/10 bg-black/25 p-4">
|
||||||
|
<h3 className="mb-2 text-sm font-medium text-slate-100">修改登录密码</h3>
|
||||||
|
<p className="mb-3 text-xs text-slate-500">密码保存在服务器数据库(哈希存储)。修改成功后将退出登录,请用新密码重新登录。</p>
|
||||||
|
<div className="grid gap-3 sm:grid-cols-3">
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
当前密码
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={current}
|
||||||
|
onChange={(e) => setCurrent(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
autoComplete="current-password"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
新密码(≥8 位)
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={newPw}
|
||||||
|
onChange={(e) => setNewPw(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
autoComplete="new-password"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
确认新密码
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={confirm}
|
||||||
|
onChange={(e) => setConfirm(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
autoComplete="new-password"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busy || !current || !newPw || !confirm}
|
||||||
|
onClick={() => void submit()}
|
||||||
|
className="rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white hover:bg-[#ff4d6d] disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy ? "保存中…" : "更新密码"}
|
||||||
|
</button>
|
||||||
|
{msg ? <span className="text-xs text-teal-300">{msg}</span> : null}
|
||||||
|
{error ? <span className="text-xs text-rose-300">{error}</span> : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ApiKeyPanel() {
|
||||||
|
const [required, setRequired] = useState(false);
|
||||||
|
const [key, setKey] = useState("");
|
||||||
|
const [saved, setSaved] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void fetchJson("/api/auth/status")
|
||||||
|
.then((d) => setRequired(Boolean(d.api_key_required)))
|
||||||
|
.catch(() => setRequired(false));
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
setKey(window.localStorage.getItem("dy_api_key") || "");
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
function saveKey() {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
window.localStorage.setItem("dy_api_key", key.trim());
|
||||||
|
setSaved(true);
|
||||||
|
window.setTimeout(() => setSaved(false), 2000);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mb-6 rounded-xl border border-white/10 bg-black/25 p-4">
|
||||||
|
<h3 className="mb-2 text-sm font-medium text-slate-100">API Key(写操作保护)</h3>
|
||||||
|
<p className="mb-3 text-xs text-slate-500">
|
||||||
|
服务端设置环境变量 <code className="text-slate-400">DY_API_KEY</code> 后,所有 POST/PATCH/DELETE 需携带请求头{" "}
|
||||||
|
<code className="text-slate-400">X-API-Key</code>。密钥仅存浏览器本地,不会写入服务器设置。
|
||||||
|
{required ? (
|
||||||
|
<span className="ml-1 text-amber-300">当前服务端已启用 Key 校验。</span>
|
||||||
|
) : (
|
||||||
|
<span className="ml-1 text-slate-600">当前服务端未启用(留空即无限制)。</span>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={key}
|
||||||
|
onChange={(e) => setKey(e.target.value)}
|
||||||
|
placeholder="输入与 DY_API_KEY 相同的密钥"
|
||||||
|
className="min-w-[240px] flex-1 rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm"
|
||||||
|
/>
|
||||||
|
<button type="button" onClick={saveKey} className="rounded-lg bg-white/10 px-3 py-2 text-sm hover:bg-white/15">
|
||||||
|
保存到浏览器
|
||||||
|
</button>
|
||||||
|
{saved ? <span className="text-xs text-teal-300">已保存</span> : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function OpsPanel() {
|
function OpsPanel() {
|
||||||
const [health, setHealth] = useState<Record<string, any> | null>(null);
|
const [health, setHealth] = useState<Record<string, any> | null>(null);
|
||||||
|
const [pbHealth, setPbHealth] = useState<Record<string, any> | null>(null);
|
||||||
const [busy, setBusy] = useState("");
|
const [busy, setBusy] = useState("");
|
||||||
const [log, setLog] = useState("");
|
const [log, setLog] = useState("");
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
setHealth(await fetchJson("/api/health"));
|
const [h, pb] = await Promise.all([
|
||||||
|
fetchJson("/api/health"),
|
||||||
|
fetchJson("/api/pb/health").catch(() => null),
|
||||||
|
]);
|
||||||
|
setHealth(h);
|
||||||
|
setPbHealth(pb);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setLog((e as Error).message);
|
setLog((e as Error).message);
|
||||||
}
|
}
|
||||||
@ -566,6 +812,7 @@ function OpsPanel() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const pbOk = Boolean(health?.pocketbase?.ok);
|
const pbOk = Boolean(health?.pocketbase?.ok);
|
||||||
|
const pbSync = Boolean(pbHealth?.in_sync);
|
||||||
const s3Ok = Boolean(health?.s3?.ok);
|
const s3Ok = Boolean(health?.s3?.ok);
|
||||||
const s3Enabled = Boolean(health?.s3?.enabled);
|
const s3Enabled = Boolean(health?.s3?.enabled);
|
||||||
|
|
||||||
@ -577,11 +824,17 @@ function OpsPanel() {
|
|||||||
刷新状态
|
刷新状态
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4 text-xs">
|
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-5 text-xs">
|
||||||
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
|
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
|
||||||
<div className="text-slate-500">PocketBase</div>
|
<div className="text-slate-500">PocketBase</div>
|
||||||
<div className={pbOk ? "text-teal-200" : "text-rose-200"}>{pbOk ? "正常" : "异常"}</div>
|
<div className={pbOk ? "text-teal-200" : "text-rose-200"}>{pbOk ? "正常" : "异常"}</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
|
||||||
|
<div className="text-slate-500">PB 同步漂移</div>
|
||||||
|
<div className={pbSync ? "text-teal-200" : "text-amber-200"}>
|
||||||
|
{pbHealth ? (pbSync ? "一致" : `Δ≤${pbHealth.max_abs_delta}`) : "—"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
|
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
|
||||||
<div className="text-slate-500">S3 媒体库</div>
|
<div className="text-slate-500">S3 媒体库</div>
|
||||||
<div className={s3Enabled && s3Ok ? "text-teal-200" : "text-amber-200"}>
|
<div className={s3Enabled && s3Ok ? "text-teal-200" : "text-amber-200"}>
|
||||||
@ -601,6 +854,34 @@ function OpsPanel() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{pbHealth?.drift ? (
|
||||||
|
<div className="overflow-x-auto rounded-lg border border-white/10 bg-black/20">
|
||||||
|
<table className="w-full text-left text-[11px]">
|
||||||
|
<thead className="text-slate-500">
|
||||||
|
<tr>
|
||||||
|
<th className="px-3 py-2">集合</th>
|
||||||
|
<th className="px-3 py-2">SQLite</th>
|
||||||
|
<th className="px-3 py-2">PocketBase</th>
|
||||||
|
<th className="px-3 py-2">差值</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{Object.entries(pbHealth.drift as Record<string, { sqlite?: number; pocketbase?: number; delta?: number }>).map(
|
||||||
|
([name, row]) => (
|
||||||
|
<tr key={name} className="border-t border-white/5 text-slate-300">
|
||||||
|
<td className="px-3 py-1.5">{name}</td>
|
||||||
|
<td className="px-3 py-1.5 font-mono">{row.sqlite ?? "—"}</td>
|
||||||
|
<td className="px-3 py-1.5 font-mono">{row.pocketbase ?? "—"}</td>
|
||||||
|
<td className={`px-3 py-1.5 font-mono ${Math.abs(Number(row.delta) || 0) > 0 ? "text-amber-300" : "text-teal-300"}`}>
|
||||||
|
{row.delta ?? "—"}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
{[
|
{[
|
||||||
["同步 Cookie", "/api/settings/sync-cookie"],
|
["同步 Cookie", "/api/settings/sync-cookie"],
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -1,52 +1,205 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Loader2, Radio, Search, Link2, Clapperboard, Plus } from "lucide-react";
|
import {
|
||||||
|
Clapperboard,
|
||||||
|
Eye,
|
||||||
|
EyeOff,
|
||||||
|
Loader2,
|
||||||
|
Link2,
|
||||||
|
ListVideo,
|
||||||
|
Plus,
|
||||||
|
Radio,
|
||||||
|
RefreshCw,
|
||||||
|
Save,
|
||||||
|
Search,
|
||||||
|
Trash2,
|
||||||
|
LayoutDashboard,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
import { Shell } from "@/components/Shell";
|
import { Shell } from "@/components/Shell";
|
||||||
import { fetchJson } from "@/lib/api";
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
|
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
|
||||||
|
import { fetchJson, fmtTs } from "@/lib/api";
|
||||||
|
import { shortsLiveRef } from "@/lib/youtubeLive";
|
||||||
|
|
||||||
type Tab = "channel" | "live" | "video" | "search" | "resolve";
|
type Mode = "manage" | "probe";
|
||||||
|
type ProbeTab = "channel" | "live" | "video" | "search" | "resolve";
|
||||||
|
|
||||||
|
type ManagedChannel = {
|
||||||
|
id: string;
|
||||||
|
name?: string;
|
||||||
|
youtube_channel_id?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
authorized?: boolean;
|
||||||
|
daily_min?: number;
|
||||||
|
daily_max?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type YtVideo = {
|
||||||
|
id: string;
|
||||||
|
title?: string;
|
||||||
|
description?: string;
|
||||||
|
privacyStatus?: string;
|
||||||
|
publishAt?: string;
|
||||||
|
published_at?: string;
|
||||||
|
tags?: string[];
|
||||||
|
statistics?: Record<string, string>;
|
||||||
|
thumbnails?: any;
|
||||||
|
url?: string;
|
||||||
|
shorts_url?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export default function YouTubePage() {
|
export default function YouTubePage() {
|
||||||
const [tab, setTab] = useState<Tab>("channel");
|
const confirm = useConfirm();
|
||||||
const [input, setInput] = useState("@MrBeast");
|
const toast = useToast();
|
||||||
|
const [mode, setMode] = useState<Mode>("manage");
|
||||||
|
const [channels, setChannels] = useState<ManagedChannel[]>([]);
|
||||||
|
const [channelPk, setChannelPk] = useState("");
|
||||||
|
const [dash, setDash] = useState<any>(null);
|
||||||
|
const [videos, setVideos] = useState<YtVideo[]>([]);
|
||||||
|
const [playlists, setPlaylists] = useState<any[]>([]);
|
||||||
|
const [edit, setEdit] = useState<YtVideo | null>(null);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [msg, setMsg] = useState("");
|
const [msg, setMsg] = useState("");
|
||||||
|
|
||||||
|
// probe
|
||||||
|
const [tab, setTab] = useState<ProbeTab>("channel");
|
||||||
|
const [input, setInput] = useState("@MrBeast");
|
||||||
const [result, setResult] = useState<any>(null);
|
const [result, setResult] = useState<any>(null);
|
||||||
const [svc, setSvc] = useState<any>(null);
|
const [svc, setSvc] = useState<any>(null);
|
||||||
const [addBusy, setAddBusy] = useState(false);
|
const [addBusy, setAddBusy] = useState(false);
|
||||||
|
|
||||||
|
const loadChannels = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const data = await fetchJson("/api/youtube/manage/channels");
|
||||||
|
const list = (data.channels || []).filter((c: ManagedChannel) => c.authorized);
|
||||||
|
setChannels(list);
|
||||||
|
if (!channelPk && list[0]?.id) setChannelPk(list[0].id);
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
}
|
||||||
|
}, [channelPk]);
|
||||||
|
|
||||||
|
const loadManage = useCallback(async () => {
|
||||||
|
if (!channelPk) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const [d, v, p] = await Promise.all([
|
||||||
|
fetchJson(`/api/youtube/manage/${channelPk}/dashboard`),
|
||||||
|
fetchJson(`/api/youtube/manage/${channelPk}/videos?max_results=25`),
|
||||||
|
fetchJson(`/api/youtube/manage/${channelPk}/playlists`).catch(() => ({ playlists: [] })),
|
||||||
|
]);
|
||||||
|
setDash(d);
|
||||||
|
setVideos(v.videos || []);
|
||||||
|
setPlaylists(p.playlists || []);
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
setDash(null);
|
||||||
|
setVideos([]);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}, [channelPk]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadChannels();
|
||||||
|
}, [loadChannels]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (mode === "manage" && channelPk) void loadManage();
|
||||||
|
}, [mode, channelPk, loadManage]);
|
||||||
|
|
||||||
|
async function saveVideo() {
|
||||||
|
if (!edit || !channelPk) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
setMsg("");
|
||||||
|
try {
|
||||||
|
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${edit.id}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify({
|
||||||
|
title: edit.title,
|
||||||
|
description: edit.description,
|
||||||
|
tags: edit.tags || [],
|
||||||
|
privacy_status: edit.privacyStatus,
|
||||||
|
publish_at: edit.publishAt || "",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
setMsg("视频已更新");
|
||||||
|
setEdit(null);
|
||||||
|
await loadManage();
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setPrivacy(videoId: string, privacy: string) {
|
||||||
|
if (!channelPk) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify({ privacy_status: privacy }),
|
||||||
|
});
|
||||||
|
setMsg(`已设为 ${privacy}`);
|
||||||
|
await loadManage();
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeVideo(videoId: string) {
|
||||||
|
if (!channelPk) return;
|
||||||
|
const ok = await confirm({
|
||||||
|
title: "删除 YouTube 视频",
|
||||||
|
message: "确定从 YouTube 删除该视频?此操作不可恢复。",
|
||||||
|
confirmLabel: "删除",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, { method: "DELETE" });
|
||||||
|
toast.push("视频已删除", "ok");
|
||||||
|
await loadManage();
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function checkSvc() {
|
async function checkSvc() {
|
||||||
try {
|
try {
|
||||||
const h = await fetchJson("/api/youtube/health");
|
setSvc(await fetchJson("/api/youtube/health"));
|
||||||
setSvc(h);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setSvc({ ok: false, error: (e as Error).message });
|
setSvc({ ok: false, error: (e as Error).message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function run() {
|
async function runProbe() {
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError("");
|
setError("");
|
||||||
setMsg("");
|
setMsg("");
|
||||||
setResult(null);
|
setResult(null);
|
||||||
try {
|
try {
|
||||||
let data: any;
|
|
||||||
const q = encodeURIComponent(input.trim());
|
const q = encodeURIComponent(input.trim());
|
||||||
if (tab === "channel") {
|
let data: any;
|
||||||
data = await fetchJson(`/api/youtube/channel?url=${q}&videos=1&limit=8`);
|
if (tab === "channel") data = await fetchJson(`/api/youtube/channel?url=${q}&videos=1&limit=8`);
|
||||||
} else if (tab === "live") {
|
else if (tab === "live") data = await fetchJson(`/api/youtube/channel/live?url=${q}`);
|
||||||
data = await fetchJson(`/api/youtube/channel/live?url=${q}`);
|
else if (tab === "video") data = await fetchJson(`/api/youtube/video?url=${q}`);
|
||||||
} else if (tab === "video") {
|
else if (tab === "search") data = await fetchJson(`/api/youtube/search?q=${q}&limit=12`);
|
||||||
data = await fetchJson(`/api/youtube/video?url=${q}`);
|
else data = await fetchJson(`/api/youtube/resolve?url=${q}`);
|
||||||
} else if (tab === "search") {
|
|
||||||
data = await fetchJson(`/api/youtube/search?q=${q}&limit=12`);
|
|
||||||
} else {
|
|
||||||
data = await fetchJson(`/api/youtube/resolve?url=${q}`);
|
|
||||||
}
|
|
||||||
setResult(data);
|
setResult(data);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError((e as Error).message);
|
setError((e as Error).message);
|
||||||
@ -61,24 +214,22 @@ export default function YouTubePage() {
|
|||||||
(channel?.handle ? `https://www.youtube.com/@${String(channel.handle).replace(/^@/, "")}` : "") ||
|
(channel?.handle ? `https://www.youtube.com/@${String(channel.handle).replace(/^@/, "")}` : "") ||
|
||||||
String(channel?.channel_id || input.trim());
|
String(channel?.channel_id || input.trim());
|
||||||
if (!channelUrl) {
|
if (!channelUrl) {
|
||||||
setError("缺少频道 URL,无法加入分组");
|
setError("缺少频道 URL");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setAddBusy(true);
|
setAddBusy(true);
|
||||||
setError("");
|
|
||||||
setMsg("");
|
|
||||||
try {
|
try {
|
||||||
await fetchJson("/api/groups", {
|
await fetchJson("/api/groups", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
name: String(channel?.title || channel?.handle || channel?.channel_id || "YouTube 频道").slice(0, 80),
|
name: String(channel?.title || channel?.handle || "YouTube 频道").slice(0, 80),
|
||||||
channel_url: channelUrl,
|
channel_url: channelUrl,
|
||||||
platform: "youtube",
|
platform: "youtube",
|
||||||
enabled: true,
|
enabled: true,
|
||||||
note: "从 YouTube 探测页加入",
|
note: "从 YouTube 探测页加入",
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
setMsg("已加入分组监控,可前往「分组」查看轮询状态");
|
setMsg("已加入分组监控");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError((e as Error).message);
|
setError((e as Error).message);
|
||||||
} finally {
|
} finally {
|
||||||
@ -86,251 +237,430 @@ export default function YouTubePage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const tabs: { id: Tab; label: string; icon: React.ReactNode; hint: string }[] = [
|
const profile = dash?.profile;
|
||||||
{ id: "channel", label: "频道", icon: <Radio className="h-3.5 w-3.5" />, hint: "频道资料 + 直播状态 + 近期视频" },
|
const shortsToday = dash?.shorts_today?.by_status || {};
|
||||||
{ id: "live", label: "开播检测", icon: <Clapperboard className="h-3.5 w-3.5" />, hint: "仅检测是否正在直播 / 预告" },
|
const probeChannel = result?.channel;
|
||||||
{ id: "video", label: "视频", icon: <Clapperboard className="h-3.5 w-3.5" />, hint: "视频详情 / is_live" },
|
const live = result?.live || probeChannel?.live;
|
||||||
{ id: "search", label: "搜索", icon: <Search className="h-3.5 w-3.5" />, hint: "InnerTube 搜索" },
|
const probeVideos = result?.results || probeChannel?.videos || [];
|
||||||
{ id: "resolve", label: "解析 URL", icon: <Link2 className="h-3.5 w-3.5" />, hint: "把 @handle / 短链解析为 ID" },
|
|
||||||
];
|
|
||||||
|
|
||||||
const channel = result?.channel;
|
|
||||||
const live = result?.live || channel?.live;
|
|
||||||
const videos = result?.results || channel?.videos || [];
|
|
||||||
const liveChannelHint = !channel && result && (result.channel_id || result.handle || result.url);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Shell>
|
<Shell>
|
||||||
<div className="mb-4 flex flex-wrap items-end justify-between gap-3">
|
<div className="mb-5 flex flex-wrap items-end justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="font-display text-2xl font-semibold">▶️ YouTube 模块</h2>
|
<p className="font-display text-xs uppercase tracking-[0.28em] text-rose-300/80">YouTube Studio Lite</p>
|
||||||
<p className="text-sm text-slate-400">
|
<h2 className="font-display text-3xl font-semibold">▶️ YouTube</h2>
|
||||||
基于开源{" "}
|
<p className="mt-1 max-w-2xl text-sm text-slate-400">
|
||||||
<a
|
已授权频道:片库 / 改元数据 / 可见性 / 定时公开 / 删除 / 播放列表只读。探测仍用 InnerTube。
|
||||||
href="https://github.com/LuanRT/YouTube.js"
|
|
||||||
target="_blank"
|
|
||||||
rel="noreferrer"
|
|
||||||
className="text-teal-300 hover:underline"
|
|
||||||
>
|
|
||||||
YouTube.js / youtubei.js
|
|
||||||
</a>{" "}
|
|
||||||
InnerTube 客户端;探测后可一键加入分组监控。
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
<Link href="/groups" className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10">
|
<Link href="/shorts" className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10">
|
||||||
|
Shorts →
|
||||||
|
</Link>
|
||||||
|
<Link href="/groups" className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10">
|
||||||
分组监控 →
|
分组监控 →
|
||||||
</Link>
|
</Link>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => void checkSvc()}
|
|
||||||
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
|
|
||||||
>
|
|
||||||
检查服务 {svc ? (svc.ok ? "· 正常" : "· 异常") : ""}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{svc ? (
|
<div className="mb-4 flex flex-wrap gap-2">
|
||||||
<div
|
<button
|
||||||
className={`mb-4 rounded-lg border px-4 py-3 text-sm ${
|
type="button"
|
||||||
svc.ok ? "border-teal-500/30 bg-teal-500/10" : "border-rose-500/30 bg-rose-500/10"
|
onClick={() => setMode("manage")}
|
||||||
|
className={`inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-sm ${
|
||||||
|
mode === "manage" ? "bg-rose-500/20 text-rose-50 ring-1 ring-rose-400/30" : "bg-white/5 text-slate-400"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{svc.ok
|
<LayoutDashboard className="h-3.5 w-3.5" />
|
||||||
? `youtube-svc 就绪 · ${svc.engine || "youtubei.js"}`
|
频道管理(OAuth)
|
||||||
: `youtube-svc 不可用:${svc.error || "unknown"}`}
|
</button>
|
||||||
</div>
|
<button
|
||||||
) : null}
|
type="button"
|
||||||
|
onClick={() => setMode("probe")}
|
||||||
<div className="mb-3 flex flex-wrap gap-2">
|
className={`inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-sm ${
|
||||||
{tabs.map((t) => (
|
mode === "probe" ? "bg-teal-500/20 text-teal-50 ring-1 ring-teal-400/30" : "bg-white/5 text-slate-400"
|
||||||
<button
|
}`}
|
||||||
key={t.id}
|
>
|
||||||
type="button"
|
<Search className="h-3.5 w-3.5" />
|
||||||
onClick={() => setTab(t.id)}
|
公开探测(InnerTube)
|
||||||
className={`inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-sm ${
|
</button>
|
||||||
tab === t.id
|
|
||||||
? "bg-white/15 text-white ring-1 ring-teal-400/30"
|
|
||||||
: "bg-white/5 text-slate-400 hover:bg-white/10 hover:text-white"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{t.icon}
|
|
||||||
{t.label}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mb-4 rounded-xl border border-white/10 bg-black/30 p-4">
|
{msg ? <div className="mb-3 text-sm text-teal-300">{msg}</div> : null}
|
||||||
<p className="mb-2 text-xs text-slate-500">{tabs.find((t) => t.id === tab)?.hint}</p>
|
{error ? <div className="mb-3 text-sm text-rose-300">{error}</div> : null}
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
<input
|
|
||||||
value={input}
|
|
||||||
onChange={(e) => setInput(e.target.value)}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === "Enter") void run();
|
|
||||||
}}
|
|
||||||
placeholder={
|
|
||||||
tab === "search"
|
|
||||||
? "搜索关键词"
|
|
||||||
: tab === "video"
|
|
||||||
? "视频 URL / ID"
|
|
||||||
: "频道 URL / @handle / UC…"
|
|
||||||
}
|
|
||||||
className="min-w-[240px] flex-1 rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
disabled={!input.trim() || busy}
|
|
||||||
onClick={() => void run()}
|
|
||||||
className="inline-flex items-center gap-2 rounded-lg bg-teal-500/20 px-4 py-2 text-sm text-teal-100 ring-1 ring-teal-400/30 disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
|
||||||
查询
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
|
{mode === "manage" ? (
|
||||||
{msg ? <div className="mb-4 rounded-lg border border-teal-500/30 bg-teal-500/10 px-4 py-3 text-sm">{msg}</div> : null}
|
<>
|
||||||
|
{channels.length === 0 ? (
|
||||||
{channel ? (
|
<div className="rounded-2xl border border-dashed border-amber-500/30 bg-amber-500/5 px-4 py-10 text-center text-sm text-amber-100">
|
||||||
<div className="mb-4 grid gap-4 rounded-xl border border-white/10 bg-black/20 p-4 md:grid-cols-[auto_1fr_auto]">
|
还没有已授权频道。请先到{" "}
|
||||||
{channel.avatar ? (
|
<Link href="/shorts" className="underline">
|
||||||
// eslint-disable-next-line @next/next/no-img-element
|
Shorts
|
||||||
<img src={channel.avatar} alt="" className="h-20 w-20 rounded-full object-cover" />
|
</Link>{" "}
|
||||||
) : (
|
完成 Google 授权。
|
||||||
<div className="h-20 w-20 rounded-full bg-white/10" />
|
|
||||||
)}
|
|
||||||
<div>
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
<h3 className="font-display text-xl text-white">{channel.title || "—"}</h3>
|
|
||||||
{channel.is_live ? (
|
|
||||||
<span className="rounded bg-rose-500/20 px-2 py-0.5 text-xs text-rose-200 ring-1 ring-rose-400/30">LIVE</span>
|
|
||||||
) : (
|
|
||||||
<span className="rounded bg-white/10 px-2 py-0.5 text-xs text-slate-400">离线</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1 font-mono text-xs text-slate-400">
|
) : (
|
||||||
{channel.handle ? `@${String(channel.handle).replace(/^@/, "")}` : ""} {channel.channel_id}
|
<>
|
||||||
</p>
|
<div className="mb-4 flex flex-wrap items-center gap-2">
|
||||||
<p className="mt-1 text-sm text-slate-400">{channel.subscribers || ""}</p>
|
<select
|
||||||
{live ? (
|
value={channelPk}
|
||||||
<a href={live.url} target="_blank" rel="noreferrer" className="mt-2 inline-block text-sm text-teal-300 hover:underline">
|
onChange={(e) => setChannelPk(e.target.value)}
|
||||||
正在直播:{live.title}
|
className="min-w-[220px] rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
</a>
|
>
|
||||||
) : null}
|
{channels.map((c) => (
|
||||||
{channel.url ? (
|
<option key={c.id} value={c.id}>
|
||||||
<div className="mt-2">
|
{c.name} {c.youtube_channel_id ? `(${c.youtube_channel_id.slice(0, 8)}…)` : ""}
|
||||||
<a href={channel.url} target="_blank" rel="noreferrer" className="text-xs text-slate-500 hover:text-teal-300">
|
</option>
|
||||||
打开频道
|
))}
|
||||||
</a>
|
</select>
|
||||||
|
{channelPk ? <YouTubeLiveBadge refKey={shortsLiveRef(channelPk)} /> : null}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void loadManage()}
|
||||||
|
className="inline-flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
|
||||||
|
>
|
||||||
|
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
|
||||||
|
刷新
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
|
||||||
|
{profile ? (
|
||||||
|
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<div className="rounded-2xl border border-white/10 bg-black/30 p-4 sm:col-span-2">
|
||||||
|
<div className="flex gap-3">
|
||||||
|
{profile.thumbnails?.default?.url || profile.thumbnails?.medium?.url ? (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<img
|
||||||
|
src={profile.thumbnails?.medium?.url || profile.thumbnails?.default?.url}
|
||||||
|
alt=""
|
||||||
|
className="h-14 w-14 rounded-full object-cover"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="h-14 w-14 rounded-full bg-white/10" />
|
||||||
|
)}
|
||||||
|
<div>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<div className="font-display text-xl text-white">{profile.title}</div>
|
||||||
|
{channelPk ? <YouTubeLiveBadge refKey={shortsLiveRef(channelPk)} compact /> : null}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-slate-500">{profile.custom_url || profile.youtube_channel_id}</div>
|
||||||
|
<div className="mt-1 text-xs text-slate-400">
|
||||||
|
订阅 {profile.statistics?.subscriberCount ?? "—"} · 视频 {profile.statistics?.videoCount ?? "—"} · 播放{" "}
|
||||||
|
{profile.statistics?.viewCount ?? "—"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-white/10 bg-black/30 p-4">
|
||||||
|
<div className="text-xs text-slate-500">今日 Shorts 流水</div>
|
||||||
|
<div className="mt-2 space-y-1 text-xs text-slate-300">
|
||||||
|
{Object.keys(shortsToday).length === 0 ? (
|
||||||
|
<span className="text-slate-500">无</span>
|
||||||
|
) : (
|
||||||
|
Object.entries(shortsToday).map(([k, v]) => (
|
||||||
|
<div key={k} className="flex justify-between">
|
||||||
|
<span>{k}</span>
|
||||||
|
<span>{String(v)}</span>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-white/10 bg-black/30 p-4">
|
||||||
|
<div className="text-xs text-slate-500">播放列表</div>
|
||||||
|
<div className="mt-2 font-display text-2xl text-white">{playlists.length}</div>
|
||||||
|
<div className="text-[11px] text-slate-500">只读(当前 OAuth scope)</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="mb-6 grid gap-4 xl:grid-cols-[1.5fr_1fr]">
|
||||||
|
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||||
|
<h3 className="mb-3 text-sm font-medium text-slate-100">近期上传</h3>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{videos.length === 0 ? (
|
||||||
|
<div className="py-8 text-center text-sm text-slate-500">暂无视频或加载失败</div>
|
||||||
|
) : (
|
||||||
|
videos.map((v) => (
|
||||||
|
<div key={v.id} className="flex gap-3 rounded-xl border border-white/10 bg-black/40 p-2.5">
|
||||||
|
{v.thumbnails?.medium?.url || v.thumbnails?.default?.url ? (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<img
|
||||||
|
src={v.thumbnails?.medium?.url || v.thumbnails?.default?.url}
|
||||||
|
alt=""
|
||||||
|
className="h-16 w-28 shrink-0 rounded-lg object-cover"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="h-16 w-28 shrink-0 rounded-lg bg-white/10" />
|
||||||
|
)}
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="truncate text-sm text-slate-100">{v.title}</div>
|
||||||
|
<div className="mt-0.5 text-[11px] text-slate-500">
|
||||||
|
{v.privacyStatus} · 播放 {v.statistics?.viewCount ?? 0} ·{" "}
|
||||||
|
{v.published_at ? fmtTs(Date.parse(v.published_at) / 1000) : "—"}
|
||||||
|
{v.publishAt ? ` · 定时 ${v.publishAt}` : ""}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setEdit({ ...v })}
|
||||||
|
className="rounded-lg bg-white/5 px-2 py-1 text-[11px]"
|
||||||
|
>
|
||||||
|
编辑
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void setPrivacy(v.id, "public")}
|
||||||
|
className="inline-flex items-center gap-1 rounded-lg bg-teal-500/15 px-2 py-1 text-[11px] text-teal-100"
|
||||||
|
>
|
||||||
|
<Eye className="h-3 w-3" />
|
||||||
|
公开
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void setPrivacy(v.id, "unlisted")}
|
||||||
|
className="rounded-lg bg-amber-500/15 px-2 py-1 text-[11px] text-amber-100"
|
||||||
|
>
|
||||||
|
不公开列出
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void setPrivacy(v.id, "private")}
|
||||||
|
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px]"
|
||||||
|
>
|
||||||
|
<EyeOff className="h-3 w-3" />
|
||||||
|
私密
|
||||||
|
</button>
|
||||||
|
<a
|
||||||
|
href={v.shorts_url || v.url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="rounded-lg bg-white/5 px-2 py-1 text-[11px] text-slate-300"
|
||||||
|
>
|
||||||
|
打开
|
||||||
|
</a>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void removeVideo(v.id)}
|
||||||
|
className="inline-flex items-center gap-1 rounded-lg bg-rose-500/15 px-2 py-1 text-[11px] text-rose-200"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
删
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="space-y-4">
|
||||||
|
{edit ? (
|
||||||
|
<div className="rounded-2xl border border-rose-500/25 bg-black/40 p-4">
|
||||||
|
<h3 className="mb-3 text-sm font-medium text-slate-100">编辑视频</h3>
|
||||||
|
<label className="mb-2 block text-xs text-slate-400">
|
||||||
|
标题
|
||||||
|
<input
|
||||||
|
value={edit.title || ""}
|
||||||
|
onChange={(e) => setEdit({ ...edit, title: e.target.value })}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="mb-2 block text-xs text-slate-400">
|
||||||
|
描述
|
||||||
|
<textarea
|
||||||
|
value={edit.description || ""}
|
||||||
|
onChange={(e) => setEdit({ ...edit, description: e.target.value })}
|
||||||
|
rows={5}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="mb-2 block text-xs text-slate-400">
|
||||||
|
标签(逗号分隔)
|
||||||
|
<input
|
||||||
|
value={(edit.tags || []).join(", ")}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEdit({
|
||||||
|
...edit,
|
||||||
|
tags: e.target.value
|
||||||
|
.split(",")
|
||||||
|
.map((t) => t.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="mb-2 block text-xs text-slate-400">
|
||||||
|
可见性
|
||||||
|
<select
|
||||||
|
value={edit.privacyStatus || "public"}
|
||||||
|
onChange={(e) => setEdit({ ...edit, privacyStatus: e.target.value })}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
>
|
||||||
|
<option value="public">public</option>
|
||||||
|
<option value="unlisted">unlisted</option>
|
||||||
|
<option value="private">private</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="mb-3 block text-xs text-slate-400">
|
||||||
|
定时公开(UTC ISO,如 2026-08-10T12:00:00Z;填写后会先设为 private)
|
||||||
|
<input
|
||||||
|
value={edit.publishAt || ""}
|
||||||
|
onChange={(e) => setEdit({ ...edit, publishAt: e.target.value })}
|
||||||
|
placeholder="2026-08-10T12:00:00Z"
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void saveVideo()}
|
||||||
|
className="inline-flex items-center gap-1 rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white"
|
||||||
|
>
|
||||||
|
<Save className="h-3.5 w-3.5" />
|
||||||
|
保存
|
||||||
|
</button>
|
||||||
|
<button type="button" onClick={() => setEdit(null)} className="rounded-lg bg-white/5 px-3 py-2 text-sm">
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="rounded-2xl border border-dashed border-white/10 px-4 py-8 text-center text-sm text-slate-500">
|
||||||
|
选择左侧视频点「编辑」可改标题/描述/标签/可见性/定时公开
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||||
|
<div className="mb-2 flex items-center gap-2 text-sm text-slate-100">
|
||||||
|
<ListVideo className="h-4 w-4 text-rose-300" />
|
||||||
|
播放列表
|
||||||
|
</div>
|
||||||
|
<div className="max-h-56 space-y-1 overflow-y-auto text-xs text-slate-400">
|
||||||
|
{playlists.length === 0 ? (
|
||||||
|
<div>无播放列表</div>
|
||||||
|
) : (
|
||||||
|
playlists.map((p) => (
|
||||||
|
<div key={p.id} className="flex justify-between gap-2 border-b border-white/5 py-1.5">
|
||||||
|
<span className="truncate text-slate-200">{p.title}</span>
|
||||||
|
<span>
|
||||||
|
{p.itemCount ?? 0} · {p.privacyStatus}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="mb-3 flex flex-wrap gap-2">
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
["channel", "频道", <Radio key="a" className="h-3.5 w-3.5" />],
|
||||||
|
["live", "开播检测", <Clapperboard key="b" className="h-3.5 w-3.5" />],
|
||||||
|
["video", "视频", <Clapperboard key="c" className="h-3.5 w-3.5" />],
|
||||||
|
["search", "搜索", <Search key="d" className="h-3.5 w-3.5" />],
|
||||||
|
["resolve", "解析 URL", <Link2 key="e" className="h-3.5 w-3.5" />],
|
||||||
|
] as const
|
||||||
|
).map(([id, label, icon]) => (
|
||||||
|
<button
|
||||||
|
key={id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setTab(id)}
|
||||||
|
className={`inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-sm ${
|
||||||
|
tab === id ? "bg-teal-500/20 text-teal-50" : "bg-white/5 text-slate-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
<button type="button" onClick={() => void checkSvc()} className="rounded-xl bg-white/5 px-3 py-1.5 text-sm">
|
||||||
|
检查 youtube-svc {svc ? (svc.ok ? "· 正常" : "· 异常") : ""}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-2 self-center">
|
|
||||||
|
<div className="mb-4 flex flex-wrap gap-2">
|
||||||
|
<input
|
||||||
|
value={input}
|
||||||
|
onChange={(e) => setInput(e.target.value)}
|
||||||
|
className="min-w-[240px] flex-1 rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
placeholder="@handle / URL / 关键词"
|
||||||
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={addBusy}
|
disabled={busy}
|
||||||
onClick={() => void addToGroup(channel)}
|
onClick={() => void runProbe()}
|
||||||
className="inline-flex items-center justify-center gap-1.5 rounded-lg bg-rose-500/20 px-3 py-2 text-sm text-rose-100 ring-1 ring-rose-400/30 hover:bg-rose-500/30 disabled:opacity-50"
|
className="inline-flex items-center gap-1 rounded-xl bg-[#ff2d55] px-4 py-2 text-sm text-white"
|
||||||
>
|
>
|
||||||
{addBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
|
||||||
加入分组监控
|
探测
|
||||||
</button>
|
</button>
|
||||||
<Link href="/groups" className="text-center text-xs text-slate-500 hover:text-teal-300">
|
|
||||||
查看全部分组
|
|
||||||
</Link>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{liveChannelHint ? (
|
{probeChannel ? (
|
||||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-white/10 bg-black/20 p-4 text-sm">
|
<div className="mb-4 rounded-2xl border border-white/10 bg-black/30 p-4">
|
||||||
<div>
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||||
<div className="font-medium text-white">{result.title || result.channel_id || "频道"}</div>
|
<div>
|
||||||
<div className="mt-1 text-slate-400">{result.is_live ? "直播中" : "当前未开播"}</div>
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
{result.live?.url ? (
|
<div className="font-display text-xl">{probeChannel.title}</div>
|
||||||
<a href={result.live.url} target="_blank" rel="noreferrer" className="mt-2 inline-block text-teal-300 hover:underline">
|
{live?.is_live ? (
|
||||||
{result.live.title}
|
<YouTubeLiveBadge
|
||||||
</a>
|
entry={{
|
||||||
) : null}
|
is_live: true,
|
||||||
</div>
|
live_url: live.url || live.watch_url,
|
||||||
<button
|
title: live.title,
|
||||||
type="button"
|
}}
|
||||||
disabled={addBusy}
|
/>
|
||||||
onClick={() =>
|
) : null}
|
||||||
void addToGroup({
|
</div>
|
||||||
title: result.title,
|
<div className="text-xs text-slate-500">{probeChannel.url || probeChannel.handle}</div>
|
||||||
handle: result.handle,
|
</div>
|
||||||
channel_id: result.channel_id,
|
<button
|
||||||
url: result.url || input.trim(),
|
type="button"
|
||||||
})
|
disabled={addBusy}
|
||||||
}
|
onClick={() => void addToGroup(probeChannel)}
|
||||||
className="inline-flex items-center gap-1.5 rounded-lg bg-rose-500/20 px-3 py-2 text-sm text-rose-100 ring-1 ring-rose-400/30 disabled:opacity-50"
|
className="inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100"
|
||||||
>
|
>
|
||||||
{addBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
|
<Plus className="h-3.5 w-3.5" />
|
||||||
加入分组监控
|
加入分组
|
||||||
</button>
|
</button>
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{result && !channel && !liveChannelHint && (result.is_live != null || result.video) ? (
|
|
||||||
<div className="mb-4 rounded-xl border border-white/10 bg-black/20 p-4 text-sm">
|
|
||||||
{result.video ? (
|
|
||||||
<>
|
|
||||||
<div className="font-medium text-white">{result.video.title}</div>
|
|
||||||
<div className="mt-1 text-slate-400">
|
|
||||||
{result.video.channel} · {result.video.is_live ? "直播中" : result.video.is_upcoming ? "即将开始" : "点播"}
|
|
||||||
</div>
|
</div>
|
||||||
<a href={result.video.url} target="_blank" rel="noreferrer" className="mt-2 inline-block text-teal-300 hover:underline">
|
</div>
|
||||||
打开视频
|
) : null}
|
||||||
</a>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className="font-medium text-white">{result.title || result.channel_id}</div>
|
|
||||||
<div className="mt-1 text-slate-400">{result.is_live ? "直播中" : "当前未开播"}</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{Array.isArray(videos) && videos.length > 0 ? (
|
{probeVideos?.length ? (
|
||||||
<div className="mb-4 overflow-hidden rounded-xl border border-white/10 bg-black/20">
|
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
<table className="min-w-full text-left text-sm">
|
{probeVideos.map((v: any, i: number) => (
|
||||||
<thead className="bg-white/5 text-xs uppercase text-slate-400">
|
<a
|
||||||
<tr>
|
key={v.id || v.url || i}
|
||||||
<th className="px-3 py-3">标题</th>
|
href={v.url || "#"}
|
||||||
<th className="px-3 py-3">状态</th>
|
target="_blank"
|
||||||
<th className="px-3 py-3">播放</th>
|
rel="noreferrer"
|
||||||
</tr>
|
className="rounded-xl border border-white/10 bg-black/30 p-3 text-sm hover:bg-white/5"
|
||||||
</thead>
|
>
|
||||||
<tbody>
|
<div className="font-medium text-slate-100">{v.title || "video"}</div>
|
||||||
{videos.map((v: any) => (
|
<div className="mt-1 text-xs text-slate-500">{v.id}</div>
|
||||||
<tr key={v.id || v.url} className="border-t border-white/5">
|
</a>
|
||||||
<td className="px-3 py-3">
|
|
||||||
<a href={v.url} target="_blank" rel="noreferrer" className="text-teal-200 hover:underline">
|
|
||||||
{v.title || v.id}
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
<td className="px-3 py-3 text-slate-400">
|
|
||||||
{v.is_live ? "LIVE" : v.is_upcoming ? "预告" : "—"}
|
|
||||||
</td>
|
|
||||||
<td className="px-3 py-3 text-slate-500">{v.view_count || v.published || "—"}</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</div>
|
||||||
</table>
|
) : null}
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{result ? (
|
{result && !probeChannel && !probeVideos?.length ? (
|
||||||
<details className="rounded-xl border border-white/10 bg-black/20 p-4">
|
<pre className="mt-4 overflow-x-auto rounded-xl border border-white/10 bg-black/40 p-3 text-xs text-slate-400">
|
||||||
<summary className="cursor-pointer text-sm text-slate-400">原始 JSON</summary>
|
{JSON.stringify(result, null, 2)}
|
||||||
<pre className="mt-3 max-h-[420px] overflow-auto text-xs text-slate-300">{JSON.stringify(result, null, 2)}</pre>
|
</pre>
|
||||||
</details>
|
) : null}
|
||||||
) : null}
|
</>
|
||||||
|
)}
|
||||||
</Shell>
|
</Shell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
94
frontend/src/components/ConfirmDialog.tsx
Normal file
94
frontend/src/components/ConfirmDialog.tsx
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
|
||||||
|
import { Loader2 } from "lucide-react";
|
||||||
|
|
||||||
|
import { Modal } from "@/components/Modal";
|
||||||
|
|
||||||
|
export type ConfirmOptions = {
|
||||||
|
title: string;
|
||||||
|
message?: string;
|
||||||
|
confirmLabel?: string;
|
||||||
|
cancelLabel?: string;
|
||||||
|
destructive?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Pending = ConfirmOptions & {
|
||||||
|
resolve: (ok: boolean) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ConfirmCtx = createContext<(opts: ConfirmOptions) => Promise<boolean>>(async () => false);
|
||||||
|
|
||||||
|
export function ConfirmProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [pending, setPending] = useState<Pending | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
const confirm = useCallback((opts: ConfirmOptions) => {
|
||||||
|
return new Promise<boolean>((resolve) => {
|
||||||
|
setPending({ ...opts, resolve });
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const close = useCallback(
|
||||||
|
(ok: boolean) => {
|
||||||
|
pending?.resolve(ok);
|
||||||
|
setPending(null);
|
||||||
|
setBusy(false);
|
||||||
|
},
|
||||||
|
[pending],
|
||||||
|
);
|
||||||
|
|
||||||
|
const value = useMemo(() => confirm, [confirm]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ConfirmCtx.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
<Modal
|
||||||
|
open={Boolean(pending)}
|
||||||
|
onClose={() => close(false)}
|
||||||
|
panelClassName="w-full max-w-md rounded-2xl border border-white/10 bg-[#0b1626] p-0 shadow-2xl"
|
||||||
|
>
|
||||||
|
{pending ? (
|
||||||
|
<>
|
||||||
|
<div className="border-b border-white/10 px-5 py-4">
|
||||||
|
<h3 className="font-display text-lg font-semibold text-white">{pending.title}</h3>
|
||||||
|
{pending.message ? (
|
||||||
|
<p className="mt-2 text-sm leading-relaxed text-slate-400">{pending.message}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 px-5 py-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => close(false)}
|
||||||
|
className="flex-1 rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-slate-300 hover:bg-white/10"
|
||||||
|
>
|
||||||
|
{pending.cancelLabel || "取消"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => {
|
||||||
|
setBusy(true);
|
||||||
|
close(true);
|
||||||
|
}}
|
||||||
|
className={`inline-flex flex-1 items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium text-white ${
|
||||||
|
pending.destructive
|
||||||
|
? "bg-rose-500 hover:bg-rose-400"
|
||||||
|
: "bg-teal-500 hover:bg-teal-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
||||||
|
{pending.confirmLabel || "确认"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</Modal>
|
||||||
|
</ConfirmCtx.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useConfirm() {
|
||||||
|
return useContext(ConfirmCtx);
|
||||||
|
}
|
||||||
@ -11,6 +11,9 @@ type NotifyFlags = {
|
|||||||
live: boolean;
|
live: boolean;
|
||||||
offline: boolean;
|
offline: boolean;
|
||||||
risk: boolean;
|
risk: boolean;
|
||||||
|
shortsFail: boolean;
|
||||||
|
shortsOk: boolean;
|
||||||
|
shortsQuota: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
function applyFlags(s: Record<string, unknown>): NotifyFlags {
|
function applyFlags(s: Record<string, unknown>): NotifyFlags {
|
||||||
@ -18,6 +21,9 @@ function applyFlags(s: Record<string, unknown>): NotifyFlags {
|
|||||||
live: s.notify_on_live !== false,
|
live: s.notify_on_live !== false,
|
||||||
offline: Boolean(s.notify_on_offline),
|
offline: Boolean(s.notify_on_offline),
|
||||||
risk: s.notify_on_risk !== false,
|
risk: s.notify_on_risk !== false,
|
||||||
|
shortsFail: s.notify_on_shorts_fail !== false,
|
||||||
|
shortsOk: Boolean(s.notify_on_shorts_ok),
|
||||||
|
shortsQuota: s.notify_on_shorts_quota !== false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -28,7 +34,14 @@ function applyFlags(s: Record<string, unknown>): NotifyFlags {
|
|||||||
export function GlobalEventAlerts() {
|
export function GlobalEventAlerts() {
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const { last, tick } = useEventStream(true);
|
const { last, tick } = useEventStream(true);
|
||||||
const flagsRef = useRef<NotifyFlags>({ live: true, offline: false, risk: true });
|
const flagsRef = useRef<NotifyFlags>({
|
||||||
|
live: true,
|
||||||
|
offline: false,
|
||||||
|
risk: true,
|
||||||
|
shortsFail: true,
|
||||||
|
shortsOk: false,
|
||||||
|
shortsQuota: true,
|
||||||
|
});
|
||||||
const seenRef = useRef<Set<string>>(new Set());
|
const seenRef = useRef<Set<string>>(new Set());
|
||||||
const [detail, setDetail] = useState<SessionDetail | null>(null);
|
const [detail, setDetail] = useState<SessionDetail | null>(null);
|
||||||
|
|
||||||
@ -63,11 +76,14 @@ export function GlobalEventAlerts() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!last?.message) return;
|
if (!last?.message) return;
|
||||||
const kind = last.kind || "";
|
const kind = last.kind || "";
|
||||||
if (!["live", "offline", "risk"].includes(kind)) return;
|
if (!["live", "offline", "risk", "shorts_fail", "shorts_ok", "shorts_quota"].includes(kind)) return;
|
||||||
const flags = flagsRef.current;
|
const flags = flagsRef.current;
|
||||||
if (kind === "live" && !flags.live) return;
|
if (kind === "live" && !flags.live) return;
|
||||||
if (kind === "offline" && !flags.offline) return;
|
if (kind === "offline" && !flags.offline) return;
|
||||||
if (kind === "risk" && !flags.risk) return;
|
if (kind === "risk" && !flags.risk) return;
|
||||||
|
if (kind === "shorts_fail" && !flags.shortsFail) return;
|
||||||
|
if (kind === "shorts_ok" && !flags.shortsOk) return;
|
||||||
|
if (kind === "shorts_quota" && !flags.shortsQuota) return;
|
||||||
|
|
||||||
const key = String(last.id || `${kind}:${last.message}:${last.ts || tick}`);
|
const key = String(last.id || `${kind}:${last.message}:${last.ts || tick}`);
|
||||||
if (seenRef.current.has(key)) return;
|
if (seenRef.current.has(key)) return;
|
||||||
@ -77,45 +93,75 @@ export function GlobalEventAlerts() {
|
|||||||
seenRef.current = new Set(keep);
|
seenRef.current = new Set(keep);
|
||||||
}
|
}
|
||||||
|
|
||||||
const tone = kind === "risk" ? "warn" : kind === "offline" ? "err" : "ok";
|
const tone =
|
||||||
|
kind === "risk" || kind === "shorts_fail" || kind === "shorts_quota"
|
||||||
|
? "warn"
|
||||||
|
: kind === "offline"
|
||||||
|
? "err"
|
||||||
|
: "ok";
|
||||||
const sid = last.session_id;
|
const sid = last.session_id;
|
||||||
const meta = (last.meta && typeof last.meta === "object" ? last.meta : {}) as Record<string, unknown>;
|
const meta = (last.meta && typeof last.meta === "object" ? last.meta : {}) as Record<string, unknown>;
|
||||||
const isYt = meta.platform === "youtube" || String(last.room_id || "").startsWith("yt:");
|
const isYt = meta.platform === "youtube" || String(last.room_id || "").startsWith("yt:");
|
||||||
|
const isShorts = kind === "shorts_fail" || kind === "shorts_ok" || kind === "shorts_quota";
|
||||||
|
const ytUrl = String(meta.youtube_url || "").trim();
|
||||||
const liveUrl = String(meta.live_url || meta.url || "").trim();
|
const liveUrl = String(meta.live_url || meta.url || "").trim();
|
||||||
const fallbackHref = !liveUrl
|
const shortsHref = "/shorts";
|
||||||
? isYt
|
const fallbackHref = isShorts
|
||||||
? "/groups"
|
? shortsHref
|
||||||
: last.room_id
|
: !liveUrl
|
||||||
? `/events?q=${encodeURIComponent(last.room_id)}`
|
? isYt
|
||||||
: last.anchor_name
|
? "/groups"
|
||||||
? `/events?q=${encodeURIComponent(last.anchor_name)}`
|
: last.room_id
|
||||||
: undefined
|
? `/events?q=${encodeURIComponent(last.room_id)}`
|
||||||
: undefined;
|
: last.anchor_name
|
||||||
|
? `/events?q=${encodeURIComponent(last.anchor_name)}`
|
||||||
|
: undefined
|
||||||
|
: undefined;
|
||||||
toast.push(last.message, tone, {
|
toast.push(last.message, tone, {
|
||||||
onClick: sid
|
onClick: sid
|
||||||
? () => void openSession(sid)
|
? () => void openSession(sid)
|
||||||
: liveUrl
|
: ytUrl
|
||||||
? () => window.open(liveUrl, "_blank", "noopener,noreferrer")
|
? () => window.open(ytUrl, "_blank", "noopener,noreferrer")
|
||||||
: undefined,
|
: liveUrl
|
||||||
href: sid || liveUrl ? undefined : fallbackHref,
|
? () => window.open(liveUrl, "_blank", "noopener,noreferrer")
|
||||||
|
: undefined,
|
||||||
|
href: sid || ytUrl || liveUrl ? undefined : fallbackHref,
|
||||||
actionLabel: sid
|
actionLabel: sid
|
||||||
? "查看场次 →"
|
? "查看场次 →"
|
||||||
: liveUrl
|
: ytUrl
|
||||||
? "打开直播 →"
|
? "打开 Shorts →"
|
||||||
: fallbackHref
|
: liveUrl
|
||||||
? isYt
|
? "打开直播 →"
|
||||||
? "查看分组 →"
|
: fallbackHref
|
||||||
: "查看事件 →"
|
? isShorts
|
||||||
: undefined,
|
? "打开 Shorts →"
|
||||||
|
: isYt
|
||||||
|
? "查看分组 →"
|
||||||
|
: "查看事件 →"
|
||||||
|
: undefined,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (typeof window !== "undefined" && "Notification" in window && Notification.permission === "granted") {
|
if (typeof window !== "undefined" && "Notification" in window && Notification.permission === "granted") {
|
||||||
const title = kind === "risk" ? "风控告警" : kind === "offline" ? "停播提醒" : isYt ? "YouTube 开播" : "开播提醒";
|
const title =
|
||||||
|
kind === "risk"
|
||||||
|
? "风控告警"
|
||||||
|
: kind === "offline"
|
||||||
|
? "停播提醒"
|
||||||
|
: kind === "shorts_fail"
|
||||||
|
? "Shorts 失败"
|
||||||
|
: kind === "shorts_ok"
|
||||||
|
? "Shorts 已上传"
|
||||||
|
: kind === "shorts_quota"
|
||||||
|
? "Shorts 配额落后"
|
||||||
|
: isYt
|
||||||
|
? "YouTube 开播"
|
||||||
|
: "开播提醒";
|
||||||
try {
|
try {
|
||||||
const n = new Notification(title, { body: last.message, tag: key });
|
const n = new Notification(title, { body: last.message, tag: key });
|
||||||
n.onclick = () => {
|
n.onclick = () => {
|
||||||
window.focus();
|
window.focus();
|
||||||
if (sid) void openSession(sid);
|
if (sid) void openSession(sid);
|
||||||
|
else if (ytUrl) window.open(ytUrl, "_blank", "noopener,noreferrer");
|
||||||
else if (liveUrl) window.open(liveUrl, "_blank", "noopener,noreferrer");
|
else if (liveUrl) window.open(liveUrl, "_blank", "noopener,noreferrer");
|
||||||
else if (fallbackHref) window.location.href = fallbackHref;
|
else if (fallbackHref) window.location.href = fallbackHref;
|
||||||
};
|
};
|
||||||
|
|||||||
@ -132,12 +132,21 @@ export function GoogleOauthSetupWizard({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ol className="list-decimal space-y-1 pl-5 text-xs text-slate-400">
|
<ol className="list-decimal space-y-1 pl-5 text-xs text-slate-400">
|
||||||
<li>弹出页里启用 YouTube Data API v3</li>
|
<li>弹出页里启用 YouTube Data API v3(建议同时启用 YouTube Analytics API)</li>
|
||||||
<li>同意屏幕选 External,加你自己为 Test user</li>
|
<li>
|
||||||
|
同意屏幕选 External,加你自己为 Test user;Scopes 尽量加全:
|
||||||
|
<code className="ml-1 text-[10px] text-slate-300">youtube</code>、
|
||||||
|
<code className="text-[10px] text-slate-300">youtube.force-ssl</code>、
|
||||||
|
<code className="text-[10px] text-slate-300">youtube.upload</code>、
|
||||||
|
<code className="text-[10px] text-slate-300">youtube.readonly</code>、
|
||||||
|
<code className="text-[10px] text-slate-300">youtubepartner</code>、
|
||||||
|
<code className="text-[10px] text-slate-300">yt-analytics.readonly</code>
|
||||||
|
</li>
|
||||||
<li>
|
<li>
|
||||||
创建 <b className="text-slate-200">Web application</b>,重定向 URI 填下面这行(先复制)
|
创建 <b className="text-slate-200">Web application</b>,重定向 URI 填下面这行(先复制)
|
||||||
</li>
|
</li>
|
||||||
<li>把 Client ID / Secret 粘贴到下方 → 保存</li>
|
<li>把 Client ID / Secret 粘贴到下方 → 保存</li>
|
||||||
|
<li>权限变更后,到 Shorts 页对每个频道点「重新授权」才会拿到新 scope</li>
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
|||||||
@ -1,7 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { ConfirmProvider } from "@/components/ConfirmDialog";
|
||||||
import { ToastProvider } from "@/components/Toast";
|
import { ToastProvider } from "@/components/Toast";
|
||||||
|
|
||||||
export function Providers({ children }: { children: React.ReactNode }) {
|
export function Providers({ children }: { children: React.ReactNode }) {
|
||||||
return <ToastProvider>{children}</ToastProvider>;
|
return (
|
||||||
|
<ToastProvider>
|
||||||
|
<ConfirmProvider>{children}</ConfirmProvider>
|
||||||
|
</ToastProvider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
|
|||||||
import { Ban, Loader2, Star } from "lucide-react";
|
import { Ban, Loader2, Star } from "lucide-react";
|
||||||
|
|
||||||
import { fetchJson, detectPlatform } from "@/lib/api";
|
import { fetchJson, detectPlatform } from "@/lib/api";
|
||||||
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
|
|
||||||
export type RoomRef = {
|
export type RoomRef = {
|
||||||
room_pk?: string;
|
room_pk?: string;
|
||||||
@ -64,6 +65,7 @@ export function RoomQuickActions({
|
|||||||
className = "",
|
className = "",
|
||||||
disabled = false,
|
disabled = false,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
|
const confirm = useConfirm();
|
||||||
const [busy, setBusy] = useState("");
|
const [busy, setBusy] = useState("");
|
||||||
const [fav, setFav] = useState(Boolean(favoritedProp));
|
const [fav, setFav] = useState(Boolean(favoritedProp));
|
||||||
const isYt =
|
const isYt =
|
||||||
@ -114,7 +116,13 @@ export function RoomQuickActions({
|
|||||||
if (disabled || busy) return;
|
if (disabled || busy) return;
|
||||||
if (action === "ban") {
|
if (action === "ban") {
|
||||||
const label = room.anchor_name || room.room_id || room.source_url || room.url || "该直播间";
|
const label = room.anchor_name || room.room_id || room.source_url || room.url || "该直播间";
|
||||||
if (!confirm(`将「${label}」加入黑名单并停用?`)) return;
|
const ok = await confirm({
|
||||||
|
title: "加入黑名单",
|
||||||
|
message: `将「${label}」加入黑名单并停用?`,
|
||||||
|
confirmLabel: "拉黑",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
}
|
}
|
||||||
setBusy(action);
|
setBusy(action);
|
||||||
try {
|
try {
|
||||||
|
|||||||
@ -5,7 +5,9 @@ import Link from "next/link";
|
|||||||
import { ExternalLink, Loader2, RefreshCw, Square } from "lucide-react";
|
import { ExternalLink, Loader2, RefreshCw, Square } from "lucide-react";
|
||||||
|
|
||||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||||
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
import { Modal } from "@/components/Modal";
|
import { Modal } from "@/components/Modal";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
import { RoomQuickActions } from "@/components/RoomQuickActions";
|
import { RoomQuickActions } from "@/components/RoomQuickActions";
|
||||||
import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc } from "@/lib/api";
|
import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc } from "@/lib/api";
|
||||||
|
|
||||||
@ -33,6 +35,8 @@ type Props = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function SessionDetailModal({ session, onClose, onUpdated, extraRows }: Props) {
|
export function SessionDetailModal({ session, onClose, onUpdated, extraRows }: Props) {
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const toast = useToast();
|
||||||
const [busy, setBusy] = useState("");
|
const [busy, setBusy] = useState("");
|
||||||
const [err, setErr] = useState("");
|
const [err, setErr] = useState("");
|
||||||
const [local, setLocal] = useState<SessionDetail | null>(null);
|
const [local, setLocal] = useState<SessionDetail | null>(null);
|
||||||
@ -60,7 +64,13 @@ export function SessionDetailModal({ session, onClose, onUpdated, extraRows }: P
|
|||||||
|
|
||||||
async function endNow() {
|
async function endNow() {
|
||||||
if (!current?.id) return;
|
if (!current?.id) return;
|
||||||
if (!confirm(`确认手动结束「${current.anchor_name || current.room_id}」这场?`)) return;
|
const ok = await confirm({
|
||||||
|
title: "结束场次",
|
||||||
|
message: `确认手动结束「${current.anchor_name || current.room_id}」这场?`,
|
||||||
|
confirmLabel: "结束",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
setBusy("end");
|
setBusy("end");
|
||||||
setErr("");
|
setErr("");
|
||||||
try {
|
try {
|
||||||
@ -68,8 +78,10 @@ export function SessionDetailModal({ session, onClose, onUpdated, extraRows }: P
|
|||||||
const next = (data.session || data) as SessionDetail;
|
const next = (data.session || data) as SessionDetail;
|
||||||
setLocal(next);
|
setLocal(next);
|
||||||
onUpdated?.(next);
|
onUpdated?.(next);
|
||||||
|
toast.push("场次已结束", "ok");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setErr((e as Error).message);
|
setErr((e as Error).message);
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
} finally {
|
} finally {
|
||||||
setBusy("");
|
setBusy("");
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,10 +1,13 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
|
|
||||||
import { BrandMark } from "@/components/ui";
|
import { BrandMark, LivePulse } from "@/components/ui";
|
||||||
import { GlobalEventAlerts } from "@/components/GlobalEventAlerts";
|
import { GlobalEventAlerts } from "@/components/GlobalEventAlerts";
|
||||||
|
import { fetchJson } from "@/lib/api";
|
||||||
|
import { YouTubeLiveContextProvider, useYouTubeLiveCount, useYouTubeLiveMap, useYouTubeLiveProviderValue } from "@/lib/youtubeLive";
|
||||||
|
|
||||||
const NAV = [
|
const NAV = [
|
||||||
{ href: "/", label: "概览", emoji: "📡" },
|
{ href: "/", label: "概览", emoji: "📡" },
|
||||||
@ -21,10 +24,39 @@ const NAV = [
|
|||||||
{ href: "/settings", label: "设置", emoji: "⚙️" },
|
{ href: "/settings", label: "设置", emoji: "⚙️" },
|
||||||
];
|
];
|
||||||
|
|
||||||
const MOBILE_PRIMARY = ["/", "/slots", "/sessions", "/groups", "/settings"];
|
const MOBILE_PRIMARY = ["/", "/groups", "/shorts", "/youtube", "/settings"];
|
||||||
|
|
||||||
export function Shell({ children }: { children: React.ReactNode }) {
|
export function Shell({ children }: { children: React.ReactNode }) {
|
||||||
|
const liveCtx = useYouTubeLiveProviderValue();
|
||||||
|
return (
|
||||||
|
<YouTubeLiveContextProvider value={liveCtx}>
|
||||||
|
<ShellFrame>{children}</ShellFrame>
|
||||||
|
</YouTubeLiveContextProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ShellFrame({ children }: { children: React.ReactNode }) {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
const router = useRouter();
|
||||||
|
const ytLiveCount = useYouTubeLiveCount();
|
||||||
|
const { map: ytLiveMap } = useYouTubeLiveMap();
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void fetchJson("/api/auth/status")
|
||||||
|
.then((d) => setUsername(String(d.username || "")))
|
||||||
|
.catch(() => setUsername(""));
|
||||||
|
}, [pathname]);
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
try {
|
||||||
|
await fetchJson("/api/auth/logout", { method: "POST" });
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
router.replace("/login");
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<div className="relative min-h-screen">
|
<div className="relative min-h-screen">
|
||||||
<GlobalEventAlerts />
|
<GlobalEventAlerts />
|
||||||
@ -45,8 +77,49 @@ export function Shell({ children }: { children: React.ReactNode }) {
|
|||||||
<p className="mt-1 max-w-2xl text-sm text-slate-400">
|
<p className="mt-1 max-w-2xl text-sm text-slate-400">
|
||||||
抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证
|
抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证
|
||||||
</p>
|
</p>
|
||||||
|
{ytLiveCount > 0 ? (
|
||||||
|
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||||
|
<Link href="/groups">
|
||||||
|
<LivePulse label={`YouTube ${ytLiveCount} 路在播`} />
|
||||||
|
</Link>
|
||||||
|
{ytLiveMap?.checked_at ? (
|
||||||
|
<span className="text-[10px] text-slate-500">
|
||||||
|
轮询 {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="mt-2 flex flex-wrap items-center gap-2 text-[11px] text-slate-500">
|
||||||
|
{ytLiveMap?.svc_error ? (
|
||||||
|
<span className="text-amber-300" title={ytLiveMap.svc_error}>
|
||||||
|
⚠ YouTube 探测异常(轮询兜底中)
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span>YouTube 直播轮询中</span>
|
||||||
|
)}
|
||||||
|
{ytLiveMap?.checked_at ? (
|
||||||
|
<span className="text-[10px]">
|
||||||
|
· {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前刷新
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
{username ? (
|
||||||
|
<span className="rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300">
|
||||||
|
{username}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void logout()}
|
||||||
|
className="rounded-xl border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-400 hover:bg-white/10 hover:text-white"
|
||||||
|
>
|
||||||
|
退出
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<nav className="hidden max-w-full flex-wrap gap-2 md:flex">
|
<nav className="hidden max-w-full flex-wrap gap-2 md:flex">
|
||||||
{NAV.map((item) => {
|
{NAV.map((item) => {
|
||||||
const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
|
const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
|
||||||
|
|||||||
175
frontend/src/components/ShortsJobDetailModal.tsx
Normal file
175
frontend/src/components/ShortsJobDetailModal.tsx
Normal file
@ -0,0 +1,175 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ExternalLink, Loader2, X } from "lucide-react";
|
||||||
|
import { useEffect, useState, type ReactNode } from "react";
|
||||||
|
|
||||||
|
import { Modal } from "@/components/Modal";
|
||||||
|
import { fetchJson, fmtTs } from "@/lib/api";
|
||||||
|
|
||||||
|
type JobDetail = {
|
||||||
|
id: string;
|
||||||
|
status: string;
|
||||||
|
anchor_name?: string;
|
||||||
|
room_id?: string;
|
||||||
|
channel_name?: string;
|
||||||
|
channel_pk?: string;
|
||||||
|
push_date?: string;
|
||||||
|
clip_path?: string;
|
||||||
|
clip_ready?: boolean;
|
||||||
|
clip_seconds?: number;
|
||||||
|
youtube_url?: string;
|
||||||
|
youtube_video_id?: string;
|
||||||
|
error?: string;
|
||||||
|
attempts?: number;
|
||||||
|
session_id?: string;
|
||||||
|
source_url?: string;
|
||||||
|
created_at?: number;
|
||||||
|
updated_at?: number;
|
||||||
|
upload_at?: number;
|
||||||
|
started_at?: number;
|
||||||
|
finished_at?: number;
|
||||||
|
preview_title?: string;
|
||||||
|
preview_description?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const STATUS_STYLE: Record<string, string> = {
|
||||||
|
pending: "bg-slate-500/20 text-slate-200",
|
||||||
|
recording: "bg-sky-500/20 text-sky-100",
|
||||||
|
recorded: "bg-indigo-500/20 text-indigo-100",
|
||||||
|
scheduled: "bg-amber-500/20 text-amber-100",
|
||||||
|
uploading: "bg-violet-500/20 text-violet-100",
|
||||||
|
uploaded: "bg-teal-500/20 text-teal-100",
|
||||||
|
failed: "bg-rose-500/20 text-rose-100",
|
||||||
|
};
|
||||||
|
|
||||||
|
function Row({ label, children }: { label: string; children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="grid grid-cols-[88px_1fr] gap-2 border-t border-white/5 py-2 text-xs first:border-t-0">
|
||||||
|
<div className="text-slate-500">{label}</div>
|
||||||
|
<div className="min-w-0 text-slate-200">{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ShortsJobDetailModal({
|
||||||
|
jobId,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
jobId: string | null;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const [job, setJob] = useState<JobDetail | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [err, setErr] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!jobId) {
|
||||||
|
setJob(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cancelled = false;
|
||||||
|
setLoading(true);
|
||||||
|
setErr("");
|
||||||
|
void fetchJson(`/api/shorts/jobs/${jobId}`)
|
||||||
|
.then((data) => {
|
||||||
|
if (!cancelled) setJob(data.job || data);
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
if (!cancelled) setErr((e as Error).message);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!cancelled) setLoading(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [jobId]);
|
||||||
|
|
||||||
|
const clipUrl = job?.clip_ready ? `/api/shorts/jobs/${job.id}/clip` : "";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal open={Boolean(jobId)} onClose={onClose} panelClassName="w-full max-w-lg rounded-2xl border border-white/10 bg-[#0b1626] p-0 shadow-2xl">
|
||||||
|
<div className="flex items-start justify-between gap-3 border-b border-white/10 px-5 py-4">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-xs uppercase tracking-wider text-teal-300/80">任务详情</p>
|
||||||
|
<h3 className="mt-1 truncate font-display text-lg font-semibold text-white">
|
||||||
|
{job?.anchor_name || job?.room_id || jobId || "—"}
|
||||||
|
</h3>
|
||||||
|
</div>
|
||||||
|
<button type="button" onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:bg-white/5 hover:text-white">
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="max-h-[70vh] overflow-y-auto px-5 py-4">
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center justify-center gap-2 py-12 text-sm text-slate-400">
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
加载中…
|
||||||
|
</div>
|
||||||
|
) : err ? (
|
||||||
|
<p className="py-8 text-center text-sm text-rose-300">{err}</p>
|
||||||
|
) : job ? (
|
||||||
|
<>
|
||||||
|
{clipUrl ? (
|
||||||
|
<video
|
||||||
|
src={clipUrl}
|
||||||
|
controls
|
||||||
|
playsInline
|
||||||
|
preload="metadata"
|
||||||
|
className="mb-4 aspect-[9/16] max-h-64 w-full rounded-xl bg-black object-contain"
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<Row label="状态">
|
||||||
|
<span className={`inline-block rounded-md px-2 py-0.5 text-[11px] ${STATUS_STYLE[job.status] || "bg-white/10"}`}>
|
||||||
|
{job.status}
|
||||||
|
</span>
|
||||||
|
</Row>
|
||||||
|
<Row label="频道">{job.channel_name || "—"}</Row>
|
||||||
|
<Row label="北京日">{job.push_date || "—"}</Row>
|
||||||
|
<Row label="排程上传">{job.upload_at ? fmtTs(Number(job.upload_at)) : "—"}</Row>
|
||||||
|
<Row label="创建">{job.created_at ? fmtTs(Number(job.created_at)) : "—"}</Row>
|
||||||
|
<Row label="尝试次数">{String(job.attempts ?? 0)}</Row>
|
||||||
|
<Row label="成片">
|
||||||
|
{job.clip_ready ? `${Math.round(Number(job.clip_seconds || 15))}s · 可预览` : job.clip_path ? "路径失效" : "无"}
|
||||||
|
</Row>
|
||||||
|
{job.preview_title ? (
|
||||||
|
<Row label="标题预览">
|
||||||
|
<span className="break-words text-slate-300">{job.preview_title}</span>
|
||||||
|
</Row>
|
||||||
|
) : null}
|
||||||
|
{job.error ? (
|
||||||
|
<Row label="错误">
|
||||||
|
<span className="break-words text-rose-300">{job.error}</span>
|
||||||
|
</Row>
|
||||||
|
) : null}
|
||||||
|
{job.youtube_url ? (
|
||||||
|
<Row label="YouTube">
|
||||||
|
<a href={job.youtube_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-teal-300 hover:underline">
|
||||||
|
已发布
|
||||||
|
<ExternalLink className="h-3 w-3" />
|
||||||
|
</a>
|
||||||
|
</Row>
|
||||||
|
) : null}
|
||||||
|
{job.session_id ? (
|
||||||
|
<Row label="场次">
|
||||||
|
<a href={`/sessions?highlight=${job.session_id}`} className="font-mono text-[10px] text-sky-300 hover:underline">
|
||||||
|
{job.session_id.slice(0, 8)}…
|
||||||
|
</a>
|
||||||
|
</Row>
|
||||||
|
) : null}
|
||||||
|
{job.source_url ? (
|
||||||
|
<Row label="来源">
|
||||||
|
<a href={job.source_url} target="_blank" rel="noreferrer" className="break-all text-sky-300 hover:underline">
|
||||||
|
{job.source_url}
|
||||||
|
</a>
|
||||||
|
</Row>
|
||||||
|
) : null}
|
||||||
|
<Row label="任务 ID">
|
||||||
|
<span className="break-all font-mono text-[10px] text-slate-500">{job.id}</span>
|
||||||
|
</Row>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
365
frontend/src/components/ShortsUploadUx.tsx
Normal file
365
frontend/src/components/ShortsUploadUx.tsx
Normal file
@ -0,0 +1,365 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import {
|
||||||
|
AlertCircle,
|
||||||
|
CheckCircle2,
|
||||||
|
ExternalLink,
|
||||||
|
Loader2,
|
||||||
|
Upload,
|
||||||
|
X,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
|
import { Modal } from "@/components/Modal";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
|
import { fetchJson, fmtTs } from "@/lib/api";
|
||||||
|
|
||||||
|
export type ShortsUploadTarget = {
|
||||||
|
id: string;
|
||||||
|
anchor_name?: string;
|
||||||
|
room_id?: string;
|
||||||
|
channel_name?: string;
|
||||||
|
channel_pk?: string;
|
||||||
|
upload_at?: number;
|
||||||
|
clip_ready?: boolean;
|
||||||
|
status?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type UploadPhase = "idle" | "uploading" | "success" | "failed";
|
||||||
|
|
||||||
|
type UploadTrack = {
|
||||||
|
phase: UploadPhase;
|
||||||
|
startedAt: number;
|
||||||
|
youtubeUrl?: string;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function sleep(ms: number) {
|
||||||
|
return new Promise((r) => setTimeout(r, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
function labelOf(t: ShortsUploadTarget) {
|
||||||
|
return t.anchor_name || t.room_id || "素材";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useShortsUpload(onRefresh: () => Promise<void>) {
|
||||||
|
const toast = useToast();
|
||||||
|
const [confirmTarget, setConfirmTarget] = useState<ShortsUploadTarget | null>(null);
|
||||||
|
const [tracks, setTracks] = useState<Record<string, UploadTrack>>({});
|
||||||
|
const pollRef = useRef<AbortController | null>(null);
|
||||||
|
|
||||||
|
const patchTrack = useCallback((id: string, patch: Partial<UploadTrack>) => {
|
||||||
|
setTracks((prev) => {
|
||||||
|
const cur = prev[id] || { phase: "idle" as const, startedAt: Date.now() };
|
||||||
|
return { ...prev, [id]: { ...cur, ...patch } };
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const finishSuccess = useCallback(
|
||||||
|
async (jobId: string, label: string, url: string) => {
|
||||||
|
patchTrack(jobId, { phase: "success", youtubeUrl: url });
|
||||||
|
toast.push(`「${label}」上传成功`, "ok", {
|
||||||
|
href: url || undefined,
|
||||||
|
actionLabel: url ? "在 YouTube 查看 Shorts →" : undefined,
|
||||||
|
durationMs: 8000,
|
||||||
|
});
|
||||||
|
await onRefresh();
|
||||||
|
window.setTimeout(() => {
|
||||||
|
setTracks((prev) => {
|
||||||
|
const next = { ...prev };
|
||||||
|
delete next[jobId];
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, 4000);
|
||||||
|
},
|
||||||
|
[onRefresh, patchTrack, toast],
|
||||||
|
);
|
||||||
|
|
||||||
|
const pollJob = useCallback(
|
||||||
|
async (jobId: string, label: string, signal: AbortSignal) => {
|
||||||
|
for (let i = 0; i < 120; i++) {
|
||||||
|
if (signal.aborted) return;
|
||||||
|
try {
|
||||||
|
const data = await fetchJson(`/api/shorts/jobs/${jobId}`);
|
||||||
|
const job = data.job || data;
|
||||||
|
const st = String(job.status || "");
|
||||||
|
if (st === "uploaded" || st === "done") {
|
||||||
|
const url = String(job.youtube_url || "");
|
||||||
|
await finishSuccess(jobId, label, url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (st === "failed") {
|
||||||
|
const err = String(job.error || "上传失败");
|
||||||
|
patchTrack(jobId, { phase: "failed", error: err });
|
||||||
|
toast.push(`「${label}」上传失败:${err}`, "err", { durationMs: 6000 });
|
||||||
|
await onRefresh();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (st === "pending") {
|
||||||
|
const err = String(job.error || "成片已丢失,已重新排队录制");
|
||||||
|
patchTrack(jobId, { phase: "failed", error: err });
|
||||||
|
toast.push(`「${label}」${err}`, "warn", { durationMs: 6000 });
|
||||||
|
await onRefresh();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (signal.aborted) return;
|
||||||
|
if (i >= 2) {
|
||||||
|
const err = (e as Error).message;
|
||||||
|
patchTrack(jobId, { phase: "failed", error: err });
|
||||||
|
toast.push(err, "err");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await sleep(i < 20 ? 1000 : 2000);
|
||||||
|
}
|
||||||
|
patchTrack(jobId, { phase: "failed", error: "上传耗时较长,请稍后刷新查看" });
|
||||||
|
toast.push(`「${label}」仍在处理,请稍后刷新`, "warn", { durationMs: 5000 });
|
||||||
|
await onRefresh();
|
||||||
|
},
|
||||||
|
[finishSuccess, onRefresh, patchTrack, toast],
|
||||||
|
);
|
||||||
|
|
||||||
|
const startUpload = useCallback(
|
||||||
|
async (target: ShortsUploadTarget) => {
|
||||||
|
const id = target.id;
|
||||||
|
const label = labelOf(target);
|
||||||
|
setConfirmTarget(null);
|
||||||
|
patchTrack(id, { phase: "uploading", startedAt: Date.now(), error: "", youtubeUrl: "" });
|
||||||
|
|
||||||
|
pollRef.current?.abort();
|
||||||
|
const ac = new AbortController();
|
||||||
|
pollRef.current = ac;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await fetchJson(`/api/shorts/jobs/${id}/upload-now`, { method: "POST" });
|
||||||
|
const job = data.job || data;
|
||||||
|
const st = String(job.status || "");
|
||||||
|
if (st === "uploaded" || st === "done") {
|
||||||
|
await finishSuccess(id, label, String(job.youtube_url || ""));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (st === "failed") {
|
||||||
|
const err = String(job.error || "上传失败");
|
||||||
|
patchTrack(id, { phase: "failed", error: err });
|
||||||
|
toast.push(`「${label}」上传失败:${err}`, "err");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
toast.push(`「${label}」上传中…`, "ok", { durationMs: 2000 });
|
||||||
|
void pollJob(id, label, ac.signal);
|
||||||
|
} catch (e) {
|
||||||
|
const err = (e as Error).message;
|
||||||
|
patchTrack(id, { phase: "failed", error: err });
|
||||||
|
toast.push(err, "err");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[finishSuccess, patchTrack, pollJob, toast],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => () => pollRef.current?.abort(), []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
confirmTarget,
|
||||||
|
openConfirm: setConfirmTarget,
|
||||||
|
cancelConfirm: () => setConfirmTarget(null),
|
||||||
|
confirmUpload: () => confirmTarget && void startUpload(confirmTarget),
|
||||||
|
tracks,
|
||||||
|
retryUpload: (target: ShortsUploadTarget) => void startUpload(target),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ShortsUploadConfirmModal({
|
||||||
|
target,
|
||||||
|
onCancel,
|
||||||
|
onConfirm,
|
||||||
|
busy,
|
||||||
|
}: {
|
||||||
|
target: ShortsUploadTarget | null;
|
||||||
|
onCancel: () => void;
|
||||||
|
onConfirm: () => void;
|
||||||
|
busy?: boolean;
|
||||||
|
}) {
|
||||||
|
if (!target) return null;
|
||||||
|
const label = labelOf(target);
|
||||||
|
const scheduled = target.upload_at ? fmtTs(Number(target.upload_at)) : "未排程";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal open={Boolean(target)} onClose={onCancel} panelClassName="w-full max-w-md rounded-2xl border border-white/10 bg-[#0b1626] p-0 shadow-2xl">
|
||||||
|
<div className="border-b border-white/10 px-5 py-4">
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<p className="text-xs uppercase tracking-wider text-teal-300/80">手动上传</p>
|
||||||
|
<h3 className="mt-1 font-display text-lg font-semibold text-white">确认立即上传?</h3>
|
||||||
|
</div>
|
||||||
|
<button type="button" onClick={onCancel} className="rounded-lg p-1 text-slate-400 hover:bg-white/5 hover:text-white">
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-3 px-5 py-4 text-sm">
|
||||||
|
<div className="rounded-xl border border-white/10 bg-black/30 p-3">
|
||||||
|
<div className="font-medium text-slate-100">{label}</div>
|
||||||
|
<div className="mt-2 space-y-1 text-xs text-slate-400">
|
||||||
|
<div>目标频道 · {target.channel_name || "—"}</div>
|
||||||
|
<div>原错峰排程 · {scheduled}</div>
|
||||||
|
<div>{target.clip_ready === false ? "成片状态 · 等待录制完成" : "成片状态 · 已就绪"}</div>
|
||||||
|
</div>
|
||||||
|
{target.clip_ready !== false && target.id ? (
|
||||||
|
<video
|
||||||
|
src={`/api/shorts/jobs/${target.id}/clip`}
|
||||||
|
controls
|
||||||
|
playsInline
|
||||||
|
preload="metadata"
|
||||||
|
className="mt-3 aspect-[9/16] max-h-48 w-full rounded-lg bg-black object-contain"
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs leading-relaxed text-amber-200/90">
|
||||||
|
将跳过错峰等待,立即发布到 YouTube Shorts。15 秒成片通常需 20–60 秒(含 OAuth 与传到 Google)。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 border-t border-white/10 px-5 py-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={onCancel}
|
||||||
|
className="flex-1 rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-slate-300 hover:bg-white/10"
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busy || target.clip_ready === false}
|
||||||
|
onClick={onConfirm}
|
||||||
|
className="inline-flex flex-1 items-center justify-center gap-2 rounded-xl bg-teal-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-teal-400 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
|
||||||
|
确认上传
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function elapsedSec(startedAt: number) {
|
||||||
|
return Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ShortsUpcomingUploadRow({
|
||||||
|
item,
|
||||||
|
track,
|
||||||
|
onRequestUpload,
|
||||||
|
onRetry,
|
||||||
|
}: {
|
||||||
|
item: ShortsUploadTarget;
|
||||||
|
track?: UploadTrack;
|
||||||
|
onRequestUpload: (item: ShortsUploadTarget) => void;
|
||||||
|
onRetry: (item: ShortsUploadTarget) => void;
|
||||||
|
}) {
|
||||||
|
const phase = track?.phase || "idle";
|
||||||
|
const [tick, setTick] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (phase !== "uploading") return;
|
||||||
|
const t = window.setInterval(() => setTick((n) => n + 1), 1000);
|
||||||
|
return () => window.clearInterval(t);
|
||||||
|
}, [phase]);
|
||||||
|
|
||||||
|
const label = labelOf(item);
|
||||||
|
const clipReady = item.clip_ready !== false;
|
||||||
|
const border =
|
||||||
|
phase === "uploading"
|
||||||
|
? "border-violet-500/40 bg-violet-500/[0.06]"
|
||||||
|
: phase === "success"
|
||||||
|
? "border-teal-500/40 bg-teal-500/[0.06]"
|
||||||
|
: phase === "failed"
|
||||||
|
? "border-rose-500/35 bg-rose-500/[0.05]"
|
||||||
|
: "border-white/10 bg-black/40";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`rounded-xl border px-3 py-2.5 transition-colors ${border}`}>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div
|
||||||
|
className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${
|
||||||
|
phase === "success"
|
||||||
|
? "bg-teal-500/20 text-teal-300"
|
||||||
|
: phase === "failed"
|
||||||
|
? "bg-rose-500/15 text-rose-300"
|
||||||
|
: phase === "uploading"
|
||||||
|
? "bg-violet-500/20 text-violet-300"
|
||||||
|
: "bg-amber-500/15 text-amber-300"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{phase === "uploading" ? (
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
) : phase === "success" ? (
|
||||||
|
<CheckCircle2 className="h-4 w-4" />
|
||||||
|
) : phase === "failed" ? (
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<Upload className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="text-sm font-medium text-slate-100">{label}</div>
|
||||||
|
<div className="text-[11px] text-slate-500">
|
||||||
|
{item.channel_name || "频道"}
|
||||||
|
{item.upload_at ? ` · 排程 ${fmtTs(Number(item.upload_at))}` : " · 待排程"}
|
||||||
|
{!clipReady ? " · 等待成片" : phase === "idle" ? " · 成片就绪" : ""}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{phase === "idle" && clipReady ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onRequestUpload(item)}
|
||||||
|
className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-teal-500 px-3 py-1.5 text-xs font-medium text-white shadow-sm hover:bg-teal-400"
|
||||||
|
>
|
||||||
|
<Upload className="h-3.5 w-3.5" />
|
||||||
|
立即上传
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
{phase === "failed" ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onRetry(item)}
|
||||||
|
className="inline-flex shrink-0 items-center gap-1 rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-1.5 text-xs text-rose-100"
|
||||||
|
>
|
||||||
|
重试
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
{phase === "success" && track?.youtubeUrl ? (
|
||||||
|
<a
|
||||||
|
href={track.youtubeUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="inline-flex shrink-0 items-center gap-1 rounded-lg bg-teal-500/15 px-3 py-1.5 text-xs text-teal-100"
|
||||||
|
>
|
||||||
|
<ExternalLink className="h-3 w-3" />
|
||||||
|
查看
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{phase === "uploading" ? (
|
||||||
|
<div className="mt-3">
|
||||||
|
<div className="mb-1 flex items-center justify-between text-[11px] text-violet-200/90">
|
||||||
|
<span>
|
||||||
|
{elapsedSec(track?.startedAt || Date.now()) >= 45
|
||||||
|
? "YouTube 仍在接收,请稍候…"
|
||||||
|
: "正在上传到 YouTube…"}
|
||||||
|
</span>
|
||||||
|
<span>{elapsedSec(track?.startedAt || Date.now())}s</span>
|
||||||
|
</div>
|
||||||
|
<div className="h-1.5 overflow-hidden rounded-full bg-white/10">
|
||||||
|
<div className="h-full w-full animate-pulse rounded-full bg-gradient-to-r from-violet-600/40 via-violet-400/80 to-violet-600/40" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{phase === "failed" && track?.error ? (
|
||||||
|
<p className="mt-2 text-[11px] leading-relaxed text-rose-300">{track.error}</p>
|
||||||
|
) : null}
|
||||||
|
{phase === "success" ? (
|
||||||
|
<p className="mt-2 text-[11px] text-teal-300">上传完成,已从排队列表移除</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -50,7 +50,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
|
|||||||
return (
|
return (
|
||||||
<ToastCtx.Provider value={value}>
|
<ToastCtx.Provider value={value}>
|
||||||
{children}
|
{children}
|
||||||
<div className="pointer-events-none fixed bottom-4 right-4 z-[80] flex w-[min(92vw,22rem)] flex-col gap-2">
|
<div className="pointer-events-none fixed inset-x-4 bottom-20 z-[80] flex flex-col gap-2 md:inset-x-auto md:bottom-4 md:right-4 md:w-[min(92vw,22rem)] md:pb-[env(safe-area-inset-bottom)]">
|
||||||
{items.map((t) => {
|
{items.map((t) => {
|
||||||
const clickable = Boolean(t.onClick || t.href);
|
const clickable = Boolean(t.onClick || t.href);
|
||||||
const body = (
|
const body = (
|
||||||
|
|||||||
77
frontend/src/components/YouTubeLiveBadge.tsx
Normal file
77
frontend/src/components/YouTubeLiveBadge.tsx
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { LivePulse } from "@/components/ui";
|
||||||
|
import { useYouTubeLiveEntry, type YouTubeLiveEntry } from "@/lib/youtubeLive";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
/** e.g. group:uuid, shorts:uuid, channel:UCxxx */
|
||||||
|
refKey?: string;
|
||||||
|
/** Direct entry override (probe tab, etc.) */
|
||||||
|
entry?: YouTubeLiveEntry | null;
|
||||||
|
className?: string;
|
||||||
|
/** Show stream title next to badge */
|
||||||
|
showTitle?: boolean;
|
||||||
|
compact?: boolean;
|
||||||
|
/** When not live, still show 离线/检测中 instead of hiding */
|
||||||
|
showOffline?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function YouTubeLiveBadge({
|
||||||
|
refKey,
|
||||||
|
entry,
|
||||||
|
className = "",
|
||||||
|
showTitle = false,
|
||||||
|
compact = false,
|
||||||
|
showOffline = false,
|
||||||
|
}: Props) {
|
||||||
|
const fromMap = useYouTubeLiveEntry(refKey);
|
||||||
|
const live = entry ?? fromMap;
|
||||||
|
|
||||||
|
if (!live) {
|
||||||
|
if (!showOffline) return null;
|
||||||
|
return (
|
||||||
|
<span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] text-slate-500 ring-1 ring-white/10 ${className}`}>
|
||||||
|
检测中
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!live.is_live) {
|
||||||
|
if (!showOffline) return null;
|
||||||
|
const tip = live.error ? String(live.error) : "YouTube 未开播";
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] text-slate-500 ring-1 ring-white/10 ${className}`}
|
||||||
|
title={tip}
|
||||||
|
>
|
||||||
|
离线
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const label = compact ? "LIVE" : "LIVE";
|
||||||
|
const inner = (
|
||||||
|
<>
|
||||||
|
<LivePulse label={label} />
|
||||||
|
{showTitle && live.title ? (
|
||||||
|
<span className="max-w-[180px] truncate text-[11px] text-rose-100/90">{live.title}</span>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (live.live_url) {
|
||||||
|
return (
|
||||||
|
<a
|
||||||
|
href={live.live_url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className={`inline-flex items-center gap-2 hover:opacity-90 ${className}`}
|
||||||
|
title={live.title || "打开直播"}
|
||||||
|
>
|
||||||
|
{inner}
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return <span className={`inline-flex items-center gap-2 ${className}`}>{inner}</span>;
|
||||||
|
}
|
||||||
51
frontend/src/components/YouTubeLiveTicker.tsx
Normal file
51
frontend/src/components/YouTubeLiveTicker.tsx
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { LivePulse } from "@/components/ui";
|
||||||
|
import { useYouTubeLiveMap } from "@/lib/youtubeLive";
|
||||||
|
|
||||||
|
/** Home ticker: all live YouTube groups + Shorts channels from live-map. */
|
||||||
|
export function YouTubeLiveTicker() {
|
||||||
|
const { map } = useYouTubeLiveMap();
|
||||||
|
const entries = map?.entries || {};
|
||||||
|
const live = Object.entries(entries).filter(
|
||||||
|
([k, v]) => (k.startsWith("group:") || k.startsWith("shorts:")) && v?.is_live,
|
||||||
|
);
|
||||||
|
if (!live.length) return null;
|
||||||
|
|
||||||
|
const items = live.map(([key, v]) => ({
|
||||||
|
key,
|
||||||
|
title: v.title || key.replace(/^(group|shorts):/, ""),
|
||||||
|
url: v.live_url || "#",
|
||||||
|
source: v.source,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mb-6 overflow-hidden rounded-2xl border border-red-500/25 bg-red-500/5">
|
||||||
|
<div className="flex items-center gap-2 border-b border-white/5 px-4 py-2 text-xs text-red-100/90">
|
||||||
|
<LivePulse label={`YouTube ${items.length} 路在播`} />
|
||||||
|
<Link href="/groups" className="ml-auto text-teal-300 hover:underline">
|
||||||
|
分组 →
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<div className="relative overflow-hidden py-3">
|
||||||
|
<div className="ticker-track gap-8 px-4 text-sm text-slate-200">
|
||||||
|
{[...items, ...items].map((item, idx) => (
|
||||||
|
<a
|
||||||
|
key={`${item.key}-${idx}`}
|
||||||
|
href={item.url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="inline-flex items-center gap-2 whitespace-nowrap hover:text-white"
|
||||||
|
>
|
||||||
|
<span className="live-dot" />
|
||||||
|
<span className="font-medium">{item.title}</span>
|
||||||
|
{item.source ? <span className="text-[10px] text-slate-500">{item.source}</span> : null}
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState, type ReactNode } from "react";
|
import { useEffect, useState, type ReactNode } from "react";
|
||||||
|
import { Loader2 } from "lucide-react";
|
||||||
|
|
||||||
export function AnimatedNumber({
|
export function AnimatedNumber({
|
||||||
value,
|
value,
|
||||||
@ -142,3 +143,26 @@ export function PlatformBadge({
|
|||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function PageLoader({ label = "加载中…" }: { label?: string }) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center gap-2 py-16 text-sm text-slate-400">
|
||||||
|
<Loader2 className="h-5 w-5 animate-spin text-teal-400" />
|
||||||
|
{label}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TableSkeleton({ rows = 5, cols = 4 }: { rows?: number; cols?: number }) {
|
||||||
|
return (
|
||||||
|
<div className="animate-pulse space-y-2">
|
||||||
|
{Array.from({ length: rows }).map((_, i) => (
|
||||||
|
<div key={i} className="flex gap-3 rounded-lg bg-white/[0.04] px-3 py-3">
|
||||||
|
{Array.from({ length: cols }).map((__, j) => (
|
||||||
|
<div key={j} className="h-3 flex-1 rounded bg-white/10" style={{ maxWidth: j === 0 ? "40%" : undefined }} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -1,8 +1,18 @@
|
|||||||
|
export function clearAuthRedirect() {
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
delete window.__dyAuthRedirect;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function fetchJson(url, init) {
|
export async function fetchJson(url, init) {
|
||||||
|
const apiKey =
|
||||||
|
typeof window !== "undefined" ? window.localStorage.getItem("dy_api_key") || "" : "";
|
||||||
const res = await fetch(url, {
|
const res = await fetch(url, {
|
||||||
...init,
|
...init,
|
||||||
|
credentials: "include",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
|
...(apiKey ? { "X-API-Key": apiKey } : {}),
|
||||||
...(init?.headers || {}),
|
...(init?.headers || {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@ -13,6 +23,22 @@ export async function fetchJson(url, init) {
|
|||||||
} catch {
|
} catch {
|
||||||
data = { raw: text };
|
data = { raw: text };
|
||||||
}
|
}
|
||||||
|
if (res.status === 401 && typeof window !== "undefined") {
|
||||||
|
const path = window.location.pathname;
|
||||||
|
const detail = typeof data?.detail === "string" ? data.detail : "";
|
||||||
|
const authFail =
|
||||||
|
path !== "/login" &&
|
||||||
|
(detail.includes("未登录") ||
|
||||||
|
detail.includes("登录") ||
|
||||||
|
detail.includes("API Key") ||
|
||||||
|
detail.includes("Unauthorized") ||
|
||||||
|
url.includes("/api/"));
|
||||||
|
if (authFail && !window.__dyAuthRedirect) {
|
||||||
|
window.__dyAuthRedirect = true;
|
||||||
|
const next = encodeURIComponent(path + window.location.search);
|
||||||
|
window.location.assign(`/login?next=${next}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const detail = data?.detail || data?.message || text || res.statusText;
|
const detail = data?.detail || data?.message || text || res.statusText;
|
||||||
throw new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
|
throw new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
|
||||||
|
|||||||
@ -68,27 +68,31 @@ export function useAutoRefresh(
|
|||||||
intervalMs?: number;
|
intervalMs?: number;
|
||||||
/** false = 仅轮询;默认 live/offline/risk */
|
/** false = 仅轮询;默认 live/offline/risk */
|
||||||
eventKinds?: string[] | false;
|
eventKinds?: string[] | false;
|
||||||
|
/** false = 暂停自动刷新(仍遵守 hook 规则) */
|
||||||
|
enabled?: boolean;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const intervalMs = opts?.intervalMs ?? 20000;
|
const intervalMs = opts?.intervalMs ?? 20000;
|
||||||
|
const enabled = opts?.enabled !== false;
|
||||||
const eventKinds = opts?.eventKinds === false ? null : opts?.eventKinds ?? ["live", "offline", "risk"];
|
const eventKinds = opts?.eventKinds === false ? null : opts?.eventKinds ?? ["live", "offline", "risk"];
|
||||||
const { connected, last, tick } = useEventStream(Boolean(eventKinds));
|
const { connected, last, tick } = useEventStream(Boolean(eventKinds) && enabled);
|
||||||
const loadRef = useRef(load);
|
const loadRef = useRef(load);
|
||||||
loadRef.current = load;
|
loadRef.current = load;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!enabled) return;
|
||||||
void loadRef.current({ silent: false });
|
void loadRef.current({ silent: false });
|
||||||
if (!intervalMs || intervalMs <= 0) return;
|
if (!intervalMs || intervalMs <= 0) return;
|
||||||
const t = window.setInterval(() => void loadRef.current({ silent: true }), intervalMs);
|
const t = window.setInterval(() => void loadRef.current({ silent: true }), intervalMs);
|
||||||
return () => window.clearInterval(t);
|
return () => window.clearInterval(t);
|
||||||
}, [load, intervalMs]);
|
}, [load, intervalMs, enabled]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!eventKinds || !last?.kind) return;
|
if (!enabled || !eventKinds || !last?.kind) return;
|
||||||
if (!eventKinds.includes(String(last.kind))) return;
|
if (!eventKinds.includes(String(last.kind))) return;
|
||||||
void loadRef.current({ silent: true });
|
void loadRef.current({ silent: true });
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [tick]);
|
}, [tick, enabled]);
|
||||||
|
|
||||||
return { connected };
|
return { connected };
|
||||||
}
|
}
|
||||||
|
|||||||
102
frontend/src/lib/youtubeLive.ts
Normal file
102
frontend/src/lib/youtubeLive.ts
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||||
|
|
||||||
|
import { fetchJson } from "@/lib/api";
|
||||||
|
|
||||||
|
export type YouTubeLiveEntry = {
|
||||||
|
is_live?: boolean;
|
||||||
|
live_url?: string;
|
||||||
|
title?: string;
|
||||||
|
channel_id?: string;
|
||||||
|
source?: string;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type YouTubeLiveMap = {
|
||||||
|
ok?: boolean;
|
||||||
|
checked_at?: number;
|
||||||
|
live_count?: number;
|
||||||
|
source?: string;
|
||||||
|
entries?: Record<string, YouTubeLiveEntry>;
|
||||||
|
svc_error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const YouTubeLiveContext = createContext<{
|
||||||
|
map: YouTubeLiveMap | null;
|
||||||
|
loading: boolean;
|
||||||
|
refresh: () => Promise<void>;
|
||||||
|
}>({
|
||||||
|
map: null,
|
||||||
|
loading: false,
|
||||||
|
refresh: async () => {},
|
||||||
|
});
|
||||||
|
|
||||||
|
export function groupLiveRef(groupId: string) {
|
||||||
|
return `group:${groupId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shortsLiveRef(channelPk: string) {
|
||||||
|
return `shorts:${channelPk}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function channelLiveRef(channelId: string) {
|
||||||
|
return `channel:${channelId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useYouTubeLiveProviderValue(intervalMs = 15000) {
|
||||||
|
const [map, setMap] = useState<YouTubeLiveMap | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const refresh = useCallback(async (silent = false) => {
|
||||||
|
if (!silent) setLoading(true);
|
||||||
|
try {
|
||||||
|
// 不 force:读服务端后台轮询写入的缓存(约 15–20s 更新)
|
||||||
|
const data = (await fetchJson("/api/youtube/live-map")) as YouTubeLiveMap;
|
||||||
|
setMap(data);
|
||||||
|
} catch {
|
||||||
|
/* keep last map */
|
||||||
|
} finally {
|
||||||
|
if (!silent) setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void refresh(true);
|
||||||
|
const id = window.setInterval(() => void refresh(true), intervalMs);
|
||||||
|
const onVis = () => {
|
||||||
|
if (document.visibilityState === "visible") void refresh(true);
|
||||||
|
};
|
||||||
|
document.addEventListener("visibilitychange", onVis);
|
||||||
|
return () => {
|
||||||
|
window.clearInterval(id);
|
||||||
|
document.removeEventListener("visibilitychange", onVis);
|
||||||
|
};
|
||||||
|
}, [intervalMs, refresh]);
|
||||||
|
|
||||||
|
return useMemo(
|
||||||
|
() => ({
|
||||||
|
map,
|
||||||
|
loading,
|
||||||
|
refresh: () => refresh(false),
|
||||||
|
}),
|
||||||
|
[map, loading, refresh],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const YouTubeLiveContextProvider = YouTubeLiveContext.Provider;
|
||||||
|
|
||||||
|
export function useYouTubeLiveMap() {
|
||||||
|
return useContext(YouTubeLiveContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useYouTubeLiveEntry(refKey?: string): YouTubeLiveEntry | null {
|
||||||
|
const { map } = useYouTubeLiveMap();
|
||||||
|
if (!refKey) return null;
|
||||||
|
return map?.entries?.[refKey] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useYouTubeLiveCount() {
|
||||||
|
const { map } = useYouTubeLiveMap();
|
||||||
|
return Number(map?.live_count || 0);
|
||||||
|
}
|
||||||
35
frontend/src/middleware.ts
Normal file
35
frontend/src/middleware.ts
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import type { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
const PUBLIC = ["/login"];
|
||||||
|
|
||||||
|
export function middleware(request: NextRequest) {
|
||||||
|
const { pathname } = request.nextUrl;
|
||||||
|
if (
|
||||||
|
pathname.startsWith("/_next") ||
|
||||||
|
pathname.startsWith("/favicon") ||
|
||||||
|
pathname.match(/\.(ico|png|jpg|jpeg|svg|webp|css|js)$/)
|
||||||
|
) {
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = request.cookies.get("dy_session")?.value;
|
||||||
|
const isLogin = PUBLIC.some((p) => pathname === p || pathname.startsWith(`${p}/`));
|
||||||
|
|
||||||
|
if (!session && !isLogin) {
|
||||||
|
const url = request.nextUrl.clone();
|
||||||
|
url.pathname = "/login";
|
||||||
|
url.searchParams.set("next", pathname);
|
||||||
|
return NextResponse.redirect(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session && isLogin) {
|
||||||
|
return NextResponse.redirect(new URL("/", request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ["/((?!_next/static|_next/image).*)"],
|
||||||
|
};
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
77
scripts/deploy_all_features.py
Normal file
77
scripts/deploy_all_features.py
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy P1-P5: API key, PB health, group URL probe, tests support."""
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "107.173.30.245"
|
||||||
|
USER = "root"
|
||||||
|
PASSWORD = "Xiao4669805"
|
||||||
|
REMOTE = "/opt/douyinWEB"
|
||||||
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
|
FILES = [
|
||||||
|
"backend/app/auth.py",
|
||||||
|
"backend/app/config.py",
|
||||||
|
"backend/app/main.py",
|
||||||
|
"backend/app/pb_sync.py",
|
||||||
|
"backend/app/db.py",
|
||||||
|
"backend/app/youtube_monitor.py",
|
||||||
|
"backend/requirements.txt",
|
||||||
|
"backend/tests/conftest.py",
|
||||||
|
"backend/tests/test_reconcile_yt.py",
|
||||||
|
"backend/tests/test_youtube_live.py",
|
||||||
|
"frontend/src/lib/api.js",
|
||||||
|
"frontend/src/app/settings/page.tsx",
|
||||||
|
"frontend/src/app/groups/page.tsx",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, timeout=420):
|
||||||
|
print("$", cmd[:180], flush=True)
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(timeout)
|
||||||
|
chan.get_pty()
|
||||||
|
chan.exec_command(cmd)
|
||||||
|
buf = []
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.25)
|
||||||
|
while chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
code = chan.recv_exit_status()
|
||||||
|
text = "".join(buf)
|
||||||
|
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
|
||||||
|
print(clean[-2500:], flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
run(c, f"mkdir -p {REMOTE}/backend/tests")
|
||||||
|
for rel in FILES:
|
||||||
|
print("upload", rel, flush=True)
|
||||||
|
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
|
||||||
|
sftp.close()
|
||||||
|
run(c, f"cd {REMOTE}/backend && pip install -q -r requirements.txt", timeout=180)
|
||||||
|
run(c, "systemctl restart douyinweb-api --no-block; sleep 5; systemctl is-active douyinweb-api")
|
||||||
|
run(c, "curl -sS http://127.0.0.1:8014/api/auth/status; echo")
|
||||||
|
run(c, "curl -sS http://127.0.0.1:8014/api/pb/health | head -c 600; echo")
|
||||||
|
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
|
||||||
|
raise SystemExit(1)
|
||||||
|
run(c, "systemctl restart douyinweb-web --no-block; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
|
||||||
|
run(c, f"cd {REMOTE}/backend && python -m pytest tests/ -q", timeout=120)
|
||||||
|
c.close()
|
||||||
|
print("DONE")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@ -1,33 +1,29 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy YT session fix, live-map server refresh, Shorts concurrency."""
|
||||||
|
import sys
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import paramiko
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
HOST = "107.173.30.245"
|
HOST = "107.173.30.245"
|
||||||
USER = "root"
|
USER = "root"
|
||||||
PASSWORD = "Xiao4669805"
|
PASSWORD = "Xiao4669805"
|
||||||
REMOTE = "/opt/douyinWEB"
|
REMOTE = "/opt/douyinWEB"
|
||||||
LOCAL = Path(__file__).resolve().parents[1]
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
FILES = [
|
FILES = [
|
||||||
"frontend/src/lib/api.js",
|
|
||||||
"frontend/src/components/SessionDetailModal.tsx",
|
|
||||||
"frontend/src/app/covers/page.tsx",
|
|
||||||
"frontend/src/app/settings/page.tsx",
|
|
||||||
"frontend/src/app/page.tsx",
|
|
||||||
"frontend/src/app/sessions/page.tsx",
|
|
||||||
"frontend/src/app/slots/page.tsx",
|
|
||||||
"frontend/src/app/anchors/page.tsx",
|
|
||||||
"backend/app/main.py",
|
|
||||||
"backend/app/db.py",
|
"backend/app/db.py",
|
||||||
"backend/app/cover.py",
|
"backend/app/main.py",
|
||||||
"backend/app/pb_sync.py",
|
"backend/app/shorts_pipeline.py",
|
||||||
"backend/app/monitor.py",
|
"frontend/src/lib/youtubeLive.ts",
|
||||||
"backend/app/douyin.py",
|
"frontend/src/components/Shell.tsx",
|
||||||
|
"frontend/src/app/groups/page.tsx",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def run(c, cmd, timeout=360):
|
def run(c, cmd, timeout=420):
|
||||||
print("$", cmd[:140], flush=True)
|
print("$", cmd[:180], flush=True)
|
||||||
chan = c.get_transport().open_session()
|
chan = c.get_transport().open_session()
|
||||||
chan.settimeout(timeout)
|
chan.settimeout(timeout)
|
||||||
chan.get_pty()
|
chan.get_pty()
|
||||||
@ -42,7 +38,9 @@ def run(c, cmd, timeout=360):
|
|||||||
while chan.recv_ready():
|
while chan.recv_ready():
|
||||||
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
code = chan.recv_exit_status()
|
code = chan.recv_exit_status()
|
||||||
print("".join(buf)[-2200:], flush=True)
|
text = "".join(buf)
|
||||||
|
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
|
||||||
|
print(clean[-2000:], flush=True)
|
||||||
return code
|
return code
|
||||||
|
|
||||||
|
|
||||||
@ -52,24 +50,17 @@ def main():
|
|||||||
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
sftp = c.open_sftp()
|
sftp = c.open_sftp()
|
||||||
for rel in FILES:
|
for rel in FILES:
|
||||||
local = LOCAL / rel
|
|
||||||
if not local.exists():
|
|
||||||
print("skip", rel)
|
|
||||||
continue
|
|
||||||
print("upload", rel, flush=True)
|
print("upload", rel, flush=True)
|
||||||
sftp.put(str(local), f"{REMOTE}/{rel}")
|
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
|
||||||
sftp.close()
|
sftp.close()
|
||||||
run(c, "systemctl restart douyinweb-api --no-block; sleep 3; systemctl is-active douyinweb-api")
|
|
||||||
code = run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=360)
|
|
||||||
if code != 0:
|
|
||||||
raise SystemExit(1)
|
|
||||||
run(c, "systemctl restart douyinweb-web --no-block; sleep 4; systemctl start douyinweb-api douyinweb-web; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
|
|
||||||
run(
|
run(
|
||||||
c,
|
c,
|
||||||
"curl -s http://127.0.0.1:8014/api/health | head -c 500; echo; "
|
"systemctl restart douyinweb-api --no-block; sleep 4; systemctl is-active douyinweb-api",
|
||||||
"curl -s -o /dev/null -w 'home=%{http_code} settings=%{http_code} covers=%{http_code}\\n' "
|
|
||||||
"http://127.0.0.1:4015/ http://127.0.0.1:4015/settings http://127.0.0.1:4015/covers",
|
|
||||||
)
|
)
|
||||||
|
run(c, "curl -sS 'http://127.0.0.1:8014/api/shorts/status' | head -c 400; echo")
|
||||||
|
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
|
||||||
|
raise SystemExit(1)
|
||||||
|
run(c, "systemctl restart douyinweb-web --no-block; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
|
||||||
c.close()
|
c.close()
|
||||||
print("DONE")
|
print("DONE")
|
||||||
|
|
||||||
|
|||||||
64
scripts/deploy_oauth_scopes.py
Normal file
64
scripts/deploy_oauth_scopes.py
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
HOST = "107.173.30.245"
|
||||||
|
USER = "root"
|
||||||
|
PASSWORD = "Xiao4669805"
|
||||||
|
REMOTE = "/opt/douyinWEB"
|
||||||
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
|
FILES = [
|
||||||
|
"backend/app/shorts_oauth.py",
|
||||||
|
"backend/app/main.py",
|
||||||
|
"frontend/src/components/GoogleOauthSetupWizard.tsx",
|
||||||
|
"docs/SHORTS.md",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, timeout=420):
|
||||||
|
print("$", cmd[:160], flush=True)
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(timeout)
|
||||||
|
chan.get_pty()
|
||||||
|
chan.exec_command(cmd)
|
||||||
|
buf = []
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.25)
|
||||||
|
while chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
code = chan.recv_exit_status()
|
||||||
|
print("".join(buf)[-1800:], flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
for rel in FILES:
|
||||||
|
print("upload", rel, flush=True)
|
||||||
|
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
|
||||||
|
sftp.close()
|
||||||
|
run(c, "systemctl restart douyinweb-api; sleep 3; systemctl is-active douyinweb-api")
|
||||||
|
run(
|
||||||
|
c,
|
||||||
|
"cd /opt/douyinWEB/backend && .venv/bin/python -c "
|
||||||
|
"\"from app.shorts_oauth import requested_scopes; print('\\n'.join(requested_scopes()))\"",
|
||||||
|
)
|
||||||
|
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
|
||||||
|
raise SystemExit(1)
|
||||||
|
run(c, "systemctl restart douyinweb-web --no-block; sleep 2; systemctl is-active douyinweb-web")
|
||||||
|
c.close()
|
||||||
|
print("DONE")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@ -13,16 +13,27 @@ PASSWORD = "Xiao4669805"
|
|||||||
REMOTE = "/opt/douyinWEB"
|
REMOTE = "/opt/douyinWEB"
|
||||||
LOCAL = Path(__file__).resolve().parents[1]
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
FILES = [
|
FILES = [
|
||||||
"backend/app/models.py",
|
|
||||||
"backend/app/db.py",
|
"backend/app/db.py",
|
||||||
"backend/app/main.py",
|
"backend/app/models.py",
|
||||||
"backend/app/shorts_oauth.py",
|
|
||||||
"backend/app/shorts_pipeline.py",
|
"backend/app/shorts_pipeline.py",
|
||||||
|
"backend/app/main.py",
|
||||||
|
"backend/app/timeutil.py",
|
||||||
|
"backend/app/shorts_oauth.py",
|
||||||
"backend/app/shorts_clip.py",
|
"backend/app/shorts_clip.py",
|
||||||
|
"backend/app/shorts_schedule.py",
|
||||||
|
"backend/app/shorts_upload.py",
|
||||||
|
"backend/app/youtube_live.py",
|
||||||
|
"frontend/src/lib/youtubeLive.ts",
|
||||||
|
"frontend/src/components/YouTubeLiveBadge.tsx",
|
||||||
"frontend/src/components/Shell.tsx",
|
"frontend/src/components/Shell.tsx",
|
||||||
"frontend/src/components/GoogleOauthSetupWizard.tsx",
|
"frontend/src/components/ShortsUploadUx.tsx",
|
||||||
|
"frontend/src/components/ShortsJobDetailModal.tsx",
|
||||||
|
"frontend/src/components/GlobalEventAlerts.tsx",
|
||||||
"frontend/src/app/settings/page.tsx",
|
"frontend/src/app/settings/page.tsx",
|
||||||
"frontend/src/app/shorts/page.tsx",
|
"frontend/src/app/shorts/page.tsx",
|
||||||
|
"backend/app/notify.py",
|
||||||
|
"docs/SHORTS.md",
|
||||||
|
"README.md",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -54,7 +65,7 @@ def main():
|
|||||||
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
sftp = c.open_sftp()
|
sftp = c.open_sftp()
|
||||||
# ensure remote dirs for new paths
|
# ensure remote dirs for new paths
|
||||||
for d in ("frontend/src/app/shorts", "backend/app"):
|
for d in ("frontend/src/app/shorts", "backend/app", "docs"):
|
||||||
try:
|
try:
|
||||||
sftp.stat(f"{REMOTE}/{d}")
|
sftp.stat(f"{REMOTE}/{d}")
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
@ -77,8 +88,10 @@ def main():
|
|||||||
"cd /opt/douyinWEB/backend && .venv/bin/python -c "
|
"cd /opt/douyinWEB/backend && .venv/bin/python -c "
|
||||||
"\"from app import db; from app.shorts_pipeline import shorts_pipeline; "
|
"\"from app import db; from app.shorts_pipeline import shorts_pipeline; "
|
||||||
"db.init_db(); "
|
"db.init_db(); "
|
||||||
|
"n=db.enforce_shorts_daily_force(); "
|
||||||
"db.update_settings_map({'shorts_clip_sec': 15}); "
|
"db.update_settings_map({'shorts_clip_sec': 15}); "
|
||||||
"cfg=db.get_settings_map(); "
|
"cfg=db.get_settings_map(); "
|
||||||
|
"print('enforced', n); "
|
||||||
"print('shorts_enabled', cfg.get('shorts_enabled')); "
|
"print('shorts_enabled', cfg.get('shorts_enabled')); "
|
||||||
"print('clip_sec', cfg.get('shorts_clip_sec')); "
|
"print('clip_sec', cfg.get('shorts_clip_sec')); "
|
||||||
"print('live_sample', cfg.get('shorts_live_sample')); "
|
"print('live_sample', cfg.get('shorts_live_sample')); "
|
||||||
|
|||||||
85
scripts/deploy_shorts_live_analytics.py
Normal file
85
scripts/deploy_shorts_live_analytics.py
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy Shorts channel live analytics."""
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "107.173.30.245"
|
||||||
|
USER = "root"
|
||||||
|
PASSWORD = "Xiao4669805"
|
||||||
|
REMOTE = "/opt/douyinWEB"
|
||||||
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
|
FILES = [
|
||||||
|
"backend/app/db.py",
|
||||||
|
"backend/app/main.py",
|
||||||
|
"backend/app/youtube_live.py",
|
||||||
|
"frontend/src/app/shorts/page.tsx",
|
||||||
|
"frontend/src/app/sessions/page.tsx",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, timeout=420):
|
||||||
|
print("$", cmd[:180], flush=True)
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(timeout)
|
||||||
|
chan.get_pty()
|
||||||
|
chan.exec_command(cmd)
|
||||||
|
buf = []
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.25)
|
||||||
|
while chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
print("".join(buf)[-2200:], flush=True)
|
||||||
|
return chan.recv_exit_status()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
for rel in FILES:
|
||||||
|
print("upload", rel, flush=True)
|
||||||
|
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
|
||||||
|
sftp.close()
|
||||||
|
run(
|
||||||
|
c,
|
||||||
|
"systemctl kill -s SIGKILL douyinweb-api || true; sleep 1; "
|
||||||
|
"systemctl reset-failed douyinweb-api || true; "
|
||||||
|
"systemctl start douyinweb-api; sleep 5; systemctl is-active douyinweb-api",
|
||||||
|
timeout=90,
|
||||||
|
)
|
||||||
|
py = r"""
|
||||||
|
from app import db, youtube_live
|
||||||
|
from app.session_auth import create_session_token, get_admin_credentials, SESSION_COOKIE
|
||||||
|
import httpx, asyncio
|
||||||
|
db.init_db()
|
||||||
|
user,_=get_admin_credentials(); tok=create_session_token(user)
|
||||||
|
async def go():
|
||||||
|
m=await youtube_live.build_live_map(force=True)
|
||||||
|
print('live_count', m.get('live_count'), 'sync', m.get('shorts_live_sync'))
|
||||||
|
asyncio.get_event_loop().run_until_complete(go())
|
||||||
|
with httpx.Client(base_url='http://127.0.0.1:8014', timeout=90, cookies={SESSION_COOKIE: tok}) as c:
|
||||||
|
r=c.get('/api/shorts/live-analytics')
|
||||||
|
print('analytics', r.status_code)
|
||||||
|
d=r.json()
|
||||||
|
st=(d.get('stats') or {}).get('overview') or {}
|
||||||
|
print('sessions', st.get('sessions'), 'hours', st.get('total_hours'), 'live_now', d.get('live_now'), 'channels', len(d.get('channels') or []))
|
||||||
|
"""
|
||||||
|
run(c, "cd /opt/douyinWEB/backend && .venv/bin/python - <<'PY'\n" + py + "\nPY\n", timeout=180)
|
||||||
|
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
|
||||||
|
raise SystemExit(1)
|
||||||
|
run(c, "systemctl restart douyinweb-web --no-block; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
|
||||||
|
c.close()
|
||||||
|
print("DONE")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
70
scripts/deploy_site_auth.py
Normal file
70
scripts/deploy_site_auth.py
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "107.173.30.245"
|
||||||
|
USER = "root"
|
||||||
|
PASSWORD = "Xiao4669805"
|
||||||
|
REMOTE = "/opt/douyinWEB"
|
||||||
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
|
FILES = [
|
||||||
|
"backend/app/session_auth.py",
|
||||||
|
"backend/app/main.py",
|
||||||
|
"frontend/src/app/login/page.tsx",
|
||||||
|
"frontend/src/app/settings/page.tsx",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, timeout=420):
|
||||||
|
print("$", cmd[:180], flush=True)
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(timeout)
|
||||||
|
chan.get_pty()
|
||||||
|
chan.exec_command(cmd)
|
||||||
|
buf = []
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.25)
|
||||||
|
while chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
code = chan.recv_exit_status()
|
||||||
|
text = "".join(buf)
|
||||||
|
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
|
||||||
|
print(clean[-2000:], flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
run(c, f"mkdir -p {REMOTE}/frontend/src/app/login")
|
||||||
|
for rel in FILES:
|
||||||
|
print("upload", rel, flush=True)
|
||||||
|
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
|
||||||
|
sftp.close()
|
||||||
|
run(c, "systemctl restart douyinweb-api --no-block; sleep 6; systemctl is-active douyinweb-api")
|
||||||
|
run(
|
||||||
|
c,
|
||||||
|
"curl -sS -X POST http://127.0.0.1:8014/api/auth/login "
|
||||||
|
"-H 'Content-Type: application/json' "
|
||||||
|
"-d '{\"username\":\"hackrobot\",\"password\":\"Xiao4669805@!\"}' -c /tmp/dyck.txt | head -c 200; echo",
|
||||||
|
)
|
||||||
|
run(c, "curl -sS http://127.0.0.1:8014/api/auth/me -b /tmp/dyck.txt; echo")
|
||||||
|
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
|
||||||
|
raise SystemExit(1)
|
||||||
|
run(c, "systemctl restart douyinweb-web --no-block; sleep 4; systemctl is-active douyinweb-api douyinweb-web")
|
||||||
|
c.close()
|
||||||
|
print("DONE")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
78
scripts/deploy_ux.py
Normal file
78
scripts/deploy_ux.py
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy frontend UX pass (ConfirmDialog, Toast, loading, pagination)."""
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "107.173.30.245"
|
||||||
|
USER = "root"
|
||||||
|
PASSWORD = "Xiao4669805"
|
||||||
|
REMOTE = "/opt/douyinWEB"
|
||||||
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
|
FILES = [
|
||||||
|
"frontend/src/components/ConfirmDialog.tsx",
|
||||||
|
"frontend/src/components/Providers.tsx",
|
||||||
|
"frontend/src/components/Toast.tsx",
|
||||||
|
"frontend/src/components/Shell.tsx",
|
||||||
|
"frontend/src/components/YouTubeLiveTicker.tsx",
|
||||||
|
"frontend/src/components/ui.tsx",
|
||||||
|
"frontend/src/components/SessionDetailModal.tsx",
|
||||||
|
"frontend/src/components/RoomQuickActions.tsx",
|
||||||
|
"frontend/src/components/ShortsUploadUx.tsx",
|
||||||
|
"frontend/src/lib/api.js",
|
||||||
|
"frontend/src/app/login/page.tsx",
|
||||||
|
"frontend/src/app/page.tsx",
|
||||||
|
"frontend/src/app/events/page.tsx",
|
||||||
|
"frontend/src/app/sessions/page.tsx",
|
||||||
|
"frontend/src/app/groups/page.tsx",
|
||||||
|
"frontend/src/app/rooms/page.tsx",
|
||||||
|
"frontend/src/app/blacklist/page.tsx",
|
||||||
|
"frontend/src/app/shorts/page.tsx",
|
||||||
|
"frontend/src/app/youtube/page.tsx",
|
||||||
|
"frontend/src/app/settings/page.tsx",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, timeout=420):
|
||||||
|
print("$", cmd[:180], flush=True)
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(timeout)
|
||||||
|
chan.get_pty()
|
||||||
|
chan.exec_command(cmd)
|
||||||
|
buf = []
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.25)
|
||||||
|
while chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
code = chan.recv_exit_status()
|
||||||
|
text = "".join(buf)
|
||||||
|
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
|
||||||
|
print(clean[-2500:], flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
for rel in FILES:
|
||||||
|
print("upload", rel, flush=True)
|
||||||
|
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
|
||||||
|
sftp.close()
|
||||||
|
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
|
||||||
|
raise SystemExit(1)
|
||||||
|
run(c, "systemctl restart douyinweb-web --no-block; sleep 3; systemctl is-active douyinweb-web")
|
||||||
|
c.close()
|
||||||
|
print("DONE")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
84
scripts/deploy_youtube_live.py
Normal file
84
scripts/deploy_youtube_live.py
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "107.173.30.245"
|
||||||
|
USER = "root"
|
||||||
|
PASSWORD = "Xiao4669805"
|
||||||
|
REMOTE = "/opt/douyinWEB"
|
||||||
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
|
FILES = [
|
||||||
|
"backend/app/youtube_live.py",
|
||||||
|
"backend/app/main.py",
|
||||||
|
"youtube-svc/src/youtube.mjs",
|
||||||
|
"frontend/src/lib/youtubeLive.ts",
|
||||||
|
"frontend/src/components/YouTubeLiveBadge.tsx",
|
||||||
|
"frontend/src/components/Shell.tsx",
|
||||||
|
"frontend/src/app/groups/page.tsx",
|
||||||
|
"frontend/src/app/shorts/page.tsx",
|
||||||
|
"frontend/src/app/youtube/page.tsx",
|
||||||
|
"frontend/src/app/page.tsx",
|
||||||
|
"frontend/src/app/sessions/page.tsx",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, timeout=420):
|
||||||
|
print("$", cmd[:180], flush=True)
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(timeout)
|
||||||
|
chan.get_pty()
|
||||||
|
chan.exec_command(cmd)
|
||||||
|
buf = []
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.25)
|
||||||
|
while chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
code = chan.recv_exit_status()
|
||||||
|
text = "".join(buf)
|
||||||
|
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
|
||||||
|
print(clean[-2000:], flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
for rel in FILES:
|
||||||
|
print("upload", rel, flush=True)
|
||||||
|
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
|
||||||
|
sftp.close()
|
||||||
|
run(
|
||||||
|
c,
|
||||||
|
"systemctl restart douyinweb-yt --no-block; sleep 2; "
|
||||||
|
"systemctl kill -s SIGKILL douyinweb-api || true; sleep 1; "
|
||||||
|
"systemctl reset-failed douyinweb-api || true; "
|
||||||
|
"systemctl start douyinweb-api; sleep 3; "
|
||||||
|
"systemctl is-active douyinweb-yt douyinweb-api",
|
||||||
|
)
|
||||||
|
run(
|
||||||
|
c,
|
||||||
|
"curl -sS 'http://127.0.0.1:8020/channel/live?url=https://www.youtube.com/channel/UCtVfMFdLTN4ap__8g7MFtVw' | head -c 500; echo",
|
||||||
|
)
|
||||||
|
run(
|
||||||
|
c,
|
||||||
|
"curl -sS 'http://127.0.0.1:8014/api/youtube/live-map?force=1' | python3 -c \"import sys,json; d=json.load(sys.stdin); print('live_count',d.get('live_count')); [print(k,v) for k,v in d.get('entries',{}).items() if 'UCtVfMFdLTN4ap' in k]\"",
|
||||||
|
)
|
||||||
|
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
|
||||||
|
raise SystemExit(1)
|
||||||
|
run(c, "systemctl restart douyinweb-web --no-block; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
|
||||||
|
c.close()
|
||||||
|
print("DONE")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
68
scripts/deploy_youtube_manage.py
Normal file
68
scripts/deploy_youtube_manage.py
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "107.173.30.245"
|
||||||
|
USER = "root"
|
||||||
|
PASSWORD = "Xiao4669805"
|
||||||
|
REMOTE = "/opt/douyinWEB"
|
||||||
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
|
FILES = [
|
||||||
|
"backend/app/models.py",
|
||||||
|
"backend/app/main.py",
|
||||||
|
"backend/app/youtube_manage.py",
|
||||||
|
"frontend/src/app/youtube/page.tsx",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, timeout=420):
|
||||||
|
print("$", cmd[:180], flush=True)
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(timeout)
|
||||||
|
chan.get_pty()
|
||||||
|
chan.exec_command(cmd)
|
||||||
|
buf = []
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.25)
|
||||||
|
while chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
code = chan.recv_exit_status()
|
||||||
|
text = "".join(buf)
|
||||||
|
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
|
||||||
|
print(clean[-2000:], flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
for rel in FILES:
|
||||||
|
print("upload", rel, flush=True)
|
||||||
|
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
|
||||||
|
sftp.close()
|
||||||
|
run(
|
||||||
|
c,
|
||||||
|
"systemctl kill -s SIGKILL douyinweb-api || true; sleep 1; "
|
||||||
|
"systemctl reset-failed douyinweb-api || true; "
|
||||||
|
"systemctl start douyinweb-api; sleep 3; systemctl is-active douyinweb-api",
|
||||||
|
)
|
||||||
|
run(c, "curl -sS http://127.0.0.1:8014/api/youtube/manage/channels | head -c 500; echo")
|
||||||
|
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
|
||||||
|
raise SystemExit(1)
|
||||||
|
run(c, "systemctl restart douyinweb-web --no-block; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
|
||||||
|
c.close()
|
||||||
|
print("DONE")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
81
scripts/deploy_yt_analytics.py
Normal file
81
scripts/deploy_yt_analytics.py
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy YouTube analytics (groups tab + API)."""
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "107.173.30.245"
|
||||||
|
USER = "root"
|
||||||
|
PASSWORD = "Xiao4669805"
|
||||||
|
REMOTE = "/opt/douyinWEB"
|
||||||
|
LOCAL = Path(__file__).resolve().parents[1]
|
||||||
|
FILES = [
|
||||||
|
"backend/app/db.py",
|
||||||
|
"backend/app/main.py",
|
||||||
|
"frontend/src/lib/realtime.ts",
|
||||||
|
"frontend/src/app/groups/page.tsx",
|
||||||
|
"frontend/src/app/page.tsx",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run(c, cmd, timeout=420):
|
||||||
|
print("$", cmd[:180], flush=True)
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(timeout)
|
||||||
|
chan.get_pty()
|
||||||
|
chan.exec_command(cmd)
|
||||||
|
buf = []
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.25)
|
||||||
|
while chan.recv_ready():
|
||||||
|
buf.append(chan.recv(65535).decode("utf-8", "replace"))
|
||||||
|
out = "".join(buf)
|
||||||
|
print(out[-2000:], flush=True)
|
||||||
|
return chan.recv_exit_status()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
for rel in FILES:
|
||||||
|
print("upload", rel, flush=True)
|
||||||
|
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
|
||||||
|
sftp.close()
|
||||||
|
run(
|
||||||
|
c,
|
||||||
|
"systemctl kill -s SIGKILL douyinweb-api || true; sleep 1; "
|
||||||
|
"systemctl reset-failed douyinweb-api || true; "
|
||||||
|
"systemctl start douyinweb-api; sleep 4; systemctl is-active douyinweb-api",
|
||||||
|
timeout=90,
|
||||||
|
)
|
||||||
|
py = r"""
|
||||||
|
from app.session_auth import create_session_token, get_admin_credentials, SESSION_COOKIE
|
||||||
|
import httpx
|
||||||
|
user,_=get_admin_credentials(); tok=create_session_token(user)
|
||||||
|
with httpx.Client(base_url='http://127.0.0.1:8014', timeout=60, cookies={SESSION_COOKIE: tok}) as c:
|
||||||
|
r=c.get('/api/groups/analytics')
|
||||||
|
print('status', r.status_code)
|
||||||
|
d=r.json()
|
||||||
|
st=(d.get('stats') or {}).get('overview') or {}
|
||||||
|
print('sessions', st.get('sessions'), 'hours', st.get('total_hours'), 'active', st.get('active_sessions'))
|
||||||
|
print('channels', len(d.get('channels') or []), 'recent', len(d.get('recent_sessions') or []))
|
||||||
|
"""
|
||||||
|
run(c, "cd /opt/douyinWEB/backend && .venv/bin/python - <<'PY'\n" + py + "\nPY\n", timeout=120)
|
||||||
|
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=420) != 0:
|
||||||
|
raise SystemExit(1)
|
||||||
|
run(c, "systemctl restart douyinweb-web --no-block; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
|
||||||
|
c.close()
|
||||||
|
print("DONE")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
22
scripts/reconcile_clips_vps.py
Normal file
22
scripts/reconcile_clips_vps.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
import paramiko
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
cmd = (
|
||||||
|
"cd /opt/douyinWEB/backend && .venv/bin/python -c "
|
||||||
|
"'from app import db; db.init_db(); "
|
||||||
|
"m=db.reconcile_missing_shorts_clips(); h=db.reconcile_false_failed_shorts(); "
|
||||||
|
"print(\"missing\", m, \"healed\", h); "
|
||||||
|
"j=db.get_shorts_job(\"7c0e94e0-338a-4060-bbf9-7a16e7e26bc5\"); print(\"job\", j)'"
|
||||||
|
)
|
||||||
|
_, stdout, stderr = c.exec_command(cmd)
|
||||||
|
print(stdout.read().decode())
|
||||||
|
err = stderr.read().decode()
|
||||||
|
if err.strip():
|
||||||
|
print("stderr:", err)
|
||||||
|
c.close()
|
||||||
@ -2,21 +2,27 @@
|
|||||||
setlocal
|
setlocal
|
||||||
cd /d %~dp0\..
|
cd /d %~dp0\..
|
||||||
|
|
||||||
echo [1/3] Starting PocketBase on :8090 ...
|
echo [1/4] Starting PocketBase on :8090 ...
|
||||||
start "pocketbase" cmd /c "cd /d %~dp0\..\pb && pocketbase.exe serve --http=127.0.0.1:8090"
|
start "pocketbase" cmd /c "cd /d %~dp0\..\pb && pocketbase.exe serve --http=127.0.0.1:8090"
|
||||||
|
|
||||||
timeout /t 2 /nobreak >nul
|
timeout /t 2 /nobreak >nul
|
||||||
|
|
||||||
echo [2/3] Starting FastAPI on :8000 ...
|
echo [2/4] Starting YouTube sidecar on :8020 ...
|
||||||
start "fastapi" cmd /c "cd /d %~dp0\..\backend && python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload"
|
start "youtube-svc" cmd /c "cd /d %~dp0\..\youtube-svc && npm start"
|
||||||
|
|
||||||
timeout /t 2 /nobreak >nul
|
timeout /t 2 /nobreak >nul
|
||||||
|
|
||||||
echo [3/3] Starting Next.js on :3000 ...
|
echo [3/4] Starting FastAPI on :8000 ...
|
||||||
|
start "fastapi" cmd /c "cd /d %~dp0\..\backend && set DY_YOUTUBE_SVC_URL=http://127.0.0.1:8020 && python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload"
|
||||||
|
|
||||||
|
timeout /t 2 /nobreak >nul
|
||||||
|
|
||||||
|
echo [4/4] Starting Next.js on :3000 ...
|
||||||
start "nextjs" cmd /c "cd /d %~dp0\..\frontend && npx --yes next dev --port 3000 --hostname 127.0.0.1"
|
start "nextjs" cmd /c "cd /d %~dp0\..\frontend && npx --yes next dev --port 3000 --hostname 127.0.0.1"
|
||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo Open http://127.0.0.1:3000
|
echo Open http://127.0.0.1:3000
|
||||||
echo API http://127.0.0.1:8000/docs
|
echo API http://127.0.0.1:8000/docs
|
||||||
echo PB http://127.0.0.1:8090/_/
|
echo PB http://127.0.0.1:8090/_/
|
||||||
|
echo YT http://127.0.0.1:8020/health
|
||||||
endlocal
|
endlocal
|
||||||
|
|||||||
@ -160,39 +160,81 @@ export async function getChannelBundle(raw, { includeLive = true, includeVideos
|
|||||||
let live = null;
|
let live = null;
|
||||||
let upcoming = [];
|
let upcoming = [];
|
||||||
let lives = [];
|
let lives = [];
|
||||||
|
|
||||||
|
async function confirmLive(item) {
|
||||||
|
if (!item?.id) return null;
|
||||||
|
if (item.is_live) return item;
|
||||||
|
try {
|
||||||
|
const basic = await withYtRetry((client) => client.getBasicInfo(item.id));
|
||||||
|
const bi = basic?.basic_info || {};
|
||||||
|
if (bi.is_live) {
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
title: bi.title || item.title,
|
||||||
|
is_live: true,
|
||||||
|
is_upcoming: Boolean(bi.is_upcoming),
|
||||||
|
is_live_content: Boolean(bi.is_live_content),
|
||||||
|
view_count: bi.view_count != null ? String(bi.view_count) : item.view_count,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function scanFeedVideos(videos, limit = 12) {
|
||||||
|
for (const v of (videos || []).slice(0, limit)) {
|
||||||
|
const item = serializeVideo(v);
|
||||||
|
if (!item) continue;
|
||||||
|
lives.push(item);
|
||||||
|
if (item.is_upcoming) upcoming.push(item);
|
||||||
|
if (item.is_live && !live) {
|
||||||
|
live = item;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((item.is_live_content || item.is_live) && !live) {
|
||||||
|
const confirmed = await confirmLive(item);
|
||||||
|
if (confirmed) {
|
||||||
|
live = confirmed;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (includeLive) {
|
if (includeLive) {
|
||||||
|
// 1) Live tab
|
||||||
try {
|
try {
|
||||||
const feed = await channel.getLiveStreams();
|
const feed = await channel.getLiveStreams();
|
||||||
const videos = feed?.videos || [];
|
await scanFeedVideos(feed?.videos, 20);
|
||||||
for (const v of videos.slice(0, 20)) {
|
|
||||||
const item = serializeVideo(v);
|
|
||||||
if (!item) continue;
|
|
||||||
lives.push(item);
|
|
||||||
if (item.is_live && !live) live = item;
|
|
||||||
if (item.is_upcoming) upcoming.push(item);
|
|
||||||
}
|
|
||||||
// If badges weren't parsed, probe first item with getBasicInfo
|
|
||||||
if (!live && lives[0]?.id) {
|
if (!live && lives[0]?.id) {
|
||||||
try {
|
const confirmed = await confirmLive(lives[0]);
|
||||||
const basic = await withYtRetry((client) => client.getBasicInfo(lives[0].id));
|
if (confirmed) live = confirmed;
|
||||||
const bi = basic?.basic_info || {};
|
|
||||||
if (bi.is_live) {
|
|
||||||
live = {
|
|
||||||
...lives[0],
|
|
||||||
title: bi.title || lives[0].title,
|
|
||||||
is_live: true,
|
|
||||||
is_upcoming: Boolean(bi.is_upcoming),
|
|
||||||
is_live_content: Boolean(bi.is_live_content),
|
|
||||||
view_count: bi.view_count != null ? String(bi.view_count) : lives[0].view_count,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* some channels have no live tab */
|
/* some channels have no live tab */
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2) Home tab — active streams often pinned here
|
||||||
|
if (!live) {
|
||||||
|
try {
|
||||||
|
const home = await channel.getHome();
|
||||||
|
await scanFeedVideos(home?.videos, 10);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) Videos tab — recent live may appear as first upload
|
||||||
|
if (!live) {
|
||||||
|
try {
|
||||||
|
const feed = await channel.getVideos();
|
||||||
|
await scanFeedVideos(feed?.videos, 8);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let videos = [];
|
let videos = [];
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user