douyinWEB/backend/app/clip_archive.py
eric b4e07d792e feat: add dashboard, oauth health, ops alerts, readonly role, and S3 archive replay
New pages and APIs for cross-platform jobs, YouTube OAuth health, mobile ops,
settings audit, optional DB backup, quota/disk alerts, and clip archive replay.
All new behavior defaults off to avoid changing production pipelines.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-23 08:02:58 -05:00

150 lines
5.0 KiB
Python

# -*- coding: utf-8 -*-
"""Archive clips to S3 before deletion; replay upload from archive."""
from __future__ import annotations
import time
from pathlib import Path
from typing import Any
from .config import settings
def _archive_enabled(cfg: dict[str, Any] | None = None) -> bool:
from . import db
m = cfg if cfg is not None else db.get_settings_map()
if not m.get("clip_archive_to_s3_enabled", False):
return False
from . import s3_storage
return s3_storage.s3_enabled()
def archive_key(platform: str, job_id: str, ext: str = "mp4") -> str:
pid = str(platform or "unknown").strip().lower()
jid = str(job_id or "unknown").strip()
return f"clips/archive/{pid}/{jid}.{ext.lstrip('.')}"
def maybe_archive_clip(
path: str,
*,
platform: str,
job_id: str,
cfg: dict[str, Any] | None = None,
) -> dict[str, Any]:
if not _archive_enabled(cfg):
return {"skipped": True}
p = Path(str(path or "").strip())
if not p.is_file():
return {"skipped": True, "reason": "no_file"}
key = archive_key(platform, job_id)
try:
from . import s3_storage
url = s3_storage.upload_file(p, key, content_type="video/mp4")
if not url:
return {"ok": False, "error": "upload_empty"}
meta = s3_storage.head_object(key) or {}
return {"ok": True, "key": key, "url": url, "size": meta.get("size")}
except Exception as exc:
return {"ok": False, "error": str(exc)[:200]}
def get_archive_meta(platform: str, job_id: str) -> dict[str, Any] | None:
from . import s3_storage
if not s3_storage.s3_enabled():
return None
key = archive_key(platform, job_id)
return s3_storage.head_object(key)
def archive_clip_for_path(path: str) -> dict[str, Any]:
"""Find job by clip_path and archive if enabled."""
from . import db
from . import tiktok_db
from . import yt_long_db
p = str(path or "").strip()
if not p:
return {"skipped": True}
cfg = db.get_settings_map()
for plat, table, mod in (
("shorts", "shorts_jobs", db),
("tiktok", "tiktok_jobs", tiktok_db),
("yt_long", "yt_long_jobs", yt_long_db),
):
try:
lock = getattr(mod, "_lock", db._lock)
connect = getattr(mod, "_connect", db._connect)
with lock:
conn = connect()
try:
row = conn.execute(
f"SELECT id FROM {table} WHERE clip_path = ? ORDER BY updated_at DESC LIMIT 1",
(p,),
).fetchone()
if row:
jid = str(row["id"])
return maybe_archive_clip(p, platform=plat, job_id=jid, cfg=cfg)
finally:
conn.close()
except Exception:
continue
return {"skipped": True, "reason": "job_not_found"}
async def replay_from_archive(platform: str, job_id: str) -> dict[str, Any]:
"""Download archived clip to local temp and re-queue upload for the job."""
import asyncio
import tempfile
from . import db
from . import s3_storage
from . import tiktok_db
from . import yt_long_db
plat = str(platform or "").strip().lower()
jid = str(job_id or "").strip()
if not jid:
return {"ok": False, "error": "no_job_id"}
meta = get_archive_meta(plat, jid)
if not meta or not meta.get("key"):
return {"ok": False, "error": "archive_not_found"}
key = str(meta["key"])
try:
client = s3_storage._client()
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
dest = tmp.name
await asyncio.to_thread(
client.download_file,
settings.s3_bucket,
key,
dest,
)
except Exception as exc:
return {"ok": False, "error": f"download:{exc}"[:200]}
now = time.time()
if plat == "shorts":
job = db.get_shorts_job(jid)
if not job:
return {"ok": False, "error": "job_not_found"}
db.update_shorts_job(jid, status="scheduled", clip_path=dest, upload_at=now + 30, error="archive_replay")
return {"ok": True, "platform": plat, "job_id": jid, "clip_path": dest}
if plat == "tiktok":
job = tiktok_db.get_tiktok_job(jid)
if not job:
return {"ok": False, "error": "job_not_found"}
tiktok_db.update_tiktok_job(jid, status="scheduled", clip_path=dest, upload_at=now + 30, error="archive_replay")
return {"ok": True, "platform": plat, "job_id": jid, "clip_path": dest}
if plat == "yt_long":
job = yt_long_db.get_yt_long_job(jid)
if not job:
return {"ok": False, "error": "job_not_found"}
yt_long_db.update_yt_long_job(jid, status="scheduled", clip_path=dest, upload_at=now + 30, error="archive_replay")
return {"ok": True, "platform": plat, "job_id": jid, "clip_path": dest}
return {"ok": False, "error": "unsupported_platform"}