# -*- 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")