# album Core Media Library with Postgres-indexed metadata, virtual folders, immutable SEO-slug blob keys, synchronous WebP srcset variants, single-use upload tokens and zero-DB-hit static serving. `import "git.golem15.com/golem15/summercms/modules/album"` **Name:** A holiday photo album where you keep, organize and share your pictures and clippings. ## Overview album is the shared Media Library of SummerCMS. Uploaded files are stored directly in the application's `gocloud.dev/blob` bucket under immutable keys of the form `media//.`, while metadata, virtual folders, WebP variant records and single-use upload tokens live in PostgreSQL (`summer_media_folders`, `summer_media_items` and `summer_media_upload_tokens`). Because `` and `` are frozen at upload time, moving items between virtual folders or editing `alt`, `title` or `caption` never changes a published URL. ## Role in the framework A core service module built on `backpack`, `compass`, `lagoon/attach` and `lagoon/attach/webp`. album does not import `lagoon`, matching `postcard`'s import graph: `lagoon` runs `album.Migrations` under the `summercms.album` migration history, `surf` installs `album.Service` on `backpack.App` and mounts the zero-DB-hit `/media/{short_id}/{file}` and signed `/media/upload/{token}` routes, and admin or plugin code consumes `album.ServiceFrom`. ## Features - Immutable public URLs (`media//.`) with zero-DB-hit static serving (`album.StaticHandler`), `Cache-Control: public, max-age=31536000, immutable`, `X-Content-Type-Options: nosniff`, sandboxing `Content-Security-Policy` and `Content-Disposition: attachment` for non-inline file types. - Strict upload validation reusing `attach.DefaultImageExtensions`, `attach.DefaultFileExtensions`, `attach.IsAllowedImage` (including `attach.MaxImagePixels` decompression-bomb guard), `attach.DiskExtension` and `attach.UploadWriterOptions`. SVG, HTML and JavaScript uploads are explicitly rejected. - Synchronous WebP `srcset` variant generation (`480w`, `960w`, `1600w`, never upscaling past the original width) via `lagoon/attach/webp` and `golang.org/x/image/draw`, stored beside the original at `media//-w.webp` and recorded in `summer_media_items.variants`. - Streaming SHA-256 computation stored for search and inspection with no automatic deduplication, so every upload owns an independent blob key. - Single-use DB-backed upload tokens (`album.Service.PrepareUpload` and `album.Service.ConsumeUploadToken`) storing only the SHA-256 hash in `summer_media_upload_tokens` and atomically marking `used_at = NOW()` before reading bytes. - Safe post-commit deletion seam (`album.Service.DeleteItemInTx` + `album.DeleteBlobs`) so callers can wrap deletes in `lagoon.Transaction` and `lagoon.AfterCommit` without risking blob loss on rollback. - Idempotent Mail Images backfill (`album.BackfillMailImages`) indexing legacy `system_files` rows under virtual folder `mail` while preserving existing `/uploads/...` URLs. ## Usage Install or look up the app-scoped service on `backpack.App`: ```go src=modules/album/example_test.go#installAndLookup // installAndLookup shows how application or plugin code obtains the published *album.Service. func installAndLookup(app *backpack.App) (*album.Service, error) { svc, err := album.Install(app) if err != nil { return nil, err } if found, ok := album.ServiceFrom(app); ok { return found, nil } return svc, nil } ``` Serve immutable blobs with zero database hits using `album.StaticHandler`: ```go src=modules/album/example_test.go#ExampleStaticHandler ctx := context.Background() bucket := memblob.OpenBucket(nil) defer bucket.Close() key := "media/abc123456789/summer-banner.png" _ = bucket.WriteAll(ctx, key, []byte("png-bytes"), attach.UploadWriterOptions("image/png")) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/media/abc123456789/summer-banner.png", nil) album.StaticHandler(bucket, "/media").ServeHTTP(rec, req) fmt.Println(rec.Code) fmt.Println(rec.Header().Get("Cache-Control")) fmt.Println(rec.Header().Get("X-Content-Type-Options")) // Output: // 200 // public, max-age=31536000, immutable // nosniff ``` Build a responsive `srcset` attribute from an item's recorded variants: ```go src=modules/album/example_test.go#ExampleItem_Srcset item := album.Item{ ShortID: "abc123456789", BlobKey: "media/abc123456789/hero.jpg", Variants: album.Variants{ {Width: 480, Height: 320, Key: "media/abc123456789/hero-480w.webp"}, {Width: 960, Height: 640, Key: "media/abc123456789/hero-960w.webp"}, }, } fmt.Println(item.PublicURL(nil)) fmt.Println(item.Srcset(nil)) // Output: // /media/abc123456789/hero.jpg // /media/abc123456789/hero-480w.webp 480w, /media/abc123456789/hero-960w.webp 960w ``` ## API reference | Identifier | Description | |------------|-------------| | `album.Migrations` | Gormigrate migration set creating `summer_media_folders`, `summer_media_items` and `summer_media_upload_tokens`. | | `album.Install` | Idempotently publishes a `*album.Service` onto a `*backpack.App`. | | `album.ServiceFrom` | Looks up the published `*album.Service` on a `*backpack.App`. | | `album.NewService` | Constructs a `*album.Service` from `*compass.Config`. | | `album.Service` | Orchestrates uploads, folders, item queries, signed upload tokens and transactional deletion. | | `album.UploadInput` | Input parameters for `album.Service.Upload`. | | `album.Folder` | Virtual folder model mapped to `summer_media_folders`. | | `album.Item` | Indexed media item model mapped to `summer_media_items`, with `PublicURL`, `AbsolutePublicURL`, `Srcset` and `AllBlobKeys`. | | `album.Variant`, `album.Variants` | Responsive WebP variant record and JSONB slice type. | | `album.VariantWidths` | Responsive width breakpoints (`480`, `960`, `1600`). | | `album.GenerateWebPVariants` | Generates non-upscaling WebP variants and writes them to the bucket. | | `album.UploadToken`, `album.PrepareUploadInput`, `album.PreparedUpload` | Single-use DB-backed upload token model and prepare inputs/outputs. | | `album.StaticHandler` | Zero-DB-hit HTTP handler for `GET`/`HEAD /media/{short_id}/{file}`. | | `album.SignedUploadHandler` | Raw `PUT`/`POST /media/upload/{token}` handler with atomic token consumption and `http.MaxBytesReader`. | | `album.BackfillMailImages` | Idempotently indexes legacy `System\Models\MailImageLibrary` rows into virtual folder `mail`. | | `album.DeleteBlobs` | Deletes original and variant blob keys from the bucket, ignoring `NotFound`. | ## Configuration | Key | Default | Controls | |-----|---------|----------| | `media.max_bytes` | `26214400` (25 MiB) | Maximum binary upload size for admin multipart and signed URL uploads (`album.MaxBytes`). | | `media.base64_max_bytes` | `5242880` (5 MiB) | Maximum decoded size for base64 uploads (`album.Base64MaxBytes`). | | `media.public_path_prefix` | `"/media"` | Public URL prefix for media serving and signed upload routes (`album.PublicPathPrefix`). | | `media.serve` | follows `storage.uploads.serve` | Mounts the zero-DB-hit `GET /{short_id}/{file}` route in `surf` (`album.ServeEnabled`). | ## Dependencies - SummerCMS modules: [backpack](../backpack/README.md), [compass](../compass/README.md), and the `attach` / `attach/webp` packages of [lagoon](../lagoon/README.md) (`lagoon` itself is not imported). - Third-party: `gocloud.dev/blob`, `gorm.io/gorm`, `github.com/go-gormigrate/gormigrate/v2`, `golang.org/x/image/draw`, `golang.org/x/image/webp`. - Standard library: `bufio`, `bytes`, `context`, `crypto/rand`, `crypto/sha256`, `database/sql/driver`, `encoding/base64`, `encoding/hex`, `encoding/json`, `errors`, `fmt`, `image`, `image/gif`, `image/jpeg`, `image/png`, `io`, `math`, `math/big`, `mime`, `net/http`, `net/url`, `path`, `regexp`, `slices`, `sort`, `strconv`, `strings`, `time`, `unicode`. ## Testing ```sh go test -short ./modules/album/... ```