diff --git a/shared/r2.py b/shared/r2.py index 85fab0d..0782d56 100644 --- a/shared/r2.py +++ b/shared/r2.py @@ -2,6 +2,7 @@ from __future__ import annotations from functools import lru_cache +from urllib.parse import urlsplit, urlunsplit from src.core.config import get_settings @@ -26,26 +27,37 @@ def _client(): ) +def _publicize(url: str) -> str: + """Expose an internal signed URL through the HTTPS storage proxy.""" + public_base = get_settings().r2_public_base.rstrip("/") + if not public_base: + return url + public = urlsplit(public_base) + signed = urlsplit(url) + return urlunsplit((public.scheme, public.netloc, + f"{public.path}{signed.path}", signed.query, signed.fragment)) + + def presign_put(key: str, content_type: str = "application/octet-stream") -> str: """Direct-upload URL: browser/app PUTs bytes straight to R2 (saves Class-A + bandwidth).""" s = get_settings() - return _client().generate_presigned_url( + url = _client().generate_presigned_url( "put_object", Params={"Bucket": s.r2_bucket, "Key": key, "ContentType": content_type}, ExpiresIn=s.presign_put_ttl, ) + return _publicize(url) def presign_get(key: str) -> str: """Short-lived read URL for preview/download. Thumbnails preferred over full images.""" s = get_settings() - if s.r2_public_base: - return f"{s.r2_public_base.rstrip('/')}/{key}" - return _client().generate_presigned_url( + url = _client().generate_presigned_url( "get_object", Params={"Bucket": s.r2_bucket, "Key": key}, ExpiresIn=s.presign_get_ttl, ) + return _publicize(url) def head_exists(key: str) -> bool: @@ -88,11 +100,12 @@ def create_multipart(key: str, content_type: str = "application/octet-stream") - def presign_part(key: str, upload_id: str, part_number: int, expires_in: int = 3600) -> str: s = get_settings() - return _client().generate_presigned_url( + url = _client().generate_presigned_url( "upload_part", Params={"Bucket": s.r2_bucket, "Key": key, "UploadId": upload_id, "PartNumber": part_number}, ExpiresIn=expires_in) + return _publicize(url) def complete_multipart(key: str, upload_id: str, parts: list[dict]) -> str: