diff --git a/backend/app/main.py b/backend/app/main.py index 4ef5270..a02db3b 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1257,13 +1257,130 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st @app.get("/api/yt-long/jobs") async def yt_long_jobs_list( + status: str = "", push_date: str = "", - limit: int = Query(40, ge=1, le=200), + channel_pk: str = "", + limit: int = Query(50, ge=1, le=200), + offset: int = Query(0, ge=0), ) -> dict[str, Any]: from . import yt_long_db - jobs = await _db(yt_long_db.list_yt_long_jobs, limit=limit, push_date=push_date) - return {"jobs": jobs, "total": len(jobs)} + return await _db( + yt_long_db.list_yt_long_jobs_page, + status=status, + push_date=push_date, + channel_pk=channel_pk, + limit=limit, + offset=offset, + ) + + +@app.get("/api/yt-long/channels") +async def yt_long_channels_list(enabled: Optional[bool] = None) -> dict[str, Any]: + from . import yt_long_db + + rows = await _db(yt_long_db.list_yt_long_channels, enabled=enabled) + return {"channels": [yt_long_db.public_yt_long_channel(c) for c in rows]} + + +@app.post("/api/yt-long/channels/import-shorts") +async def yt_long_channels_import_shorts() -> dict[str, Any]: + """Copy OAuth from Shorts channels into yt_long_channels only (Shorts untouched).""" + from . import yt_long_db + + result = await _db(yt_long_db.import_channels_from_shorts) + return {"ok": True, **result} + + +@app.post("/api/yt-long/channels") +async def yt_long_channels_create(body: dict[str, Any] | None = None) -> dict[str, Any]: + from . import yt_long_db + + raw = body or {} + ch = await _db( + yt_long_db.create_yt_long_channel, + name=str(raw.get("name") or ""), + youtube_channel_id=str(raw.get("youtube_channel_id") or ""), + oauth_profile_id=str(raw.get("oauth_profile_id") or "A"), + client_id=str(raw.get("client_id") or ""), + client_secret=str(raw.get("client_secret") or ""), + refresh_token=str(raw.get("refresh_token") or ""), + enabled=bool(raw.get("enabled", True)), + daily_max=int(raw.get("daily_max") or 1), + title_template=str(raw.get("title_template") or "{anchor} street food live"), + description_template=str(raw.get("description_template") or ""), + privacy=str(raw.get("privacy") or "public"), + note=str(raw.get("note") or ""), + ) + return {"channel": yt_long_db.public_yt_long_channel(ch)} + + +@app.patch("/api/yt-long/channels/{channel_pk}") +async def yt_long_channels_update(channel_pk: str, body: dict[str, Any] | None = None) -> dict[str, Any]: + from . import yt_long_db + + patch = dict(body or {}) + for secret_key in ("client_secret", "refresh_token", "client_id"): + if secret_key in patch and ( + not str(patch.get(secret_key) or "").strip() or str(patch[secret_key]).startswith("***") + ): + patch.pop(secret_key, None) + try: + ch = await _db(yt_long_db.update_yt_long_channel, channel_pk, **patch) + except ValueError as exc: + raise HTTPException(404, str(exc)) from exc + return {"channel": yt_long_db.public_yt_long_channel(ch)} + + +@app.delete("/api/yt-long/channels/{channel_pk}") +async def yt_long_channels_delete(channel_pk: str) -> dict[str, Any]: + from . import yt_long_db + + stats = await _db(yt_long_db.delete_yt_long_channel, channel_pk) + return {"ok": True, **stats} + + +@app.get("/api/yt-long/events") +async def yt_long_events_list( + limit: int = Query(50, ge=1, le=200), + offset: int = Query(0, ge=0), +) -> dict[str, Any]: + from . import yt_long_db + + return await _db(yt_long_db.list_yt_long_events, limit=limit, offset=offset) + + +@app.post("/api/yt-long/jobs/{job_id}/retry") +async def yt_long_job_retry(job_id: str) -> dict[str, Any]: + from pathlib import Path + + from . import yt_long_db + + job = await _db(yt_long_db.get_yt_long_job, job_id) + if not job: + raise HTTPException(404, "任务不存在") + st = str(job.get("status") or "") + if st not in {"failed", "skipped"}: + raise HTTPException(400, "仅失败/跳过任务可重试") + clip = str(job.get("clip_path") or "").strip() + if clip and Path(clip).is_file(): + updated = yt_long_db.update_yt_long_job( + job_id, + status="scheduled", + upload_at=time.time() + 30, + error="", + finished_at=0, + ) + else: + updated = yt_long_db.update_yt_long_job( + job_id, + status="pending", + error="", + finished_at=0, + started_at=0, + clip_path="", + ) + return {"ok": True, "job": updated or job} @app.post("/api/x2/jobs/{job_id}/cancel") diff --git a/backend/app/yt_long_db.py b/backend/app/yt_long_db.py index 588ed70..7820f38 100644 --- a/backend/app/yt_long_db.py +++ b/backend/app/yt_long_db.py @@ -19,6 +19,32 @@ YT_LONG_MAX_SEC = 480 # 8 min def ensure_yt_long_tables(conn: sqlite3.Connection) -> None: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS yt_long_channels ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + youtube_channel_id TEXT NOT NULL DEFAULT '', + oauth_profile_id TEXT NOT NULL DEFAULT 'A', + client_id TEXT NOT NULL DEFAULT '', + client_secret TEXT NOT NULL DEFAULT '', + refresh_token TEXT NOT NULL DEFAULT '', + enabled INTEGER NOT NULL DEFAULT 1, + daily_max INTEGER NOT NULL DEFAULT 1, + title_template TEXT NOT NULL DEFAULT '{anchor} street food live', + description_template TEXT NOT NULL DEFAULT '{anchor}\n{url}\n#StreetFood #Live', + privacy TEXT NOT NULL DEFAULT 'public', + note TEXT NOT NULL DEFAULT '', + source_shorts_channel_pk TEXT NOT NULL DEFAULT '', + last_assigned_at REAL NOT NULL DEFAULT 0, + oauth_ok INTEGER NOT NULL DEFAULT -1, + oauth_checked_at REAL NOT NULL DEFAULT 0, + oauth_error TEXT NOT NULL DEFAULT '', + created_at REAL NOT NULL, + updated_at REAL NOT NULL + ) + """ + ) conn.execute( """ CREATE TABLE IF NOT EXISTS yt_long_jobs ( @@ -63,6 +89,9 @@ def ensure_yt_long_tables(conn: sqlite3.Connection) -> None: conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_channel ON yt_long_jobs(channel_pk, push_date)" ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_yt_long_channels_enabled ON yt_long_channels(enabled, last_assigned_at)" + ) def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int: @@ -437,3 +466,357 @@ def yt_long_stats(push_date: str = "") -> dict[str, Any]: } finally: conn.close() + + +def list_yt_long_channels(*, enabled: Optional[bool] = None) -> list[dict[str, Any]]: + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + if enabled is None: + rows = conn.execute( + "SELECT * FROM yt_long_channels ORDER BY created_at ASC, name COLLATE NOCASE ASC" + ).fetchall() + else: + rows = conn.execute( + """ + SELECT * FROM yt_long_channels WHERE enabled = ? + ORDER BY created_at ASC, name COLLATE NOCASE ASC + """, + (1 if enabled else 0,), + ).fetchall() + return [_row_to_dict(r) for r in rows] + finally: + conn.close() + + +def get_yt_long_channel(channel_pk: str) -> dict[str, Any] | None: + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + row = conn.execute("SELECT * FROM yt_long_channels WHERE id = ?", (channel_pk,)).fetchone() + return _row_to_dict(row) if row else None + finally: + conn.close() + + +def create_yt_long_channel( + *, + name: str = "", + youtube_channel_id: str = "", + oauth_profile_id: str = "A", + client_id: str = "", + client_secret: str = "", + refresh_token: str = "", + enabled: bool = True, + daily_max: int = 1, + title_template: str = "{anchor} street food live", + description_template: str = "{anchor}\n{url}\n#StreetFood #Live", + privacy: str = "public", + note: str = "", + source_shorts_channel_pk: str = "", +) -> dict[str, Any]: + now = time.time() + cid = str(uuid.uuid4()) + dmax = max(0, min(20, int(daily_max or 1))) + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + conn.execute( + """ + INSERT INTO yt_long_channels( + id, name, youtube_channel_id, oauth_profile_id, client_id, client_secret, + refresh_token, enabled, daily_max, title_template, description_template, + privacy, note, source_shorts_channel_pk, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + cid, + (name or "未命名长视频频道").strip()[:120], + str(youtube_channel_id or "").strip()[:80], + str(oauth_profile_id or "A").strip().upper()[:8] or "A", + str(client_id or "").strip(), + str(client_secret or "").strip(), + str(refresh_token or "").strip(), + 1 if enabled else 0, + dmax, + (title_template or "{anchor} street food live").strip()[:200], + (description_template or "").strip()[:2000], + privacy if privacy in {"public", "unlisted", "private"} else "public", + (note or "").strip()[:200], + str(source_shorts_channel_pk or "").strip(), + now, + now, + ), + ) + conn.commit() + return _row_to_dict( + conn.execute("SELECT * FROM yt_long_channels WHERE id = ?", (cid,)).fetchone() + ) # type: ignore + finally: + conn.close() + + +def update_yt_long_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: + allowed = { + "name", + "youtube_channel_id", + "oauth_profile_id", + "client_id", + "client_secret", + "refresh_token", + "enabled", + "daily_max", + "title_template", + "description_template", + "privacy", + "note", + "source_shorts_channel_pk", + "last_assigned_at", + "oauth_ok", + "oauth_checked_at", + "oauth_error", + } + sets: list[str] = [] + params: list[Any] = [] + for k, v in fields.items(): + if k not in allowed: + continue + if k == "enabled": + v = 1 if v else 0 + if k == "daily_max": + try: + v = max(0, min(20, int(v))) + except Exception: + continue + if k == "oauth_profile_id": + v = str(v or "A").strip().upper()[:8] or "A" + sets.append(f"{k} = ?") + params.append(v) + if not sets: + ch = get_yt_long_channel(channel_pk) + if not ch: + raise ValueError("频道不存在") + return ch + sets.append("updated_at = ?") + params.append(time.time()) + params.append(channel_pk) + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + cur = conn.execute(f"UPDATE yt_long_channels SET {', '.join(sets)} WHERE id = ?", params) + if cur.rowcount == 0: + raise ValueError("频道不存在") + conn.commit() + return _row_to_dict( + conn.execute("SELECT * FROM yt_long_channels WHERE id = ?", (channel_pk,)).fetchone() + ) # type: ignore + finally: + conn.close() + + +def delete_yt_long_channel(channel_pk: str) -> dict[str, int]: + """Delete channel + its jobs only (never touches shorts_*).""" + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + jobs = conn.execute( + "SELECT COUNT(*) AS c FROM yt_long_jobs WHERE channel_pk = ?", + (channel_pk,), + ).fetchone()["c"] + conn.execute("DELETE FROM yt_long_jobs WHERE channel_pk = ?", (channel_pk,)) + conn.execute("DELETE FROM yt_long_channels WHERE id = ?", (channel_pk,)) + conn.commit() + return {"jobs": int(jobs or 0)} + finally: + conn.close() + + +def import_channels_from_shorts() -> dict[str, Any]: + """Copy OAuth from Shorts channels into yt_long_channels (read Shorts, write only yt_long_*).""" + from . import db + + created = 0 + skipped = 0 + for ch in db.list_shorts_channels(enabled=None): + src = str(ch.get("id") or "") + if not src: + continue + existing = None + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + existing = conn.execute( + "SELECT id FROM yt_long_channels WHERE source_shorts_channel_pk = ?", + (src,), + ).fetchone() + finally: + conn.close() + if existing: + skipped += 1 + continue + create_yt_long_channel( + name=str(ch.get("name") or "Shorts 频道").strip() + " · 长视频", + youtube_channel_id=str(ch.get("youtube_channel_id") or ""), + oauth_profile_id=str(ch.get("oauth_profile_id") or "A"), + client_id=str(ch.get("client_id") or ""), + client_secret=str(ch.get("client_secret") or ""), + refresh_token=str(ch.get("refresh_token") or ""), + enabled=bool(ch.get("enabled", True)), + daily_max=1, + title_template="{anchor} street food live", + description_template="{anchor}\n{url}\n#StreetFood #Live", + privacy=str(ch.get("privacy") or "public"), + note=f"imported from shorts:{src}", + source_shorts_channel_pk=src, + ) + created += 1 + return {"created": created, "skipped": skipped} + + +def public_yt_long_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: + if not ch: + return None + out = dict(ch) + rt = str(out.get("refresh_token") or "") + cs = str(out.get("client_secret") or "") + out["has_refresh_token"] = bool(rt.strip()) + out["authorized"] = bool(rt.strip()) + out["has_client_secret"] = bool(cs.strip()) + out["refresh_token"] = ("***" + rt[-4:]) if len(rt) > 8 else ("***" if rt else "") + out["client_secret"] = "***" if cs else "" + return out + + +def channel_board(push_date: str = "") -> dict[str, Any]: + day = push_date or push_date_from_ts(time.time()) + placeholders = ",".join("?" for _ in _QUOTA_STATUSES) + channels = list_yt_long_channels(enabled=None) + board: list[dict[str, Any]] = [] + total_gap = 0 + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + for ch in channels: + cid = str(ch.get("id") or "") + dmax = max(0, int(ch.get("daily_max") or 0)) + used_row = conn.execute( + f""" + SELECT COUNT(*) AS c FROM yt_long_jobs + WHERE push_date = ? AND channel_pk = ? AND status IN ({placeholders}) + """, + (day, cid, *_QUOTA_STATUSES), + ).fetchone() + used = int(used_row["c"]) if used_row else 0 + by = { + str(r["status"]): int(r["c"]) + for r in conn.execute( + """ + SELECT status, COUNT(*) AS c FROM yt_long_jobs + WHERE push_date = ? AND channel_pk = ? + GROUP BY status + """, + (day, cid), + ).fetchall() + } + gap = max(0, dmax - used) if ch.get("enabled") else 0 + total_gap += gap + board.append( + { + "id": cid, + "name": ch.get("name"), + "youtube_channel_id": ch.get("youtube_channel_id"), + "oauth_profile_id": ch.get("oauth_profile_id"), + "enabled": bool(ch.get("enabled")), + "authorized": bool(str(ch.get("refresh_token") or "").strip()), + "daily_max": dmax, + "used": used, + "gap": gap, + "uploaded": int(by.get("uploaded") or 0), + "scheduled": int(by.get("scheduled") or 0) + int(by.get("uploading") or 0), + "pending": int(by.get("pending") or 0) + int(by.get("recording") or 0), + "failed": int(by.get("failed") or 0), + "oauth_ok": ch.get("oauth_ok"), + "oauth_error": ch.get("oauth_error") or "", + } + ) + finally: + conn.close() + return {"push_date": day, "channels": board, "total_gap": total_gap} + + +def list_yt_long_jobs_page( + *, + status: str = "", + push_date: str = "", + channel_pk: str = "", + limit: int = 50, + offset: int = 0, +) -> dict[str, Any]: + clauses: list[str] = [] + params: list[Any] = [] + if status.strip(): + clauses.append("status = ?") + params.append(status.strip()) + if push_date.strip(): + clauses.append("push_date = ?") + params.append(push_date.strip()) + if channel_pk.strip(): + clauses.append("channel_pk = ?") + params.append(channel_pk.strip()) + where = ("WHERE " + " AND ".join(clauses)) if clauses else "" + lim = max(1, min(int(limit), 200)) + off = max(0, int(offset)) + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + total = conn.execute(f"SELECT COUNT(*) AS c FROM yt_long_jobs {where}", params).fetchone()["c"] + rows = conn.execute( + f""" + SELECT * FROM yt_long_jobs {where} + ORDER BY created_at DESC LIMIT ? OFFSET ? + """, + [*params, lim, off], + ).fetchall() + return { + "jobs": [_row_to_dict(r) for r in rows], + "total": int(total), + "limit": lim, + "offset": off, + } + finally: + conn.close() + + +def list_yt_long_events(*, limit: int = 50, offset: int = 0) -> dict[str, Any]: + """Read events with kind prefix yt_long_ — does not purge/alter other kinds.""" + lim = max(1, min(int(limit), 200)) + off = max(0, int(offset)) + with _lock: + conn = _connect() + try: + total = conn.execute( + "SELECT COUNT(*) AS c FROM events WHERE kind LIKE 'yt_long%'" + ).fetchone()["c"] + rows = conn.execute( + """ + SELECT * FROM events WHERE kind LIKE 'yt_long%' + ORDER BY ts DESC LIMIT ? OFFSET ? + """, + (lim, off), + ).fetchall() + return { + "events": [_row_to_dict(r) for r in rows], + "total": int(total), + "limit": lim, + "offset": off, + } + finally: + conn.close() diff --git a/backend/app/yt_long_pipeline.py b/backend/app/yt_long_pipeline.py index 67a350a..6a56ac4 100644 --- a/backend/app/yt_long_pipeline.py +++ b/backend/app/yt_long_pipeline.py @@ -17,7 +17,6 @@ from typing import Any from . import db from . import yt_long_db from .shorts_clip import resolve_stream_candidates -from .shorts_oauth import channel_oauth_creds from .timeutil import push_date_from_ts from .yt_long_clip import record_landscape_clip from .yt_long_db import YT_LONG_MAX_SEC, YT_LONG_MIN_SEC @@ -76,28 +75,79 @@ def _build_description(job: dict[str, Any], channel: dict[str, Any], cfg: dict[s def pick_yt_long_channel(cfg: dict[str, Any], push_date: str = "") -> dict[str, Any] | None: - """Read-only pick from Shorts channels that have OAuth; own per-channel long-form quota.""" + """Pick from isolated yt_long_channels that have OAuth refresh_token.""" day = push_date or push_date_from_ts(time.time()) - per_max = yt_long_db.yt_long_channel_daily_max(cfg) - channels = db.list_shorts_channels(enabled=True) + channels = yt_long_db.list_yt_long_channels(enabled=True) scored: list[tuple[float, dict[str, Any]]] = [] for ch in channels: cid = str(ch.get("id") or "") if not cid: continue - creds = channel_oauth_creds(ch, cfg) + creds = _channel_creds(ch, cfg) if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")): continue + try: + dmax = max(0, int(ch.get("daily_max") or 0)) + except Exception: + dmax = 0 used = yt_long_db.channel_quota_used(cid, day) - if per_max > 0 and used >= per_max: + if dmax > 0 and used >= dmax: continue scored.append((float(ch.get("last_assigned_at") or 0), ch)) if not scored: return None - scored.sort(key=lambda x: x[0]) # least recently assigned first + scored.sort(key=lambda x: x[0]) return scored[0][1] +def _channel_creds(channel: dict[str, Any], cfg: dict[str, Any]) -> dict[str, str]: + """Resolve OAuth like Shorts, but never writes shorts_channels.""" + from .shorts_oauth import get_oauth_profile, list_oauth_profiles + + refresh = str(channel.get("refresh_token") or "").strip() + client_id = str(channel.get("client_id") or "").strip() + client_secret = str(channel.get("client_secret") or "").strip() + pid = str(channel.get("oauth_profile_id") or "").strip().upper() + if pid: + prof = get_oauth_profile(pid, cfg) + if prof: + if not client_id: + client_id = str(prof.get("client_id") or "").strip() + if not client_secret: + client_secret = str(prof.get("client_secret") or "").strip() + if not (client_id and client_secret): + # fallback profile A / global — read-only + for row in list_oauth_profiles(cfg, public=False): + if row.get("id") == "A" and row.get("client_id") and row.get("client_secret"): + client_id = client_id or str(row["client_id"]) + client_secret = client_secret or str(row["client_secret"]) + break + if not (client_id and client_secret): + client_id = client_id or str(cfg.get("shorts_oauth_client_id") or "").strip() + client_secret = client_secret or str(cfg.get("shorts_oauth_client_secret") or "").strip() + return {"client_id": client_id, "client_secret": client_secret, "refresh_token": refresh} + + +def _emit(kind: str, level: str, message: str, job: dict[str, Any] | None = None, extra: dict | None = None) -> None: + try: + meta = dict(extra or {}) + meta["module"] = "yt_long" + if job: + meta["job_id"] = job.get("id") + meta["channel_pk"] = job.get("channel_pk") + db.add_event( + kind=kind, + level=level, + message=message, + room_id=str((job or {}).get("room_id") or ""), + room_pk=str((job or {}).get("room_pk") or ""), + anchor_name=str((job or {}).get("anchor_name") or ""), + meta=meta, + ) + except Exception: + pass + + def try_enqueue_from_shorts(job: dict[str, Any]) -> dict[str, Any]: """Safe companion enqueue. Never raises into Shorts. No-op when disabled.""" try: @@ -125,6 +175,16 @@ def try_enqueue_from_shorts(job: dict[str, Any]) -> dict[str, Any]: shorts_job_id=str(job.get("id") or ""), push_date=day, ) + try: + yt_long_db.update_yt_long_channel(str(channel["id"]), last_assigned_at=time.time()) + except Exception: + pass + _emit( + "yt_long_ops", + "info", + f"长视频入队:{created.get('anchor_name') or room_id}", + created, + ) return {"enqueued": True, "job_id": created.get("id"), "channel_pk": channel.get("id")} except Exception as exc: return {"enqueued": False, "reason": "error", "error": str(exc)[:200]} @@ -142,6 +202,10 @@ class YtLongPipeline: def status(self) -> dict[str, Any]: cfg = db.get_settings_map() day = push_date_from_ts(time.time()) + try: + board = yt_long_db.channel_board(day) + except Exception: + board = {"channels": [], "total_gap": 0, "push_date": day} return { "running": bool(self._task and not self._task.done()), "busy": self._active_records > 0 or self._active_uploads > 0, @@ -153,6 +217,7 @@ class YtLongPipeline: "channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg), "last_error": self.last_error, "stats": yt_long_db.yt_long_stats(day), + "board": board, "settings": { "yt_long_enabled": bool(cfg.get("yt_long_enabled")), "yt_long_with_shorts": bool(cfg.get("yt_long_with_shorts", True)), @@ -263,13 +328,15 @@ class YtLongPipeline: sec = _rand_clip_sec(cfg) outcome = await record_landscape_clip(job_id=jid, stream_urls=candidates, seconds=sec) if not outcome.get("ok"): + err = str(outcome.get("error") or "录制失败")[:500] yt_long_db.update_yt_long_job( jid, status="failed", - error=str(outcome.get("error") or "录制失败")[:500], + error=err, stream_url=str(outcome.get("stream_url") or ""), finished_at=time.time(), ) + _emit("yt_long_fail", "error", f"长视频录制失败:{job.get('anchor_name') or jid} — {err[:80]}", job) return clip_path = str(outcome.get("path") or "") gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900)) @@ -305,6 +372,12 @@ class YtLongPipeline: error=str(exc)[:500], finished_at=time.time(), ) + _emit( + "yt_long_fail", + "error", + f"长视频上传失败:{job.get('anchor_name') or job.get('id')} — {str(exc)[:80]}", + job, + ) finally: self._active_uploads = max(0, self._active_uploads - 1) @@ -323,7 +396,7 @@ class YtLongPipeline: clip = str(fresh.get("clip_path") or "") if not clip or not Path(clip).is_file(): raise ValueError("成片文件不存在") - channel = db.get_shorts_channel(str(fresh.get("channel_pk") or "")) + channel = yt_long_db.get_yt_long_channel(str(fresh.get("channel_pk") or "")) if not channel: channel = pick_yt_long_channel(cfg, str(fresh.get("push_date") or "")) if channel: @@ -332,10 +405,10 @@ class YtLongPipeline: yt_long_db.update_yt_long_job( jid, status="recorded", - error="无可用 YouTube 频道(需 Shorts 频道已授权)", + error="无可用长视频频道(请先在「长视频」页导入/创建频道)", ) return - creds = channel_oauth_creds(channel, cfg) + creds = _channel_creds(channel, cfg) if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]): yt_long_db.update_yt_long_job( jid, @@ -376,6 +449,13 @@ class YtLongPipeline: finished_at=time.time(), clip_path="" if cfg.get("yt_long_delete_clip_after_upload", True) else clip, ) + _emit( + "yt_long_ok", + "info", + f"长视频已上传:{fresh.get('anchor_name') or jid} → {url}", + fresh, + {"youtube_url": url, "video_id": vid}, + ) if cfg.get("yt_long_delete_clip_after_upload", True): try: Path(clip).unlink(missing_ok=True) diff --git a/frontend/src/app/yt-long/page.tsx b/frontend/src/app/yt-long/page.tsx index 1b1c553..147ddbc 100644 --- a/frontend/src/app/yt-long/page.tsx +++ b/frontend/src/app/yt-long/page.tsx @@ -1,9 +1,17 @@ "use client"; -import { useCallback, useEffect, useState } from "react"; -import { Film, RefreshCw } from "lucide-react"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { + Film, + Loader2, + RefreshCw, + RotateCcw, + Trash2, + Download, +} from "lucide-react"; import { Shell } from "@/components/Shell"; +import { useConfirm } from "@/components/ConfirmDialog"; import { useToast } from "@/components/Toast"; import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api"; import { useAutoRefresh } from "@/lib/realtime"; @@ -14,10 +22,44 @@ const field = "mt-1 w-full rounded-xl border border-white/10 bg-black/45 px-3 py-2 text-sm text-slate-100 outline-none focus:border-sky-400/50"; const label = "block text-[11px] text-slate-400"; const btn = - "inline-flex items-center justify-center gap-1.5 rounded-xl px-3 py-2 text-xs font-semibold transition hover:-translate-y-0.5"; + "inline-flex items-center justify-center gap-1.5 rounded-xl px-3 py-2 text-xs font-semibold transition hover:-translate-y-0.5 disabled:opacity-40"; const primary = `${btn} bg-gradient-to-br from-sky-400 to-indigo-500 text-[#0a1220] shadow-lg shadow-sky-500/20`; const ghost = `${btn} border border-white/10 bg-white/5 text-slate-200 hover:bg-white/10`; +type Channel = { + id: string; + name?: string; + youtube_channel_id?: string; + enabled?: boolean; + daily_max?: number; + title_template?: string; + description_template?: string; + privacy?: string; + note?: string; + authorized?: boolean; + has_refresh_token?: boolean; + oauth_profile_id?: string; + oauth_ok?: number; + oauth_error?: string; + source_shorts_channel_pk?: string; +}; + +type BoardChannel = { + id: string; + name?: string; + enabled?: boolean; + authorized?: boolean; + daily_max: number; + used: number; + gap: number; + uploaded: number; + scheduled: number; + pending: number; + failed: number; + oauth_profile_id?: string; + oauth_error?: string; +}; + type Job = { id: string; status?: string; @@ -26,9 +68,21 @@ type Job = { title?: string; clip_seconds?: number; youtube_url?: string; + channel_pk?: string; error?: string; upload_at?: number; created_at?: number; + push_date?: string; +}; + +type Ev = { + id: string; + ts?: number; + level?: string; + kind?: string; + message?: string; + anchor_name?: string; + room_id?: string; }; type Status = { @@ -38,8 +92,8 @@ type Status = { quota_used?: number; quota_gap?: number; daily_max?: number; - channel_daily_max?: number; last_error?: string; + board?: { channels?: BoardChannel[]; total_gap?: number; push_date?: string }; settings?: Record; }; @@ -54,50 +108,95 @@ const STATUS_ZH: Record = { skipped: "跳过", }; +const STATUS_STYLE: Record = { + pending: "bg-slate-500/20 text-slate-200", + recording: "bg-sky-500/20 text-sky-100", + recorded: "bg-indigo-500/20 text-indigo-100", + scheduled: "bg-amber-500/20 text-amber-100", + uploading: "bg-violet-500/20 text-violet-100", + uploaded: "bg-teal-500/20 text-teal-100", + failed: "bg-rose-500/20 text-rose-100", + skipped: "bg-white/10 text-slate-400", +}; + export default function YtLongPage() { const toast = useToast(); + const confirm = useConfirm(); + const [tab, setTab] = useState<"channels" | "jobs" | "logs">("channels"); const [st, setSt] = useState(null); + const [channels, setChannels] = useState([]); const [jobs, setJobs] = useState([]); + const [jobTotal, setJobTotal] = useState(0); + const [events, setEvents] = useState([]); + const [eventTotal, setEventTotal] = useState(0); const [busy, setBusy] = useState(""); + const [jobFilter, setJobFilter] = useState(""); + const [jobChannel, setJobChannel] = useState(""); + const [editId, setEditId] = useState(""); + const [form, setForm] = useState({ + name: "", + enabled: true, + daily_max: 1, + title_template: "{anchor} street food live", + description_template: "{anchor}\n{url}\n#StreetFood #Live", + privacy: "public", + note: "", + oauth_profile_id: "A", + }); const [dailyMax, setDailyMax] = useState("3"); - const [channelMax, setChannelMax] = useState("1"); const [minSec, setMinSec] = useState("180"); const [maxSec, setMaxSec] = useState("480"); - const [titleTpl, setTitleTpl] = useState("{anchor} street food live"); - const [descTpl, setDescTpl] = useState("{anchor}\n{url}\n#StreetFood #Live"); const [withShorts, setWithShorts] = useState(true); const [autoUpload, setAutoUpload] = useState(true); const [dedupe, setDedupe] = useState(true); - const load = useCallback(async () => { - try { - const [status, jobData] = await Promise.all([ - fetchJson("/api/yt-long/status"), - fetchJson(`/api/yt-long/jobs?push_date=${todayBeijingISO()}&limit=40`), - ]); - setSt(status); - setJobs(jobData.jobs || []); - const s = status.settings || {}; - if (s.yt_long_daily_max != null) setDailyMax(String(s.yt_long_daily_max)); - if (s.yt_long_channel_daily_max != null) setChannelMax(String(s.yt_long_channel_daily_max)); - if (s.yt_long_min_sec != null) setMinSec(String(s.yt_long_min_sec)); - if (s.yt_long_max_sec != null) setMaxSec(String(s.yt_long_max_sec)); - if (typeof s.yt_long_title_template === "string") setTitleTpl(s.yt_long_title_template); - if (typeof s.yt_long_description_template === "string") { - setDescTpl(s.yt_long_description_template); + const channelNameMap = useMemo(() => { + const m: Record = {}; + for (const c of channels) m[c.id] = c.name || c.id.slice(0, 8); + return m; + }, [channels]); + + const load = useCallback( + async (opts?: { silent?: boolean }) => { + try { + const jobQs = new URLSearchParams({ + push_date: todayBeijingISO(), + limit: "50", + offset: "0", + }); + if (jobFilter) jobQs.set("status", jobFilter); + if (jobChannel) jobQs.set("channel_pk", jobChannel); + + const [status, ch, jb, ev] = await Promise.all([ + fetchJson("/api/yt-long/status"), + fetchJson("/api/yt-long/channels"), + fetchJson(`/api/yt-long/jobs?${jobQs}`), + fetchJson("/api/yt-long/events?limit=40"), + ]); + setSt(status); + setChannels(ch.channels || []); + setJobs(jb.jobs || []); + setJobTotal(Number(jb.total) || 0); + setEvents(ev.events || []); + setEventTotal(Number(ev.total) || 0); + const s = status.settings || {}; + if (s.yt_long_daily_max != null) setDailyMax(String(s.yt_long_daily_max)); + if (s.yt_long_min_sec != null) setMinSec(String(s.yt_long_min_sec)); + if (s.yt_long_max_sec != null) setMaxSec(String(s.yt_long_max_sec)); + if (typeof s.yt_long_with_shorts === "boolean") setWithShorts(s.yt_long_with_shorts); + if (typeof s.yt_long_auto_upload === "boolean") setAutoUpload(s.yt_long_auto_upload); + if (typeof s.yt_long_dedupe_room_day === "boolean") setDedupe(s.yt_long_dedupe_room_day); + } catch (e) { + if (!opts?.silent) toast.push((e as Error).message || "加载失败", "err"); } - if (typeof s.yt_long_with_shorts === "boolean") setWithShorts(s.yt_long_with_shorts); - if (typeof s.yt_long_auto_upload === "boolean") setAutoUpload(s.yt_long_auto_upload); - if (typeof s.yt_long_dedupe_room_day === "boolean") setDedupe(s.yt_long_dedupe_room_day); - } catch (e) { - toast.push((e as Error).message || "加载失败", "err"); - } - }, [toast]); + }, + [toast, jobFilter, jobChannel], + ); useEffect(() => { void load(); }, [load]); - useAutoRefresh(load, { intervalMs: 12000 }); + useAutoRefresh(() => load({ silent: true }), { intervalMs: 12000 }); async function toggle(enable: boolean) { setBusy(enable ? "start" : "stop"); @@ -119,11 +218,8 @@ export default function YtLongPage() { method: "POST", body: JSON.stringify({ yt_long_daily_max: Number(dailyMax) || 0, - yt_long_channel_daily_max: Number(channelMax) || 0, yt_long_min_sec: Number(minSec) || 180, yt_long_max_sec: Number(maxSec) || 480, - yt_long_title_template: titleTpl, - yt_long_description_template: descTpl, yt_long_with_shorts: withShorts, yt_long_auto_upload: autoUpload, yt_long_dedupe_room_day: dedupe, @@ -138,10 +234,117 @@ export default function YtLongPage() { } } + async function importFromShorts() { + const ok = await confirm({ + title: "从 Shorts 导入频道", + message: "只复制 OAuth 到长视频独立频道表,不会修改 Shorts 频道或任务。", + }); + if (!ok) return; + setBusy("import"); + try { + const r = await fetchJson("/api/yt-long/channels/import-shorts", { method: "POST" }); + toast.push(`导入完成:新建 ${r.created ?? 0} · 跳过 ${r.skipped ?? 0}`, "ok"); + await load(); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(""); + } + } + + function openEdit(ch?: Channel) { + if (ch) { + setEditId(ch.id); + setForm({ + name: ch.name || "", + enabled: Boolean(ch.enabled), + daily_max: Number(ch.daily_max) || 1, + title_template: ch.title_template || "{anchor} street food live", + description_template: ch.description_template || "", + privacy: ch.privacy || "public", + note: ch.note || "", + oauth_profile_id: ch.oauth_profile_id || "A", + }); + } else { + setEditId(""); + setForm({ + name: "", + enabled: true, + daily_max: 1, + title_template: "{anchor} street food live", + description_template: "{anchor}\n{url}\n#StreetFood #Live", + privacy: "public", + note: "", + oauth_profile_id: "A", + }); + } + } + + async function saveChannel() { + setBusy("ch"); + try { + const body = { ...form, name: form.name.trim() || "未命名长视频频道" }; + if (editId) { + await fetchJson(`/api/yt-long/channels/${editId}`, { + method: "PATCH", + body: JSON.stringify(body), + }); + toast.push("频道已更新", "ok"); + } else { + await fetchJson("/api/yt-long/channels", { method: "POST", body: JSON.stringify(body) }); + toast.push("频道已创建", "ok"); + } + setEditId(""); + await load(); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(""); + } + } + + async function removeChannel(id: string) { + const ok = await confirm({ + title: "删除长视频频道", + message: "将删除该频道及其长视频任务(不影响 Shorts)。", + }); + if (!ok) return; + setBusy(`del-${id}`); + try { + const r = await fetchJson(`/api/yt-long/channels/${id}`, { method: "DELETE" }); + toast.push(`已删除(任务 ${r.jobs ?? 0})`, "ok"); + await load(); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(""); + } + } + + async function retryJob(id: string) { + setBusy(`retry-${id}`); + try { + await fetchJson(`/api/yt-long/jobs/${id}/retry`, { method: "POST" }); + toast.push("已重新入队", "ok"); + await load(); + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(""); + } + } + + const board = st?.board?.channels || []; const used = st?.quota_used ?? 0; const max = st?.daily_max ?? 0; const gap = st?.quota_gap ?? 0; + const tabs: Array<{ id: typeof tab; label: string }> = [ + { id: "channels", label: `频道(${channels.length})` }, + { id: "jobs", label: `任务(${jobTotal})` }, + { id: "logs", label: `日志(${eventTotal})` }, + ]; + return (
@@ -150,14 +353,25 @@ export default function YtLongPage() { YouTube 长视频 -

- 独立模块:3–8 分钟随机时长,9:16 居中进 16:9,上传为普通 YouTube 视频(非 Shorts)。默认关闭。 +

+ 独立模块:自有频道表 / 任务表 / 日志(yt_long_*)。3–8 分钟 16:9 横屏上传为普通视频,默认关闭,不碰 Shorts 数据。

- +
+ + {st?.enabled ? ( + + ) : ( + + )} +
@@ -176,22 +390,13 @@ export default function YtLongPage() {
{st?.busy ? "忙碌" : "空闲"}
-
每频道日上限
-
{st?.channel_daily_max ?? "—"}
+
频道缺口
+
{st?.board?.total_gap ?? 0}
-
操作
-
- {st?.enabled ? ( - - ) : ( - - )} -
+
成片规格
+
16:9 · 3–8 分钟
+
watch?v= 非 Shorts
@@ -201,100 +406,372 @@ export default function YtLongPage() { ) : null} -
-
-

参数

-

只写 yt_long_* / yt_long_jobs,不碰 shorts_jobs。

-
- - - - -
- -