douyinWEB/backend/app/s3_storage.py
eric d27387cb9e Add SeaweedFS S3 covers and click-to-zoom lightbox.
Capture frames upload to SeaweedFS; active sessions show covers with enlarge preview.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 09:37:46 -05:00

75 lines
2.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 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 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_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")