nomadro/apps/api/services/social_svc/s3_upload.py
Eric 756f02594d Add optional resume uploads to social hiring applications.
Let applicants attach PDF/Word/image resumes on team apply, store the file URL with the gig application, and surface it in admin gig apps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 14:14:40 +08:00

236 lines
6.8 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
_RESUME_SUFFIX = {".pdf", ".doc", ".docx", ".txt", ".rtf", ".png", ".jpg", ".jpeg", ".webp"}
_RESUME_MIME = {
".pdf": "application/pdf",
".doc": "application/msword",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".txt": "text/plain",
".rtf": "application/rtf",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
}
def _allow_resume(purpose: str) -> bool:
return (purpose or "").strip().lower() in {"resume", "cv", "gig-resume"}
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",
}
allow_resume = _allow_resume(purpose)
if suffix in img_ok:
pass
elif allow_resume and suffix in _RESUME_SUFFIX:
pass
elif allow_video and suffix in vid_ok:
pass
elif allow_video:
suffix = ".webm"
elif allow_resume:
suffix = ".pdf"
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",
}
allow_resume = _allow_resume(purpose)
# Browser FormData Blob parts often arrive as application/octet-stream
if ctype.startswith("image/"):
pass
elif allow_resume and (
suffix in _RESUME_SUFFIX
or ctype in {
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/rtf",
"text/plain",
"application/octet-stream",
}
):
if suffix not in _RESUME_SUFFIX:
# octet-stream without extension → treat as pdf
suffix = ".pdf"
ctype = _RESUME_MIME.get(suffix) or guessed or "application/pdf"
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 resume files allowed"
if allow_resume
else ("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/
if (purpose or "") in {"room-archive", "meetup-archive"}:
sub = "room-archive"
elif allow_resume:
sub = "resumes"
elif (
allow_video
or ctype.startswith("video/")
or (purpose or "").startswith("liveness")
):
sub = "liveness"
else:
sub = "avatars"
path = SOCIAL_UPLOAD_DIR / sub / Path(key).name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
if sub == "liveness":
route = "liveness"
elif sub == "resumes":
route = "resume"
else:
route = "avatar"
return UploadResult(
url=f"/api/social/v1/files/{route}/{path.name}",
object_key=str(path),
size=len(data),
content_type=ctype,
storage="local",
)