Add isolated Shorts OAuth/clip/upload worker (default off), youtube-svc + group poller, Beijing time UX, and SHORTS.md. Co-authored-by: Cursor <cursoragent@cursor.com>
101 lines
2.9 KiB
Python
101 lines
2.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Record a short Douyin live clip with ffmpeg (default 15s, vertical-friendly)."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import subprocess
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from .config import settings
|
|
from .douyin import check_room
|
|
|
|
|
|
def _headers_arg() -> str:
|
|
return (
|
|
"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15\r\n"
|
|
"Referer: https://live.douyin.com/\r\n"
|
|
)
|
|
|
|
|
|
async def resolve_stream_url(*, source_url: str = "", stream_url: str = "", cookie: str = "") -> str:
|
|
url = (stream_url or "").strip()
|
|
if url:
|
|
return url
|
|
src = (source_url or "").strip()
|
|
if not src:
|
|
return ""
|
|
result = await check_room(src, cookie=cookie)
|
|
if not result.get("ok") or not result.get("is_live"):
|
|
return ""
|
|
return str(result.get("stream_url") or "").strip()
|
|
|
|
|
|
async def record_clip(
|
|
*,
|
|
job_id: str,
|
|
stream_url: str,
|
|
seconds: int = 15,
|
|
) -> dict[str, Any]:
|
|
"""Pull stream for `seconds` and write mp4 under clips_dir."""
|
|
url = (stream_url or "").strip()
|
|
if not url:
|
|
return {"ok": False, "error": "无可用流地址"}
|
|
sec = max(10, min(int(seconds or 15), 180))
|
|
out_dir = settings.clips_dir
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
out_path = out_dir / f"{job_id}.mp4"
|
|
|
|
# Scale to 1080x1920 Shorts canvas (letterbox/crop center).
|
|
# Prefer crop-to-fill for vertical phones; fallback scale+pad.
|
|
vf = (
|
|
"scale=1080:1920:force_original_aspect_ratio=increase,"
|
|
"crop=1080:1920,setsar=1"
|
|
)
|
|
cmd = [
|
|
settings.ffmpeg_bin,
|
|
"-hide_banner",
|
|
"-loglevel",
|
|
"error",
|
|
"-y",
|
|
"-headers",
|
|
_headers_arg(),
|
|
"-rw_timeout",
|
|
"20000000",
|
|
"-i",
|
|
url,
|
|
"-t",
|
|
str(sec),
|
|
"-vf",
|
|
vf,
|
|
"-c:v",
|
|
"libx264",
|
|
"-preset",
|
|
"veryfast",
|
|
"-crf",
|
|
"23",
|
|
"-c:a",
|
|
"aac",
|
|
"-b:a",
|
|
"128k",
|
|
"-movflags",
|
|
"+faststart",
|
|
str(out_path),
|
|
]
|
|
|
|
def _run() -> dict[str, Any]:
|
|
try:
|
|
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=sec + 90)
|
|
except subprocess.TimeoutExpired:
|
|
return {"ok": False, "error": "ffmpeg 录制超时"}
|
|
except Exception as exc:
|
|
return {"ok": False, "error": f"ffmpeg 启动失败: {exc}"}
|
|
if proc.returncode != 0:
|
|
err = (proc.stderr or proc.stdout or "ffmpeg failed")[-400:]
|
|
return {"ok": False, "error": err}
|
|
if not out_path.is_file() or out_path.stat().st_size < 50_000:
|
|
return {"ok": False, "error": "成片过小或不存在"}
|
|
return {"ok": True, "path": str(out_path), "bytes": out_path.stat().st_size, "seconds": sec}
|
|
|
|
return await asyncio.to_thread(_run)
|