douyinWEB/backend/app/s3_storage.py
eric 11394a2a80 Document Pro relay/time-slot ops and harden relay worker stability.
README covers YouTube RTMPS relay, time-slot mode, ops/Netdata, and global SOCKS plan. Relay pipeline keeps FFmpeg alive across probe flicker, stabilizes time-slot source selection, and fixes misleading start-button copy in the UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:53:29 -05:00

136 lines
4.3 KiB
Python

# -*- coding: utf-8 -*-
"""SeaweedFS S3-compatible object storage helper."""
from __future__ import annotations
import mimetypes
from pathlib import Path
from typing import Any, Optional
from urllib.parse import quote
from .config import settings
def s3_enabled() -> bool:
return bool(settings.s3_enabled and settings.s3_endpoint and settings.s3_bucket)
def _client():
import boto3
from botocore.client import Config
return boto3.client(
"s3",
endpoint_url=settings.s3_endpoint.rstrip("/"),
aws_access_key_id=settings.s3_access_key or "any",
aws_secret_access_key=settings.s3_secret_key or "any",
region_name=settings.s3_region or "us-east-1",
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
def ensure_bucket() -> None:
if not s3_enabled():
return
client = _client()
bucket = settings.s3_bucket
try:
client.head_bucket(Bucket=bucket)
except Exception:
try:
client.create_bucket(Bucket=bucket)
except Exception:
# race / already exists
pass
def public_url_for_key(key: str) -> str:
base = (settings.s3_public_base or settings.s3_endpoint or "").rstrip("/")
bucket = settings.s3_bucket.strip("/")
# path-style: http://host:8333/bucket/key
return f"{base}/{bucket}/{quote(key, safe='/')}"
def head_object(key: str) -> dict[str, Any] | None:
"""Return size / etag / last_modified for a key, or None if missing."""
if not s3_enabled():
return None
try:
client = _client()
resp = client.head_object(Bucket=settings.s3_bucket, Key=key)
lm = resp.get("LastModified")
return {
"key": key,
"size": int(resp.get("ContentLength") or 0),
"etag": str(resp.get("ETag") or "").strip('"'),
"content_type": str(resp.get("ContentType") or ""),
"last_modified": float(lm.timestamp()) if lm is not None else 0.0,
"url": public_url_for_key(key),
}
except Exception:
return None
def upload_file(local_path: str | Path, key: str, content_type: str = "") -> str:
"""Upload local file to SeaweedFS S3 API. Returns public URL."""
path = Path(local_path)
if not path.is_file():
return ""
if not s3_enabled():
return ""
ensure_bucket()
ctype = content_type or mimetypes.guess_type(str(path))[0] or "application/octet-stream"
client = _client()
extra = {"ContentType": ctype, "ACL": "public-read"}
try:
client.upload_file(str(path), settings.s3_bucket, key, ExtraArgs=extra)
except Exception:
# some SeaweedFS builds ignore ACL
client.upload_file(str(path), settings.s3_bucket, key, ExtraArgs={"ContentType": ctype})
return public_url_for_key(key)
def upload_bytes(data: bytes, key: str, content_type: str = "application/octet-stream") -> str:
if not data or not s3_enabled():
return ""
ensure_bucket()
client = _client()
ctype = content_type or "application/octet-stream"
try:
client.put_object(
Bucket=settings.s3_bucket,
Key=key,
Body=data,
ContentType=ctype,
ACL="public-read",
)
except Exception:
client.put_object(Bucket=settings.s3_bucket, Key=key, Body=data, ContentType=ctype)
return public_url_for_key(key)
def delete_object(key: str) -> bool:
"""Delete an object from the bucket. Returns True if delete was attempted successfully."""
k = str(key or "").strip().lstrip("/")
if not k or not s3_enabled():
return False
try:
_client().delete_object(Bucket=settings.s3_bucket, Key=k)
return True
except Exception:
return False
def upload_cover(session_id: str, local_path: str | Path) -> str:
key = f"covers/{session_id}.jpg"
return upload_file(local_path, key, content_type="image/jpeg")
def upload_room_avatar(room_id: str, local_path: str | Path) -> str:
"""Stable per-room avatar object (频道头像), not session stream frame."""
rid = str(room_id or "").strip()
if not rid:
return ""
safe = "".join(ch if ch.isalnum() or ch in "-_" else "_" for ch in rid)[:80]
key = f"covers/avatars/{safe}.jpg"
return upload_file(local_path, key, content_type="image/jpeg")