Unify city+cafe into one places page, gate join with on-page modal, and enrich ntfy with icons, tables, and action buttons across portal/API/admin. Co-authored-by: Cursor <cursoragent@cursor.com>
187 lines
5.4 KiB
Python
187 lines
5.4 KiB
Python
"""Avatar / media upload via SeaweedFS S3 (s3.nomadro.com), with local fallback."""
|
|
from __future__ import annotations
|
|
|
|
import mimetypes
|
|
import os
|
|
import uuid
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
from social_svc.config import SOCIAL_UPLOAD_DIR
|
|
|
|
|
|
@dataclass
|
|
class UploadResult:
|
|
url: str
|
|
object_key: str
|
|
size: int
|
|
content_type: str
|
|
storage: str # "s3" | "local"
|
|
|
|
|
|
def _env(name: str, *alts: str, default: str = "") -> str:
|
|
for key in (name, *alts):
|
|
val = (os.getenv(key) or "").strip()
|
|
if val:
|
|
return val
|
|
return default
|
|
|
|
|
|
def s3_enabled() -> bool:
|
|
"""Same SeaweedFS defaults as community_svc (s3.nomadro.com → :8333)."""
|
|
if _env("S3_ENABLED", default="true").lower() not in {"1", "true", "yes", "on"}:
|
|
return False
|
|
# Access key defaults to nomadweb (US SeaweedFS); secret must come from env on prod.
|
|
return bool(
|
|
_env("S3_ACCESS_KEY", "S3_ACCESS_KEY_ID", default="nomadweb")
|
|
and _env("S3_SECRET_KEY", "S3_SECRET_ACCESS_KEY")
|
|
)
|
|
|
|
|
|
_boto = None
|
|
|
|
|
|
def _client():
|
|
global _boto
|
|
if _boto is not None:
|
|
return _boto
|
|
import boto3
|
|
from botocore.client import Config
|
|
|
|
_boto = boto3.client(
|
|
"s3",
|
|
endpoint_url=_env("S3_ENDPOINT", default="http://127.0.0.1:8333").rstrip("/"),
|
|
aws_access_key_id=_env(
|
|
"S3_ACCESS_KEY", "S3_ACCESS_KEY_ID", default="nomadweb"
|
|
),
|
|
aws_secret_access_key=_env("S3_SECRET_KEY", "S3_SECRET_ACCESS_KEY"),
|
|
region_name=_env("S3_REGION", default="us-east-1"),
|
|
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
|
|
)
|
|
return _boto
|
|
|
|
|
|
def _object_key(filename: str, purpose: str, guest_id: str) -> str:
|
|
suffix = Path(filename or "upload.bin").suffix.lower() or ".jpg"
|
|
img_ok = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
|
|
vid_ok = {".webm", ".mp4", ".mov", ".m4v", ".mkv", ".ogg"}
|
|
allow_video = (purpose or "").startswith("liveness") or purpose in {
|
|
"liveness-video",
|
|
"audit-video",
|
|
"room-archive",
|
|
"meetup-archive",
|
|
}
|
|
if suffix in img_ok:
|
|
pass
|
|
elif allow_video and suffix in vid_ok:
|
|
pass
|
|
elif allow_video:
|
|
suffix = ".webm"
|
|
else:
|
|
suffix = ".jpg"
|
|
day = datetime.now(timezone.utc).strftime("%Y/%m/%d")
|
|
prefix = (os.getenv("S3_UPLOAD_PREFIX") or "social").strip("/")
|
|
purpose_part = (purpose or "avatar").replace("/", "-")[:40]
|
|
guest = "".join(c for c in guest_id if c.isalnum() or c in "_-")[:32] or "guest"
|
|
return f"{prefix}/{purpose_part}/{day}/{guest}_{uuid.uuid4().hex}{suffix}"
|
|
|
|
|
|
def public_url_for_key(key: str) -> str:
|
|
base = _env(
|
|
"S3_PUBLIC_URL", default="https://s3.nomadro.com"
|
|
).rstrip("/")
|
|
bucket = _env("S3_BUCKET", default="nomadweb").strip("/")
|
|
return f"{base}/{bucket}/{quote(key, safe='/')}"
|
|
|
|
|
|
def upload_bytes(
|
|
data: bytes,
|
|
*,
|
|
filename: str,
|
|
content_type: str,
|
|
purpose: str,
|
|
guest_id: str,
|
|
max_size: int,
|
|
) -> UploadResult:
|
|
if not data:
|
|
raise ValueError("empty file")
|
|
if len(data) > max_size:
|
|
raise ValueError(f"file too large (max {max_size // 1024 // 1024}MB)")
|
|
|
|
guessed = mimetypes.guess_type(filename or "")[0] or ""
|
|
ctype = (content_type or "").strip().lower() or guessed or "image/jpeg"
|
|
suffix = Path(filename or "").suffix.lower()
|
|
allow_video = (purpose or "").startswith("liveness") or purpose in {
|
|
"liveness-video",
|
|
"audit-video",
|
|
"room-archive",
|
|
"meetup-archive",
|
|
}
|
|
# Browser FormData Blob parts often arrive as application/octet-stream
|
|
if ctype.startswith("image/"):
|
|
pass
|
|
elif allow_video and (
|
|
ctype.startswith("video/")
|
|
or suffix in {".webm", ".mp4", ".mov", ".mkv"}
|
|
or guessed.startswith("video/")
|
|
):
|
|
if not ctype.startswith("video/"):
|
|
ctype = guessed if guessed.startswith("video/") else (
|
|
"video/webm" if suffix in {".webm", ""} else f"video/{suffix[1:] or 'mp4'}"
|
|
)
|
|
elif not ctype.startswith("image/"):
|
|
if suffix in {".jpg", ".jpeg", ".png", ".webp", ".gif"} or guessed.startswith(
|
|
"image/"
|
|
):
|
|
ctype = guessed if guessed.startswith("image/") else (
|
|
"image/jpeg" if suffix in {".jpg", ".jpeg", ""} else f"image/{suffix[1:]}"
|
|
)
|
|
else:
|
|
raise ValueError("only images allowed" if not allow_video else "only images/videos allowed")
|
|
|
|
key = _object_key(filename, purpose, guest_id)
|
|
|
|
if s3_enabled():
|
|
bucket = _env("S3_BUCKET", default="nomadweb")
|
|
client = _client()
|
|
try:
|
|
# SeaweedFS often rejects canned ACL — skip ACL for lower latency
|
|
client.put_object(Bucket=bucket, Key=key, Body=data, ContentType=ctype)
|
|
return UploadResult(
|
|
url=public_url_for_key(key),
|
|
object_key=key,
|
|
size=len(data),
|
|
content_type=ctype,
|
|
storage="s3",
|
|
)
|
|
except Exception:
|
|
# Fall through to local if SeaweedFS is briefly unreachable
|
|
pass
|
|
|
|
# Local fallback (dev / S3 off / S3 error)
|
|
# Live audit assets never land in avatars/
|
|
sub = (
|
|
"room-archive"
|
|
if (purpose or "") in {"room-archive", "meetup-archive"}
|
|
else (
|
|
"liveness"
|
|
if allow_video
|
|
or ctype.startswith("video/")
|
|
or (purpose or "").startswith("liveness")
|
|
else "avatars"
|
|
)
|
|
)
|
|
path = SOCIAL_UPLOAD_DIR / sub / Path(key).name
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_bytes(data)
|
|
route = "liveness" if sub == "liveness" else "avatar"
|
|
return UploadResult(
|
|
url=f"/api/social/v1/files/{route}/{path.name}",
|
|
object_key=str(path),
|
|
size=len(data),
|
|
content_type=ctype,
|
|
storage="local",
|
|
)
|