feat(yt-long): independent channels board, jobs table, and logs UI

Own yt_long_channels (+ import from Shorts OAuth), filtered jobs/events APIs, Shorts-like page tabs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-20 09:56:15 -05:00
parent 7bfead371a
commit 72ef4c62e0
4 changed files with 1212 additions and 155 deletions

View File

@ -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")

View File

@ -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()

View File

@ -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)

View File

@ -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<string, unknown>;
};
@ -54,50 +108,95 @@ const STATUS_ZH: Record<string, string> = {
skipped: "跳过",
};
const STATUS_STYLE: Record<string, string> = {
pending: "bg-slate-500/20 text-slate-200",
recording: "bg-sky-500/20 text-sky-100",
recorded: "bg-indigo-500/20 text-indigo-100",
scheduled: "bg-amber-500/20 text-amber-100",
uploading: "bg-violet-500/20 text-violet-100",
uploaded: "bg-teal-500/20 text-teal-100",
failed: "bg-rose-500/20 text-rose-100",
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<Status | null>(null);
const [channels, setChannels] = useState<Channel[]>([]);
const [jobs, setJobs] = useState<Job[]>([]);
const [jobTotal, setJobTotal] = useState(0);
const [events, setEvents] = useState<Ev[]>([]);
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<string, string> = {};
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 (
<Shell>
<div className="mb-4 flex flex-wrap items-end justify-between gap-3">
@ -150,14 +353,25 @@ export default function YtLongPage() {
<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 className="mt-1 max-w-2xl text-xs text-slate-400">
独立模块:自有频道表 / 任务表 / 日志(yt_long_*)。3–8 分钟 16:9 横屏上传为普通视频,默认关闭,不碰 Shorts 数据。
</p>
</div>
<button type="button" onClick={() => void load()} className={ghost}>
<RefreshCw className="h-3.5 w-3.5" />
刷新
</button>
<div className="flex flex-wrap gap-2">
<button type="button" onClick={() => void load()} className={ghost}>
<RefreshCw className="h-3.5 w-3.5" />
刷新
</button>
{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 className="mb-4 grid gap-3 sm:grid-cols-4">
@ -176,22 +390,13 @@ export default function YtLongPage() {
<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 className="text-[11px] text-slate-400">频道缺口</div>
<div className="mt-1 text-2xl font-semibold text-white">{st?.board?.total_gap ?? 0}</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 className="text-[11px] text-slate-400">成片规格</div>
<div className="mt-1 text-sm font-medium text-white">16:9 · 3–8 分钟</div>
<div className="mt-0.5 text-[11px] text-slate-500">watch?v= 非 Shorts</div>
</div>
</div>
@ -201,100 +406,372 @@ export default function YtLongPage() {
</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`}>
保存设置
<div className="mb-4 flex flex-wrap gap-2">
{tabs.map((t) => (
<button
key={t.id}
type="button"
onClick={() => setTab(t.id)}
className={`rounded-xl px-3 py-1.5 text-xs font-medium ${
tab === t.id
? "bg-sky-500/20 text-sky-100 ring-1 ring-sky-400/40"
: "border border-white/10 bg-white/5 text-slate-400 hover:bg-white/10"
}`}
>
{t.label}
</button>
</div>
))}
</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>
{tab === "channels" ? (
<div className="grid gap-4 lg:grid-cols-[1.2fr_0.8fr]">
<div className="space-y-4">
<div className={panel}>
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<h2 className="text-sm font-semibold text-white">频道配额</h2>
<p className="text-[11px] text-slate-400">独立 yt_long_channels · 可从 Shorts 导入 OAuth</p>
</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 className="flex flex-wrap gap-2">
<button type="button" disabled={busy === "import"} onClick={() => void importFromShorts()} className={ghost}>
{busy === "import" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Download className="h-3.5 w-3.5" />}
从 Shorts 导入
</button>
<button type="button" onClick={() => openEdit()} className={primary}>
新频道
</button>
</div>
</div>
))}
{!jobs.length ? <div className="py-8 text-center text-xs text-slate-500">今日暂无长视频任务</div> : null}
{!board.length && !channels.length ? (
<div className="py-10 text-center text-xs text-slate-500">
暂无长视频频道。点「从 Shorts 导入」或「新频道」。
</div>
) : (
<div className="grid gap-2 sm:grid-cols-2">
{(board.length ? board : channels.map((c) => ({
id: c.id,
name: c.name,
enabled: c.enabled,
authorized: c.authorized,
daily_max: Number(c.daily_max) || 0,
used: 0,
gap: 0,
uploaded: 0,
scheduled: 0,
pending: 0,
failed: 0,
oauth_profile_id: c.oauth_profile_id,
oauth_error: c.oauth_error,
}))).map((ch) => {
const full = channels.find((x) => x.id === ch.id);
return (
<div key={ch.id} className="rounded-xl border border-white/10 bg-black/30 p-3">
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<div className="truncate text-sm font-medium text-slate-100">{ch.name || "未命名"}</div>
<div className="mt-0.5 text-[10px] text-slate-500">
Client {ch.oauth_profile_id || "—"}
{ch.enabled ? " · 启用" : " · 停用"}
{ch.authorized ? " · 已授权" : " · 未授权"}
</div>
</div>
<span className="shrink-0 text-xs text-slate-300">
{ch.used}/{ch.daily_max}
</span>
</div>
<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-white/10">
<div
className="h-full rounded-full bg-sky-400/70"
style={{
width: `${ch.daily_max > 0 ? Math.min(100, (ch.used / ch.daily_max) * 100) : 0}%`,
}}
/>
</div>
<div className="mt-2 flex flex-wrap gap-2 text-[10px] text-slate-400">
<span>上传 {ch.uploaded}</span>
<span>待传 {ch.scheduled}</span>
<span>排队 {ch.pending}</span>
<span className="text-rose-300">失败 {ch.failed}</span>
</div>
{ch.oauth_error ? (
<div className="mt-1 truncate text-[10px] text-amber-300">{ch.oauth_error}</div>
) : null}
<div className="mt-2 flex flex-wrap gap-1.5">
<button type="button" className={ghost} onClick={() => openEdit(full || ({ id: ch.id, name: ch.name } as Channel))}>
编辑
</button>
<button
type="button"
className={`${ghost} text-rose-200`}
disabled={busy === `del-${ch.id}`}
onClick={() => void removeChannel(ch.id)}
>
<Trash2 className="h-3 w-3" />
删除
</button>
</div>
</div>
);
})}
</div>
)}
</div>
<div className={panel}>
<h2 className="text-sm font-semibold text-white">全局参数</h2>
<div className="mt-3 grid grid-cols-3 gap-3">
<label className={label}>
每日总上限
<input className={field} value={dailyMax} onChange={(e) => setDailyMax(e.target.value)} />
</label>
<label className={label}>
最短秒
<input className={field} value={minSec} onChange={(e) => setMinSec(e.target.value)} />
</label>
<label className={label}>
最长秒
<input className={field} value={maxSec} onChange={(e) => setMaxSec(e.target.value)} />
</label>
</div>
<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>
<div className={panel}>
<h2 className="text-sm font-semibold text-white">{editId ? "编辑频道" : "新增频道"}</h2>
<p className="mt-0.5 text-[11px] text-slate-400">标题勿含 #Shorts;OAuth 可用「从 Shorts 导入」带入。</p>
<label className={`${label} mt-3`}>
名称
<input className={field} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
</label>
<div className="mt-3 grid grid-cols-2 gap-3">
<label className={label}>
日上限
<input
className={field}
type="number"
value={form.daily_max}
onChange={(e) => setForm({ ...form, daily_max: Number(e.target.value) || 0 })}
/>
</label>
<label className={label}>
OAuth 档
<select
className={field}
value={form.oauth_profile_id}
onChange={(e) => setForm({ ...form, oauth_profile_id: e.target.value })}
>
{["A", "B", "C", "D"].map((p) => (
<option key={p} value={p}>
Client {p}
</option>
))}
</select>
</label>
</div>
<label className={`${label} mt-3`}>
标题模板
<input
className={field}
value={form.title_template}
onChange={(e) => setForm({ ...form, title_template: e.target.value })}
/>
</label>
<label className={`${label} mt-3`}>
描述模板
<textarea
className={`${field} min-h-[72px]`}
value={form.description_template}
onChange={(e) => setForm({ ...form, description_template: e.target.value })}
/>
</label>
<div className="mt-3 grid grid-cols-2 gap-3">
<label className={label}>
隐私
<select
className={field}
value={form.privacy}
onChange={(e) => setForm({ ...form, privacy: e.target.value })}
>
<option value="public">public</option>
<option value="unlisted">unlisted</option>
<option value="private">private</option>
</select>
</label>
<label className={`${label} flex items-end gap-2 pb-2`}>
<input
type="checkbox"
checked={form.enabled}
onChange={(e) => setForm({ ...form, enabled: e.target.checked })}
/>
启用
</label>
</div>
<label className={`${label} mt-3`}>
备注
<input className={field} value={form.note} onChange={(e) => setForm({ ...form, note: e.target.value })} />
</label>
<div className="mt-4 flex flex-wrap gap-2">
<button type="button" disabled={busy === "ch"} onClick={() => void saveChannel()} className={primary}>
{editId ? "保存频道" : "创建频道"}
</button>
{editId ? (
<button type="button" className={ghost} onClick={() => openEdit()}>
取消编辑
</button>
) : null}
</div>
</div>
</div>
</div>
) : null}
{tab === "jobs" ? (
<div className={panel}>
<div className="mb-3 flex flex-wrap items-center gap-2">
<h2 className="mr-auto text-sm font-semibold text-white">任务流水({jobTotal})</h2>
<select
value={jobFilter}
onChange={(e) => setJobFilter(e.target.value)}
className="rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-xs"
>
<option value="">全部状态</option>
{Object.keys(STATUS_ZH).map((k) => (
<option key={k} value={k}>
{STATUS_ZH[k]}
</option>
))}
</select>
<select
value={jobChannel}
onChange={(e) => setJobChannel(e.target.value)}
className="rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-xs"
>
<option value="">全部频道</option>
{channels.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</div>
<div className="overflow-x-auto">
<table className="min-w-[720px] w-full text-left text-sm">
<thead className="text-[11px] uppercase text-slate-500">
<tr>
<th className="pb-2 pr-2">状态</th>
<th className="pb-2 pr-2">主播</th>
<th className="pb-2 pr-2">频道</th>
<th className="pb-2 pr-2">标题 / 链接</th>
<th className="pb-2 pr-2">时间</th>
<th className="pb-2">操作</th>
</tr>
</thead>
<tbody>
{jobs.map((j) => (
<tr key={j.id} className="border-t border-white/5 align-top">
<td className="py-2 pr-2">
<span className={`rounded px-1.5 py-0.5 text-[10px] ${STATUS_STYLE[j.status || ""] || STATUS_STYLE.pending}`}>
{STATUS_ZH[j.status || ""] || j.status}
</span>
</td>
<td className="py-2 pr-2 text-xs text-slate-200">
<div>{j.anchor_name || "—"}</div>
<div className="font-mono text-[10px] text-slate-500">{j.room_id}</div>
</td>
<td className="py-2 pr-2 text-xs text-slate-300">
{channelNameMap[j.channel_pk || ""] || "—"}
</td>
<td className="py-2 pr-2 text-xs">
<div className="line-clamp-2 text-slate-300">{j.title || "—"}</div>
{j.clip_seconds ? (
<div className="text-[10px] text-slate-500">{Math.round(j.clip_seconds)}s</div>
) : null}
{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}
</td>
<td className="whitespace-nowrap py-2 pr-2 text-[10px] text-slate-500">
<div>{j.created_at ? fmtTs(j.created_at) : "—"}</div>
{j.upload_at ? <div>上传 {fmtTs(j.upload_at)}</div> : null}
</td>
<td className="py-2">
{j.status === "failed" || j.status === "skipped" ? (
<button
type="button"
className={ghost}
disabled={busy === `retry-${j.id}`}
onClick={() => void retryJob(j.id)}
>
<RotateCcw className="h-3 w-3" />
重试
</button>
) : (
<span className="text-[10px] text-slate-600">—</span>
)}
</td>
</tr>
))}
{!jobs.length ? (
<tr>
<td colSpan={6} className="py-10 text-center text-xs text-slate-500">
暂无任务
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</div>
) : null}
{tab === "logs" ? (
<div className={panel}>
<h2 className="mb-1 text-sm font-semibold text-white">长视频日志</h2>
<p className="mb-3 text-[11px] text-slate-400">仅 kind 以 yt_long 开头 · 与 Shorts / TikTok / X 事件隔离展示</p>
<div className="max-h-[32rem] space-y-2 overflow-y-auto">
{events.map((e) => (
<div key={e.id} className="rounded-xl border border-white/10 bg-black/30 px-3 py-2">
<div className="flex flex-wrap items-center gap-2 text-[10px]">
<span
className={`rounded px-1.5 py-0.5 ${
e.level === "error"
? "bg-rose-500/20 text-rose-100"
: e.level === "warn"
? "bg-amber-500/20 text-amber-100"
: "bg-white/10 text-slate-300"
}`}
>
{e.kind}
</span>
<span className="text-slate-500">{e.ts ? fmtTs(e.ts) : ""}</span>
{e.anchor_name ? <span className="text-slate-400">{e.anchor_name}</span> : null}
</div>
<div className="mt-1 text-xs text-slate-200">{e.message}</div>
</div>
))}
{!events.length ? <div className="py-10 text-center text-xs text-slate-500">暂无长视频日志</div> : null}
</div>
</div>
) : null}
</Shell>
);
}