diff --git a/README.md b/README.md index ef0d08d..5276801 100644 --- a/README.md +++ b/README.md @@ -4,17 +4,20 @@ 可选旁路:**Shorts**(在播随机/开播入队 → 短成片 → YouTube Shorts 上传)。**默认关闭**,失败不影响监控 / 封面 / Webhook / 场次。 +控制台默认开启 **站点登录**(Cookie 会话);可选 `DY_API_KEY` 保护写操作。 + ## 线上地址 | 用途 | URL | |------|-----| | 控制台 | https://dylive.nomadro.com/ | +| 登录 | https://dylive.nomadro.com/login | | API Health | https://dylive.nomadro.com/api/health | | PocketBase | https://dylive.nomadro.com/_/ | | SeaweedFS S3 | https://feiniu.nomadro.com/ | | S3 别名 | https://s3.nomadro.com/ | | Shorts | https://dylive.nomadro.com/shorts | -| YouTube 探测 | https://dylive.nomadro.com/youtube | +| YouTube | https://dylive.nomadro.com/youtube | HTTPS 由服务器 **Caddy** 自动签发。进程端口: @@ -32,15 +35,25 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口: | 层 | 职责 | |----|------| -| **SQLite**(`backend/data/monitor.db`) | 监控热路径:轮询队列、场次、事件、Shorts 任务 | +| **SQLite**(`backend/data/monitor.db`) | 监控热路径:轮询队列、场次、事件、Shorts 任务、登录凭据哈希 | | **PocketBase** | 业务元数据双写镜像(房间 / 场次 / 事件 / yt_groups) | | **SeaweedFS S3** | 封面媒体存储;UI 经 API 代理展示(私有桶可读) | -| **Next.js 15** | 控制台 | -| **FastAPI** | 轮询、REST、SSE、封面补抓、Shorts worker | +| **Next.js 15** | 控制台(中间件校验登录 Cookie) | +| **FastAPI** | 轮询、REST、SSE、封面补抓、Shorts worker、YT live-map / manage | | **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 导出 @@ -51,12 +64,25 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口: - 进行中实时计时;列表页静默自动刷新 + SSE 开播/停播提示 - UI 时间统一 **北京时间** -### YouTube 分组轮询 +### YouTube 分组与在播地图 -- `/groups`:添加频道 URL / @handle,独立轮询开播状态 -- `/youtube`:InnerTube 探测(频道 / 直播 / 视频 / 搜索),可一键加入分组 +- `/groups`:添加频道 URL / @handle,独立轮询开播状态;**分析**页签看 YT 场次统计 +- `/youtube`:**管理**(OAuth 频道内容 CRUD)+ **探测**(InnerTube) +- **在播地图** `GET /api/youtube/live-map`:合并分组监控 + Shorts 频道;约 20s 后台刷新 / 15s 前端轮询 +- 首页 `YouTubeLiveTicker`、导航 LIVE 角标、分组/Shorts/场次 `YouTubeLiveBadge` +- Shorts 频道开播可同步为场次(`source: shorts_live`) - 设置页可启停 YouTube 轮询(与抖音监控开关分离) +### YouTube 频道管理 + +复用 Shorts OAuth refresh token(需含 manage / analytics 相关 scope): + +| 能力 | API | +|------|-----| +| 频道列表 / 画像 / 看板 | `/api/youtube/manage/...` | +| 视频列表、改元数据、删视频 | GET / PATCH / DELETE `.../videos/{video_id}` | +| 播放列表 | `.../playlists` | + ### Shorts 旁路(默认关) 详见 [docs/SHORTS.md](docs/SHORTS.md)。摘要: @@ -64,7 +90,8 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口: - **隔离**:`shorts_enabled=false` 时仅空转;入队/录制/上传异常不进入监控主路径 - **入队**:开播边缘钩子 + **当前在播随机取样**(默认开启,同房北京日仅一次) - **成片**:默认 **15 秒**,设置可切换 15 / 30 / 60 / 90 秒 -- **上传**:每频道 Google OAuth 一键授权;按频道日配额 5–9 轮转 +- **错峰上传**:录完 → `scheduled` + 抖动 `upload_at`;可「立即上传」绕过排程 +- **上传**:每频道 Google OAuth 一键授权;每频道北京日配额固定 **9** 条 - **不复用** sh2 RTMP 转播通道 ### 封面(S3) @@ -78,17 +105,18 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口: | 路由 | 说明 | |------|------| -| `/` | 雷达台:健康条、重点看板、今日六段、预计开播、抖音/YT 在播 | +| `/login` | 站点登录 | +| `/` | 雷达台:健康条、重点看板、今日六段、预计开播、抖音/YT 在播 ticker | | `/slots` | 开播时段规律:24h→6×4h,日/周热力 | -| `/sessions` | 场次列表 + 图表;日期预设;标签筛选;CSV | +| `/sessions` | 场次列表 + 图表;`platform` 可筛抖音 / youtube / shorts | | `/rooms` | 批量管理;预检;重检;批量标签;快捷收藏/拉黑 | | `/anchors` | 主播画像与下次开播启发式 | | `/covers` | 截图库(有图墙 / 缺图表) | | `/events` | SSE 时间线;场次详情;导出 | -| `/groups` | YouTube 频道分组监控 | -| `/youtube` | YouTube InnerTube 探测 | -| `/shorts` | Shorts 频道授权 / 任务队列 / 一键取样 | -| `/settings` | 防风控、通知、静默、YT/Shorts、PB/S3 运维 | +| `/groups` | YouTube 频道分组 + 分析页签 | +| `/youtube` | 频道管理(默认)+ InnerTube 探测 | +| `/shorts` | 授权 / 任务 / 排程 / 立即上传 / 在播分析 | +| `/settings` | 防风控、通知、静默、YT/Shorts、改密、PB/S3 运维 | | `/blacklist` | 黑名单 | ### 运维与通知 @@ -103,13 +131,14 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口: ``` 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、封面/成片缓存 - frontend/src/ Next.js App Router + frontend/src/ Next.js App Router(含 middleware) youtube-svc/ YouTube.js sidecar(InnerTube) pb/ PocketBase 数据与 migrations 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 - PB:http://127.0.0.1:8090/_/ -默认 PB:`admin@douyin.local` / `DouyinMonitor_Admin_2026` +默认 PB:`admin@douyin.local` / `DouyinMonitor_Admin_2026` +站点登录:见 `DY_ADMIN_*`(首次写入库后可在设置页改密)。 ```bat 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/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/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/sample-now` | 立即从在播房间随机入队 | | GET | `/api/shorts/oauth/start` | 跳转 Google 授权 | @@ -168,12 +208,22 @@ python scripts\sync_cookie_and_probe.py # 同步 Cookie 并抽样探测 VPS(需 SSH): ```bat -python scripts\deploy_ubuntu.py # 基础 Ubuntu 部署 -python scripts\deploy_seaweedfs.py # SeaweedFS + 封面能力 -python scripts\setup_caddy_dylive.py # dylive / feiniu / s3 反代 -python scripts\deploy_shorts.py # Shorts 旁路增量部署 -python scripts\deploy_dual_platform.py # 双平台 / 分组相关增量 -python scripts\restart_vps.py # 重启 douyinWEB 进程 +python scripts\deploy_ubuntu.py # 基础 Ubuntu 部署 +python scripts\deploy_seaweedfs.py # SeaweedFS + 封面能力 +python scripts\setup_caddy_dylive.py # dylive / feiniu / s3 反代 +python scripts\deploy_shorts.py # Shorts 旁路增量 +python scripts\deploy_dual_platform.py # 双平台 / 分组相关增量 +python scripts\deploy_site_auth.py # 站点登录 +python scripts\deploy_youtube_live.py # 在播地图 / LIVE 角标 +python scripts\deploy_youtube_manage.py # 频道管理 CRUD +python scripts\deploy_yt_analytics.py # 分组分析 +python scripts\deploy_shorts_live_analytics.py # Shorts 在播分析 +python scripts\deploy_oauth_scopes.py # OAuth scope 扩展 +python scripts\deploy_ux.py # 确认框 / 上传 UX / ticker +python scripts\deploy_feature_pass.py # 综合特性增量 +python scripts\deploy_all_features.py # 多特性打包部署 +python scripts\reconcile_clips_vps.py # VPS 成片对账 +python scripts\restart_vps.py # 重启 douyinWEB 进程 ``` ## 关键设置(防风控) @@ -192,6 +242,7 @@ python scripts\restart_vps.py # 重启 douyinWEB 进程 | `shorts_live_sample` | 默认 `true`;在播随机取样 | | `shorts_sample_any_live` | 默认 `true`;取样不限标签 | | `shorts_dedupe_room_day` | 默认 `true`;同房北京日仅一次 | +| `shorts_upload_spread` | 默认 `true`;错峰排程 | ## 环境变量(`DY_` 前缀) @@ -206,6 +257,11 @@ DY_S3_ACCESS_KEY=douyin DY_S3_SECRET_KEY=… DY_S3_BUCKET=douyin-covers DY_YOUTUBE_SVC_URL=http://127.0.0.1:8020 +DY_AUTH_ENABLED=true +DY_ADMIN_USERNAME=… +DY_ADMIN_PASSWORD=… +DY_SESSION_SECRET=… +DY_API_KEY= # 可选;非空则写操作需密钥 TZ=Asia/Shanghai ``` @@ -219,5 +275,6 @@ https://gitea.dsx2020.com/eric/douyinWEB.git - 仓库含 `backend/data/` 与 `pb/pb_data/`,便于部署后带真实房间与 Cookie 开箱可用。 - Windows `pocketbase.exe` 不入库;Ubuntu 使用 Linux 版 `pocketbase`。 +- **勿提交** Google `client_secret_*.json`;Client ID/Secret 走设置页或环境配置。 - **监控主路径**不含推流转播(推流仍在 sh2);**Shorts** 为可选短成片旁路,不占用 sh2 RTMP 车道。 - 「无图」历史场次:停播后接口常无封面,多数无法回补;以在播补抓与后续开播为准。 diff --git a/backend/app/auth.py b/backend/app/auth.py new file mode 100644 index 0000000..9647e79 --- /dev/null +++ b/backend/app/auth.py @@ -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) diff --git a/backend/app/config.py b/backend/app/config.py index 4e107be..fd4d6dd 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -47,6 +47,15 @@ class Settings(BaseSettings): # Node sidecar: youtubei.js (https://github.com/LuanRT/YouTube.js) 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: env_prefix = "DY_" env_file = ".env" diff --git a/backend/app/db.py b/backend/app/db.py index 6ab9a23..45aff61 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -13,6 +13,13 @@ from .models import extract_room_id, normalize_room_url, push_date_from_ts _lock = threading.RLock() +# Each Shorts channel is forced to exactly this many slots per Beijing day. +SHORTS_DAILY_FORCE = 9 + + +def _force_daily_quota(value: Any = None) -> int: + return int(SHORTS_DAILY_FORCE) + def _connect() -> sqlite3.Connection: conn = sqlite3.connect(str(settings.sqlite_path), check_same_thread=False) @@ -191,8 +198,37 @@ def init_db() -> None: conn.execute( "CREATE INDEX IF NOT EXISTS idx_channel_groups_next ON channel_groups(enabled, next_check_at)" ) + # shorts_jobs.upload_at for staggered uploads + sj_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_jobs)").fetchall()} + if "upload_at" not in sj_cols: + conn.execute("ALTER TABLE shorts_jobs ADD COLUMN upload_at REAL NOT NULL DEFAULT 0") + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_shorts_jobs_upload ON shorts_jobs(status, upload_at)" + ) + sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()} + for col, ddl in [ + ("oauth_ok", "INTEGER NOT NULL DEFAULT -1"), + ("oauth_checked_at", "REAL NOT NULL DEFAULT 0"), + ("oauth_error", "TEXT NOT NULL DEFAULT ''"), + ("last_status", "TEXT NOT NULL DEFAULT 'unknown'"), + ("last_checked_at", "REAL NOT NULL DEFAULT 0"), + ("last_title", "TEXT NOT NULL DEFAULT ''"), + ("last_live_url", "TEXT NOT NULL DEFAULT ''"), + ("last_live_video_id", "TEXT NOT NULL DEFAULT ''"), + ("active_session_id", "TEXT NOT NULL DEFAULT ''"), + ]: + if col not in sc_cols: + conn.execute(f"ALTER TABLE shorts_channels ADD COLUMN {col} {ddl}") conn.commit() _seed_defaults(conn) + try: + conn.execute( + "UPDATE shorts_channels SET daily_min = ?, daily_max = ?", + (SHORTS_DAILY_FORCE, SHORTS_DAILY_FORCE), + ) + conn.commit() + except Exception: + pass finally: conn.close() # repair leftover duplicate actives from concurrent go-live races @@ -202,6 +238,25 @@ def init_db() -> None: pass +def enforce_shorts_daily_force() -> int: + """Force every channel to daily_min=daily_max=SHORTS_DAILY_FORCE. Returns rows updated.""" + with _lock: + conn = _connect() + try: + cur = conn.execute( + """ + UPDATE shorts_channels + SET daily_min = ?, daily_max = ?, updated_at = ? + WHERE daily_min != ? OR daily_max != ? + """, + (SHORTS_DAILY_FORCE, SHORTS_DAILY_FORCE, time.time(), SHORTS_DAILY_FORCE, SHORTS_DAILY_FORCE), + ) + conn.commit() + return int(cur.rowcount) + finally: + conn.close() + + def _seed_defaults(conn: sqlite3.Connection) -> None: defaults = { "max_concurrency": settings.max_concurrency, @@ -220,6 +275,9 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "notify_on_live": True, "notify_on_offline": False, "notify_on_risk": True, + "notify_on_shorts_fail": True, + "notify_on_shorts_ok": False, + "notify_on_shorts_quota": True, "quiet_hours_enabled": False, "quiet_hours_start": 2, "quiet_hours_end": 7, @@ -243,6 +301,14 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "shorts_live_sample_interval_sec": 180, "shorts_live_sample_batch": 1, "shorts_sample_any_live": True, + "shorts_upload_spread": True, + "shorts_upload_min_gap_sec": 720, + "shorts_channel_min_gap_sec": 2400, + "shorts_delete_clip_after_upload": True, + "shorts_auto_retry_failed": True, + "shorts_auto_retry_max_attempts": 3, + "shorts_auto_retry_interval_sec": 300, + "shorts_oauth_check_interval_sec": 3600, "shorts_oauth_client_id": "", "shorts_oauth_client_secret": "", "shorts_oauth_redirect_uri": "https://dylive.nomadro.com/api/shorts/oauth/callback", @@ -381,13 +447,20 @@ def _platform_clause(platform: str, *, room_col: str, meta_col: str) -> tuple[st p = (platform or "").strip().lower() if p in ("youtube", "yt"): return ( - f"({room_col} LIKE 'yt:%' OR {meta_col} LIKE '%\"platform\": \"youtube\"%' " + f"({room_col} LIKE 'yt:%' OR {room_col} LIKE 'shorts:%' OR {meta_col} LIKE '%\"platform\": \"youtube\"%' " f"OR {meta_col} LIKE '%\"platform\":\"youtube\"%')", [], ) + if p in ("shorts", "shorts_live"): + return ( + f"({room_col} LIKE 'shorts:%' OR {meta_col} LIKE '%\"source\": \"shorts_live\"%' " + f"OR {meta_col} LIKE '%\"source\":\"shorts_live\"%')", + [], + ) if p in ("douyin", "dy"): return ( - f"({room_col} NOT LIKE 'yt:%' AND IFNULL({meta_col},'') NOT LIKE '%\"platform\": \"youtube\"%' " + f"({room_col} NOT LIKE 'yt:%' AND {room_col} NOT LIKE 'shorts:%' " + f"AND IFNULL({meta_col},'') NOT LIKE '%\"platform\": \"youtube\"%' " f"AND IFNULL({meta_col},'') NOT LIKE '%\"platform\":\"youtube\"%')", [], ) @@ -1319,6 +1392,58 @@ def counts() -> dict[str, int]: # ---------- sessions ---------- +def _is_yt_room_id(room_id: str) -> bool: + return str(room_id or "").startswith("yt:") + + +def _set_live_owner(conn, *, room_pk: str, session_id: str, now: float) -> None: + """Mark Douyin room / YouTube group / Shorts channel as live with active session.""" + cur = conn.execute( + "UPDATE rooms SET active_session_id = ?, last_status = 'live', updated_at = ? WHERE id = ?", + (session_id, now, room_pk), + ) + if cur.rowcount: + return + cur = conn.execute( + """ + UPDATE channel_groups SET active_session_id = ?, last_status = 'live', updated_at = ? + WHERE id = ? + """, + (session_id, now, room_pk), + ) + if cur.rowcount: + return + conn.execute( + """ + UPDATE shorts_channels SET active_session_id = ?, last_status = 'live', updated_at = ? + WHERE id = ? + """, + (session_id, now, room_pk), + ) + + +def _clear_live_owner_for_session(conn, *, session_id: str, room_pk: str, now: float) -> None: + conn.execute( + "UPDATE rooms SET active_session_id = '', updated_at = ? WHERE active_session_id = ?", + (now, session_id), + ) + if room_pk: + conn.execute( + """ + UPDATE channel_groups SET active_session_id = '', updated_at = ? + WHERE id = ? AND active_session_id = ? + """, + (now, room_pk, session_id), + ) + conn.execute( + """ + UPDATE shorts_channels SET active_session_id = '', updated_at = ? + WHERE id = ? AND active_session_id = ? + """, + (now, room_pk, session_id), + ) + + def start_session( *, room_pk: str, @@ -1365,10 +1490,7 @@ def start_session( """, (anchor_name, title, source_url, now, existing["id"]), ) - conn.execute( - "UPDATE rooms SET active_session_id = ?, last_status = 'live', updated_at = ? WHERE id = ?", - (existing["id"], now, room_pk), - ) + _set_live_owner(conn, room_pk=room_pk, session_id=existing["id"], now=now) conn.commit() out = _row_to_dict(conn.execute("SELECT * FROM sessions WHERE id = ?", (existing["id"],)).fetchone()) out["_reused"] = True @@ -1397,10 +1519,7 @@ def start_session( now, ), ) - conn.execute( - "UPDATE rooms SET active_session_id = ?, last_status = 'live', updated_at = ? WHERE id = ?", - (sid, now, room_pk), - ) + _set_live_owner(conn, room_pk=room_pk, session_id=sid, now=now) conn.commit() out = _row_to_dict(conn.execute("SELECT * FROM sessions WHERE id = ?", (sid,)).fetchone()) out["_reused"] = False @@ -1427,9 +1546,8 @@ def end_session(session_id: str, *, end_reason: str = "offline") -> dict[str, An """, (now, duration, end_reason, now, session_id), ) - conn.execute( - "UPDATE rooms SET active_session_id = '', updated_at = ? WHERE active_session_id = ?", - (now, session_id), + _clear_live_owner_for_session( + conn, session_id=session_id, room_pk=str(row["room_pk"] or ""), now=now ) conn.commit() return _row_to_dict(conn.execute("SELECT * FROM sessions WHERE id = ?", (session_id,)).fetchone()) @@ -1480,6 +1598,14 @@ def end_active_sessions_for_room( "UPDATE rooms SET active_session_id = '', updated_at = ? WHERE id = ?", (now, room_pk), ) + conn.execute( + "UPDATE channel_groups SET active_session_id = '', updated_at = ? WHERE id = ?", + (now, room_pk), + ) + conn.execute( + "UPDATE shorts_channels SET active_session_id = '', updated_at = ? WHERE id = ?", + (now, room_pk), + ) conn.commit() return ended finally: @@ -1499,25 +1625,62 @@ def reconcile_stale_active_sessions() -> dict[str, Any]: ).fetchall() now = time.time() for row in rows: - room = None - if row["room_pk"]: - room = conn.execute("SELECT * FROM rooms WHERE id = ?", (row["room_pk"],)).fetchone() - if not room and row["room_id"]: - room = conn.execute( - "SELECT * FROM rooms WHERE room_id = ?", (row["room_id"],) - ).fetchone() - room_status = (room["last_status"] if room else "") or "" + room_id = str(row["room_id"] or "") + room_pk = str(row["room_pk"] or "") stale = False reason = "keep" - if not room: - stale = True - reason = "no_room" - elif room_status in {"offline", "error", "unknown"}: - stale = True - reason = f"room_{room_status}" - elif room["active_session_id"] and room["active_session_id"] != row["id"]: - stale = True - reason = "orphaned" + owner = None + + if _is_yt_room_id(room_id): + if room_pk: + owner = conn.execute( + "SELECT * FROM channel_groups WHERE id = ?", (room_pk,) + ).fetchone() + owner_status = (owner["last_status"] if owner else "") or "" + if not owner: + stale = True + reason = "no_group" + elif owner_status in {"offline", "error", "unknown"}: + stale = True + reason = f"group_{owner_status}" + elif owner["active_session_id"] and owner["active_session_id"] != row["id"]: + stale = True + reason = "orphaned" + elif str(room_id).startswith("shorts:"): + if room_pk: + owner = conn.execute( + "SELECT * FROM shorts_channels WHERE id = ?", (room_pk,) + ).fetchone() + owner_status = (owner["last_status"] if owner else "") or "" + if not owner: + stale = True + reason = "no_shorts_channel" + elif owner_status in {"offline", "error", "unknown"}: + stale = True + reason = f"shorts_{owner_status}" + elif owner["active_session_id"] and owner["active_session_id"] != row["id"]: + stale = True + reason = "orphaned" + else: + room = None + if room_pk: + room = conn.execute("SELECT * FROM rooms WHERE id = ?", (room_pk,)).fetchone() + if not room and room_id: + room = conn.execute( + "SELECT * FROM rooms WHERE room_id = ?", (room_id,) + ).fetchone() + owner = room + room_status = (room["last_status"] if room else "") or "" + if not room: + stale = True + reason = "no_room" + elif room_status in {"offline", "error", "unknown"}: + stale = True + reason = f"room_{room_status}" + elif room["active_session_id"] and room["active_session_id"] != row["id"]: + stale = True + reason = "orphaned" + if stale: duration = max(0.0, now - float(row["started_at"])) conn.execute( @@ -1527,11 +1690,22 @@ def reconcile_stale_active_sessions() -> dict[str, Any]: """, (now, duration, f"reconcile:{reason}", now, row["id"]), ) - if room and (room["active_session_id"] or "") == row["id"]: - conn.execute( - "UPDATE rooms SET active_session_id = '', updated_at = ? WHERE id = ?", - (now, room["id"]), - ) + if owner and (owner["active_session_id"] or "") == row["id"]: + if _is_yt_room_id(room_id): + conn.execute( + "UPDATE channel_groups SET active_session_id = '', updated_at = ? WHERE id = ?", + (now, owner["id"]), + ) + elif str(room_id).startswith("shorts:"): + conn.execute( + "UPDATE shorts_channels SET active_session_id = '', updated_at = ? WHERE id = ?", + (now, owner["id"]), + ) + else: + conn.execute( + "UPDATE rooms SET active_session_id = '', updated_at = ? WHERE id = ?", + (now, owner["id"]), + ) closed += 1 details.append( {"id": row["id"], "anchor": row["anchor_name"] or "", "reason": reason} @@ -1780,6 +1954,115 @@ def all_sessions_for_stats( finally: conn.close() +def youtube_group_channel_stats( + *, + date_from: str = "", + date_to: str = "", +) -> list[dict[str, Any]]: + """Per YouTube monitored channel: session counts / hours (Beijing push_date range).""" + with _lock: + conn = _connect() + try: + clauses = [ + "(s.room_id LIKE 'yt:%' OR IFNULL(s.metadata_json,'') LIKE '%\"platform\": \"youtube\"%' " + "OR IFNULL(s.metadata_json,'') LIKE '%\"platform\":\"youtube\"%')" + ] + params: list[Any] = [time.time()] + if date_from: + clauses.append("s.push_date >= ?") + params.append(date_from) + if date_to: + clauses.append("s.push_date <= ?") + params.append(date_to) + where = " AND ".join(clauses) + rows = conn.execute( + f""" + SELECT + s.room_pk AS group_id, + s.room_id AS room_id, + COALESCE(NULLIF(MAX(s.anchor_name), ''), MAX(s.room_id)) AS anchor_name, + COUNT(*) AS sessions, + SUM(CASE WHEN s.ended_at IS NULL THEN (? - s.started_at) ELSE s.duration_seconds END) AS duration_seconds, + MAX(s.started_at) AS last_started_at, + SUM(CASE WHEN s.ended_at IS NULL THEN 1 ELSE 0 END) AS active + FROM sessions s + WHERE {where} + GROUP BY s.room_pk, s.room_id + ORDER BY sessions DESC, duration_seconds DESC + """, + params, + ).fetchall() + + groups = { + str(g["id"]): g + for g in ( + conn.execute( + "SELECT id, name, channel_id, channel_url, handle, enabled, last_status, last_title, last_live_url, last_checked_at FROM channel_groups WHERE platform = 'youtube'" + ).fetchall() + ) + } + out: list[dict[str, Any]] = [] + for r in rows: + gid = str(r["group_id"] or "") + g = groups.get(gid) or {} + cid = "" + rid = str(r["room_id"] or "") + if rid.startswith("yt:"): + cid = rid[3:] + if not cid: + cid = str(g.get("channel_id") or "") + out.append( + { + "group_id": gid or None, + "name": str(g.get("name") or r["anchor_name"] or cid or rid), + "channel_id": cid, + "channel_url": str(g.get("channel_url") or ""), + "handle": str(g.get("handle") or ""), + "enabled": bool(g.get("enabled")) if g else None, + "last_status": str(g.get("last_status") or ("live" if int(r["active"] or 0) else "offline")), + "last_title": str(g.get("last_title") or ""), + "last_live_url": str(g.get("last_live_url") or ""), + "last_checked_at": g.get("last_checked_at"), + "room_id": rid, + "anchor_name": r["anchor_name"], + "sessions": int(r["sessions"] or 0), + "hours_total": round(float(r["duration_seconds"] or 0) / 3600.0, 2), + "last_started_at": r["last_started_at"], + "active": int(r["active"] or 0), + } + ) + + # Include enabled groups with zero sessions so ranking is complete + seen = {str(x.get("group_id") or "") for x in out if x.get("group_id")} + for gid, g in groups.items(): + if gid in seen or not bool(g["enabled"]): + continue + out.append( + { + "group_id": gid, + "name": str(g["name"] or ""), + "channel_id": str(g["channel_id"] or ""), + "channel_url": str(g["channel_url"] or ""), + "handle": str(g["handle"] or ""), + "enabled": True, + "last_status": str(g["last_status"] or "offline"), + "last_title": str(g["last_title"] or ""), + "last_live_url": str(g["last_live_url"] or ""), + "last_checked_at": g["last_checked_at"], + "room_id": f"yt:{g['channel_id']}" if g["channel_id"] else "", + "anchor_name": str(g["name"] or ""), + "sessions": 0, + "hours_total": 0.0, + "last_started_at": None, + "active": 1 if str(g["last_status"] or "") == "live" else 0, + } + ) + out.sort(key=lambda x: (-int(x.get("sessions") or 0), -float(x.get("hours_total") or 0))) + return out + finally: + conn.close() + + # ---------- YouTube channel groups ---------- def _urls_to_storage(urls: Any) -> str: @@ -2178,7 +2461,7 @@ def create_shorts_channel( client_secret: str = "", refresh_token: str = "", enabled: bool = True, - daily_min: int = 5, + daily_min: int = 9, daily_max: int = 9, title_template: str = "{anchor} 直播瞬间 #Shorts", description_template: str = "{anchor}\n{url}\n#Shorts #直播", @@ -2187,6 +2470,8 @@ def create_shorts_channel( ) -> dict[str, Any]: now = time.time() cid = str(uuid.uuid4()) + daily_min = _force_daily_quota(daily_min) + daily_max = _force_daily_quota(daily_max) with _lock: conn = _connect() try: @@ -2206,8 +2491,8 @@ def create_shorts_channel( (client_secret or "").strip(), (refresh_token or "").strip(), 1 if enabled else 0, - max(0, int(daily_min)), - max(1, int(daily_max)), + daily_min, + daily_max, title_template or "{anchor} #Shorts", description_template or "", (privacy or "public").strip() or "public", @@ -2237,6 +2522,9 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: "privacy", "note", "last_assigned_at", + "oauth_ok", + "oauth_checked_at", + "oauth_error", } with _lock: conn = _connect() @@ -2249,12 +2537,16 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: for k, v in fields.items(): if k not in allowed or v is None: continue + if k in {"daily_min", "daily_max"}: + continue # forced below if k == "enabled": v = 1 if v else 0 sets.append(f"{k} = ?") params.append(v) - if not sets: - return _row_to_dict(row) # type: ignore + sets.append("daily_min = ?") + params.append(SHORTS_DAILY_FORCE) + sets.append("daily_max = ?") + params.append(SHORTS_DAILY_FORCE) sets.append("updated_at = ?") params.append(time.time()) params.append(channel_pk) @@ -2275,23 +2567,310 @@ def delete_shorts_channel(channel_pk: str) -> None: conn.close() +def touch_shorts_channel_live( + channel_pk: str, + *, + last_status: str, + last_title: str = "", + last_live_url: str = "", + last_live_video_id: str = "", + active_session_id: str = "", +) -> None: + now = time.time() + with _lock: + conn = _connect() + try: + conn.execute( + """ + UPDATE shorts_channels SET + last_status = ?, + last_checked_at = ?, + last_title = COALESCE(NULLIF(?, ''), last_title), + last_live_url = ?, + last_live_video_id = COALESCE(NULLIF(?, ''), last_live_video_id), + active_session_id = ?, + updated_at = ? + WHERE id = ? + """, + ( + last_status, + now, + last_title, + last_live_url, + last_live_video_id, + active_session_id, + now, + channel_pk, + ), + ) + conn.commit() + finally: + conn.close() + + +def sync_shorts_channel_lives_from_map(entries: dict[str, Any]) -> dict[str, int]: + """Persist Shorts upload-channel live edges into sessions (same analytics as Douyin).""" + started = 0 + ended = 0 + touched = 0 + for ch in list_shorts_channels(): + pk = str(ch.get("id") or "") + if not pk: + continue + ref = f"shorts:{pk}" + entry = entries.get(ref) if isinstance(entries.get(ref), dict) else {} + is_live = bool(entry.get("is_live")) + rid = f"shorts:{pk}" + prev = str(ch.get("last_status") or "") + active_sid = str(ch.get("active_session_id") or "") + title = str(entry.get("title") or ch.get("last_title") or "") + live_url = str(entry.get("live_url") or "") + vid = "" + if "watch?v=" in live_url: + vid = live_url.split("watch?v=", 1)[-1].split("&", 1)[0].strip() + name = str(ch.get("name") or ch.get("youtube_channel_id") or pk) + + if is_live: + if prev != "live" or not active_sid: + session = start_session( + room_pk=pk, + room_id=rid, + source_url=live_url + or f"https://www.youtube.com/channel/{ch.get('youtube_channel_id') or ''}", + anchor_name=name, + title=title, + metadata={ + "platform": "youtube", + "source": "shorts_live", + "shorts_channel_pk": pk, + "channel_id": ch.get("youtube_channel_id"), + "live_url": live_url, + "video_id": vid, + "detect_source": entry.get("source") or "", + }, + ) + active_sid = str(session.get("id") or "") + if not session.get("_reused"): + started += 1 + msg = f"Shorts 频道开播:{name}" + if title: + msg = f"Shorts 频道开播:{name} — {title}" + add_event( + kind="live", + level="info", + message=msg, + room_id=rid, + room_pk=pk, + session_id=active_sid, + anchor_name=name, + meta={ + "platform": "youtube", + "source": "shorts_live", + "shorts_channel_pk": pk, + "channel_id": ch.get("youtube_channel_id"), + "live_url": live_url, + "url": live_url, + }, + ) + touch_shorts_channel_live( + pk, + last_status="live", + last_title=title, + last_live_url=live_url, + last_live_video_id=vid, + active_session_id=active_sid, + ) + touched += 1 + else: + if prev == "live" or active_sid: + closed = end_active_sessions_for_room(room_pk=pk, room_id=rid, end_reason="offline") + ended += len(closed) + for item in closed: + add_event( + kind="offline", + level="info", + message=f"Shorts 频道停播:{name}", + room_id=rid, + room_pk=pk, + session_id=str(item.get("id") or ""), + anchor_name=name, + meta={ + "platform": "youtube", + "source": "shorts_live", + "shorts_channel_pk": pk, + "duration_seconds": item.get("duration_seconds"), + }, + ) + touch_shorts_channel_live( + pk, + last_status="offline", + last_title="", + last_live_url="", + last_live_video_id="", + active_session_id="", + ) + touched += 1 + return {"started": started, "ended": ended, "touched": touched} + + +def shorts_live_channel_stats(*, date_from: str = "", date_to: str = "") -> list[dict[str, Any]]: + """Per Shorts upload channel: live-session counts/hours.""" + with _lock: + conn = _connect() + try: + clauses = [ + "(s.room_id LIKE 'shorts:%' OR IFNULL(s.metadata_json,'') LIKE '%\"source\":\"shorts_live\"%' " + "OR IFNULL(s.metadata_json,'') LIKE '%\"source\": \"shorts_live\"%')" + ] + params: list[Any] = [time.time()] + if date_from: + clauses.append("s.push_date >= ?") + params.append(date_from) + if date_to: + clauses.append("s.push_date <= ?") + params.append(date_to) + where = " AND ".join(clauses) + rows = conn.execute( + f""" + SELECT + s.room_pk AS channel_pk, + s.room_id AS room_id, + COALESCE(NULLIF(MAX(s.anchor_name), ''), MAX(s.room_id)) AS anchor_name, + COUNT(*) AS sessions, + SUM(CASE WHEN s.ended_at IS NULL THEN (? - s.started_at) ELSE s.duration_seconds END) AS duration_seconds, + MAX(s.started_at) AS last_started_at, + SUM(CASE WHEN s.ended_at IS NULL THEN 1 ELSE 0 END) AS active + FROM sessions s + WHERE {where} + GROUP BY s.room_pk, s.room_id + ORDER BY sessions DESC, duration_seconds DESC + """, + params, + ).fetchall() + channels = { + str(c["id"]): dict(c) + for c in conn.execute( + "SELECT id, name, youtube_channel_id, enabled, last_status, last_title, last_live_url, last_checked_at, active_session_id FROM shorts_channels" + ).fetchall() + } + out: list[dict[str, Any]] = [] + seen: set[str] = set() + for r in rows: + pk = str(r["channel_pk"] or "") + ch = channels.get(pk) or {} + seen.add(pk) + out.append( + { + "id": pk or None, + "name": str(ch.get("name") or r["anchor_name"] or pk), + "youtube_channel_id": str(ch.get("youtube_channel_id") or ""), + "enabled": bool(ch.get("enabled")) if ch else None, + "last_status": str( + ch.get("last_status") or ("live" if int(r["active"] or 0) else "offline") + ), + "last_title": str(ch.get("last_title") or ""), + "last_live_url": str(ch.get("last_live_url") or ""), + "last_checked_at": ch.get("last_checked_at"), + "room_id": str(r["room_id"] or ""), + "sessions": int(r["sessions"] or 0), + "hours_total": round(float(r["duration_seconds"] or 0) / 3600.0, 2), + "last_started_at": r["last_started_at"], + "active": int(r["active"] or 0), + } + ) + for pk, ch in channels.items(): + if pk in seen: + continue + out.append( + { + "id": pk, + "name": str(ch["name"] or ""), + "youtube_channel_id": str(ch["youtube_channel_id"] or ""), + "enabled": bool(ch["enabled"]), + "last_status": str(ch["last_status"] or "offline"), + "last_title": str(ch["last_title"] or ""), + "last_live_url": str(ch["last_live_url"] or ""), + "last_checked_at": ch["last_checked_at"], + "room_id": f"shorts:{pk}", + "sessions": 0, + "hours_total": 0.0, + "last_started_at": None, + "active": 1 if str(ch["last_status"] or "") == "live" else 0, + } + ) + out.sort( + key=lambda x: ( + -int(x.get("active") or 0), + -int(x.get("sessions") or 0), + -float(x.get("hours_total") or 0), + ) + ) + return out + finally: + conn.close() + + +# Jobs that consume a channel's Beijing-day quota (aligned with schedule_board.used). +_SHORTS_QUOTA_STATUSES = ( + "pending", + "recording", + "recorded", + "scheduled", + "uploading", + "uploaded", + "done", +) + + def shorts_channel_upload_count(channel_pk: str, push_date: str) -> int: + placeholders = ",".join("?" for _ in _SHORTS_QUOTA_STATUSES) with _lock: conn = _connect() try: row = conn.execute( - """ + f""" SELECT COUNT(*) AS c FROM shorts_jobs WHERE channel_pk = ? AND push_date = ? - AND status IN ('pending','recording','recorded','uploading','uploaded','done') + AND status IN ({placeholders}) """, - (channel_pk, push_date), + (channel_pk, push_date, *_SHORTS_QUOTA_STATUSES), ).fetchone() return int(row["c"] if row else 0) finally: conn.close() +def shorts_channels_quota_summary(push_date: str = "") -> list[dict[str, Any]]: + """Per enabled channel: used/gap toward daily_max for the Beijing day.""" + day = push_date or push_date_from_ts(time.time()) + rows: list[dict[str, Any]] = [] + for ch in list_shorts_channels(enabled=True): + cid = str(ch["id"]) + daily_min = max(0, int(ch.get("daily_min") or SHORTS_DAILY_FORCE)) + daily_max = max(1, int(ch.get("daily_max") or SHORTS_DAILY_FORCE)) + daily_min = SHORTS_DAILY_FORCE + daily_max = SHORTS_DAILY_FORCE + used = shorts_channel_upload_count(cid, day) + rows.append( + { + "id": cid, + "name": ch.get("name"), + "daily_min": daily_min, + "daily_max": daily_max, + "used": used, + "gap": max(0, daily_max - used), + "min_met": used >= daily_min, + "max_met": used >= daily_max, + } + ) + rows.sort(key=lambda r: (0 if not r["min_met"] else 1, r["used"], r["id"])) + return rows + + +def shorts_total_quota_gap(push_date: str = "") -> int: + return sum(r["gap"] for r in shorts_channels_quota_summary(push_date)) + + def list_live_douyin_rooms_for_shorts(*, limit: int = 300) -> list[dict[str, Any]]: """Currently-live Douyin rooms from monitor state (no extra network).""" with _lock: @@ -2332,23 +2911,23 @@ def room_ids_with_shorts_job_today(push_date: str) -> set[str]: def pick_shorts_channel(push_date: str) -> dict[str, Any] | None: + """Pick enabled channel with most room left today (Beijing day); under daily_min first.""" channels = list_shorts_channels(enabled=True) if not channels: return None - scored: list[tuple[int, float, dict[str, Any]]] = [] + scored: list[tuple[int, int, float, dict[str, Any]]] = [] for ch in channels: used = shorts_channel_upload_count(str(ch["id"]), push_date) - daily_max = max(1, int(ch.get("daily_max") or 9)) + daily_max = SHORTS_DAILY_FORCE if used >= daily_max: continue - daily_min = max(0, int(ch.get("daily_min") or 5)) - # prefer under-min, then least used, then least recently assigned + daily_min = SHORTS_DAILY_FORCE under = 0 if used < daily_min else 1 - scored.append((under, used + float(ch.get("last_assigned_at") or 0) / 1e12, ch)) + scored.append((under, used, float(ch.get("last_assigned_at") or 0), ch)) if not scored: return None - scored.sort(key=lambda x: (x[0], x[1])) - return scored[0][2] + scored.sort(key=lambda x: (x[0], x[1], x[2])) + return scored[0][3] def list_shorts_jobs( @@ -2456,6 +3035,7 @@ def update_shorts_job(job_id: str, **fields: Any) -> dict[str, Any] | None: "attempts", "started_at", "finished_at", + "upload_at", } with _lock: conn = _connect() @@ -2482,34 +3062,52 @@ def update_shorts_job(job_id: str, **fields: Any) -> dict[str, Any] | None: conn.close() -def claim_next_shorts_job() -> dict[str, Any] | None: - """Atomically claim one pending/recorded job for processing.""" +def claim_due_shorts_upload() -> dict[str, Any] | None: + """Claim one due scheduled/recorded clip for upload.""" now = time.time() with _lock: conn = _connect() try: - # prefer pending (need record), then recorded (need upload) row = conn.execute( """ SELECT * FROM shorts_jobs - WHERE status IN ('pending', 'recorded') - ORDER BY CASE status WHEN 'pending' THEN 0 ELSE 1 END, created_at ASC + WHERE status = 'scheduled' + AND clip_path != '' + AND youtube_video_id = '' + AND upload_at > 0 + AND upload_at <= ? + ORDER BY upload_at ASC, created_at ASC LIMIT 1 - """ + """, + (now,), ).fetchone() + if not row: + row = conn.execute( + """ + SELECT * FROM shorts_jobs + WHERE status = 'recorded' + AND clip_path != '' + AND youtube_video_id = '' + AND upload_at > 0 + AND upload_at <= ? + ORDER BY upload_at ASC + LIMIT 1 + """, + (now,), + ).fetchone() if not row: return None jid = row["id"] status = row["status"] - next_status = "recording" if status == "pending" else "uploading" conn.execute( """ UPDATE shorts_jobs - SET status = ?, attempts = attempts + 1, started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END, + SET status = 'uploading', attempts = attempts + 1, + started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END, updated_at = ?, error = '' WHERE id = ? AND status = ? """, - (next_status, now, now, jid, status), + (now, now, jid, status), ) if conn.total_changes == 0: conn.rollback() @@ -2520,6 +3118,186 @@ def claim_next_shorts_job() -> dict[str, Any] | None: conn.close() +def claim_pending_shorts_record() -> dict[str, Any] | None: + """Claim one pending job for recording.""" + now = time.time() + with _lock: + conn = _connect() + try: + row = conn.execute( + """ + SELECT * FROM shorts_jobs + WHERE status = 'pending' + ORDER BY created_at ASC + LIMIT 1 + """ + ).fetchone() + if not row: + return None + jid = row["id"] + conn.execute( + """ + UPDATE shorts_jobs + SET status = 'recording', attempts = attempts + 1, + started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END, + updated_at = ?, error = '' + WHERE id = ? AND status = 'pending' + """, + (now, now, jid), + ) + if conn.total_changes == 0: + conn.rollback() + return None + conn.commit() + return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (jid,)).fetchone()) + finally: + conn.close() + + +def claim_next_shorts_job() -> dict[str, Any] | None: + """Prefer due upload, then pending record.""" + job = claim_due_shorts_upload() + if job: + return job + return claim_pending_shorts_record() + + +def reclaim_stale_shorts_uploads(*, max_age_sec: float = 180.0) -> int: + """Reset stuck uploading jobs back to scheduled (immediate retry).""" + cutoff = time.time() - max(60.0, float(max_age_sec)) + now = time.time() + with _lock: + conn = _connect() + try: + cur = conn.execute( + """ + UPDATE shorts_jobs + SET status = 'scheduled', upload_at = ?, error = '', updated_at = ? + WHERE status = 'uploading' + AND clip_path != '' + AND youtube_video_id = '' + AND COALESCE(NULLIF(started_at, 0), updated_at) < ? + """, + (now, now, cutoff), + ) + conn.commit() + return int(cur.rowcount) + finally: + conn.close() + + +def reconcile_false_failed_shorts(*, limit: int = 200) -> int: + """Restore jobs wrongly marked failed after a successful YouTube upload.""" + with _lock: + conn = _connect() + try: + rows = conn.execute( + """ + SELECT id FROM shorts_jobs + WHERE status = 'failed' + AND youtube_video_id != '' + ORDER BY updated_at DESC + LIMIT ? + """, + (max(1, min(int(limit), 500)),), + ).fetchall() + if not rows: + return 0 + now = time.time() + fixed = 0 + for row in rows: + conn.execute( + """ + UPDATE shorts_jobs + SET status = 'uploaded', error = '', clip_path = '', + finished_at = CASE WHEN finished_at = 0 THEN ? ELSE finished_at END, + updated_at = ? + WHERE id = ? AND status = 'failed' AND youtube_video_id != '' + """, + (now, now, row["id"]), + ) + if conn.total_changes: + fixed += 1 + conn.commit() + return fixed + finally: + conn.close() + + +def reconcile_missing_shorts_clips(*, limit: int = 200) -> int: + """Reset jobs whose clip_path points to a deleted file → pending re-record.""" + from pathlib import Path + + with _lock: + conn = _connect() + try: + rows = conn.execute( + """ + SELECT id, clip_path FROM shorts_jobs + WHERE clip_path != '' + AND status IN ('recorded', 'scheduled', 'uploading') + ORDER BY updated_at DESC + LIMIT ? + """, + (max(1, min(int(limit), 500)),), + ).fetchall() + fixed = 0 + now = time.time() + for row in rows: + path = str(row["clip_path"] or "").strip() + if not path or Path(path).is_file(): + continue + conn.execute( + """ + UPDATE shorts_jobs + SET status = 'pending', clip_path = '', clip_seconds = 0, + upload_at = 0, error = '成片已丢失,已重新排队录制', + finished_at = 0, updated_at = ? + WHERE id = ? AND status IN ('recorded', 'scheduled', 'uploading') + """, + (now, row["id"]), + ) + if conn.total_changes: + fixed += 1 + conn.commit() + return fixed + finally: + conn.close() + + +def claim_shorts_job_manual_upload(job_id: str) -> dict[str, Any] | None: + """Flip scheduled/recorded clip to uploading for manual upload-now.""" + now = time.time() + with _lock: + conn = _connect() + try: + row = conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone() + if not row: + return None + st = str(row["status"] or "") + if st not in {"scheduled", "recorded"}: + return None + if not str(row["clip_path"] or "").strip(): + return None + conn.execute( + """ + UPDATE shorts_jobs + SET status = 'uploading', upload_at = ?, attempts = attempts + 1, + started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END, + updated_at = ?, error = '' + WHERE id = ? AND status = ? + """, + (now, now, now, job_id, st), + ) + if conn.total_changes == 0: + conn.rollback() + return None + conn.commit() + return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone()) + finally: + conn.close() + + def has_shorts_job_for_room_day(room_id: str, push_date: str) -> bool: if not room_id: return False @@ -2556,3 +3334,335 @@ def shorts_stats(push_date: str = "") -> dict[str, Any]: return {"push_date": day, "by_status": by_status, "enabled_channels": int(channels)} finally: conn.close() + + +def _classify_shorts_error(error: str) -> str: + err = (error or "").lower() + if not err.strip(): + return "unknown" + if "oauth" in err or "refresh" in err or "授权" in err or "token" in err: + return "oauth" + if "成片" in err or "no such file" in err or "丢失" in err or "clip" in err: + return "missing_clip" + if "quota" in err or "rate" in err or "429" in err or "daily limit" in err: + return "quota" + if "ffmpeg" in err or "录制" in err or "stream" in err or "直播流" in err: + return "record" + if "上传" in err or "upload" in err or "youtube" in err or "googleapis" in err: + return "upload" + return "other" + + +def shorts_failed_groups(*, push_date: str = "", limit: int = 40) -> dict[str, Any]: + """Group recent failed jobs by error category for ops panel.""" + day = (push_date or "").strip() + with _lock: + conn = _connect() + try: + if day: + rows = conn.execute( + """ + SELECT * FROM shorts_jobs + WHERE status = 'failed' AND push_date = ? + ORDER BY COALESCE(NULLIF(finished_at, 0), updated_at) DESC + LIMIT ? + """, + (day, max(1, min(int(limit), 200))), + ).fetchall() + else: + rows = conn.execute( + """ + SELECT * FROM shorts_jobs + WHERE status = 'failed' + ORDER BY COALESCE(NULLIF(finished_at, 0), updated_at) DESC + LIMIT ? + """, + (max(1, min(int(limit), 200)),), + ).fetchall() + jobs = [_row_to_dict(r) for r in rows] + finally: + conn.close() + + buckets: dict[str, dict[str, Any]] = {} + labels = { + "oauth": "OAuth / 授权", + "missing_clip": "成片丢失", + "quota": "配额 / 限流", + "record": "录制失败", + "upload": "上传失败", + "other": "其他", + "unknown": "未知", + } + for j in jobs: + cat = _classify_shorts_error(str(j.get("error") or "")) + bucket = buckets.setdefault( + cat, + {"category": cat, "label": labels.get(cat, cat), "count": 0, "jobs": []}, + ) + bucket["count"] += 1 + if len(bucket["jobs"]) < 8: + bucket["jobs"].append( + { + "id": j.get("id"), + "anchor_name": j.get("anchor_name"), + "room_id": j.get("room_id"), + "channel_pk": j.get("channel_pk"), + "error": j.get("error"), + "push_date": j.get("push_date"), + "finished_at": j.get("finished_at"), + "updated_at": j.get("updated_at"), + } + ) + groups = sorted(buckets.values(), key=lambda x: (-int(x["count"]), str(x["category"]))) + return {"total": len(jobs), "groups": groups} + + +def shorts_stats_history(*, days: int = 7) -> dict[str, Any]: + """Beijing-day upload/fail/pending counts for the last N days.""" + n = max(1, min(int(days or 7), 30)) + today = push_date_from_ts(time.time()) + from datetime import datetime, timedelta + from zoneinfo import ZoneInfo + + bj = ZoneInfo("Asia/Shanghai") + base = datetime.strptime(today, "%Y-%m-%d").replace(tzinfo=bj) + day_list = [(base - timedelta(days=i)).strftime("%Y-%m-%d") for i in range(n - 1, -1, -1)] + with _lock: + conn = _connect() + try: + placeholders = ",".join("?" * len(day_list)) + rows = conn.execute( + f""" + SELECT push_date, status, COUNT(*) AS c + FROM shorts_jobs + WHERE push_date IN ({placeholders}) + GROUP BY push_date, status + """, + day_list, + ).fetchall() + finally: + conn.close() + by_day: dict[str, dict[str, int]] = {d: {} for d in day_list} + for r in rows: + d = str(r["push_date"] or "") + if d in by_day: + by_day[d][str(r["status"] or "")] = int(r["c"]) + series = [] + for d in day_list: + st = by_day[d] + uploaded = int(st.get("uploaded") or 0) + int(st.get("done") or 0) + failed = int(st.get("failed") or 0) + queued = ( + int(st.get("pending") or 0) + + int(st.get("recording") or 0) + + int(st.get("recorded") or 0) + + int(st.get("scheduled") or 0) + + int(st.get("uploading") or 0) + ) + total = sum(st.values()) + series.append( + { + "push_date": d, + "uploaded": uploaded, + "failed": failed, + "queued": queued, + "total": total, + "by_status": st, + "success_rate": round(uploaded / total, 3) if total else None, + } + ) + return {"days": n, "series": series} + + +def shorts_channel_performance(*, days: int = 7) -> dict[str, Any]: + """Per-channel uploaded/failed/success rate over recent Beijing days.""" + n = max(1, min(int(days or 7), 30)) + today = push_date_from_ts(time.time()) + from datetime import datetime, timedelta + from zoneinfo import ZoneInfo + + bj = ZoneInfo("Asia/Shanghai") + base = datetime.strptime(today, "%Y-%m-%d").replace(tzinfo=bj) + day_list = [(base - timedelta(days=i)).strftime("%Y-%m-%d") for i in range(n - 1, -1, -1)] + channels = list_shorts_channels(enabled=None) + ch_map = {str(c["id"]): c for c in channels} + with _lock: + conn = _connect() + try: + placeholders = ",".join("?" * len(day_list)) + rows = conn.execute( + f""" + SELECT channel_pk, status, COUNT(*) AS c + FROM shorts_jobs + WHERE push_date IN ({placeholders}) + GROUP BY channel_pk, status + """, + day_list, + ).fetchall() + finally: + conn.close() + by_ch: dict[str, dict[str, int]] = {} + for r in rows: + cid = str(r["channel_pk"] or "") + bucket = by_ch.setdefault(cid, {}) + bucket[str(r["status"] or "")] = int(r["c"]) + out = [] + for cid, ch in ch_map.items(): + st = by_ch.get(cid, {}) + uploaded = int(st.get("uploaded") or 0) + int(st.get("done") or 0) + failed = int(st.get("failed") or 0) + decided = uploaded + failed + out.append( + { + "id": cid, + "name": ch.get("name") or "", + "enabled": bool(ch.get("enabled")), + "authorized": bool(str(ch.get("refresh_token") or "").strip()), + "uploaded": uploaded, + "failed": failed, + "pending": int(st.get("pending") or 0), + "scheduled": int(st.get("scheduled") or 0), + "total": sum(st.values()), + "success_rate": round(uploaded / decided, 3) if decided else None, + } + ) + out.sort(key=lambda x: (-(x["uploaded"] or 0), -(x["total"] or 0), str(x["name"] or ""))) + return {"days": n, "push_dates": day_list, "channels": out} + + +def list_failed_shorts_job_ids(*, push_date: str = "", limit: int = 50) -> list[str]: + day = (push_date or "").strip() + lim = max(1, min(int(limit), 100)) + with _lock: + conn = _connect() + try: + if day: + rows = conn.execute( + """ + SELECT id FROM shorts_jobs + WHERE status = 'failed' AND push_date = ? + ORDER BY COALESCE(NULLIF(finished_at, 0), updated_at) DESC + LIMIT ? + """, + (day, lim), + ).fetchall() + else: + rows = conn.execute( + """ + SELECT id FROM shorts_jobs + WHERE status = 'failed' + ORDER BY COALESCE(NULLIF(finished_at, 0), updated_at) DESC + LIMIT ? + """, + (lim,), + ).fetchall() + return [str(r["id"]) for r in rows] + finally: + conn.close() + + +def list_auto_retry_failed_jobs(*, max_attempts: int = 3, limit: int = 8) -> list[dict[str, Any]]: + """Failed jobs eligible for automatic re-queue (skip permanent OAuth errors).""" + lim = max(1, min(int(limit), 30)) + max_att = max(1, min(int(max_attempts), 10)) + with _lock: + conn = _connect() + try: + rows = conn.execute( + """ + SELECT * FROM shorts_jobs + WHERE status = 'failed' + AND attempts < ? + AND COALESCE(finished_at, 0) > 0 + AND finished_at < ? + ORDER BY finished_at ASC + LIMIT ? + """, + (max_att, time.time() - 60, lim), + ).fetchall() + out: list[dict[str, Any]] = [] + for r in rows: + job = _row_to_dict(r) + err = str(job.get("error") or "") + low = err.lower() + if "invalid_grant" in low: + continue + if "oauth" in low and ("刷新" in err or "授权" in err): + continue + if "频道不存在" in err: + continue + out.append(job) + return out + finally: + conn.close() + + +def shorts_upload_heatmap(*, days: int = 1) -> dict[str, Any]: + """Beijing-hour distribution of uploaded / scheduled / failed jobs.""" + from .timeutil import beijing_hour + + n = max(1, min(int(days or 1), 14)) + today = push_date_from_ts(time.time()) + from datetime import datetime, timedelta + from zoneinfo import ZoneInfo + + bj = ZoneInfo("Asia/Shanghai") + base = datetime.strptime(today, "%Y-%m-%d").replace(tzinfo=bj) + day_list = [(base - timedelta(days=i)).strftime("%Y-%m-%d") for i in range(n - 1, -1, -1)] + with _lock: + conn = _connect() + try: + placeholders = ",".join("?" * len(day_list)) + rows = conn.execute( + f""" + SELECT status, finished_at, upload_at, created_at, updated_at + FROM shorts_jobs + WHERE push_date IN ({placeholders}) + AND status IN ('uploaded', 'done', 'scheduled', 'uploading', 'failed') + """, + day_list, + ).fetchall() + finally: + conn.close() + uploaded_hours = [0] * 24 + scheduled_hours = [0] * 24 + failed_hours = [0] * 24 + for r in rows: + st = str(r["status"] or "") + if st in {"uploaded", "done"}: + ts = float(r["finished_at"] or r["upload_at"] or r["created_at"] or 0) + if ts > 0: + uploaded_hours[beijing_hour(ts)] += 1 + elif st in {"scheduled", "uploading"}: + ts = float(r["upload_at"] or r["created_at"] or 0) + if ts > 0: + scheduled_hours[beijing_hour(ts)] += 1 + elif st == "failed": + ts = float(r["finished_at"] or r["updated_at"] or r["created_at"] or 0) + if ts > 0: + failed_hours[beijing_hour(ts)] += 1 + return { + "days": n, + "push_dates": day_list, + "hours": list(range(24)), + "uploaded": uploaded_hours, + "scheduled": scheduled_hours, + "failed": failed_hours, + "peak_hour": max(range(24), key=lambda i: uploaded_hours[i]) if sum(uploaded_hours) else None, + } + + +def table_counts() -> dict[str, int]: + """Row counts for PB drift diagnostics.""" + with _lock: + conn = _connect() + try: + return { + "rooms": int(conn.execute("SELECT COUNT(*) FROM rooms").fetchone()[0]), + "sessions": int(conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]), + "groups": int(conn.execute("SELECT COUNT(*) FROM channel_groups").fetchone()[0]), + "events": int(conn.execute("SELECT COUNT(*) FROM events").fetchone()[0]), + "blacklist": int(conn.execute("SELECT COUNT(*) FROM blacklist").fetchone()[0]), + } + finally: + conn.close() diff --git a/backend/app/main.py b/backend/app/main.py index b60aa4d..4706edf 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -10,11 +10,11 @@ from urllib.parse import quote from fastapi import FastAPI, HTTPException, Query, Request 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 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 .cover import cover_path_for, ensure_session_cover from .douyin import check_room @@ -33,10 +33,23 @@ from .models import ( SettingsUpdate, ShortsChannelCreate, ShortsChannelUpdate, + ShortsJobsBulkBody, + YouTubeVideoUpdate, ) from .monitor import monitor from .stats import summarize_anchor_schedule, summarize_sessions 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 .shorts_pipeline import shorts_pipeline from .timeutil import stamp_beijing @@ -57,6 +70,22 @@ async def lifespan(_: FastAPI): pass 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 yt_monitor.start() # 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.add_middleware( - CORSMiddleware, +app.add_middleware(ApiKeyMiddleware) + +app.add_middleware(CORSMiddleware, allow_origins=[o.strip() for o in settings.cors_origins.split(",") if o.strip()], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) +app.add_middleware(SessionAuthMiddleware) covers_dir = settings.covers_dir covers_dir.mkdir(parents=True, exist_ok=True) @@ -115,9 +146,64 @@ async def health() -> dict[str, Any]: "youtube_monitor": yt_monitor.status(), "monitor": monitor.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") async def monitor_status() -> dict[str, Any]: return monitor.status() @@ -185,6 +271,12 @@ def _public_shorts_channel(ch: dict[str, Any]) -> dict[str, Any]: out["authorized"] = bool(refresh.strip()) 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 "") + 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 @@ -197,16 +289,93 @@ def _request_public_base(request: Request) -> str: 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") async def shorts_status() -> dict[str, Any]: st = shorts_pipeline.status() st["oauth_configured"] = shorts_oauth.oauth_client_configured() 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() st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104") 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") async def shorts_oauth_start(channel_pk: str, request: Request) -> RedirectResponse: try: @@ -263,14 +432,31 @@ async def shorts_stop() -> dict[str, Any]: @app.post("/api/shorts/sample-now") async def shorts_sample_now() -> dict[str, Any]: """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() if not cfg.get("shorts_enabled"): raise HTTPException(400, "请先启用 Shorts") n = try_sample_live_rooms(cfg) + qn = try_fill_daily_quota(cfg) 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 @@ -316,27 +502,172 @@ async def shorts_jobs_list( limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), ) -> 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 ) + data["jobs"] = [_enrich_shorts_job(j) for j in data.get("jobs") or []] + return data @app.post("/api/shorts/jobs/{job_id}/retry") 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) if not job: raise HTTPException(404, "任务不存在") clip = str(job.get("clip_path") or "").strip() - next_status = "recorded" if clip else "pending" - updated = db.update_shorts_job( - job_id, - status=next_status, - error="", - finished_at=0, - youtube_video_id="", - youtube_url="", + if not clip: + raise HTTPException(404, "无成片") + path = Path(clip).resolve() + clips_root = settings.clips_dir.resolve() + try: + path.relative_to(clips_root) + except ValueError as exc: + 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}") @@ -574,6 +905,32 @@ async def groups_list( 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") async def groups_export() -> StreamingResponse: rows = db.export_channel_groups_rows() @@ -713,6 +1070,81 @@ async def youtube_health() -> dict[str, Any]: 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") async def youtube_resolve(url: str = Query(..., min_length=1)) -> dict[str, Any]: 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 +@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") async def events_list( 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} +@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") async def pb_bootstrap() -> dict[str, Any]: return await pb_sync.ensure_collections() diff --git a/backend/app/models.py b/backend/app/models.py index 011760f..1e0160c 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -193,6 +193,9 @@ class SettingsUpdate(BaseModel): notify_on_live: Optional[bool] = None notify_on_offline: 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_start: 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_batch: Optional[int] = 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_secret: Optional[str] = None shorts_oauth_redirect_uri: Optional[str] = None @@ -227,7 +238,7 @@ class ShortsChannelCreate(BaseModel): client_secret: str = "" refresh_token: str = "" enabled: bool = True - daily_min: int = 5 + daily_min: int = 9 daily_max: int = 9 title_template: str = "{anchor} 直播瞬间 #Shorts" description_template: str = "{anchor}\n{url}\n#Shorts #直播" @@ -250,6 +261,21 @@ class ShortsChannelUpdate(BaseModel): 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): older_than_days: float = 7 kind: str = "" diff --git a/backend/app/notify.py b/backend/app/notify.py index 3630a3d..31076fc 100644 --- a/backend/app/notify.py +++ b/backend/app/notify.py @@ -19,6 +19,12 @@ async def send_webhook(event: str, payload: dict[str, Any]) -> None: return if event == "risk" and not cfg.get("notify_on_risk", True): 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 body = { diff --git a/backend/app/pb_sync.py b/backend/app/pb_sync.py index 7808697..1d554d0 100644 --- a/backend/app/pb_sync.py +++ b/backend/app/pb_sync.py @@ -490,3 +490,69 @@ async def health() -> dict[str, Any]: return {"ok": ok, "status_code": resp.status_code, "body": body} except Exception as 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, + } diff --git a/backend/app/session_auth.py b/backend/app/session_auth.py new file mode 100644 index 0000000..17def7e --- /dev/null +++ b/backend/app/session_auth.py @@ -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) diff --git a/backend/app/shorts_oauth.py b/backend/app/shorts_oauth.py index 22d52d1..d0d9b13 100644 --- a/backend/app/shorts_oauth.py +++ b/backend/app/shorts_oauth.py @@ -13,8 +13,16 @@ from . import db 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.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) +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]: packed = _oauth_states.pop(state, None) 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(), "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} diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index 9459e1f..b0b6f1d 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -44,6 +44,7 @@ def _enqueue_job( room: dict[str, Any], stream_url: str = "", cfg: dict[str, Any] | None = None, + channel_pk: str = "", ) -> Optional[dict[str, Any]]: """Internal enqueue; never raises.""" try: @@ -56,7 +57,16 @@ def _enqueue_job( 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): 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: return None 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 +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: """Background worker; idle when shorts_enabled is false.""" def __init__(self) -> None: self._task: asyncio.Task | None = None self._stop = asyncio.Event() - self._busy = False + self._active_records = 0 + self._active_uploads = 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.processed = 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]: cfg = db.get_settings_map() @@ -169,17 +392,83 @@ class ShortsPipeline: stats = db.shorts_stats() except Exception: 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 { "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")), "processed": self.processed, "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, "clip_sec": int(cfg.get("shorts_clip_sec") or 15), "live_sample": bool(cfg.get("shorts_live_sample", True)), "sample_any_live": bool(cfg.get("shorts_sample_any_live", True)), + "douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)), + "douyin_live_rooms": [ + { + "room_id": r.get("room_id"), + "anchor": r.get("last_anchor") or r.get("last_title") or r.get("room_id"), + "session_id": r.get("active_session_id"), + } + for r in db.list_live_douyin_rooms_for_shorts(limit=12) + ], + "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, + "board": board, + "history": history, + "failed_groups": failed_groups, + "channel_perf": channel_perf, + "heatmap": heatmap, + "oauth_issues": oauth_issues, } async def start(self) -> None: @@ -205,6 +494,11 @@ class ShortsPipeline: await asyncio.sleep(5) continue + try: + db.enforce_shorts_daily_force() + except Exception: + pass + # Random sample from currently-live rooms (does not touch monitor loop) interval = float(cfg.get("shorts_live_sample_interval_sec") or 180) interval = max(60.0, interval) @@ -214,27 +508,346 @@ class ShortsPipeline: if n: self.sampled += n - max_c = max(1, int(cfg.get("shorts_max_concurrent") or 1)) - if self._busy: - await asyncio.sleep(1) - continue - _ = max_c - job = db.claim_next_shorts_job() + quota_interval = float(cfg.get("shorts_quota_fill_interval_sec") or 120) + quota_interval = max(60.0, quota_interval) + if (time.time() - self._last_quota_fill_at) >= quota_interval: + self._last_quota_fill_at = time.time() + qn = try_fill_daily_quota(cfg) + 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: await asyncio.sleep(2) continue - self._busy = True - try: - await self._process(job, cfg) - self.processed += 1 - finally: - self._busy = False + if runner == "upload": + self._active_uploads += 1 + asyncio.create_task(self._run_upload_only(job, cfg)) + else: + self._active_records += 1 + asyncio.create_task(self._run_job(job, cfg)) except asyncio.CancelledError: break except Exception as exc: self.last_error = str(exc)[:300] 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: jid = str(job["id"]) status = str(job.get("status") or "") @@ -243,21 +856,22 @@ class ShortsPipeline: await self._do_record(job, cfg) job = db.get_shorts_job(jid) or job status = str(job.get("status") or "") - if status == "uploading" or ( - status == "recorded" and cfg.get("shorts_auto_upload", True) - ): - if status == "recorded": - db.update_shorts_job(jid, status="uploading") - job = db.get_shorts_job(jid) or job + # Only upload when claim already flipped to uploading (due slot) + if status == "uploading": await self._do_upload(job, cfg) except Exception as exc: - self.last_error = str(exc)[:300] - db.update_shorts_job( - jid, - status="failed", - error=self.last_error, - finished_at=time.time(), - ) + 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]) async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None: jid = str(job["id"]) @@ -268,43 +882,100 @@ class ShortsPipeline: cookie=cookie, ) 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( jid, status="failed", error="无法获取直播流(可能已停播)", 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 sec = int(cfg.get("shorts_clip_sec") or 15) outcome = await record_clip(job_id=jid, stream_url=stream, seconds=sec) if not outcome.get("ok"): + err = str(outcome.get("error") or "录制失败") db.update_shorts_job( jid, status="failed", - error=str(outcome.get("error") or "录制失败"), + error=err, stream_url=stream, 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 - 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( jid, - status=next_status, - clip_path=str(outcome.get("path") or ""), + status="scheduled", + clip_path=clip_path, clip_seconds=float(outcome.get("seconds") or sec), stream_url=stream, + upload_at=upload_at, error="", ) async def _do_upload(self, job: dict[str, Any], cfg: dict[str, Any]) -> None: + from pathlib import Path + 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 "") if not clip: - db.update_shorts_job(jid, status="failed", error="无成片路径", finished_at=time.time()) + self._mark_failed(job, "无成片路径") return + if not Path(clip).is_file(): + raise ValueError("成片文件不存在,已重新排队录制") channel = db.get_shorts_channel(str(job.get("channel_pk") or "")) if not channel: - db.update_shorts_job(jid, status="failed", error="频道不存在", finished_at=time.time()) + self._mark_failed(job, "频道不存在") return 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"]): db.update_shorts_job( jid, - status="recorded", + status="scheduled" if float(job.get("upload_at") or 0) else "recorded", error="频道未授权 Google,已保留成片待上传", ) return @@ -340,17 +1011,27 @@ class ShortsPipeline: youtube_url=str(result.get("url") or ""), error="", 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: - db.add_event( - kind="ops", - level="info", - message=f"Shorts 已上传:{result.get('url')}", - room_id=str(job.get("room_id") or ""), - session_id=str(job.get("session_id") or ""), - anchor_name=anchor, - meta={"shorts_job_id": jid, "video_id": result.get("video_id")}, - ) + from pathlib import Path + + p = Path(path) + if p.is_file(): + p.unlink() except Exception: pass diff --git a/backend/app/shorts_schedule.py b/backend/app/shorts_schedule.py new file mode 100644 index 0000000..cc4776c --- /dev/null +++ b/backend/app/shorts_schedule.py @@ -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"), + } diff --git a/backend/app/shorts_upload.py b/backend/app/shorts_upload.py index 04739b7..83967e9 100644 --- a/backend/app/shorts_upload.py +++ b/backend/app/shorts_upload.py @@ -39,11 +39,15 @@ async def upload_shorts_mp4( ) -> dict[str, Any]: path = Path(file_path) if not path.is_file(): - raise ValueError("成片文件不存在") + raise ValueError("成片文件不存在,已重新排队录制") access = await refresh_access_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 = { "snippet": { "title": (title or "Shorts")[:100], @@ -59,7 +63,7 @@ async def upload_shorts_mp4( "https://www.googleapis.com/upload/youtube/v3/videos" "?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_url, headers={ @@ -73,7 +77,6 @@ async def upload_shorts_mp4( upload_url = init.headers.get("location") or init.headers.get("Location") if init.status_code >= 400 or not upload_url: raise ValueError(f"初始化上传失败: {init.text[:400]}") - raw = path.read_bytes() put = await client.put( upload_url, headers={ diff --git a/backend/app/timeutil.py b/backend/app/timeutil.py index 868968a..3b453ac 100644 --- a/backend/app/timeutil.py +++ b/backend/app/timeutil.py @@ -48,3 +48,12 @@ def next_hour_boundary_ts(ts: float) -> float: def beijing_today_at(hour: int, minute: int = 0) -> datetime: now = beijing_now() 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() diff --git a/backend/app/youtube_live.py b/backend/app/youtube_live.py new file mode 100644 index 0000000..50c9948 --- /dev/null +++ b/backend/app/youtube_live.py @@ -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 diff --git a/backend/app/youtube_manage.py b/backend/app/youtube_manage.py new file mode 100644 index 0000000..4b95df5 --- /dev/null +++ b/backend/app/youtube_manage.py @@ -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}, + } diff --git a/backend/app/youtube_monitor.py b/backend/app/youtube_monitor.py index cc0ad7b..232824e 100644 --- a/backend/app/youtube_monitor.py +++ b/backend/app/youtube_monitor.py @@ -182,6 +182,38 @@ class YouTubeMonitorService: item = {"ok": False, "error": str(exc), "input": key} 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]: self.checked_total += 1 self.last_check_at = time.time() @@ -217,6 +249,11 @@ class YouTubeMonitorService: return item 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 {} title = str(live.get("title") or item.get("title") or group.get("last_title") or "") live_url = str(live.get("url") or "") diff --git a/backend/data/monitor.db b/backend/data/monitor.db index 99d31a4..336211e 100644 Binary files a/backend/data/monitor.db and b/backend/data/monitor.db differ diff --git a/backend/requirements.txt b/backend/requirements.txt index 3e630e4..c588ab7 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -6,3 +6,5 @@ pydantic-settings==2.7.0 python-multipart==0.0.20 aiofiles==24.1.0 boto3==1.35.99 +pytest==8.3.4 + diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 0000000..9c7a4e6 --- /dev/null +++ b/backend/tests/conftest.py @@ -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 diff --git a/backend/tests/test_reconcile_yt.py b/backend/tests/test_reconcile_yt.py new file mode 100644 index 0000000..3df013c --- /dev/null +++ b/backend/tests/test_reconcile_yt.py @@ -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 diff --git a/backend/tests/test_shorts_missing_clip.py b/backend/tests/test_shorts_missing_clip.py new file mode 100644 index 0000000..967dd1b --- /dev/null +++ b/backend/tests/test_shorts_missing_clip.py @@ -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"]) diff --git a/backend/tests/test_shorts_ops.py b/backend/tests/test_shorts_ops.py new file mode 100644 index 0000000..812dae6 --- /dev/null +++ b/backend/tests/test_shorts_ops.py @@ -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" diff --git a/backend/tests/test_shorts_quota.py b/backend/tests/test_shorts_quota.py new file mode 100644 index 0000000..81f3f1d --- /dev/null +++ b/backend/tests/test_shorts_quota.py @@ -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 diff --git a/backend/tests/test_shorts_stats.py b/backend/tests/test_shorts_stats.py new file mode 100644 index 0000000..fa11a9c --- /dev/null +++ b/backend/tests/test_shorts_stats.py @@ -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 diff --git a/backend/tests/test_shorts_upload_now.py b/backend/tests/test_shorts_upload_now.py new file mode 100644 index 0000000..050b3f8 --- /dev/null +++ b/backend/tests/test_shorts_upload_now.py @@ -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 diff --git a/backend/tests/test_shorts_worker.py b/backend/tests/test_shorts_worker.py new file mode 100644 index 0000000..2b17100 --- /dev/null +++ b/backend/tests/test_shorts_worker.py @@ -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" diff --git a/backend/tests/test_youtube_live.py b/backend/tests/test_youtube_live.py new file mode 100644 index 0000000..6dbe9fe --- /dev/null +++ b/backend/tests/test_youtube_live.py @@ -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" diff --git a/docs/SHORTS.md b/docs/SHORTS.md index 7adab70..9744d0a 100644 --- a/docs/SHORTS.md +++ b/docs/SHORTS.md @@ -4,7 +4,8 @@ **独立可选路径**:默认关闭;异常不影响抖音监控、封面、Webhook、场次。 线上: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. **开播边缘**:监控检测到新开播且房间匹配触发规则时入队 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 → 成片时长」下拉切换,保存后对新任务生效。 +设置页「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(一键授权) -1. Google Cloud 启用 **YouTube Data API v3** -2. OAuth 同意屏幕(External)+ Test users +授权时请求的 scope(尽量完整,便于后续能力): + +- `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** 客户端: - JavaScript origins:`https://dylive.nomadro.com`(不要带路径) - Redirect URI:`https://dylive.nomadro.com/api/shorts/oauth/callback` 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_tag` | `shorts` | tagged 模式标签名 | | `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 | ## 主要代码 @@ -68,11 +122,30 @@ OAuth 回调:`https://dylive.nomadro.com/api/shorts/oauth/callback` | 文件 | 职责 | |------|------| | `backend/app/shorts_pipeline.py` | worker、取样、入队、录制/上传编排 | +| `backend/app/shorts_schedule.py` | 错峰 `upload_at`、日程看板 | | `backend/app/shorts_clip.py` | ffmpeg 成片 | | `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` | 管理页 | -| `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 ``` +相关增量:`deploy_oauth_scopes.py`、`deploy_shorts_live_analytics.py`、`deploy_ux.py`、`deploy_youtube_live.py`。 + 验证: ```bash 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 ``` diff --git a/frontend/next.config.mjs b/frontend/next.config.mjs index a6a19b9..c6b63d1 100644 --- a/frontend/next.config.mjs +++ b/frontend/next.config.mjs @@ -1,14 +1,16 @@ /** @type {import('next').NextConfig} */ +const apiBase = process.env.DY_INTERNAL_API_URL || "http://127.0.0.1:8014"; + const nextConfig = { async rewrites() { return [ { source: "/api/:path*", - destination: "http://127.0.0.1:8000/api/:path*", + destination: `${apiBase}/api/:path*`, }, { source: "/covers/:path*", - destination: "http://127.0.0.1:8000/covers/:path*", + destination: `${apiBase}/covers/:path*`, }, ]; }, diff --git a/frontend/src/app/blacklist/page.tsx b/frontend/src/app/blacklist/page.tsx index 16100b7..d7b91e4 100644 --- a/frontend/src/app/blacklist/page.tsx +++ b/frontend/src/app/blacklist/page.tsx @@ -3,7 +3,10 @@ import { useCallback, useEffect, useState } from "react"; import { Loader2, Plus, Trash2 } from "lucide-react"; +import { useConfirm } from "@/components/ConfirmDialog"; import { Shell } from "@/components/Shell"; +import { useToast } from "@/components/Toast"; +import { EmptyState, PageLoader } from "@/components/ui"; import { fetchJson, fmtTs } from "@/lib/api"; type Item = { @@ -15,10 +18,14 @@ type Item = { }; export default function BlacklistPage() { + const confirm = useConfirm(); + const toast = useToast(); const [items, setItems] = useState([]); const [value, setValue] = 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 load = useCallback(async () => { @@ -39,6 +46,8 @@ export default function BlacklistPage() { }, [load]); async function add() { + setAdding(true); + setError(""); try { await fetchJson("/api/blacklist", { method: "POST", @@ -46,15 +55,35 @@ export default function BlacklistPage() { }); setValue(""); setReason(""); + toast.push("已加入黑名单", "ok"); await load(); } 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) { - await fetchJson(`/api/blacklist/${id}`, { method: "DELETE" }); - await load(); + async function remove(item: Item) { + const ok = await confirm({ + 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 ( @@ -67,20 +96,28 @@ export default function BlacklistPage() {
@@ -88,40 +125,46 @@ export default function BlacklistPage() { {error ?
{error}
: null} -
- - - - - - - - - - - - {items.map((item) => ( - - - - - - - - ))} - {items.length === 0 ? ( + {loading ? ( + + ) : items.length === 0 ? ( + + ) : ( +
+
内容房间号原因时间操作
{item.value}{item.room_id || "—"}{item.reason || "—"}{fmtTs(item.created_at)} - -
+ - + + + + + - ) : null} - -
黑名单为空内容房间号原因时间操作
-
+ + + {items.map((item) => ( + + {item.value} + {item.room_id || "—"} + {item.reason || "—"} + {fmtTs(item.created_at)} + + + + + ))} + + +
+ )} ); } diff --git a/frontend/src/app/events/page.tsx b/frontend/src/app/events/page.tsx index b2d34f7..fde0677 100644 --- a/frontend/src/app/events/page.tsx +++ b/frontend/src/app/events/page.tsx @@ -4,6 +4,8 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import { Loader2, RefreshCw } from "lucide-react"; import { Shell } from "@/components/Shell"; +import { useConfirm } from "@/components/ConfirmDialog"; +import { useToast } from "@/components/Toast"; import { EmptyState, PlatformBadge } from "@/components/ui"; import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal"; import { fetchJson, fmtTs, detectPlatform } from "@/lib/api"; @@ -31,13 +33,18 @@ const KIND_META: Record demo: { emoji: "✨", color: "text-teal-200 border-teal-500/30 bg-teal-500/10", label: "演示" }, }; +const PAGE_SIZE = 50; + export default function EventsPage() { + const confirm = useConfirm(); + const toast = useToast(); const [events, setEvents] = useState([]); const [total, setTotal] = useState(0); const [kind, setKind] = useState(""); const [platform, setPlatform] = useState(""); const [q, setQ] = useState(""); const [loading, setLoading] = useState(false); + const [loadingMore, setLoadingMore] = useState(false); const [error, setError] = useState(""); const [detail, setDetail] = useState(null); const [detailBusy, setDetailBusy] = useState(false); @@ -54,24 +61,32 @@ export default function EventsPage() { if (qq) setQ(qq); }, []); - const load = useCallback(async () => { - setLoading(true); - setError(""); - try { - const params = new URLSearchParams(); - if (kind) params.set("kind", kind); - if (platform) params.set("platform", platform); - if (q.trim()) params.set("q", q.trim()); - params.set("limit", "150"); - const data = await fetchJson(`/api/events?${params}`); - setEvents(data.events || []); - setTotal(Number(data.total) || 0); - } catch (e) { - setError((e as Error).message); - } finally { - setLoading(false); - } - }, [kind, platform, q]); + const load = useCallback( + async (opts?: { append?: boolean; offset?: number }) => { + const append = Boolean(opts?.append); + if (append) setLoadingMore(true); + else setLoading(true); + setError(""); + try { + const params = new URLSearchParams(); + if (kind) params.set("kind", kind); + if (platform) params.set("platform", platform); + if (q.trim()) params.set("q", q.trim()); + params.set("limit", String(PAGE_SIZE)); + params.set("offset", String(append ? opts?.offset ?? 0 : 0)); + const data = await fetchJson(`/api/events?${params}`); + const rows = data.events || []; + setEvents((prev) => (append ? [...prev, ...rows] : rows)); + setTotal(Number(data.total) || 0); + } catch (e) { + setError((e as Error).message); + } finally { + setLoading(false); + setLoadingMore(false); + } + }, + [kind, platform, q], + ); useEffect(() => { void load(); @@ -196,12 +211,23 @@ export default function EventsPage() { + + ) : null} + {detail ? setDetail(null)} /> : null} ); diff --git a/frontend/src/app/groups/page.tsx b/frontend/src/app/groups/page.tsx index c64b978..6077dde 100644 --- a/frontend/src/app/groups/page.tsx +++ b/frontend/src/app/groups/page.tsx @@ -1,11 +1,17 @@ "use client"; import { useCallback, useEffect, useMemo, useState } from "react"; +import Link from "next/link"; import { Loader2, Pencil, Plus, Trash2, Download, Zap } from "lucide-react"; import { Shell } from "@/components/Shell"; +import { useConfirm } from "@/components/ConfirmDialog"; +import { useToast } from "@/components/Toast"; 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"; type Group = { @@ -28,6 +34,35 @@ type Group = { 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 = { name: "", channel_url: "", @@ -37,6 +72,9 @@ const emptyForm = { }; export default function GroupsPage() { + const confirm = useConfirm(); + const toast = useToast(); + const [tab, setTab] = useState<"monitor" | "analytics">("monitor"); const [groups, setGroups] = useState([]); const [total, setTotal] = useState(0); const [q, setQ] = useState(""); @@ -55,6 +93,13 @@ export default function GroupsPage() { const [probeInfo, setProbeInfo] = useState>({}); const [monStatus, setMonStatus] = useState(null); + const [ytStats, setYtStats] = useState(null); + const [channelStats, setChannelStats] = useState([]); + const [recentSessions, setRecentSessions] = useState([]); + const [analyticsBusy, setAnalyticsBusy] = useState(false); + const [dateFrom, setDateFrom] = useState(() => shiftBeijingISO(todayBeijingISO(), -29)); + const [dateTo, setDateTo] = useState(() => todayBeijingISO()); + const query = useMemo(() => { const p = new URLSearchParams(); p.set("platform", "youtube"); @@ -87,13 +132,36 @@ export default function GroupsPage() { } }, [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(() => { if (typeof window === "undefined") return; const p = new URLSearchParams(window.location.search); const channel = p.get("channel") || p.get("url") || ""; const name = p.get("name") || ""; + const t = p.get("tab"); + if (t === "analytics") setTab("analytics"); if (channel || name) { setForm((f) => ({ ...f, @@ -103,6 +171,10 @@ export default function GroupsPage() { } }, []); + useEffect(() => { + if (tab === "analytics") void loadAnalytics(); + }, [tab, loadAnalytics]); + const urlLineCount = form.urls .split(/\r?\n/) .map((l) => l.trim()) @@ -171,14 +243,21 @@ export default function GroupsPage() { } async function removeOne(id: string) { - if (!confirm("确定删除该分组?")) return; + const ok = await confirm({ + title: "删除分组", + message: "确定删除该 YouTube 分组?关联监控将停止。", + confirmLabel: "删除", + destructive: true, + }); + if (!ok) return; setBusy(id); try { await fetchJson(`/api/groups/${id}`, { method: "DELETE" }); - setMsg("已删除"); + toast.push("分组已删除", "ok"); await load(); } catch (e) { setError((e as Error).message); + toast.push((e as Error).message, "err"); } finally { setBusy(""); } @@ -225,7 +304,15 @@ export default function GroupsPage() { setMsg("请先勾选分组"); 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); setError(""); try { @@ -261,10 +348,22 @@ export default function GroupsPage() {

📺 YouTube 频道分组

- 每个分组对应一个 YouTube 频道;启用后自动轮询开播,Toast / 浏览器通知 / Webhook 提醒。 + 开播轮询入库场次,与抖音共用同一套时长 / 时段 / 排行分析。

+ + 场次明细 + + + 时段分析 +
+
+ + +
+
轮询:{monStatus?.yt_monitor_enabled ? "运行中" : "已暂停"} @@ -306,6 +440,149 @@ export default function GroupsPage() {
+ {error ?
{error}
: null} + {msg ?
{msg}
: null} + + {tab === "analytics" ? ( +
+
+ + + + 北京日 · 与抖音场次统计同一口径 +
+ +
+ {[ + ["场次", 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]) => ( +
+
{label}
+
{value}
+
{hint}
+
+ ))} +
+ +
+

可视化分析

+ +
+ +
+
频道排行
+
+ + + + + + + + + + + + {channelStats.map((ch) => ( + + + + + + + + ))} + {!channelStats.length ? ( + + + + ) : null} + +
频道状态场次小时最近开播
+
+ {ch.name || "—"} + {ch.group_id ? : null} +
+
{ch.channel_id || ch.room_id || "—"}
+
+ 0 || ch.last_status === "live" ? "text-rose-300" : "text-slate-500"}> + {Number(ch.active) > 0 || ch.last_status === "live" ? "LIVE" : ch.last_status || "offline"} + + {ch.sessions ?? 0}{Number(ch.hours_total || 0).toFixed(1)}{ch.last_started_at ? fmtTs(ch.last_started_at) : "—"}
+ 暂无 YouTube 场次。开启分组轮询并等频道开播后会出现在这里。 +
+
+
+ +
+
+ 最近场次 + + 全部 → + +
+
+ + + + + + + + + + + + {recentSessions.map((s) => ( + + + + + + + + ))} + {!recentSessions.length ? ( + + + + ) : null} + +
频道标题开始时长状态
{s.anchor_name || s.room_id || "—"}{s.title || "—"}{fmtTs(s.started_at)}{fmtDuration(s.duration_seconds)}{s.ended_at ? "已结束" : 在播}
+ 暂无场次 +
+
+
+
+ ) : null} + + {tab === "monitor" ? ( + <>