feat: isolated YouTube long-form 16:9 module (default off)
Companion to Shorts: 3-8min landscape (9:16 centered), upload as watch?v= not Shorts. Own yt_long_jobs table/settings; read-only Shorts channel OAuth; never writes shorts_*. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
565081678b
commit
7bfead371a
@ -321,9 +321,11 @@ def init_db() -> None:
|
||||
from . import caption_pool as _caption_pool
|
||||
from . import x2_db as _x2_db
|
||||
from . import x_clips_db as _x_clips_db
|
||||
from . import yt_long_db as _yt_long_db
|
||||
|
||||
_x2_db.ensure_x2_tables(conn)
|
||||
_x_clips_db.ensure_x_clips_tables(conn)
|
||||
_yt_long_db.ensure_yt_long_tables(conn)
|
||||
_caption_pool.ensure_caption_pool_table(conn)
|
||||
_caption_pool.seed_caption_pool(conn)
|
||||
sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()}
|
||||
@ -498,6 +500,20 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"x_clips_daily_max": 20,
|
||||
"x_clips_caption_template": "{anchor}",
|
||||
"x_clips_account_username": "",
|
||||
# YouTube long-form 16:9 (isolated; default OFF — does not affect Shorts)
|
||||
"yt_long_enabled": False,
|
||||
"yt_long_with_shorts": True,
|
||||
"yt_long_auto_upload": True,
|
||||
"yt_long_daily_max": 3,
|
||||
"yt_long_channel_daily_max": 1,
|
||||
"yt_long_min_sec": 180,
|
||||
"yt_long_max_sec": 480,
|
||||
"yt_long_dedupe_room_day": True,
|
||||
"yt_long_max_concurrent": 1,
|
||||
"yt_long_upload_min_gap_sec": 900,
|
||||
"yt_long_delete_clip_after_upload": True,
|
||||
"yt_long_title_template": "{anchor} street food live",
|
||||
"yt_long_description_template": "{anchor}\n{url}\n#StreetFood #Live",
|
||||
"tiktok_auto_retry_failed": False,
|
||||
"tiktok_auto_retry_max_attempts": 3,
|
||||
"tiktok_auto_retry_interval_sec": 300,
|
||||
|
||||
@ -73,6 +73,7 @@ from .youtube_monitor import yt_monitor
|
||||
from .shorts_pipeline import shorts_pipeline
|
||||
from .tiktok_pipeline import tiktok_pipeline
|
||||
from .x_clips_pipeline import x_clips_pipeline
|
||||
from .yt_long_pipeline import yt_long_pipeline
|
||||
from . import tiktok_session
|
||||
from .timeutil import stamp_beijing
|
||||
|
||||
@ -140,9 +141,17 @@ async def lifespan(_: FastAPI):
|
||||
await x_clips_pipeline.start()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await yt_long_pipeline.start()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
asyncio.create_task(_start_workers())
|
||||
yield
|
||||
try:
|
||||
await yt_long_pipeline.stop()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await x_clips_pipeline.stop()
|
||||
except Exception:
|
||||
@ -1170,6 +1179,93 @@ async def x_clips_job_retry(job_id: str) -> dict[str, Any]:
|
||||
return {"ok": True, "job": updated or job}
|
||||
|
||||
|
||||
# ── YouTube long-form 16:9 (isolated; default disabled) ──────────────────────
|
||||
|
||||
|
||||
@app.get("/api/yt-long/status")
|
||||
async def yt_long_status() -> dict[str, Any]:
|
||||
return await asyncio.to_thread(yt_long_pipeline.status)
|
||||
|
||||
|
||||
@app.post("/api/yt-long/start")
|
||||
async def yt_long_start() -> dict[str, Any]:
|
||||
db.update_settings_map({"yt_long_enabled": True})
|
||||
try:
|
||||
await yt_long_pipeline.start()
|
||||
except Exception:
|
||||
pass
|
||||
return yt_long_pipeline.status()
|
||||
|
||||
|
||||
@app.post("/api/yt-long/stop")
|
||||
async def yt_long_stop() -> dict[str, Any]:
|
||||
db.update_settings_map({"yt_long_enabled": False})
|
||||
return yt_long_pipeline.status()
|
||||
|
||||
|
||||
@app.post("/api/yt-long/settings")
|
||||
async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
patch: dict[str, Any] = {}
|
||||
raw = body or {}
|
||||
for k in (
|
||||
"yt_long_with_shorts",
|
||||
"yt_long_auto_upload",
|
||||
"yt_long_dedupe_room_day",
|
||||
"yt_long_delete_clip_after_upload",
|
||||
):
|
||||
if k in raw:
|
||||
patch[k] = bool(raw[k])
|
||||
if "yt_long_daily_max" in raw:
|
||||
try:
|
||||
patch["yt_long_daily_max"] = max(0, min(50, int(raw["yt_long_daily_max"])))
|
||||
except Exception:
|
||||
raise HTTPException(400, "daily_max 无效") from None
|
||||
if "yt_long_channel_daily_max" in raw:
|
||||
try:
|
||||
patch["yt_long_channel_daily_max"] = max(0, min(20, int(raw["yt_long_channel_daily_max"])))
|
||||
except Exception:
|
||||
raise HTTPException(400, "channel_daily_max 无效") from None
|
||||
if "yt_long_min_sec" in raw:
|
||||
try:
|
||||
patch["yt_long_min_sec"] = max(180, min(480, int(raw["yt_long_min_sec"])))
|
||||
except Exception:
|
||||
raise HTTPException(400, "min_sec 无效") from None
|
||||
if "yt_long_max_sec" in raw:
|
||||
try:
|
||||
patch["yt_long_max_sec"] = max(180, min(480, int(raw["yt_long_max_sec"])))
|
||||
except Exception:
|
||||
raise HTTPException(400, "max_sec 无效") from None
|
||||
if "yt_long_upload_min_gap_sec" in raw:
|
||||
try:
|
||||
patch["yt_long_upload_min_gap_sec"] = max(60, min(7200, int(raw["yt_long_upload_min_gap_sec"])))
|
||||
except Exception:
|
||||
raise HTTPException(400, "upload_min_gap 无效") from None
|
||||
if "yt_long_title_template" in raw:
|
||||
patch["yt_long_title_template"] = str(raw.get("yt_long_title_template") or "").strip()[:200]
|
||||
if "yt_long_description_template" in raw:
|
||||
patch["yt_long_description_template"] = str(raw.get("yt_long_description_template") or "").strip()[:2000]
|
||||
if patch:
|
||||
# Keep min <= max
|
||||
cfg = {**db.get_settings_map(), **patch}
|
||||
lo = int(cfg.get("yt_long_min_sec") or 180)
|
||||
hi = int(cfg.get("yt_long_max_sec") or 480)
|
||||
if lo > hi:
|
||||
patch["yt_long_max_sec"] = lo
|
||||
db.update_settings_map(patch)
|
||||
return yt_long_pipeline.status()
|
||||
|
||||
|
||||
@app.get("/api/yt-long/jobs")
|
||||
async def yt_long_jobs_list(
|
||||
push_date: str = "",
|
||||
limit: int = Query(40, ge=1, le=200),
|
||||
) -> 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)}
|
||||
|
||||
|
||||
@app.post("/api/x2/jobs/{job_id}/cancel")
|
||||
async def x2_jobs_cancel(job_id: str) -> dict[str, Any]:
|
||||
from . import x2_db
|
||||
|
||||
@ -1058,6 +1058,13 @@ class ShortsPipeline:
|
||||
|
||||
async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
||||
jid = str(job["id"])
|
||||
# Isolated companion: enqueue 16:9 long-form (never raises into Shorts).
|
||||
try:
|
||||
from .yt_long_pipeline import try_enqueue_from_shorts
|
||||
|
||||
try_enqueue_from_shorts(job)
|
||||
except Exception:
|
||||
pass
|
||||
cookie = str(cfg.get("dy_cookie") or "")
|
||||
candidates = await resolve_stream_candidates(
|
||||
source_url=str(job.get("source_url") or ""),
|
||||
|
||||
145
backend/app/yt_long_clip.py
Normal file
145
backend/app/yt_long_clip.py
Normal file
@ -0,0 +1,145 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Record landscape 16:9 long clips — isolated from Shorts 9:16 recorder.
|
||||
|
||||
Reuses only side-effect-free stream helpers from shorts_clip.
|
||||
Writes under clips_dir/yt_long/ so filenames never collide with Shorts.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from .config import settings
|
||||
from .shorts_clip import _headers_arg, probe_stream_url
|
||||
from .yt_long_db import YT_LONG_MAX_SEC, YT_LONG_MIN_SEC
|
||||
|
||||
|
||||
def _landscape_vf() -> str:
|
||||
"""Fit source to 1080p height, center on 1920x1080 (pillarbox for 9:16)."""
|
||||
return (
|
||||
"scale=-2:1080:force_original_aspect_ratio=decrease,"
|
||||
"pad=1920:1080:(ow-iw)/2:(oh-ih)/2:black,setsar=1"
|
||||
)
|
||||
|
||||
|
||||
def clips_dir() -> Path:
|
||||
d = settings.clips_dir / "yt_long"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
async def record_landscape_clip(
|
||||
*,
|
||||
job_id: str,
|
||||
stream_urls: list[str] | None = None,
|
||||
stream_url: str = "",
|
||||
seconds: int = 300,
|
||||
) -> dict[str, Any]:
|
||||
"""Pull live stream for 3–8 minutes into a 16:9 mp4."""
|
||||
urls: list[str] = []
|
||||
for u in list(stream_urls or []) + [stream_url]:
|
||||
s = str(u or "").strip()
|
||||
if s.startswith("http") and s not in urls:
|
||||
urls.append(s)
|
||||
if not urls:
|
||||
return {"ok": False, "error": "无可用流地址"}
|
||||
|
||||
sec = max(YT_LONG_MIN_SEC, min(int(seconds or 300), YT_LONG_MAX_SEC))
|
||||
out_path = clips_dir() / f"{job_id}.mp4"
|
||||
vf = _landscape_vf()
|
||||
last_err = ""
|
||||
|
||||
for url in urls:
|
||||
if len(urls) > 1:
|
||||
alive = await probe_stream_url(url)
|
||||
if alive is False:
|
||||
last_err = f"probe 404: {url[:80]}"
|
||||
continue
|
||||
if out_path.is_file():
|
||||
try:
|
||||
out_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
is_hls = ".m3u8" in url.lower() or "/playlist" in url.lower()
|
||||
cmd = [
|
||||
settings.ffmpeg_bin,
|
||||
"-y",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-headers",
|
||||
_headers_arg(),
|
||||
"-rw_timeout",
|
||||
"20000000",
|
||||
]
|
||||
if not is_hls:
|
||||
cmd.extend(
|
||||
[
|
||||
"-reconnect",
|
||||
"1",
|
||||
"-reconnect_streamed",
|
||||
"1",
|
||||
"-reconnect_at_eof",
|
||||
"1",
|
||||
"-reconnect_delay_max",
|
||||
"8",
|
||||
]
|
||||
)
|
||||
cmd.extend(
|
||||
[
|
||||
"-i",
|
||||
url,
|
||||
"-t",
|
||||
str(sec),
|
||||
"-vf",
|
||||
vf,
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"veryfast",
|
||||
"-crf",
|
||||
"23",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"128k",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
"-avoid_negative_ts",
|
||||
"make_zero",
|
||||
str(out_path),
|
||||
]
|
||||
)
|
||||
|
||||
def _run(cmd_local: list[str] = cmd, used_url: str = url) -> dict[str, Any]:
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd_local,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=sec + 180,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"ok": False, "error": "ffmpeg 超时", "stream_url": used_url}
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": str(exc)[:400], "stream_url": used_url}
|
||||
if proc.returncode != 0:
|
||||
err = (proc.stderr or proc.stdout or "ffmpeg failed")[:500]
|
||||
return {"ok": False, "error": err, "stream_url": used_url}
|
||||
if not out_path.is_file() or out_path.stat().st_size < 50_000:
|
||||
return {"ok": False, "error": "成片过小或不存在", "stream_url": used_url}
|
||||
return {
|
||||
"ok": True,
|
||||
"path": str(out_path),
|
||||
"seconds": sec,
|
||||
"stream_url": used_url,
|
||||
}
|
||||
|
||||
outcome = await asyncio.to_thread(_run)
|
||||
if outcome.get("ok"):
|
||||
return outcome
|
||||
last_err = str(outcome.get("error") or last_err)
|
||||
|
||||
return {"ok": False, "error": last_err or "录制失败"}
|
||||
439
backend/app/yt_long_db.py
Normal file
439
backend/app/yt_long_db.py
Normal file
@ -0,0 +1,439 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""YouTube long-form (16:9) jobs — fully isolated from shorts_* / tiktok_* / x_clip_*."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
from .db import _connect, _lock, _row_to_dict
|
||||
from .timeutil import push_date_from_ts
|
||||
|
||||
# Quota-consuming statuses for daily long-form caps
|
||||
_QUOTA_STATUSES = ("scheduled", "uploading", "uploaded")
|
||||
|
||||
YT_LONG_DAILY_DEFAULT = 3
|
||||
YT_LONG_MIN_SEC = 180 # 3 min
|
||||
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_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
room_pk TEXT NOT NULL DEFAULT '',
|
||||
room_id TEXT NOT NULL DEFAULT '',
|
||||
source_url TEXT NOT NULL DEFAULT '',
|
||||
anchor_name TEXT NOT NULL DEFAULT '',
|
||||
stream_url TEXT NOT NULL DEFAULT '',
|
||||
channel_pk TEXT NOT NULL DEFAULT '',
|
||||
shorts_job_id TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
clip_path TEXT NOT NULL DEFAULT '',
|
||||
clip_seconds REAL NOT NULL DEFAULT 0,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
youtube_video_id TEXT NOT NULL DEFAULT '',
|
||||
youtube_url TEXT NOT NULL DEFAULT '',
|
||||
error TEXT NOT NULL DEFAULT '',
|
||||
push_date TEXT NOT NULL DEFAULT '',
|
||||
upload_at REAL NOT NULL DEFAULT 0,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
created_at REAL NOT NULL,
|
||||
updated_at REAL NOT NULL,
|
||||
started_at REAL NOT NULL DEFAULT 0,
|
||||
finished_at REAL NOT NULL DEFAULT 0
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_status ON yt_long_jobs(status, created_at)"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_date ON yt_long_jobs(push_date, status)"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_room_day ON yt_long_jobs(room_id, push_date, status)"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_upload ON yt_long_jobs(status, upload_at)"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_yt_long_jobs_channel ON yt_long_jobs(channel_pk, push_date)"
|
||||
)
|
||||
|
||||
|
||||
def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int:
|
||||
from . import db
|
||||
|
||||
settings = cfg if cfg is not None else db.get_settings_map()
|
||||
try:
|
||||
v = int(settings.get("yt_long_daily_max") or YT_LONG_DAILY_DEFAULT)
|
||||
except Exception:
|
||||
v = YT_LONG_DAILY_DEFAULT
|
||||
return max(0, min(50, v))
|
||||
|
||||
|
||||
def yt_long_channel_daily_max(cfg: dict[str, Any] | None = None) -> int:
|
||||
from . import db
|
||||
|
||||
settings = cfg if cfg is not None else db.get_settings_map()
|
||||
try:
|
||||
v = int(settings.get("yt_long_channel_daily_max") or 1)
|
||||
except Exception:
|
||||
v = 1
|
||||
return max(0, min(20, v))
|
||||
|
||||
|
||||
def yt_long_quota_used(push_date: str = "") -> int:
|
||||
day = push_date or push_date_from_ts(time.time())
|
||||
placeholders = ",".join("?" for _ in _QUOTA_STATUSES)
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
row = conn.execute(
|
||||
f"""
|
||||
SELECT COUNT(*) AS c FROM yt_long_jobs
|
||||
WHERE push_date = ? AND status IN ({placeholders})
|
||||
""",
|
||||
(day, *_QUOTA_STATUSES),
|
||||
).fetchone()
|
||||
return int(row["c"]) if row else 0
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def yt_long_quota_gap(push_date: str = "", cfg: dict[str, Any] | None = None) -> int:
|
||||
day = push_date or push_date_from_ts(time.time())
|
||||
return max(0, yt_long_daily_max(cfg) - yt_long_quota_used(day))
|
||||
|
||||
|
||||
def channel_quota_used(channel_pk: str, push_date: str = "") -> int:
|
||||
day = push_date or push_date_from_ts(time.time())
|
||||
placeholders = ",".join("?" for _ in _QUOTA_STATUSES)
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
row = conn.execute(
|
||||
f"""
|
||||
SELECT COUNT(*) AS c FROM yt_long_jobs
|
||||
WHERE push_date = ? AND channel_pk = ? AND status IN ({placeholders})
|
||||
""",
|
||||
(day, channel_pk, *_QUOTA_STATUSES),
|
||||
).fetchone()
|
||||
return int(row["c"]) if row else 0
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def has_job_for_room_day(room_id: str, push_date: str) -> bool:
|
||||
if not room_id:
|
||||
return False
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT 1 FROM yt_long_jobs
|
||||
WHERE room_id = ? AND push_date = ?
|
||||
AND status NOT IN ('failed', 'skipped')
|
||||
LIMIT 1
|
||||
""",
|
||||
(room_id, push_date),
|
||||
).fetchone()
|
||||
return bool(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_yt_long_job(
|
||||
*,
|
||||
room_pk: str = "",
|
||||
room_id: str = "",
|
||||
source_url: str = "",
|
||||
anchor_name: str = "",
|
||||
stream_url: str = "",
|
||||
channel_pk: str = "",
|
||||
shorts_job_id: str = "",
|
||||
push_date: str = "",
|
||||
) -> dict[str, Any]:
|
||||
now = time.time()
|
||||
day = push_date or push_date_from_ts(now)
|
||||
jid = str(uuid.uuid4())
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO yt_long_jobs(
|
||||
id, room_pk, room_id, source_url, anchor_name, stream_url,
|
||||
channel_pk, shorts_job_id, status, push_date,
|
||||
created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
jid,
|
||||
room_pk,
|
||||
room_id,
|
||||
source_url,
|
||||
anchor_name,
|
||||
stream_url,
|
||||
channel_pk,
|
||||
shorts_job_id,
|
||||
day,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return _row_to_dict(
|
||||
conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (jid,)).fetchone()
|
||||
) # type: ignore
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_yt_long_job(job_id: str) -> dict[str, Any] | None:
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
row = conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
return _row_to_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_yt_long_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
|
||||
if not fields:
|
||||
return get_yt_long_job(job_id)
|
||||
allowed = {
|
||||
"status",
|
||||
"clip_path",
|
||||
"clip_seconds",
|
||||
"title",
|
||||
"description",
|
||||
"youtube_video_id",
|
||||
"youtube_url",
|
||||
"error",
|
||||
"channel_pk",
|
||||
"stream_url",
|
||||
"upload_at",
|
||||
"attempts",
|
||||
"started_at",
|
||||
"finished_at",
|
||||
"anchor_name",
|
||||
"source_url",
|
||||
}
|
||||
sets: list[str] = []
|
||||
params: list[Any] = []
|
||||
for k, v in fields.items():
|
||||
if k not in allowed:
|
||||
continue
|
||||
sets.append(f"{k} = ?")
|
||||
params.append(v)
|
||||
if not sets:
|
||||
return get_yt_long_job(job_id)
|
||||
sets.append("updated_at = ?")
|
||||
params.append(time.time())
|
||||
params.append(job_id)
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
conn.execute(f"UPDATE yt_long_jobs SET {', '.join(sets)} WHERE id = ?", params)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
return _row_to_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_yt_long_jobs(*, limit: int = 40, push_date: str = "") -> list[dict[str, Any]]:
|
||||
day = push_date.strip()
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
if day:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT * FROM yt_long_jobs WHERE push_date = ?
|
||||
ORDER BY created_at DESC LIMIT ?
|
||||
""",
|
||||
(day, max(1, min(int(limit), 200))),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT * FROM yt_long_jobs
|
||||
ORDER BY created_at DESC LIMIT ?
|
||||
""",
|
||||
(max(1, min(int(limit), 200)),),
|
||||
).fetchall()
|
||||
return [_row_to_dict(r) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_pending_yt_long_jobs(*, limit: int = 5) -> list[dict[str, Any]]:
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT * FROM yt_long_jobs
|
||||
WHERE status = 'pending'
|
||||
ORDER BY created_at ASC
|
||||
LIMIT ?
|
||||
""",
|
||||
(max(1, min(int(limit), 20)),),
|
||||
).fetchall()
|
||||
return [_row_to_dict(r) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def claim_yt_long_job_record(job_id: str) -> dict[str, Any] | None:
|
||||
now = time.time()
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
UPDATE yt_long_jobs
|
||||
SET status = 'recording', started_at = ?, updated_at = ?, attempts = attempts + 1
|
||||
WHERE id = ? AND status = 'pending'
|
||||
""",
|
||||
(now, now, job_id),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
conn.rollback()
|
||||
return None
|
||||
conn.commit()
|
||||
return _row_to_dict(
|
||||
conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def claim_due_yt_long_upload() -> dict[str, Any] | None:
|
||||
now = time.time()
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT * FROM yt_long_jobs
|
||||
WHERE status = 'scheduled'
|
||||
AND clip_path != ''
|
||||
AND upload_at > 0
|
||||
AND upload_at <= ?
|
||||
ORDER BY upload_at ASC, created_at ASC
|
||||
LIMIT 1
|
||||
""",
|
||||
(now,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
jid = str(row["id"])
|
||||
cur = conn.execute(
|
||||
"""
|
||||
UPDATE yt_long_jobs
|
||||
SET status = 'uploading', updated_at = ?, attempts = attempts + 1
|
||||
WHERE id = ? AND status = 'scheduled'
|
||||
""",
|
||||
(now, jid),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
conn.rollback()
|
||||
return None
|
||||
conn.commit()
|
||||
return _row_to_dict(
|
||||
conn.execute("SELECT * FROM yt_long_jobs WHERE id = ?", (jid,)).fetchone()
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 900) -> int:
|
||||
cutoff = time.time() - max(120.0, float(max_age_sec))
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
UPDATE yt_long_jobs
|
||||
SET status = 'pending', started_at = 0, error = 'recording_stale_reclaim', updated_at = ?
|
||||
WHERE status = 'recording' AND updated_at < ?
|
||||
""",
|
||||
(time.time(), cutoff),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.rowcount or 0)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def reclaim_stale_yt_long_uploads(*, max_age_sec: float = 1800) -> int:
|
||||
cutoff = time.time() - max(180.0, float(max_age_sec))
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
UPDATE yt_long_jobs
|
||||
SET status = 'scheduled', error = 'upload_stale_reclaim', updated_at = ?
|
||||
WHERE status = 'uploading' AND updated_at < ?
|
||||
AND IFNULL(youtube_video_id, '') = ''
|
||||
""",
|
||||
(time.time(), cutoff),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.rowcount or 0)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def yt_long_stats(push_date: str = "") -> dict[str, Any]:
|
||||
day = push_date or push_date_from_ts(time.time())
|
||||
placeholders = ",".join("?" for _ in _QUOTA_STATUSES)
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT status, COUNT(*) AS c FROM yt_long_jobs
|
||||
WHERE push_date = ?
|
||||
GROUP BY status
|
||||
""",
|
||||
(day,),
|
||||
).fetchall()
|
||||
by_status = {str(r["status"]): int(r["c"]) for r in rows}
|
||||
used_row = conn.execute(
|
||||
f"""
|
||||
SELECT COUNT(*) AS c FROM yt_long_jobs
|
||||
WHERE push_date = ? AND status IN ({placeholders})
|
||||
""",
|
||||
(day, *_QUOTA_STATUSES),
|
||||
).fetchone()
|
||||
return {
|
||||
"push_date": day,
|
||||
"by_status": by_status,
|
||||
"used": int(used_row["c"]) if used_row else 0,
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
386
backend/app/yt_long_pipeline.py
Normal file
386
backend/app/yt_long_pipeline.py
Normal file
@ -0,0 +1,386 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Isolated YouTube long-form (16:9) pipeline.
|
||||
|
||||
Companion to Shorts: when Shorts records a room, optionally enqueue a 3–8 min
|
||||
landscape job. Never writes shorts_* / tiktok_* / x_clip_* tables.
|
||||
Default: disabled (yt_long_enabled=false) so online Shorts is untouched until
|
||||
an operator turns this on.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import random
|
||||
import time
|
||||
from pathlib import Path
|
||||
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
|
||||
from .yt_long_upload import upload_youtube_long_mp4
|
||||
|
||||
|
||||
def _rand_clip_sec(cfg: dict[str, Any]) -> int:
|
||||
try:
|
||||
lo = int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC)
|
||||
except Exception:
|
||||
lo = YT_LONG_MIN_SEC
|
||||
try:
|
||||
hi = int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC)
|
||||
except Exception:
|
||||
hi = YT_LONG_MAX_SEC
|
||||
lo = max(YT_LONG_MIN_SEC, min(YT_LONG_MAX_SEC, lo))
|
||||
hi = max(lo, min(YT_LONG_MAX_SEC, hi))
|
||||
return random.randint(lo, hi)
|
||||
|
||||
|
||||
def _build_title(job: dict[str, Any], channel: dict[str, Any], cfg: dict[str, Any]) -> str:
|
||||
tpl = str(
|
||||
cfg.get("yt_long_title_template")
|
||||
or channel.get("title_template")
|
||||
or "{anchor} street food live"
|
||||
)
|
||||
# Strip Shorts hashtags from inherited channel templates
|
||||
tpl = tpl.replace("#Shorts", "").replace("#shorts", "").strip()
|
||||
anchor = str(job.get("anchor_name") or job.get("room_id") or "live").strip()
|
||||
url = str(job.get("source_url") or "").strip()
|
||||
room = str(job.get("room_id") or "").strip()
|
||||
text = (
|
||||
tpl.replace("{anchor}", anchor)
|
||||
.replace("{url}", url)
|
||||
.replace("{room}", room)
|
||||
.strip()
|
||||
)
|
||||
return (text or f"{anchor} live")[:100]
|
||||
|
||||
|
||||
def _build_description(job: dict[str, Any], channel: dict[str, Any], cfg: dict[str, Any]) -> str:
|
||||
tpl = str(
|
||||
cfg.get("yt_long_description_template")
|
||||
or channel.get("description_template")
|
||||
or "{anchor}\n{url}"
|
||||
)
|
||||
tpl = tpl.replace("#Shorts", "").replace("#shorts", "")
|
||||
anchor = str(job.get("anchor_name") or "").strip()
|
||||
url = str(job.get("source_url") or "").strip()
|
||||
return (
|
||||
tpl.replace("{anchor}", anchor)
|
||||
.replace("{url}", url)
|
||||
.replace("{room}", str(job.get("room_id") or ""))
|
||||
.strip()
|
||||
)[:4900]
|
||||
|
||||
|
||||
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."""
|
||||
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)
|
||||
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)
|
||||
if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")):
|
||||
continue
|
||||
used = yt_long_db.channel_quota_used(cid, day)
|
||||
if per_max > 0 and used >= per_max:
|
||||
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
|
||||
return scored[0][1]
|
||||
|
||||
|
||||
def try_enqueue_from_shorts(job: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Safe companion enqueue. Never raises into Shorts. No-op when disabled."""
|
||||
try:
|
||||
cfg = db.get_settings_map()
|
||||
if not cfg.get("yt_long_enabled"):
|
||||
return {"enqueued": False, "reason": "disabled"}
|
||||
if not cfg.get("yt_long_with_shorts", True):
|
||||
return {"enqueued": False, "reason": "with_shorts_off"}
|
||||
if yt_long_db.yt_long_quota_gap(cfg=cfg) <= 0:
|
||||
return {"enqueued": False, "reason": "quota_full"}
|
||||
room_id = str(job.get("room_id") or "").strip()
|
||||
day = str(job.get("push_date") or push_date_from_ts(time.time()))
|
||||
if cfg.get("yt_long_dedupe_room_day", True) and room_id and yt_long_db.has_job_for_room_day(room_id, day):
|
||||
return {"enqueued": False, "reason": "room_dedupe"}
|
||||
channel = pick_yt_long_channel(cfg, day)
|
||||
if not channel:
|
||||
return {"enqueued": False, "reason": "no_channel"}
|
||||
created = yt_long_db.create_yt_long_job(
|
||||
room_pk=str(job.get("room_pk") or ""),
|
||||
room_id=room_id,
|
||||
source_url=str(job.get("source_url") or ""),
|
||||
anchor_name=str(job.get("anchor_name") or ""),
|
||||
stream_url=str(job.get("stream_url") or ""),
|
||||
channel_pk=str(channel.get("id") or ""),
|
||||
shorts_job_id=str(job.get("id") or ""),
|
||||
push_date=day,
|
||||
)
|
||||
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]}
|
||||
|
||||
|
||||
class YtLongPipeline:
|
||||
def __init__(self) -> None:
|
||||
self._task: asyncio.Task[None] | None = None
|
||||
self._stop = asyncio.Event()
|
||||
self._active_records = 0
|
||||
self._active_uploads = 0
|
||||
self.processed = 0
|
||||
self.last_error = ""
|
||||
|
||||
def status(self) -> dict[str, Any]:
|
||||
cfg = db.get_settings_map()
|
||||
day = push_date_from_ts(time.time())
|
||||
return {
|
||||
"running": bool(self._task and not self._task.done()),
|
||||
"busy": self._active_records > 0 or self._active_uploads > 0,
|
||||
"enabled": bool(cfg.get("yt_long_enabled")),
|
||||
"processed": self.processed,
|
||||
"quota_gap": yt_long_db.yt_long_quota_gap(day, cfg),
|
||||
"quota_used": yt_long_db.yt_long_quota_used(day),
|
||||
"daily_max": yt_long_db.yt_long_daily_max(cfg),
|
||||
"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),
|
||||
"settings": {
|
||||
"yt_long_enabled": bool(cfg.get("yt_long_enabled")),
|
||||
"yt_long_with_shorts": bool(cfg.get("yt_long_with_shorts", True)),
|
||||
"yt_long_auto_upload": bool(cfg.get("yt_long_auto_upload", True)),
|
||||
"yt_long_daily_max": yt_long_db.yt_long_daily_max(cfg),
|
||||
"yt_long_channel_daily_max": yt_long_db.yt_long_channel_daily_max(cfg),
|
||||
"yt_long_min_sec": int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC),
|
||||
"yt_long_max_sec": int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC),
|
||||
"yt_long_dedupe_room_day": bool(cfg.get("yt_long_dedupe_room_day", True)),
|
||||
"yt_long_title_template": str(cfg.get("yt_long_title_template") or ""),
|
||||
"yt_long_description_template": str(cfg.get("yt_long_description_template") or ""),
|
||||
"yt_long_delete_clip_after_upload": bool(
|
||||
cfg.get("yt_long_delete_clip_after_upload", True)
|
||||
),
|
||||
"yt_long_upload_min_gap_sec": int(cfg.get("yt_long_upload_min_gap_sec") or 900),
|
||||
},
|
||||
}
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._task and not self._task.done():
|
||||
return
|
||||
self._stop.clear()
|
||||
self._task = asyncio.create_task(self._loop(), name="yt-long-pipeline")
|
||||
|
||||
async def stop(self) -> None:
|
||||
self._stop.set()
|
||||
t = self._task
|
||||
if t:
|
||||
try:
|
||||
await asyncio.wait_for(t, timeout=8)
|
||||
except Exception:
|
||||
t.cancel()
|
||||
self._task = None
|
||||
|
||||
async def _loop(self) -> None:
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
cfg = db.get_settings_map()
|
||||
if not cfg.get("yt_long_enabled"):
|
||||
await asyncio.sleep(5)
|
||||
continue
|
||||
try:
|
||||
yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=900)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
yt_long_db.reclaim_stale_yt_long_uploads(max_age_sec=1800)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1))
|
||||
while self._active_records < max_rec:
|
||||
pending = yt_long_db.list_pending_yt_long_jobs(limit=1)
|
||||
if not pending:
|
||||
break
|
||||
job = yt_long_db.claim_yt_long_job_record(str(pending[0].get("id") or ""))
|
||||
if not job:
|
||||
break
|
||||
self._active_records += 1
|
||||
asyncio.create_task(self._run_record(job))
|
||||
|
||||
if cfg.get("yt_long_auto_upload", True):
|
||||
max_up = max(1, int(cfg.get("yt_long_max_concurrent") or 1))
|
||||
while self._active_uploads < max_up:
|
||||
job = yt_long_db.claim_due_yt_long_upload()
|
||||
if not job:
|
||||
break
|
||||
self._active_uploads += 1
|
||||
asyncio.create_task(self._run_upload(job))
|
||||
except Exception as exc:
|
||||
self.last_error = str(exc)[:240]
|
||||
await asyncio.sleep(3.0)
|
||||
|
||||
async def _run_record(self, job: dict[str, Any]) -> None:
|
||||
try:
|
||||
await self._do_record(job)
|
||||
self.processed += 1
|
||||
except Exception as exc:
|
||||
self.last_error = str(exc)[:240]
|
||||
yt_long_db.update_yt_long_job(
|
||||
str(job.get("id") or ""),
|
||||
status="failed",
|
||||
error=str(exc)[:500],
|
||||
finished_at=time.time(),
|
||||
)
|
||||
finally:
|
||||
self._active_records = max(0, self._active_records - 1)
|
||||
|
||||
async def _do_record(self, job: dict[str, Any]) -> None:
|
||||
cfg = db.get_settings_map()
|
||||
jid = str(job.get("id") or "")
|
||||
cookie = str(cfg.get("dy_cookie") or "")
|
||||
candidates = await resolve_stream_candidates(
|
||||
source_url=str(job.get("source_url") or ""),
|
||||
stream_url=str(job.get("stream_url") or ""),
|
||||
cookie=cookie,
|
||||
prefer_fresh=True,
|
||||
max_candidates=8,
|
||||
)
|
||||
if not candidates:
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="failed",
|
||||
error="无法获取直播流",
|
||||
finished_at=time.time(),
|
||||
)
|
||||
return
|
||||
sec = _rand_clip_sec(cfg)
|
||||
outcome = await record_landscape_clip(job_id=jid, stream_urls=candidates, seconds=sec)
|
||||
if not outcome.get("ok"):
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="failed",
|
||||
error=str(outcome.get("error") or "录制失败")[:500],
|
||||
stream_url=str(outcome.get("stream_url") or ""),
|
||||
finished_at=time.time(),
|
||||
)
|
||||
return
|
||||
clip_path = str(outcome.get("path") or "")
|
||||
gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900))
|
||||
upload_at = time.time() + random.uniform(30, gap)
|
||||
if not cfg.get("yt_long_auto_upload", True):
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="recorded",
|
||||
clip_path=clip_path,
|
||||
clip_seconds=float(outcome.get("seconds") or sec),
|
||||
stream_url=str(outcome.get("stream_url") or ""),
|
||||
error="",
|
||||
)
|
||||
return
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="scheduled",
|
||||
clip_path=clip_path,
|
||||
clip_seconds=float(outcome.get("seconds") or sec),
|
||||
stream_url=str(outcome.get("stream_url") or ""),
|
||||
upload_at=upload_at,
|
||||
error="",
|
||||
)
|
||||
|
||||
async def _run_upload(self, job: dict[str, Any]) -> None:
|
||||
try:
|
||||
await self._do_upload(job)
|
||||
except Exception as exc:
|
||||
self.last_error = str(exc)[:240]
|
||||
yt_long_db.update_yt_long_job(
|
||||
str(job.get("id") or ""),
|
||||
status="failed",
|
||||
error=str(exc)[:500],
|
||||
finished_at=time.time(),
|
||||
)
|
||||
finally:
|
||||
self._active_uploads = max(0, self._active_uploads - 1)
|
||||
|
||||
async def _do_upload(self, job: dict[str, Any]) -> None:
|
||||
cfg = db.get_settings_map()
|
||||
jid = str(job.get("id") or "")
|
||||
fresh = yt_long_db.get_yt_long_job(jid) or job
|
||||
if str(fresh.get("youtube_video_id") or "").strip():
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="uploaded",
|
||||
finished_at=time.time(),
|
||||
error="",
|
||||
)
|
||||
return
|
||||
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 ""))
|
||||
if not channel:
|
||||
channel = pick_yt_long_channel(cfg, str(fresh.get("push_date") or ""))
|
||||
if channel:
|
||||
yt_long_db.update_yt_long_job(jid, channel_pk=str(channel["id"]))
|
||||
if not channel:
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="recorded",
|
||||
error="无可用 YouTube 频道(需 Shorts 频道已授权)",
|
||||
)
|
||||
return
|
||||
creds = channel_oauth_creds(channel, cfg)
|
||||
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="scheduled",
|
||||
error="频道未授权 Google",
|
||||
)
|
||||
return
|
||||
title = _build_title(fresh, channel, cfg)
|
||||
description = _build_description(fresh, channel, cfg)
|
||||
privacy = str(channel.get("privacy") or "public")
|
||||
proxy = ""
|
||||
try:
|
||||
from .shorts_socks import resolve_upload_socks_proxy
|
||||
|
||||
proxy = resolve_upload_socks_proxy(cfg) or ""
|
||||
except Exception:
|
||||
proxy = ""
|
||||
result = await upload_youtube_long_mp4(
|
||||
file_path=clip,
|
||||
title=title,
|
||||
description=description,
|
||||
privacy=privacy,
|
||||
client_id=str(creds["client_id"]),
|
||||
client_secret=str(creds["client_secret"]),
|
||||
refresh_token=str(creds["refresh_token"]),
|
||||
proxy_url=proxy,
|
||||
)
|
||||
vid = str(result.get("video_id") or "")
|
||||
url = str(result.get("url") or "")
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="uploaded",
|
||||
youtube_video_id=vid,
|
||||
youtube_url=url,
|
||||
title=title,
|
||||
description=description,
|
||||
error="",
|
||||
finished_at=time.time(),
|
||||
clip_path="" if cfg.get("yt_long_delete_clip_after_upload", True) else clip,
|
||||
)
|
||||
if cfg.get("yt_long_delete_clip_after_upload", True):
|
||||
try:
|
||||
Path(clip).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
yt_long_pipeline = YtLongPipeline()
|
||||
99
backend/app/yt_long_upload.py
Normal file
99
backend/app/yt_long_upload.py
Normal file
@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""YouTube long-form (16:9) upload — same OAuth transport as Shorts, watch URL not /shorts/."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .shorts_upload import (
|
||||
_client_kwargs,
|
||||
is_upload_quota_error,
|
||||
quota_error_message,
|
||||
refresh_access_token,
|
||||
)
|
||||
|
||||
|
||||
async def upload_youtube_long_mp4(
|
||||
*,
|
||||
file_path: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
privacy: str = "public",
|
||||
client_id: str = "",
|
||||
client_secret: str = "",
|
||||
refresh_token: str = "",
|
||||
proxy_url: str = "",
|
||||
) -> dict[str, Any]:
|
||||
path = Path(file_path)
|
||||
if not path.is_file():
|
||||
raise ValueError("成片文件不存在")
|
||||
access = await refresh_access_token(
|
||||
client_id=client_id,
|
||||
client_secret=client_secret,
|
||||
refresh_token=refresh_token,
|
||||
proxy_url=proxy_url,
|
||||
)
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
raw = path.read_bytes()
|
||||
except FileNotFoundError as exc:
|
||||
raise ValueError("成片文件不存在") from exc
|
||||
|
||||
# No #Shorts — this is a normal YouTube video (16:9).
|
||||
clean_title = (title or "Live clip").replace("#Shorts", "").replace("#shorts", "").strip()[:100]
|
||||
meta = {
|
||||
"snippet": {
|
||||
"title": clean_title or "Live clip",
|
||||
"description": description or "",
|
||||
"categoryId": "22",
|
||||
},
|
||||
"status": {
|
||||
"privacyStatus": privacy if privacy in {"public", "unlisted", "private"} else "public",
|
||||
"selfDeclaredMadeForKids": False,
|
||||
},
|
||||
}
|
||||
init_url = (
|
||||
"https://www.googleapis.com/upload/youtube/v3/videos"
|
||||
"?uploadType=resumable&part=snippet,status"
|
||||
)
|
||||
async with httpx.AsyncClient(**_client_kwargs(timeout=600.0, proxy_url=proxy_url)) as client:
|
||||
init = await client.post(
|
||||
init_url,
|
||||
headers={
|
||||
"Authorization": f"Bearer {access}",
|
||||
"Content-Type": "application/json; charset=UTF-8",
|
||||
"X-Upload-Content-Length": str(size),
|
||||
"X-Upload-Content-Type": "video/mp4",
|
||||
},
|
||||
json=meta,
|
||||
)
|
||||
upload_url = init.headers.get("location") or init.headers.get("Location")
|
||||
if init.status_code >= 400 or not upload_url:
|
||||
body = init.text[:800]
|
||||
if init.status_code == 429 or is_upload_quota_error(body):
|
||||
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({body[:200]})")
|
||||
raise ValueError(f"初始化上传失败: {body[:400]}")
|
||||
put = await client.put(
|
||||
upload_url,
|
||||
headers={
|
||||
"Authorization": f"Bearer {access}",
|
||||
"Content-Type": "video/mp4",
|
||||
"Content-Length": str(size),
|
||||
},
|
||||
content=raw,
|
||||
)
|
||||
data = put.json() if put.content else {}
|
||||
if put.status_code >= 400 or not data.get("id"):
|
||||
err_text = str(data.get("error") or put.text[:800])
|
||||
if put.status_code == 429 or is_upload_quota_error(err_text):
|
||||
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({err_text[:200]})")
|
||||
raise ValueError(f"上传失败: {err_text[:400]}")
|
||||
vid = str(data["id"])
|
||||
return {
|
||||
"ok": True,
|
||||
"video_id": vid,
|
||||
"url": f"https://www.youtube.com/watch?v={vid}",
|
||||
"raw": data,
|
||||
}
|
||||
300
frontend/src/app/yt-long/page.tsx
Normal file
300
frontend/src/app/yt-long/page.tsx
Normal file
@ -0,0 +1,300 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Film, RefreshCw } from "lucide-react";
|
||||
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { useToast } from "@/components/Toast";
|
||||
import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api";
|
||||
import { useAutoRefresh } from "@/lib/realtime";
|
||||
|
||||
const panel =
|
||||
"rounded-2xl border border-white/10 bg-gradient-to-b from-white/[0.07] to-black/30 p-4 shadow-[0_8px_32px_rgba(0,0,0,0.25)]";
|
||||
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";
|
||||
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 Job = {
|
||||
id: string;
|
||||
status?: string;
|
||||
anchor_name?: string;
|
||||
room_id?: string;
|
||||
title?: string;
|
||||
clip_seconds?: number;
|
||||
youtube_url?: string;
|
||||
error?: string;
|
||||
upload_at?: number;
|
||||
created_at?: number;
|
||||
};
|
||||
|
||||
type Status = {
|
||||
enabled?: boolean;
|
||||
running?: boolean;
|
||||
busy?: boolean;
|
||||
quota_used?: number;
|
||||
quota_gap?: number;
|
||||
daily_max?: number;
|
||||
channel_daily_max?: number;
|
||||
last_error?: string;
|
||||
settings?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
const STATUS_ZH: Record<string, string> = {
|
||||
pending: "排队",
|
||||
recording: "录制中",
|
||||
recorded: "已成片",
|
||||
scheduled: "待上传",
|
||||
uploading: "上传中",
|
||||
uploaded: "已上传",
|
||||
failed: "失败",
|
||||
skipped: "跳过",
|
||||
};
|
||||
|
||||
export default function YtLongPage() {
|
||||
const toast = useToast();
|
||||
const [st, setSt] = useState<Status | null>(null);
|
||||
const [jobs, setJobs] = useState<Job[]>([]);
|
||||
const [busy, setBusy] = useState("");
|
||||
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);
|
||||
}
|
||||
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]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
useAutoRefresh(load, { intervalMs: 12000 });
|
||||
|
||||
async function toggle(enable: boolean) {
|
||||
setBusy(enable ? "start" : "stop");
|
||||
try {
|
||||
await fetchJson(enable ? "/api/yt-long/start" : "/api/yt-long/stop", { method: "POST" });
|
||||
toast.push(enable ? "已开启长视频模块" : "已关闭长视频模块", "ok");
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSettings() {
|
||||
setBusy("save");
|
||||
try {
|
||||
await fetchJson("/api/yt-long/settings", {
|
||||
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,
|
||||
}),
|
||||
});
|
||||
toast.push("设置已保存", "ok");
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy("");
|
||||
}
|
||||
}
|
||||
|
||||
const used = st?.quota_used ?? 0;
|
||||
const max = st?.daily_max ?? 0;
|
||||
const gap = st?.quota_gap ?? 0;
|
||||
|
||||
return (
|
||||
<Shell>
|
||||
<div className="mb-4 flex flex-wrap items-end justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="flex items-center gap-2 text-xl font-semibold text-white">
|
||||
<Film className="h-5 w-5 text-sky-300" />
|
||||
YouTube 长视频
|
||||
</h1>
|
||||
<p className="mt-1 text-xs text-slate-400">
|
||||
独立模块:3–8 分钟随机时长,9:16 居中进 16:9,上传为普通 YouTube 视频(非 Shorts)。默认关闭。
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" onClick={() => void load()} className={ghost}>
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mb-4 grid gap-3 sm:grid-cols-4">
|
||||
<div className={panel}>
|
||||
<div className="text-[11px] text-slate-400">今日配额</div>
|
||||
<div className="mt-1 text-2xl font-semibold text-white">
|
||||
{used}/{max}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[11px] text-slate-500">剩余 {gap}</div>
|
||||
</div>
|
||||
<div className={panel}>
|
||||
<div className="text-[11px] text-slate-400">状态</div>
|
||||
<div className="mt-1 text-lg font-semibold text-white">
|
||||
{st?.enabled ? (st.running ? "运行中" : "已启用") : "已关闭"}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[11px] text-slate-500">{st?.busy ? "忙碌" : "空闲"}</div>
|
||||
</div>
|
||||
<div className={panel}>
|
||||
<div className="text-[11px] text-slate-400">每频道日上限</div>
|
||||
<div className="mt-1 text-2xl font-semibold text-white">{st?.channel_daily_max ?? "—"}</div>
|
||||
</div>
|
||||
<div className={panel}>
|
||||
<div className="text-[11px] text-slate-400">操作</div>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{st?.enabled ? (
|
||||
<button type="button" disabled={busy === "stop"} onClick={() => void toggle(false)} className={ghost}>
|
||||
关闭
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" disabled={busy === "start"} onClick={() => void toggle(true)} className={primary}>
|
||||
开启
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{st?.last_error ? (
|
||||
<div className="mb-4 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-100">
|
||||
{st.last_error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mb-4 grid gap-4 lg:grid-cols-2">
|
||||
<div className={panel}>
|
||||
<h2 className="text-sm font-semibold text-white">参数</h2>
|
||||
<p className="mt-0.5 text-[11px] text-slate-400">只写 yt_long_* / yt_long_jobs,不碰 shorts_jobs。</p>
|
||||
<div className="mt-3 grid grid-cols-2 gap-3">
|
||||
<label className={label}>
|
||||
每日总上限
|
||||
<input className={field} value={dailyMax} onChange={(e) => setDailyMax(e.target.value)} />
|
||||
</label>
|
||||
<label className={label}>
|
||||
每频道日上限
|
||||
<input className={field} value={channelMax} onChange={(e) => setChannelMax(e.target.value)} />
|
||||
</label>
|
||||
<label className={label}>
|
||||
最短秒数 (180–480)
|
||||
<input className={field} value={minSec} onChange={(e) => setMinSec(e.target.value)} />
|
||||
</label>
|
||||
<label className={label}>
|
||||
最长秒数 (180–480)
|
||||
<input className={field} value={maxSec} onChange={(e) => setMaxSec(e.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
<label className={`${label} mt-3`}>
|
||||
标题模板(勿含 #Shorts)
|
||||
<input className={field} value={titleTpl} onChange={(e) => setTitleTpl(e.target.value)} />
|
||||
</label>
|
||||
<label className={`${label} mt-3`}>
|
||||
描述模板
|
||||
<textarea
|
||||
className={`${field} min-h-[72px]`}
|
||||
value={descTpl}
|
||||
onChange={(e) => setDescTpl(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<div className="mt-3 space-y-2 text-xs text-slate-300">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={withShorts} onChange={(e) => setWithShorts(e.target.checked)} />
|
||||
随 Shorts 录制一并入队
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={autoUpload} onChange={(e) => setAutoUpload(e.target.checked)} />
|
||||
成片后自动上传长视频
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={dedupe} onChange={(e) => setDedupe(e.target.checked)} />
|
||||
同房间每天只录一条
|
||||
</label>
|
||||
</div>
|
||||
<button type="button" disabled={busy === "save"} onClick={() => void saveSettings()} className={`${primary} mt-4`}>
|
||||
保存设置
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={panel}>
|
||||
<h2 className="text-sm font-semibold text-white">今日任务</h2>
|
||||
<p className="mt-0.5 text-[11px] text-slate-400">链接为 youtube.com/watch(非 /shorts/)</p>
|
||||
<div className="mt-3 max-h-[28rem] space-y-2 overflow-y-auto">
|
||||
{jobs.map((j) => (
|
||||
<div key={j.id} className="rounded-xl border border-white/10 bg-black/30 px-3 py-2">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-xs font-medium text-slate-100">
|
||||
{j.anchor_name || j.room_id || j.id.slice(0, 8)}
|
||||
</div>
|
||||
<div className="mt-0.5 line-clamp-2 text-[10px] text-slate-400">
|
||||
{j.title || "—"}
|
||||
{j.clip_seconds ? ` · ${Math.round(j.clip_seconds)}s` : ""}
|
||||
</div>
|
||||
{j.youtube_url ? (
|
||||
<a
|
||||
href={j.youtube_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="mt-0.5 block truncate text-[10px] text-sky-300 hover:underline"
|
||||
>
|
||||
{j.youtube_url}
|
||||
</a>
|
||||
) : null}
|
||||
{j.error ? <div className="mt-0.5 text-[10px] text-amber-300">{j.error}</div> : null}
|
||||
</div>
|
||||
<span className="shrink-0 rounded border border-white/10 px-1.5 py-0.5 text-[10px] text-slate-300">
|
||||
{STATUS_ZH[j.status || ""] || j.status}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 text-[9px] text-slate-600">
|
||||
{j.created_at ? fmtTs(j.created_at) : ""}
|
||||
{j.upload_at ? ` · 上传 ${fmtTs(j.upload_at)}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!jobs.length ? <div className="py-8 text-center text-xs text-slate-500">今日暂无长视频任务</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@ -27,6 +27,7 @@ const NAV = [
|
||||
{ href: "/groups", label: "分组", emoji: "📺" },
|
||||
{ href: "/youtube", label: "YouTube", emoji: "▶️" },
|
||||
{ href: "/shorts", label: "Shorts", emoji: "📱" },
|
||||
{ href: "/yt-long", label: "长视频", emoji: "🎞️" },
|
||||
{ href: "/tiktok", label: "TikTok", emoji: "🎵" },
|
||||
{ href: "/x", label: "X", emoji: "𝕏" },
|
||||
{ href: "/clash", label: "Clash", emoji: "🧿" },
|
||||
|
||||
Loading…
Reference in New Issue
Block a user