# -*- coding: utf-8 -*- """X2 post media staging on S3 — upload then delete after job ends.""" from __future__ import annotations import mimetypes import re import tempfile import time import uuid from pathlib import Path from typing import Any from . import s3_storage from .config import settings _ALLOWED_PREFIX = "downloads/x2-media/" _MAX_FILES = 4 _MAX_BYTES = 180 * 1024 * 1024 # under Caddy 200MB body limit _ALLOWED_MIME_PREFIXES = ("image/", "video/") _SAFE_NAME = re.compile(r"[^a-zA-Z0-9._-]+") def _safe_filename(name: str) -> str: base = Path(str(name or "media.bin")).name cleaned = _SAFE_NAME.sub("_", base).strip("._") or "media.bin" return cleaned[:120] def is_x2_media_key(key: str) -> bool: k = str(key or "").strip().lstrip("/") return k.startswith(_ALLOWED_PREFIX) def media_keys_from_params(params: Any) -> list[str]: if not isinstance(params, dict): return [] keys: list[str] = [] for item in params.get("mediaUrls") or []: if not isinstance(item, dict): continue k = str(item.get("key") or "").strip() if is_x2_media_key(k): keys.append(k) for k in params.get("mediaKeys") or []: ks = str(k or "").strip() if is_x2_media_key(ks): keys.append(ks) # dedupe preserve order seen: set[str] = set() out: list[str] = [] for k in keys: if k not in seen: seen.add(k) out.append(k) return out def cleanup_media_keys(keys: list[str] | None) -> dict[str, Any]: deleted: list[str] = [] failed: list[str] = [] for k in keys or []: if not is_x2_media_key(k): failed.append(k) continue if s3_storage.delete_object(k): deleted.append(k) else: failed.append(k) return {"deleted": deleted, "failed": failed, "count": len(deleted)} def cleanup_job_media(params: Any) -> dict[str, Any]: return cleanup_media_keys(media_keys_from_params(params)) def upload_media_bytes( data: bytes, *, filename: str = "media.bin", content_type: str = "", ) -> dict[str, Any]: if not s3_storage.s3_enabled(): raise ValueError("S3 未启用") if not data: raise ValueError("空文件") if len(data) > _MAX_BYTES: raise ValueError(f"文件过大(上限 {_MAX_BYTES // (1024 * 1024)} MB)") name = _safe_filename(filename) ctype = (content_type or mimetypes.guess_type(name)[0] or "application/octet-stream").strip() if not any(ctype.startswith(p) for p in _ALLOWED_MIME_PREFIXES): raise ValueError(f"不支持的文件类型: {ctype}(仅图片/视频)") day = time.strftime("%Y%m%d", time.gmtime()) key = f"{_ALLOWED_PREFIX}{day}/{uuid.uuid4().hex[:12]}_{name}" # write temp → upload → delete local immediately tmp_path: Path | None = None try: with tempfile.NamedTemporaryFile(delete=False, suffix=Path(name).suffix or ".bin") as tmp: tmp_path = Path(tmp.name) tmp.write(data) url = s3_storage.upload_file(tmp_path, key, content_type=ctype) if not url: raise ValueError("上传 S3 失败") return { "ok": True, "key": key, "url": url, "filename": name, "mime": ctype, "size": len(data), "public_base": (settings.s3_public_base or settings.s3_endpoint or "").rstrip("/"), "bucket": settings.s3_bucket, } finally: if tmp_path is not None: try: tmp_path.unlink(missing_ok=True) except Exception: pass def upload_media_file(path: Path | str, *, filename: str = "", content_type: str = "") -> dict[str, Any]: """Stage an existing local file to S3 (does not delete the source clip).""" if not s3_storage.s3_enabled(): raise ValueError("S3 未启用") p = Path(path) if not p.is_file(): raise ValueError("文件不存在") size = p.stat().st_size if size <= 0: raise ValueError("空文件") if size > _MAX_BYTES: raise ValueError(f"文件过大(上限 {_MAX_BYTES // (1024 * 1024)} MB)") name = _safe_filename(filename or p.name) ctype = (content_type or mimetypes.guess_type(name)[0] or "application/octet-stream").strip() if not any(ctype.startswith(pref) for pref in _ALLOWED_MIME_PREFIXES): raise ValueError(f"不支持的文件类型: {ctype}(仅图片/视频)") day = time.strftime("%Y%m%d", time.gmtime()) key = f"{_ALLOWED_PREFIX}{day}/{uuid.uuid4().hex[:12]}_{name}" url = s3_storage.upload_file(p, key, content_type=ctype) if not url: raise ValueError("上传 S3 失败") return { "ok": True, "key": key, "url": url, "filename": name, "mime": ctype, "size": size, "public_base": (settings.s3_public_base or settings.s3_endpoint or "").rstrip("/"), "bucket": settings.s3_bucket, }