Add mobile save sheet with same-origin photo downloads.

Phones cannot land downloads in the photo library, so the gallery opens a share sheet for a cacheable preview while streaming via a dedicated download endpoint and recording preview sizes.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Michilis
2026-08-06 20:14:31 +00:00
co-authored by Cursor
parent 390e1dc0ea
commit be4dd5b47f
20 changed files with 962 additions and 56 deletions
+174
View File
@@ -750,3 +750,177 @@ func TestSlugCollision(t *testing.T) {
t.Fatalf("default visibility: %s", a.Visibility)
}
}
// TestDownloadEndpoint pins the guarantees the mobile save sheet is built
// on: the bytes arrive same-origin (never a redirect), typed as an image,
// named after the event, sized up front and cacheable forever.
func TestDownloadEndpoint(t *testing.T) {
e := setup(t)
admin := e.makeToken(t, uAdmin)
g := createGallery(t, e, admin, map[string]any{
"title": "Fotos Del Evento", "visibility": "public", "eventId": evPaid,
})
p := uploadPhoto(t, e, admin, g.ID, testJPEG(t))
if processQueue(t, e, p.ID).Status != "ready" {
t.Fatal("processing failed")
}
base := "/api/photos/files/" + p.ID + "/download"
for _, tc := range []struct {
name, path, wantDisposition, wantFilename string
}{
// No ?size at all must behave exactly like ?size=preview.
{"default", base, "inline", "spanglish-fiesta-1.jpg"},
{"preview", base + "?size=preview", "inline", "spanglish-fiesta-1.jpg"},
{"original", base + "?size=original", "attachment", "spanglish-fiesta-1.jpg"},
} {
t.Run(tc.name, func(t *testing.T) {
w := e.request(t, "GET", tc.path, "", nil)
if w.Code != 200 {
t.Fatalf("status %d %s", w.Code, w.Body.String())
}
if ct := w.Header().Get("Content-Type"); ct != "image/jpeg" {
t.Fatalf("content type %q: iOS only offers Save Image for image/*", ct)
}
if n := w.Header().Get("Content-Length"); n != fmt.Sprint(w.Body.Len()) || n == "0" {
t.Fatalf("content length %q, body %d bytes", n, w.Body.Len())
}
cd := w.Header().Get("Content-Disposition")
if !strings.HasPrefix(cd, tc.wantDisposition) || !strings.Contains(cd, tc.wantFilename) {
t.Fatalf("disposition %q, want %s with %s", cd, tc.wantDisposition, tc.wantFilename)
}
if cc := w.Header().Get("Cache-Control"); cc != "public, max-age=31536000, immutable" {
t.Fatalf("cache-control %q", cc)
}
})
}
// Each size serves its own variant byte-for-byte. (No size comparison
// between the two here: the fixture is a synthetic 800x600 image, so its
// 2048px preview re-encode is larger than the "original" — which says
// nothing about the multi-megapixel photos the sheet exists for.)
prev := e.request(t, "GET", base, "", nil)
orig := e.request(t, "GET", base+"?size=original", "", nil)
if !bytes.Equal(prev.Body.Bytes(), e.request(t, "GET", "/api/photos/files/"+p.ID+"/preview", "", nil).Body.Bytes()) {
t.Fatal("download?size=preview must serve the same bytes as the preview variant")
}
if !bytes.Equal(orig.Body.Bytes(), e.request(t, "GET", "/api/photos/files/"+p.ID+"/original", "", nil).Body.Bytes()) {
t.Fatal("download?size=original must serve the same bytes as the original variant")
}
// An unknown size is not a silent fallback.
if w := e.request(t, "GET", base+"?size=thumb", "", nil); w.Code != 404 {
t.Fatalf("unknown size: want 404, got %d", w.Code)
}
// The gallery response labels both rows without any extra request.
detail := decode[galleryResp](t, e.request(t, "GET", "/api/photos/public/galleries/"+g.Slug, "", nil))
got := detail.Photos[0]
if got.PreviewSizeBytes != int64(prev.Body.Len()) {
t.Fatalf("previewSizeBytes %d, served %d", got.PreviewSizeBytes, prev.Body.Len())
}
if got.SizeBytes != int64(orig.Body.Len()) {
t.Fatalf("sizeBytes %d, served %d", got.SizeBytes, orig.Body.Len())
}
if got.URLs.Download != base {
t.Fatalf("download url %q, want %q", got.URLs.Download, base)
}
if got.URLs.DownloadOriginal != base+"?size=original" {
t.Fatalf("downloadOriginal url %q", got.URLs.DownloadOriginal)
}
}
// A restricted gallery's download must obey the same token check as every
// other byte-serving route, and must not become shared-cacheable.
func TestDownloadRespectsAccess(t *testing.T) {
e := setup(t)
admin := e.makeToken(t, uAdmin)
g := createGallery(t, e, admin, map[string]any{"title": "Privada Descarga", "visibility": "private"})
p := uploadPhoto(t, e, admin, g.ID, testJPEG(t))
if processQueue(t, e, p.ID).Status != "ready" {
t.Fatal("processing failed")
}
detail := decode[galleryResp](t, e.request(t, "GET", "/api/photos/galleries/"+g.ID, admin, nil))
url := detail.Photos[0].URLs.Download
if !strings.Contains(url, "?token=v1.") {
t.Fatalf("private download URL should carry a view token: %s", url)
}
// ?size and ?token have to coexist on the original's URL.
if o := detail.Photos[0].URLs.DownloadOriginal; !strings.Contains(o, "?size=original&token=v1.") {
t.Fatalf("private original download URL: %s", o)
}
w := e.request(t, "GET", url, "", nil)
if w.Code != 200 {
t.Fatalf("view token fetch: want 200, got %d", w.Code)
}
// Restricted galleries stay out of shared caches; the browser's own
// cache (which is what the save sheet reuses) still applies.
if cc := w.Header().Get("Cache-Control"); cc != "private, max-age=31536000, immutable" {
t.Fatalf("cache-control %q must not be public for a private gallery", cc)
}
bare := strings.SplitN(url, "?", 2)[0]
if w := e.request(t, "GET", bare, "", nil); w.Code != 403 {
t.Fatalf("anon download without token: want 403, got %d", w.Code)
}
if w := e.request(t, "GET", bare+"?size=original", "", nil); w.Code != 403 {
t.Fatalf("anon original download without token: want 403, got %d", w.Code)
}
}
// Photos processed before preview_size_bytes existed have no stored size.
// The first gallery view measures them and writes the result back, so no
// separate backfill command is needed for an existing library.
func TestPreviewSizeBackfilledOnRead(t *testing.T) {
e := setup(t)
ctx := context.Background()
admin := e.makeToken(t, uAdmin)
g := createGallery(t, e, admin, map[string]any{"title": "Antigua", "visibility": "public"})
p := uploadPhoto(t, e, admin, g.ID, testJPEG(t))
if processQueue(t, e, p.ID).Status != "ready" {
t.Fatal("processing failed")
}
// Rewind to what an pre-migration row looks like.
if _, err := e.db.ExecContext(ctx, e.db.Rebind(
"UPDATE photos_photos SET preview_size_bytes = NULL WHERE id = ?"), p.ID); err != nil {
t.Fatal(err)
}
if before, err := e.db.GetPhoto(ctx, p.ID); err != nil {
t.Fatal(err)
} else if before.PreviewSizeBytes != 0 {
t.Fatalf("setup: want an unmeasured row, got %d", before.PreviewSizeBytes)
}
served := e.request(t, "GET", "/api/photos/files/"+p.ID+"/download", "", nil).Body.Len()
got := decode[galleryResp](t, e.request(t, "GET", "/api/photos/public/galleries/"+g.Slug, "", nil))
if got.Photos[0].PreviewSizeBytes != int64(served) {
t.Fatalf("response size %d, served %d", got.Photos[0].PreviewSizeBytes, served)
}
// …and it was persisted, so the next view costs no Stat.
after, err := e.db.GetPhoto(ctx, p.ID)
if err != nil {
t.Fatal(err)
}
if after.PreviewSizeBytes != int64(served) {
t.Fatalf("stored size %d, served %d", after.PreviewSizeBytes, served)
}
}
// Originals uploaded as HEIC or PNG must keep their real type and extension,
// and a row with a missing/generic type must still go out as an image.
func TestDownloadContentTypeNeverOctetStream(t *testing.T) {
for _, tc := range []struct{ ct, name, want string }{
{"image/heic", "IMG_1.HEIC", "image/heic"},
{"image/png", "shot.png", "image/png"},
{"application/octet-stream", "IMG_2.heic", "image/heic"},
{"application/octet-stream", "scan.PNG", "image/png"},
{"", "photo.jpeg", "image/jpeg"},
{"", "", "image/jpeg"},
} {
if got := imageContentType(tc.ct, tc.name); got != tc.want {
t.Errorf("imageContentType(%q, %q) = %q, want %q", tc.ct, tc.name, got, tc.want)
}
}
}
+32 -1
View File
@@ -42,6 +42,13 @@ type photoURLs struct {
Thumb string `json:"thumb,omitempty"`
Preview string `json:"preview,omitempty"`
Original string `json:"original"`
// Download / DownloadOriginal hit the download endpoint (files.go), which
// always streams the bytes same-origin instead of redirecting to S3, so a
// fetch() can read them into a Blob without CORS. Download serves the
// preview variant and doubles as the lightbox's <img> source, so the save
// fetch is answered from the HTTP cache rather than the network.
Download string `json:"download,omitempty"`
DownloadOriginal string `json:"downloadOriginal"`
}
type photoJSON struct {
@@ -51,6 +58,9 @@ type photoJSON struct {
OriginalFilename string `json:"originalFilename,omitempty"`
ContentType string `json:"contentType"`
SizeBytes int64 `json:"sizeBytes"`
// PreviewSizeBytes lets the mobile save sheet label both of its rows with
// a real file size without fetching anything. Omitted while unknown.
PreviewSizeBytes int64 `json:"previewSizeBytes,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
TakenAt string `json:"takenAt,omitempty"`
@@ -91,6 +101,22 @@ func fileURL(photoID, variant, token string) string {
return u
}
// downloadURL builds the download endpoint's URL. size is left off for the
// preview, which the endpoint serves by default — a shorter, stabler string
// for the URL the lightbox also renders.
func downloadURL(photoID, size, token string) string {
u := "/api/photos/files/" + photoID + "/download"
sep := "?"
if size != "" && size != downloadSizePreview {
u += "?size=" + size
sep = "&"
}
if token != "" {
u += sep + "token=" + token
}
return u
}
func (s *Server) photoToJSON(p store.Photo, token string, admin bool) photoJSON {
out := photoJSON{
ID: p.ID,
@@ -101,16 +127,21 @@ func (s *Server) photoToJSON(p store.Photo, token string, admin bool) photoJSON
SizeBytes: p.SizeBytes,
Width: p.Width,
Height: p.Height,
PreviewSizeBytes: p.PreviewSizeBytes,
TakenAt: isoTime(p.TakenAt),
Status: p.Status,
CreatedAt: isoTime(p.CreatedAt),
URLs: photoURLs{Original: fileURL(p.ID, "original", token)},
URLs: photoURLs{
Original: fileURL(p.ID, "original", token),
DownloadOriginal: downloadURL(p.ID, downloadSizeOriginal, token),
},
}
if p.ThumbKey != "" {
out.URLs.Thumb = fileURL(p.ID, "thumb", token)
}
if p.PreviewKey != "" {
out.URLs.Preview = fileURL(p.ID, "preview", token)
out.URLs.Download = downloadURL(p.ID, downloadSizePreview, token)
}
if admin {
out.LastError = p.LastError
+162 -21
View File
@@ -7,13 +7,24 @@ import (
"log"
"net/http"
"os"
"strings"
"time"
"git.azzamo.net/Michilis/Spanglish/photo-api/internal/storage"
"git.azzamo.net/Michilis/Spanglish/photo-api/internal/store"
)
const presignExpiry = 15 * time.Minute
// Sizes the download endpoint offers. Preview is the default because it is
// what a phone can actually save to its photo library: iOS and Android only
// reach the gallery through the share sheet, and the share sheet is worth
// handing a 2048px JPEG rather than a multi-megabyte original.
const (
downloadSizePreview = "preview"
downloadSizeOriginal = "original"
)
// serveFile delivers photo bytes after re-running the gallery access check.
// S3: 302 to a short-lived presigned URL; local: streamed directly.
func (s *Server) serveFile(w http.ResponseWriter, r *http.Request) {
@@ -22,23 +33,10 @@ func (s *Server) serveFile(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "Not Found")
return
}
p, err := s.db.GetPhoto(r.Context(), r.PathValue("photoId"))
if err != nil {
writeStoreError(w, err, "Photo not found")
p, _, ok := s.authorizedPhoto(w, r)
if !ok {
return
}
g, err := s.db.GetGallery(r.Context(), p.GalleryID)
if err != nil {
writeStoreError(w, err, "Photo not found")
return
}
user := s.optionalUser(r)
token := r.URL.Query().Get("token")
if denial := s.authorize(r, g, user, token); denial != nil {
writeError(w, denial.status, denial.msg)
return
}
isAdmin := user != nil && user.IsAdmin()
var key, contentType, downloadName string
switch variant {
@@ -58,12 +56,6 @@ func (s *Server) serveFile(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "Not ready")
return
}
// Non-ready originals stay admin-only so uploads that fail processing
// never leak to viewers.
if p.Status != "ready" && !isAdmin {
writeError(w, http.StatusNotFound, "Not ready")
return
}
if url, err := s.storage.PresignGet(r.Context(), key, downloadName, contentType, presignExpiry); err == nil {
http.Redirect(w, r, url, http.StatusFound)
@@ -100,6 +92,155 @@ func (s *Server) serveFile(w http.ResponseWriter, r *http.Request) {
}
}
// serveDownload backs the gallery's save/download actions. It differs from
// serveFile in three ways that the mobile save flow depends on:
//
// - It always streams. serveFile 302s to S3 when presigning is available,
// and a cross-origin redirect is opaque to fetch() — the client could
// never read the bytes into a Blob to hand to navigator.share().
// - It names the file (spanglish-<event>-<n>.jpg) and always declares a
// real image/* type, because iOS only offers "Save Image" in the share
// sheet for something it recognises as an image.
// - It caches for a year as immutable. ?size=preview is also the URL the
// lightbox renders, so tapping save re-reads the bytes already on screen
// out of the HTTP cache instead of fetching them again.
func (s *Server) serveDownload(w http.ResponseWriter, r *http.Request) {
size := r.URL.Query().Get("size")
if size == "" {
size = downloadSizePreview
}
if size != downloadSizePreview && size != downloadSizeOriginal {
writeError(w, http.StatusNotFound, "Not Found")
return
}
p, g, ok := s.authorizedPhoto(w, r)
if !ok {
return
}
key, contentType := p.PreviewKey, "image/jpeg"
if size == downloadSizeOriginal {
key, contentType = p.OriginalKey, imageContentType(p.ContentType, p.OriginalFilename)
}
if key == "" {
writeError(w, http.StatusNotFound, "Not ready")
return
}
reader, n, err := s.storage.Open(r.Context(), key)
if err != nil {
if os.IsNotExist(err) || errors.Is(err, storage.ErrNotExist) {
writeError(w, http.StatusNotFound, "Not Found")
return
}
log.Printf("Error: open %s: %v", key, err)
writeError(w, http.StatusInternalServerError, "Internal Server Error")
return
}
defer reader.Close()
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", fmt.Sprintf("%d", n))
w.Header().Set("X-Content-Type-Options", "nosniff")
// The preview is rendered as an <img> as well as saved, so it is marked
// inline; only the original is a pure download. Either way the filename
// travels with it, which is what a bare <a download> fallback and the
// Android share sheet display.
disposition := "inline"
if size == downloadSizeOriginal {
disposition = "attachment"
}
w.Header().Set("Content-Disposition", fmt.Sprintf("%s; filename=%q",
disposition, s.downloadFilename(r, g, p, size)))
// Objects are immutable (a new upload writes a new key), so the response
// can be cached for as long as the browser will keep it. Restricted
// galleries stay out of shared caches: access is re-checked per request
// here, and only the browser that passed the check may reuse the bytes.
scope := "private"
if g.Visibility == store.VisibilityPublic {
scope = "public"
}
w.Header().Set("Cache-Control", scope+", max-age=31536000, immutable")
if _, err := io.Copy(w, reader); err != nil {
// Routine on mobile: the client aborts the fetch when the save sheet
// is cancelled, which lands here as a broken pipe.
log.Printf("stream %s: %v", key, err)
}
}
// authorizedPhoto loads the photo and its gallery and re-runs the access
// check every byte-serving handler owes (PLAN.md §7). It writes the error
// response itself; ok=false means the caller is done.
func (s *Server) authorizedPhoto(w http.ResponseWriter, r *http.Request) (store.Photo, store.Gallery, bool) {
p, err := s.db.GetPhoto(r.Context(), r.PathValue("photoId"))
if err != nil {
writeStoreError(w, err, "Photo not found")
return store.Photo{}, store.Gallery{}, false
}
g, err := s.db.GetGallery(r.Context(), p.GalleryID)
if err != nil {
writeStoreError(w, err, "Photo not found")
return store.Photo{}, store.Gallery{}, false
}
user := s.optionalUser(r)
if denial := s.authorize(r, g, user, r.URL.Query().Get("token")); denial != nil {
writeError(w, denial.status, denial.msg)
return store.Photo{}, store.Gallery{}, false
}
// Non-ready originals stay admin-only so uploads that fail processing
// never leak to viewers.
if p.Status != "ready" && !(user != nil && user.IsAdmin()) {
writeError(w, http.StatusNotFound, "Not ready")
return store.Photo{}, store.Gallery{}, false
}
return p, g, true
}
// downloadFilename names the saved file after the event it came from rather
// than the photographer's IMG_1234.JPG: spanglish-<event-slug>-<n>.<ext>,
// numbered from 1 in gallery order. Standalone galleries use their own slug.
func (s *Server) downloadFilename(r *http.Request, g store.Gallery, p store.Photo, size string) string {
slug := g.Slug
if g.EventID != "" {
if ev, err := s.db.GetEventSummary(r.Context(), g.EventID); err == nil && ev.Slug != "" {
slug = ev.Slug
}
}
ext := ".jpg"
if size == downloadSizeOriginal {
if e := extForContentType(p.ContentType); e != "" {
ext = e
}
}
return fmt.Sprintf("spanglish-%s-%d%s", slug, p.Position+1, ext)
}
// imageContentType keeps the download endpoint's Content-Type in the image/*
// family. An original stored with a missing or generic type would otherwise
// go out as application/octet-stream, and iOS drops "Save Image" from the
// share sheet for anything it cannot see as an image.
func imageContentType(ct, filename string) string {
if strings.HasPrefix(ct, "image/") {
return ct
}
if i := strings.LastIndex(filename, "."); i >= 0 {
switch strings.ToLower(filename[i:]) {
case ".jpg", ".jpeg":
return "image/jpeg"
case ".png":
return "image/png"
case ".gif":
return "image/gif"
case ".webp":
return "image/webp"
case ".heic", ".heif":
return "image/heic"
}
}
return "image/jpeg"
}
func extForContentType(ct string) string {
switch ct {
case "image/jpeg":
+1
View File
@@ -106,6 +106,7 @@ func (s *Server) getGallery(w http.ResponseWriter, r *http.Request, _ auth.User)
writeStoreError(w, err, "")
return
}
s.fillPreviewSizes(r.Context(), photos)
urlToken := s.viewTokenFor(g)
out := make([]photoJSON, 0, len(photos))
for _, p := range photos {
+1
View File
@@ -66,6 +66,7 @@ func (s *Server) respondGalleryView(w http.ResponseWriter, r *http.Request, g st
writeStoreError(w, err, "")
return
}
s.fillPreviewSizes(r.Context(), photos)
out := make([]photoJSON, 0, len(photos))
for _, p := range photos {
out = append(out, s.photoToJSON(p, urlToken, false))
+3
View File
@@ -52,6 +52,9 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/photos/public/galleries", s.listPublicGalleries)
mux.HandleFunc("GET /api/photos/public/galleries/{slug}", s.getPublicGallery)
mux.HandleFunc("GET /api/photos/public/events/{eventSlug}/gallery", s.getEventGallery)
// The literal "download" segment takes precedence over {variant} under
// ServeMux's specificity rules, so the two can share the prefix.
mux.HandleFunc("GET /api/photos/files/{photoId}/download", s.serveDownload)
mux.HandleFunc("GET /api/photos/files/{photoId}/{variant}", s.serveFile)
return s.withCommon(mux)
+64
View File
@@ -0,0 +1,64 @@
package httpapi
import (
"context"
"log"
"sync"
"git.azzamo.net/Michilis/Spanglish/photo-api/internal/store"
)
// statConcurrency bounds the one-off Stat burst below; a gallery of ~70
// photos then costs a handful of round-trips against S3, once ever.
const statConcurrency = 8
// fillPreviewSizes measures the preview objects of photos whose
// preview_size_bytes is still unset and writes the result back, updating the
// slice in place.
//
// The worker records the size when it generates the preview, so this only
// ever fires for rows that predate the column (or arrived via `photo-api
// sync`). It is a self-healing cache fill rather than a migration step: the
// first gallery view after deploy pays for one Stat per photo, every view
// after that reads the stored value. Errors are logged and swallowed — a
// missing size costs the save sheet its row label, which is not worth
// failing a gallery response over.
func (s *Server) fillPreviewSizes(ctx context.Context, photos []store.Photo) {
var (
wg sync.WaitGroup
sem = make(chan struct{}, statConcurrency)
mu sync.Mutex
size = make(map[string]int64, len(photos))
)
for _, p := range photos {
if p.PreviewKey == "" || p.PreviewSizeBytes > 0 {
continue
}
wg.Add(1)
go func(p store.Photo) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
n, err := s.storage.Stat(ctx, p.PreviewKey)
if err != nil {
log.Printf("preview size %s: %v", p.PreviewKey, err)
return
}
mu.Lock()
size[p.ID] = n
mu.Unlock()
}(p)
}
wg.Wait()
if len(size) == 0 {
return
}
for i := range photos {
if n, ok := size[photos[i].ID]; ok {
photos[i].PreviewSizeBytes = n
if err := s.db.SetPreviewSize(ctx, photos[i].ID, n); err != nil {
log.Printf("store preview size %s: %v", photos[i].ID, err)
}
}
}
}