feat(album): add core Media Library module, migrations, and surf routes
This commit is contained in:
@@ -91,6 +91,7 @@ The `migrate`, `migrate:status`, `migrate:rollback`, `serve` and admin commands
|
||||
|
||||
| Module | Purpose | Name mnemonic |
|
||||
|--------|---------|---------------|
|
||||
| [album](modules/album/README.md) | 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. | A holiday photo album where you keep, organize and share your pictures and clippings. |
|
||||
| [backpack](modules/backpack/README.md) | Per-instance application container that holds the configuration, a typed service registry, the event bus and the set of activated plugins. | The one bag you pack for the beach; it carries everything the application needs: configuration, services, events and plugins. |
|
||||
| [beachcomber](modules/beachcomber/README.md) | Search index sync for GORM models: after-commit upserts and deletes through a pluggable engine, gated by an application kill-switch. | A beachcomber searches the shore for finds; this module keeps the search index in step so content can be found. |
|
||||
| [boardwalk](modules/boardwalk/README.md) | HTTP handler that serves the embedded admin SPA build under a configurable path prefix. | The walkway along the beach front; it is the path admins take into the admin SPA. |
|
||||
|
||||
@@ -17,5 +17,5 @@ Start with [Installation](setup/installation.md) to set up the toolchain and the
|
||||
- [Plugins](plugins/registration.md): registering a plugin, scheduling, extending other plugins, [menu item types](plugins/menu-item-types.md) and testing.
|
||||
- [Backend](backend/admin-controllers.md): admin controllers, forms, lists, relations, [plugin field types](backend/field-types.md), users and [API tokens](backend/users-and-permissions.md#api-tokens), settings and the admin SPA.
|
||||
- [Database](database/models.md): models, migrations, queries, relations, casts, attachments and transactions.
|
||||
- [Services](services/configuration.md): configuration, events, routing, authentication, [caching](services/caching.md), mail, jobs, realtime, search and the other services, plus what SummerCMS does not provide for the frontend.
|
||||
- [Services](services/configuration.md): configuration, events, routing, authentication, [caching](services/caching.md), mail, jobs, realtime, search, [media library](services/media-library.md) and the other services, plus what SummerCMS does not provide for the frontend.
|
||||
- [Console](console/introduction.md): the `summer` tool, the application binary's commands and writing your own.
|
||||
|
||||
89
docs/services/media-library.md
Normal file
89
docs/services/media-library.md
Normal file
@@ -0,0 +1,89 @@
|
||||
---
|
||||
title: Media Library
|
||||
description: Store, organize and serve shared media with immutable SEO-slug URLs, synchronous WebP srcset variants and single-use signed upload tokens.
|
||||
section: services
|
||||
order: 95
|
||||
---
|
||||
# Media Library
|
||||
|
||||
The [album](../../modules/album/README.md) module provides a shared, plugin-agnostic Media Library backed by the application's `blob.Bucket` (see [Storage](storage.md)) and PostgreSQL metadata tables (`summer_media_folders`, `summer_media_items` and `summer_media_upload_tokens`).
|
||||
|
||||
## URL contract and zero-DB-hit delivery
|
||||
|
||||
Uploaded files are written directly to the shared bucket at `media/<short-id>/<slug>.<ext>`, where `<short-id>` is a server-generated 12-character lowercase alphanumeric identifier and `<slug>` is sanitized from the filename and frozen at upload time. Moving an item between virtual folders or updating its `alt`, `title` or `caption` never changes its blob key or public URL.
|
||||
|
||||
When `media.serve` is enabled (or unset while `storage.uploads.serve` is true), [surf](../../modules/surf/README.md) mounts `GET /media/{short_id}/{file}` directly on `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
|
||||
```
|
||||
|
||||
Every response sends `Cache-Control: public, max-age=31536000, immutable`, `X-Content-Type-Options: nosniff` and a sandboxing `Content-Security-Policy`. Non-inline types (such as PDFs or archives) always carry `Content-Disposition: attachment`. SVG, HTML and JavaScript uploads are rejected.
|
||||
|
||||
## Synchronous WebP variants
|
||||
|
||||
Raster image uploads (`jpg`, `jpeg`, `png`, `gif`, `webp`) pass `attach.IsAllowedImage` (including the `attach.MaxImagePixels` decompression-bomb guard) and synchronously generate WebP width variants at `480w`, `960w` and `1600w` without upscaling past the original width. Variants are stored alongside the original at `media/<short-id>/<slug>-<width>w.webp` and recorded on `summer_media_items.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
|
||||
```
|
||||
|
||||
## Accessing the service
|
||||
|
||||
`surf.BuildRouter` publishes `*album.Service` on `backpack.App` via `album.Install`. Plugins and admin handlers look it up with `album.ServiceFrom`:
|
||||
|
||||
```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
|
||||
}
|
||||
```
|
||||
|
||||
## Single-use signed uploads
|
||||
|
||||
For binary uploads from CLIs or MCP agents, `album.Service.PrepareUpload` creates a 32-byte random token, stores only its SHA-256 hash in `summer_media_upload_tokens` with a 5-minute TTL, and returns the opaque token. The raw `PUT` / `POST /media/upload/{token}` route (`album.SignedUploadHandler`) atomically marks `used_at = NOW()` before reading bytes, preventing replay.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Key | Default | Controls |
|
||||
|-----|---------|----------|
|
||||
| `media.max_bytes` | `26214400` (25 MiB) | Maximum binary upload size. |
|
||||
| `media.base64_max_bytes` | `5242880` (5 MiB) | Maximum decoded size for base64 uploads. |
|
||||
| `media.public_path_prefix` | `"/media"` | Public URL prefix for media serving and signed upload routes. |
|
||||
| `media.serve` | follows `storage.uploads.serve` | Mounts the zero-DB-hit `GET /media/{short_id}/{file}` route. |
|
||||
126
modules/album/README.md
Normal file
126
modules/album/README.md
Normal file
@@ -0,0 +1,126 @@
|
||||
# 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/<short-id>/<slug>.<ext>`, 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 `<short-id>` and `<slug>` 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/<short-id>/<slug>.<ext>`) 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/<short-id>/<slug>-<width>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 <prefix>/{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/...
|
||||
```
|
||||
130
modules/album/album.go
Normal file
130
modules/album/album.go
Normal file
@@ -0,0 +1,130 @@
|
||||
// Package album provides the core Media Library for SummerCMS: Postgres-indexed
|
||||
// media metadata and virtual folders, immutable SEO-slug blob keys under
|
||||
// media/<short-id>/<slug>.<ext>, synchronous WebP responsive srcset variants,
|
||||
// single-use DB-backed upload tokens, and zero-DB-hit static delivery.
|
||||
package album
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
)
|
||||
|
||||
// Configuration keys read from compass.Config.
|
||||
const (
|
||||
// ConfigMaxBytes sets the maximum binary upload size in bytes (default 25 MiB).
|
||||
ConfigMaxBytes = "media.max_bytes"
|
||||
// ConfigBase64MaxBytes sets the maximum decoded base64 upload size in bytes (default 5 MiB).
|
||||
ConfigBase64MaxBytes = "media.base64_max_bytes"
|
||||
// ConfigPublicPathPrefix sets the public URL path prefix for /media serving (default "/media").
|
||||
ConfigPublicPathPrefix = "media.public_path_prefix"
|
||||
// ConfigServe toggles mounting the public /media static route (defaults to storage.uploads.serve).
|
||||
ConfigServe = "media.serve"
|
||||
)
|
||||
|
||||
// Default limits and paths.
|
||||
const (
|
||||
// DefaultMaxBytes is the default maximum binary upload size (25 MiB).
|
||||
DefaultMaxBytes int64 = 25 << 20
|
||||
// DefaultBase64MaxBytes is the default maximum decoded base64 upload size (5 MiB).
|
||||
DefaultBase64MaxBytes int64 = 5 << 20
|
||||
// DefaultPublicPathPrefix is the default public URL path prefix for media items.
|
||||
DefaultPublicPathPrefix = "/media"
|
||||
// DefaultUploadTokenTTL is the default lifetime of a single-use upload token.
|
||||
DefaultUploadTokenTTL = 5 * time.Minute
|
||||
// BlobKeyPrefix is the leading bucket key segment for all album blobs.
|
||||
BlobKeyPrefix = "media"
|
||||
)
|
||||
|
||||
// Database table names owned by album.
|
||||
const (
|
||||
// FoldersTable stores virtual media folders.
|
||||
FoldersTable = "summer_media_folders"
|
||||
// ItemsTable stores uploaded media item metadata and variant records.
|
||||
ItemsTable = "summer_media_items"
|
||||
// UploadTokensTable stores hashed single-use signed upload tokens.
|
||||
UploadTokensTable = "summer_media_upload_tokens"
|
||||
)
|
||||
|
||||
// Install idempotently publishes a *Service onto app and returns it.
|
||||
// If a *Service is already published on app, that instance is returned.
|
||||
func Install(app *backpack.App) (*Service, error) {
|
||||
if app == nil {
|
||||
return nil, fmt.Errorf("album: app is nil")
|
||||
}
|
||||
if svc, ok := ServiceFrom(app); ok {
|
||||
return svc, nil
|
||||
}
|
||||
svc := NewService(app.Config)
|
||||
if err := app.Publish[*Service](svc); err != nil {
|
||||
// Handle concurrent publish gracefully by returning the existing service.
|
||||
if existing, ok := ServiceFrom(app); ok {
|
||||
return existing, nil
|
||||
}
|
||||
return nil, fmt.Errorf("album: publish service: %w", err)
|
||||
}
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
// ServiceFrom returns the *Service published on app, if any.
|
||||
func ServiceFrom(app *backpack.App) (*Service, bool) {
|
||||
if app == nil {
|
||||
return nil, false
|
||||
}
|
||||
svc, ok := app.Lookup[*Service]()
|
||||
if !ok || svc == nil {
|
||||
return nil, false
|
||||
}
|
||||
return svc, true
|
||||
}
|
||||
|
||||
// MaxBytes returns the configured maximum binary upload size, defaulting to DefaultMaxBytes.
|
||||
func MaxBytes(cfg *compass.Config) int64 {
|
||||
if cfg != nil && cfg.Has(ConfigMaxBytes) {
|
||||
if n := int64(cfg.Int(ConfigMaxBytes)); n > 0 {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return DefaultMaxBytes
|
||||
}
|
||||
|
||||
// Base64MaxBytes returns the configured maximum decoded base64 upload size,
|
||||
// defaulting to DefaultBase64MaxBytes.
|
||||
func Base64MaxBytes(cfg *compass.Config) int64 {
|
||||
if cfg != nil && cfg.Has(ConfigBase64MaxBytes) {
|
||||
if n := int64(cfg.Int(ConfigBase64MaxBytes)); n > 0 {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return DefaultBase64MaxBytes
|
||||
}
|
||||
|
||||
// PublicPathPrefix returns the configured public URL path prefix for media,
|
||||
// trimmed of any trailing slash, defaulting to DefaultPublicPathPrefix.
|
||||
func PublicPathPrefix(cfg *compass.Config) string {
|
||||
if cfg != nil {
|
||||
if raw := strings.TrimSpace(cfg.String(ConfigPublicPathPrefix)); raw != "" {
|
||||
trimmed := strings.TrimRight(raw, "/")
|
||||
if trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
}
|
||||
return DefaultPublicPathPrefix
|
||||
}
|
||||
|
||||
// ServeEnabled reports whether the application should mount the public /media
|
||||
// static handler. When media.serve is explicitly set it wins; otherwise it
|
||||
// follows storage.uploads.serve.
|
||||
func ServeEnabled(cfg *compass.Config) bool {
|
||||
if cfg == nil {
|
||||
return false
|
||||
}
|
||||
if cfg.Has(ConfigServe) {
|
||||
return cfg.Bool(ConfigServe)
|
||||
}
|
||||
return cfg.Bool("storage.uploads.serve")
|
||||
}
|
||||
192
modules/album/album_smoke_test.go
Normal file
192
modules/album/album_smoke_test.go
Normal file
@@ -0,0 +1,192 @@
|
||||
package album_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/album"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob"
|
||||
"gocloud.dev/blob/memblob"
|
||||
)
|
||||
|
||||
func makeTestPNG(t *testing.T, w, h int) image.Image {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
img.Set(x, y, color.RGBA{R: uint8(x % 256), G: uint8(y % 256), B: 180, A: 255})
|
||||
}
|
||||
}
|
||||
return img
|
||||
}
|
||||
|
||||
func encodeTestPNG(t *testing.T, img image.Image) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
t.Fatalf("encode png: %v", err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestStaticHandlerHeadersAndTraversal(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
defer bucket.Close()
|
||||
|
||||
// Write an inline raster image and a non-inline PDF directly into memblob.
|
||||
pngBytes := encodeTestPNG(t, makeTestPNG(t, 16, 16))
|
||||
imgKey := "media/abc123456789/hero-photo.png"
|
||||
if err := bucket.WriteAll(ctx, imgKey, pngBytes, attach.UploadWriterOptions("image/png")); err != nil {
|
||||
t.Fatalf("write png: %v", err)
|
||||
}
|
||||
pdfKey := "media/abc123456789/brochure.pdf"
|
||||
if err := bucket.WriteAll(ctx, pdfKey, []byte("%PDF-1.4\n"), attach.UploadWriterOptions("application/pdf")); err != nil {
|
||||
t.Fatalf("write pdf: %v", err)
|
||||
}
|
||||
|
||||
h := album.StaticHandler(bucket, "/media")
|
||||
|
||||
// 1. Valid raster image serves inline with immutable Cache-Control, nosniff, and sandboxing CSP.
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/media/abc123456789/hero-photo.png", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("image status = %d, want 200", rec.Code)
|
||||
}
|
||||
if got := rec.Header().Get("Cache-Control"); got != album.MediaCacheControl {
|
||||
t.Fatalf("Cache-Control = %q, want %q", got, album.MediaCacheControl)
|
||||
}
|
||||
if got := rec.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
||||
t.Fatalf("X-Content-Type-Options = %q, want nosniff", got)
|
||||
}
|
||||
if got := rec.Header().Get("Content-Security-Policy"); got != album.MediaContentSecurityPolicy {
|
||||
t.Fatalf("CSP = %q, want %q", got, album.MediaContentSecurityPolicy)
|
||||
}
|
||||
if got := rec.Header().Get("Content-Disposition"); got != "" {
|
||||
t.Fatalf("inline image Content-Disposition = %q, want empty", got)
|
||||
}
|
||||
|
||||
// 2. Non-inline PDF always gets Content-Disposition: attachment.
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/media/abc123456789/brochure.pdf", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("pdf status = %d, want 200", rec.Code)
|
||||
}
|
||||
if got := rec.Header().Get("Content-Disposition"); got != "attachment" {
|
||||
t.Fatalf("pdf Content-Disposition = %q, want attachment", got)
|
||||
}
|
||||
|
||||
// 3. Traversal and malformed segments are rejected with 404.
|
||||
badPaths := []string{
|
||||
"/media/../etc/passwd",
|
||||
"/media/abc123456789/../secret.png",
|
||||
"/media/short/hero.png",
|
||||
"/media/ABC123456789/hero.png",
|
||||
"/media/abc123456789/sub/hero.png",
|
||||
"/media/abc123456789/.hidden.png",
|
||||
"/media/abc123456789/noext",
|
||||
}
|
||||
for _, p := range badPaths {
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, p, nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("path %q status = %d, want 404", p, rec.Code)
|
||||
}
|
||||
if got := rec.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
||||
t.Fatalf("path %q missing nosniff header", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateWebPVariantsNoUpscale(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
defer bucket.Close()
|
||||
|
||||
// 1200x800 PNG should generate 480w and 960w, and must NOT upscale to 1600w.
|
||||
img := makeTestPNG(t, 1200, 800)
|
||||
variants, keys, err := album.GenerateWebPVariants(ctx, nil, bucket, "abc123456789", "banner", img, "png")
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateWebPVariants: %v", err)
|
||||
}
|
||||
if len(variants) != 2 || len(keys) != 2 {
|
||||
t.Fatalf("got %d variants (%d keys), want 2 (480w, 960w)", len(variants), len(keys))
|
||||
}
|
||||
if variants[0].Width != 480 || variants[0].Height != 320 {
|
||||
t.Fatalf("variant[0] = %dx%d, want 480x320", variants[0].Width, variants[0].Height)
|
||||
}
|
||||
if variants[1].Width != 960 || variants[1].Height != 640 {
|
||||
t.Fatalf("variant[1] = %dx%d, want 960x640", variants[1].Width, variants[1].Height)
|
||||
}
|
||||
for _, key := range keys {
|
||||
exists, err := bucket.Exists(ctx, key)
|
||||
if err != nil || !exists {
|
||||
t.Fatalf("expected variant blob %q to exist (err=%v)", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
item := album.Item{
|
||||
ShortID: "abc123456789",
|
||||
BlobKey: "media/abc123456789/banner.png",
|
||||
Variants: album.Variants(variants),
|
||||
}
|
||||
srcset := item.Srcset(nil)
|
||||
if !strings.Contains(srcset, "/media/abc123456789/banner-480w.webp 480w") ||
|
||||
!strings.Contains(srcset, "/media/abc123456789/banner-960w.webp 960w") {
|
||||
t.Fatalf("unexpected srcset: %q", srcset)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlugAndShortIDGeneration(t *testing.T) {
|
||||
id, err := album.GenerateShortID()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateShortID: %v", err)
|
||||
}
|
||||
if len(id) != 12 {
|
||||
t.Fatalf("short_id length = %d, want 12", len(id))
|
||||
}
|
||||
if _, ok := album.ParsePublicMediaPath(id + "/hello-world.webp"); !ok {
|
||||
t.Fatalf("ParsePublicMediaPath rejected generated short_id %q", id)
|
||||
}
|
||||
|
||||
cases := map[string]string{
|
||||
"My Hero Photo (2026)!.PNG": "my-hero-photo-2026-png",
|
||||
" ___ ": "file",
|
||||
"summer--beach_day": "summer-beach-day",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := album.SanitizeSlug(in); got != want {
|
||||
t.Errorf("SanitizeSlug(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisallowedTypesRejectedBeforeDB(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
defer bucket.Close()
|
||||
|
||||
// Verify ParsePublicMediaPath and attach allow-lists reject SVG/HTML/JS.
|
||||
for _, ext := range []string{"svg", "html", "htm", "js", "mjs"} {
|
||||
for _, allowed := range attach.DefaultFileExtensions {
|
||||
if allowed == ext {
|
||||
t.Fatalf("extension %q must not be in DefaultFileExtensions", ext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Verify DeleteBlobs handles missing keys cleanly.
|
||||
if err := album.DeleteBlobs(ctx, bucket, []string{"media/abc123456789/missing.png"}); err != nil {
|
||||
t.Fatalf("DeleteBlobs on missing key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var _ *blob.Bucket
|
||||
96
modules/album/backfill.go
Normal file
96
modules/album/backfill.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package album
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MailImageLibraryMorph is the WinterCMS-compatible attachment_type used by
|
||||
// Phase 35 Mail Images rows in system_files.
|
||||
const MailImageLibraryMorph = `System\Models\MailImageLibrary`
|
||||
|
||||
// BackfillMailImages idempotently indexes existing system_files rows belonging
|
||||
// to the Mail Image Library into summer_media_items under the virtual "mail"
|
||||
// folder, keyed by legacy_file_id. Existing blobs and /uploads/... URLs are
|
||||
// preserved untouched so previously sent or authored mail templates never break.
|
||||
func BackfillMailImages(ctx context.Context, db *gorm.DB, cfg *compass.Config) (int, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return 0, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
|
||||
var files []attach.File
|
||||
err := db.WithContext(ctx).
|
||||
Where("attachment_type = ? AND field = ?", MailImageLibraryMorph, "images").
|
||||
Where("id NOT IN (SELECT legacy_file_id FROM "+ItemsTable+" WHERE legacy_file_id IS NOT NULL)").
|
||||
Order("id ASC").
|
||||
Find(&files).Error
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("album: query legacy mail images: %w", err)
|
||||
}
|
||||
if len(files) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
svc := NewService(cfg)
|
||||
mailFolder, err := svc.EnsureFolder(ctx, db, "mail", "Mail", nil)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("album: ensure mail folder: %w", err)
|
||||
}
|
||||
|
||||
inserted := 0
|
||||
for _, f := range files {
|
||||
shortID, err := generateUniqueShortID(ctx, db)
|
||||
if err != nil {
|
||||
return inserted, err
|
||||
}
|
||||
baseName := clientBaseName(f.FileName)
|
||||
slug := SanitizeSlug(strings.TrimSuffix(baseName, path.Ext(baseName)))
|
||||
blobKey := attach.BlobKey(f.DiskName)
|
||||
legacyURL := attach.PublicURL(blobKey)
|
||||
legacyID := f.ID
|
||||
title := ""
|
||||
if f.Title != nil {
|
||||
title = strings.TrimSpace(*f.Title)
|
||||
}
|
||||
folderID := mailFolder.ID
|
||||
|
||||
item := &Item{
|
||||
ShortID: shortID,
|
||||
FolderID: &folderID,
|
||||
BlobKey: blobKey,
|
||||
Slug: slug,
|
||||
FileName: baseName,
|
||||
ContentType: f.ContentType,
|
||||
FileSize: f.FileSize,
|
||||
Title: title,
|
||||
Variants: Variants{},
|
||||
LegacyFileID: &legacyID,
|
||||
LegacyURL: legacyURL,
|
||||
}
|
||||
res := db.WithContext(ctx).Exec(
|
||||
`INSERT INTO `+ItemsTable+`
|
||||
(short_id, folder_id, blob_key, slug, file_name, content_type, file_size, sha256, alt, title, caption, variants, legacy_file_id, legacy_url, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, '', '', ?, '', '[]'::jsonb, ?, ?, ?, ?)
|
||||
ON CONFLICT (legacy_file_id) DO NOTHING`,
|
||||
item.ShortID, item.FolderID, item.BlobKey, item.Slug, item.FileName,
|
||||
item.ContentType, item.FileSize, item.Title, *item.LegacyFileID, item.LegacyURL,
|
||||
f.CreatedAt, f.UpdatedAt,
|
||||
)
|
||||
if res.Error != nil {
|
||||
return inserted, fmt.Errorf("album: backfill legacy mail image %d: %w", f.ID, res.Error)
|
||||
}
|
||||
if res.RowsAffected > 0 {
|
||||
inserted++
|
||||
}
|
||||
}
|
||||
return inserted, nil
|
||||
}
|
||||
72
modules/album/example_test.go
Normal file
72
modules/album/example_test.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package album_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/album"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob/memblob"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// ExampleStaticHandler demonstrates zero-DB-hit serving of an immutable media blob.
|
||||
func 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
|
||||
}
|
||||
|
||||
// ExampleItem_Srcset demonstrates generating an HTML srcset string from recorded WebP variants.
|
||||
func 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
|
||||
}
|
||||
|
||||
func TestInstallAndLookup(t *testing.T) {
|
||||
svc, err := installAndLookup(backpack.New(nil))
|
||||
if err != nil || svc == nil {
|
||||
t.Fatalf("installAndLookup: svc=%v err=%v", svc, err)
|
||||
}
|
||||
}
|
||||
279
modules/album/http.go
Normal file
279
modules/album/http.go
Normal file
@@ -0,0 +1,279 @@
|
||||
package album
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
// MediaCacheControl is sent on every immutable /media/<short-id>/<file> response.
|
||||
MediaCacheControl = "public, max-age=31536000, immutable"
|
||||
// MediaContentSecurityPolicy sandboxes media files if opened directly as a document.
|
||||
MediaContentSecurityPolicy = "default-src 'none'; img-src 'self'; media-src 'self'; sandbox"
|
||||
defaultStaticContentType = "application/octet-stream"
|
||||
)
|
||||
|
||||
var (
|
||||
shortIDSegmentPattern = regexp.MustCompile(`^[a-z0-9]{10,16}$`)
|
||||
fileSegmentPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,120}\.[a-z0-9]{1,10}$`)
|
||||
)
|
||||
|
||||
// StaticHandler serves GET and HEAD requests for <prefix>/<short-id>/<file>
|
||||
// directly from bucket with zero database queries.
|
||||
//
|
||||
// Segments are strictly validated before touching bucket: short-id must match
|
||||
// ^[a-z0-9]{10,16}$ and file must match ^[a-z0-9][a-z0-9._-]{0,120}\.[a-z0-9]{1,10}$
|
||||
// with no "..", "/", or "\\".
|
||||
//
|
||||
// Every response sets X-Content-Type-Options: nosniff and MediaContentSecurityPolicy.
|
||||
// Successful responses also set Cache-Control: public, max-age=31536000, immutable,
|
||||
// the stored Content-Type, and Content-Disposition: attachment whenever
|
||||
// !attach.IsInlineContentType(contentType).
|
||||
func StaticHandler(bucket *blob.Bucket, prefix string) http.Handler {
|
||||
prefix = strings.TrimSuffix(strings.TrimSpace(prefix), "/")
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Security-Policy", MediaContentSecurityPolicy)
|
||||
if bucket == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
rel, ok := stripMediaPrefix(r.URL.Path, prefix)
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
key, ok := ParsePublicMediaPath(rel)
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
attrs, err := bucket.Attributes(r.Context(), key)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
reader, err := bucket.NewReader(r.Context(), key, nil)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
ct := strings.TrimSpace(reader.ContentType())
|
||||
if ct == "" {
|
||||
ct = defaultStaticContentType
|
||||
}
|
||||
w.Header().Set("Cache-Control", MediaCacheControl)
|
||||
w.Header().Set("Content-Type", ct)
|
||||
if !attach.IsInlineContentType(ct) {
|
||||
w.Header().Set("Content-Disposition", "attachment")
|
||||
} else if cd := safeDisposition(attrs.ContentDisposition); cd != "" {
|
||||
w.Header().Set("Content-Disposition", cd)
|
||||
}
|
||||
if r.Method == http.MethodHead {
|
||||
return
|
||||
}
|
||||
_, _ = io.Copy(w, reader)
|
||||
})
|
||||
}
|
||||
|
||||
// ParsePublicMediaPath validates a relative "<short-id>/<file>" path and returns
|
||||
// the canonical bucket key "media/<short-id>/<file>".
|
||||
func ParsePublicMediaPath(rel string) (string, bool) {
|
||||
if rel == "" || strings.Contains(rel, "\\") || strings.Contains(rel, "..") || strings.Contains(rel, "//") {
|
||||
return "", false
|
||||
}
|
||||
parts := strings.Split(rel, "/")
|
||||
if len(parts) != 2 {
|
||||
return "", false
|
||||
}
|
||||
shortID, file := parts[0], parts[1]
|
||||
if !shortIDSegmentPattern.MatchString(shortID) || !fileSegmentPattern.MatchString(file) {
|
||||
return "", false
|
||||
}
|
||||
return BlobKeyPrefix + "/" + shortID + "/" + file, true
|
||||
}
|
||||
|
||||
func stripMediaPrefix(reqPath, prefix string) (string, bool) {
|
||||
if prefix == "" {
|
||||
return strings.TrimPrefix(reqPath, "/"), true
|
||||
}
|
||||
if reqPath == prefix {
|
||||
return "", false
|
||||
}
|
||||
if strings.HasPrefix(reqPath, prefix+"/") {
|
||||
return reqPath[len(prefix)+1:], true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func safeDisposition(raw string) string {
|
||||
v := strings.TrimSpace(raw)
|
||||
if v == "" {
|
||||
return ""
|
||||
}
|
||||
if _, _, err := mime.ParseMediaType(v); err != nil {
|
||||
return "attachment"
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// ItemResponse is the JSON representation of an uploaded or fetched media item,
|
||||
// including resolved public URL and responsive srcset string.
|
||||
type ItemResponse struct {
|
||||
ID uint `json:"id"`
|
||||
ShortID string `json:"short_id"`
|
||||
FolderID *uint `json:"folder_id"`
|
||||
BlobKey string `json:"blob_key"`
|
||||
Slug string `json:"slug"`
|
||||
FileName string `json:"file_name"`
|
||||
ContentType string `json:"content_type"`
|
||||
FileSize int64 `json:"file_size"`
|
||||
Width *int `json:"width"`
|
||||
Height *int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Alt string `json:"alt"`
|
||||
Title string `json:"title"`
|
||||
Caption string `json:"caption"`
|
||||
URL string `json:"url"`
|
||||
Srcset string `json:"srcset"`
|
||||
Variants []Variant `json:"variants"`
|
||||
UploadedBy *uint `json:"uploaded_by,omitempty"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// NewItemResponse builds an ItemResponse with resolved URLs and srcset for item.
|
||||
func NewItemResponse(cfg *compass.Config, item *Item) ItemResponse {
|
||||
if item == nil {
|
||||
return ItemResponse{Variants: []Variant{}}
|
||||
}
|
||||
variants := make([]Variant, len(item.Variants))
|
||||
for i, v := range item.Variants {
|
||||
if v.Key != "" {
|
||||
v.URL = blobKeyPublicURL(cfg, v.Key)
|
||||
}
|
||||
variants[i] = v
|
||||
}
|
||||
return ItemResponse{
|
||||
ID: item.ID,
|
||||
ShortID: item.ShortID,
|
||||
FolderID: item.FolderID,
|
||||
BlobKey: item.BlobKey,
|
||||
Slug: item.Slug,
|
||||
FileName: item.FileName,
|
||||
ContentType: item.ContentType,
|
||||
FileSize: item.FileSize,
|
||||
Width: item.Width,
|
||||
Height: item.Height,
|
||||
SHA256: item.SHA256,
|
||||
Alt: item.Alt,
|
||||
Title: item.Title,
|
||||
Caption: item.Caption,
|
||||
URL: item.PublicURL(cfg),
|
||||
Srcset: item.Srcset(cfg),
|
||||
Variants: variants,
|
||||
UploadedBy: item.UploadedBy,
|
||||
CreatedAt: item.CreatedAt.UTC().Format("2006-01-02T15:04:05Z07:00"),
|
||||
UpdatedAt: item.UpdatedAt.UTC().Format("2006-01-02T15:04:05Z07:00"),
|
||||
}
|
||||
}
|
||||
|
||||
// SignedUploadHandler handles raw PUT and POST uploads to <prefix>/upload/{token}.
|
||||
// It atomically consumes the single-use token before reading bytes, caps the
|
||||
// request body with http.MaxBytesReader, runs svc.Upload, and responds with
|
||||
// 201 Created JSON {"data": ItemResponse}.
|
||||
func SignedUploadHandler(app *backpack.App, svc *Service) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPut && r.Method != http.MethodPost {
|
||||
writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
if app == nil || svc == nil {
|
||||
writeJSONError(w, http.StatusServiceUnavailable, "media service unavailable")
|
||||
return
|
||||
}
|
||||
db, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || db == nil {
|
||||
writeJSONError(w, http.StatusServiceUnavailable, "database unavailable")
|
||||
return
|
||||
}
|
||||
bucket, ok := app.Lookup[*blob.Bucket]()
|
||||
if !ok || bucket == nil {
|
||||
writeJSONError(w, http.StatusServiceUnavailable, "storage bucket unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
rawToken := strings.TrimSpace(r.PathValue("token"))
|
||||
tok, err := svc.ConsumeUploadToken(r.Context(), db, rawToken)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrInvalidUploadToken) {
|
||||
writeJSONError(w, http.StatusUnauthorized, "upload token is invalid, expired, or already used")
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "failed to verify upload token")
|
||||
return
|
||||
}
|
||||
|
||||
limit := tok.MaxBytes
|
||||
cfgMax := MaxBytes(svc.Config())
|
||||
if limit <= 0 || limit > cfgMax {
|
||||
limit = cfgMax
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
|
||||
uploadedBy := tok.CreatedBy
|
||||
item, err := svc.Upload(r.Context(), db, bucket, UploadInput{
|
||||
FileName: tok.ExpectedFilename,
|
||||
Body: r.Body,
|
||||
FolderID: tok.FolderID,
|
||||
Alt: r.URL.Query().Get("alt"),
|
||||
Title: r.URL.Query().Get("title"),
|
||||
Caption: r.URL.Query().Get("caption"),
|
||||
UploadedBy: &uploadedBy,
|
||||
MaxBytes: limit,
|
||||
})
|
||||
if err != nil {
|
||||
var maxErr *http.MaxBytesError
|
||||
switch {
|
||||
case errors.Is(err, ErrTooLarge) || errors.As(err, &maxErr):
|
||||
writeJSONError(w, http.StatusRequestEntityTooLarge, "file exceeds maximum allowed size")
|
||||
case errors.Is(err, ErrFileType) || errors.Is(err, ErrNotImage):
|
||||
writeJSONError(w, http.StatusUnprocessableEntity, err.Error())
|
||||
case errors.Is(err, ErrFolderNotFound):
|
||||
writeJSONError(w, http.StatusNotFound, "folder not found")
|
||||
default:
|
||||
writeJSONError(w, http.StatusInternalServerError, "upload failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"data": NewItemResponse(svc.Config(), item),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func writeJSONError(w http.ResponseWriter, status int, msg string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"error": msg})
|
||||
}
|
||||
85
modules/album/migrations.go
Normal file
85
modules/album/migrations.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package album
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Migrations creates the media library tables: summer_media_folders,
|
||||
// summer_media_items, and summer_media_upload_tokens.
|
||||
// lagoon runs this set under the summercms.album migration history.
|
||||
var Migrations = []*gormigrate.Migration{
|
||||
{
|
||||
ID: "202611270001_create_summer_media_tables",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
stmts := []string{
|
||||
`CREATE TABLE ` + FoldersTable + ` (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
parent_id BIGINT REFERENCES ` + FoldersTable + `(id) ON DELETE RESTRICT,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
slug VARCHAR(120) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
`CREATE UNIQUE INDEX ` + FoldersTable + `_parent_slug_uidx ON ` + FoldersTable + ` (COALESCE(parent_id, 0), slug)`,
|
||||
`CREATE TABLE ` + ItemsTable + ` (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
short_id VARCHAR(16) NOT NULL UNIQUE,
|
||||
folder_id BIGINT REFERENCES ` + FoldersTable + `(id) ON DELETE RESTRICT,
|
||||
blob_key VARCHAR(255) NOT NULL UNIQUE,
|
||||
slug VARCHAR(120) NOT NULL,
|
||||
file_name VARCHAR(255) NOT NULL,
|
||||
content_type VARCHAR(120) NOT NULL,
|
||||
file_size BIGINT NOT NULL,
|
||||
width INTEGER,
|
||||
height INTEGER,
|
||||
sha256 VARCHAR(64) NOT NULL DEFAULT '',
|
||||
alt TEXT NOT NULL DEFAULT '',
|
||||
title VARCHAR(255) NOT NULL DEFAULT '',
|
||||
caption TEXT NOT NULL DEFAULT '',
|
||||
variants JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
legacy_file_id BIGINT UNIQUE,
|
||||
legacy_url TEXT NOT NULL DEFAULT '',
|
||||
uploaded_by BIGINT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
`CREATE INDEX ` + ItemsTable + `_folder_created_idx ON ` + ItemsTable + ` (folder_id, created_at DESC)`,
|
||||
`CREATE INDEX ` + ItemsTable + `_sha256_idx ON ` + ItemsTable + ` (sha256)`,
|
||||
`CREATE INDEX ` + ItemsTable + `_content_type_idx ON ` + ItemsTable + ` (content_type)`,
|
||||
`CREATE TABLE ` + UploadTokensTable + ` (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
token_hash CHAR(64) NOT NULL UNIQUE,
|
||||
created_by BIGINT NOT NULL,
|
||||
folder_id BIGINT REFERENCES ` + FoldersTable + `(id) ON DELETE SET NULL,
|
||||
expected_filename VARCHAR(255) NOT NULL,
|
||||
expected_content_type VARCHAR(120) NOT NULL DEFAULT '',
|
||||
max_bytes BIGINT NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
used_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
`CREATE INDEX ` + UploadTokensTable + `_expires_at_idx ON ` + UploadTokensTable + ` (expires_at)`,
|
||||
}
|
||||
for _, stmt := range stmts {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
stmts := []string{
|
||||
`DROP TABLE IF EXISTS ` + UploadTokensTable,
|
||||
`DROP TABLE IF EXISTS ` + ItemsTable,
|
||||
`DROP TABLE IF EXISTS ` + FoldersTable,
|
||||
}
|
||||
for _, stmt := range stmts {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
}
|
||||
275
modules/album/models.go
Normal file
275
modules/album/models.go
Normal file
@@ -0,0 +1,275 @@
|
||||
package album
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
)
|
||||
|
||||
// Folder represents a virtual folder in summer_media_folders.
|
||||
// Moving items between folders never mutates their blob keys or public URLs.
|
||||
type Folder struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
ParentID *uint `gorm:"column:parent_id" json:"parent_id"`
|
||||
Name string `gorm:"column:name;not null" json:"name"`
|
||||
Slug string `gorm:"column:slug;not null" json:"slug"`
|
||||
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
// TableName returns the Postgres table name for Folder.
|
||||
func (Folder) TableName() string { return FoldersTable }
|
||||
|
||||
// Variant records one generated responsive image variant stored alongside the original blob.
|
||||
type Variant struct {
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Key string `json:"key"`
|
||||
URL string `json:"url"`
|
||||
Size int64 `json:"size"`
|
||||
ContentType string `json:"content_type"`
|
||||
}
|
||||
|
||||
// Variants is a JSONB slice of Variant values on Item.
|
||||
// An empty or nil slice always serializes to "[]", never SQL NULL or JSON null.
|
||||
type Variants []Variant
|
||||
|
||||
// Value implements driver.Valuer for Postgres JSONB columns.
|
||||
func (v Variants) Value() (driver.Value, error) {
|
||||
if len(v) == 0 {
|
||||
return "[]", nil
|
||||
}
|
||||
b, err := json.Marshal([]Variant(v))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("album: marshal variants: %w", err)
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// Scan implements sql.Scanner for Postgres JSONB columns.
|
||||
func (v *Variants) Scan(src any) error {
|
||||
if v == nil {
|
||||
return fmt.Errorf("album: scan into nil Variants")
|
||||
}
|
||||
if src == nil {
|
||||
*v = Variants{}
|
||||
return nil
|
||||
}
|
||||
var raw []byte
|
||||
switch val := src.(type) {
|
||||
case []byte:
|
||||
raw = val
|
||||
case string:
|
||||
raw = []byte(val)
|
||||
default:
|
||||
return fmt.Errorf("album: unsupported variants scan type %T", src)
|
||||
}
|
||||
trimmed := strings.TrimSpace(string(raw))
|
||||
if trimmed == "" || trimmed == "null" {
|
||||
*v = Variants{}
|
||||
return nil
|
||||
}
|
||||
var out []Variant
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return fmt.Errorf("album: unmarshal variants: %w", err)
|
||||
}
|
||||
if out == nil {
|
||||
out = []Variant{}
|
||||
}
|
||||
*v = Variants(out)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Item represents a media file indexed in summer_media_items.
|
||||
type Item struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
ShortID string `gorm:"column:short_id;not null;uniqueIndex" json:"short_id"`
|
||||
FolderID *uint `gorm:"column:folder_id" json:"folder_id"`
|
||||
BlobKey string `gorm:"column:blob_key;not null;uniqueIndex" json:"blob_key"`
|
||||
Slug string `gorm:"column:slug;not null" json:"slug"`
|
||||
FileName string `gorm:"column:file_name;not null" json:"file_name"`
|
||||
ContentType string `gorm:"column:content_type;not null" json:"content_type"`
|
||||
FileSize int64 `gorm:"column:file_size;not null" json:"file_size"`
|
||||
Width *int `gorm:"column:width" json:"width"`
|
||||
Height *int `gorm:"column:height" json:"height"`
|
||||
SHA256 string `gorm:"column:sha256;not null" json:"sha256"`
|
||||
Alt string `gorm:"column:alt;not null;default:''" json:"alt"`
|
||||
Title string `gorm:"column:title;not null;default:''" json:"title"`
|
||||
Caption string `gorm:"column:caption;not null;default:''" json:"caption"`
|
||||
Variants Variants `gorm:"column:variants;type:jsonb;not null;default:'[]'" json:"variants"`
|
||||
LegacyFileID *uint `gorm:"column:legacy_file_id" json:"legacy_file_id,omitempty"`
|
||||
LegacyURL string `gorm:"column:legacy_url;not null;default:''" json:"legacy_url,omitempty"`
|
||||
UploadedBy *uint `gorm:"column:uploaded_by" json:"uploaded_by,omitempty"`
|
||||
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
// TableName returns the Postgres table name for Item.
|
||||
func (Item) TableName() string { return ItemsTable }
|
||||
|
||||
// IsImage reports whether the item has an inline-safe raster image content type.
|
||||
func (i Item) IsImage() bool {
|
||||
return attach.IsInlineContentType(i.ContentType)
|
||||
}
|
||||
|
||||
// PublicURL returns the public URL of the item.
|
||||
// Legacy backfilled items preserve their original LegacyURL unchanged.
|
||||
// For standard album items, storage.uploads.public_url (CDN/S3) takes precedence;
|
||||
// otherwise PublicPathPrefix(cfg) is joined with the <short-id>/<file> path.
|
||||
func (i Item) PublicURL(cfg *compass.Config) string {
|
||||
if i.LegacyFileID != nil && strings.TrimSpace(i.LegacyURL) != "" {
|
||||
return strings.TrimSpace(i.LegacyURL)
|
||||
}
|
||||
return blobKeyPublicURL(cfg, i.BlobKey)
|
||||
}
|
||||
|
||||
// AbsolutePublicURL returns an absolute http(s) URL for the item, suitable for
|
||||
// emails and external consumers. It returns attach.ErrNoAbsoluteURL when neither
|
||||
// storage.uploads.public_url nor an absolute app.url is configured.
|
||||
func (i Item) AbsolutePublicURL(cfg *compass.Config) (string, error) {
|
||||
if i.LegacyFileID != nil && strings.TrimSpace(i.LegacyURL) != "" {
|
||||
raw := strings.TrimSpace(i.LegacyURL)
|
||||
if isAbsoluteHTTPURL(raw) {
|
||||
return raw, nil
|
||||
}
|
||||
base, err := appURLBase(cfg)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base + "/" + strings.TrimLeft(raw, "/"), nil
|
||||
}
|
||||
return blobKeyAbsolutePublicURL(cfg, i.BlobKey)
|
||||
}
|
||||
|
||||
// Srcset returns an HTML srcset attribute value built from the item's recorded
|
||||
// variants sorted by ascending width, or an empty string when none exist.
|
||||
func (i Item) Srcset(cfg *compass.Config) string {
|
||||
if len(i.Variants) == 0 {
|
||||
return ""
|
||||
}
|
||||
sorted := make([]Variant, len(i.Variants))
|
||||
copy(sorted, i.Variants)
|
||||
sort.Slice(sorted, func(a, b int) bool {
|
||||
return sorted[a].Width < sorted[b].Width
|
||||
})
|
||||
parts := make([]string, 0, len(sorted))
|
||||
for _, v := range sorted {
|
||||
if v.Width <= 0 {
|
||||
continue
|
||||
}
|
||||
u := v.URL
|
||||
if v.Key != "" {
|
||||
u = blobKeyPublicURL(cfg, v.Key)
|
||||
}
|
||||
if u == "" {
|
||||
continue
|
||||
}
|
||||
parts = append(parts, u+" "+strconv.Itoa(v.Width)+"w")
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
// AllBlobKeys returns the original blob key plus every recorded variant blob key
|
||||
// so callers can delete them after commit. For legacy backfilled items
|
||||
// (LegacyFileID != nil), it returns nil so legacy /uploads/... blobs are never deleted.
|
||||
func (i Item) AllBlobKeys() []string {
|
||||
if i.LegacyFileID != nil {
|
||||
return nil
|
||||
}
|
||||
keys := make([]string, 0, 1+len(i.Variants))
|
||||
if i.BlobKey != "" {
|
||||
keys = append(keys, i.BlobKey)
|
||||
}
|
||||
for _, v := range i.Variants {
|
||||
if v.Key != "" {
|
||||
keys = append(keys, v.Key)
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// UploadToken represents a single-use DB-backed upload token in summer_media_upload_tokens.
|
||||
type UploadToken struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
TokenHash string `gorm:"column:token_hash;not null;uniqueIndex" json:"-"`
|
||||
CreatedBy uint `gorm:"column:created_by;not null" json:"created_by"`
|
||||
FolderID *uint `gorm:"column:folder_id" json:"folder_id"`
|
||||
ExpectedFilename string `gorm:"column:expected_filename;not null" json:"expected_filename"`
|
||||
ExpectedContentType string `gorm:"column:expected_content_type;not null;default:''" json:"expected_content_type"`
|
||||
MaxBytes int64 `gorm:"column:max_bytes;not null" json:"max_bytes"`
|
||||
ExpiresAt time.Time `gorm:"column:expires_at;not null" json:"expires_at"`
|
||||
UsedAt *time.Time `gorm:"column:used_at" json:"used_at"`
|
||||
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
|
||||
}
|
||||
|
||||
// TableName returns the Postgres table name for UploadToken.
|
||||
func (UploadToken) TableName() string { return UploadTokensTable }
|
||||
|
||||
func blobKeyPublicURL(cfg *compass.Config, key string) string {
|
||||
key = strings.TrimLeft(key, "/")
|
||||
if key == "" {
|
||||
return ""
|
||||
}
|
||||
if cfg != nil {
|
||||
if pub := strings.TrimSpace(cfg.String("storage.uploads.public_url")); pub != "" {
|
||||
return strings.TrimRight(pub, "/") + "/" + key
|
||||
}
|
||||
}
|
||||
if base := attach.PublicURLBase(); base != "" {
|
||||
return strings.TrimRight(base, "/") + "/" + key
|
||||
}
|
||||
prefix := PublicPathPrefix(cfg)
|
||||
rel := strings.TrimPrefix(key, BlobKeyPrefix+"/")
|
||||
return strings.TrimRight(prefix, "/") + "/" + strings.TrimLeft(rel, "/")
|
||||
}
|
||||
|
||||
func blobKeyAbsolutePublicURL(cfg *compass.Config, key string) (string, error) {
|
||||
key = strings.TrimLeft(key, "/")
|
||||
if key == "" {
|
||||
return "", attach.ErrNoAbsoluteURL
|
||||
}
|
||||
if cfg != nil && strings.TrimSpace(cfg.String("storage.uploads.public_url")) != "" {
|
||||
return attach.AbsolutePublicURL(cfg, key)
|
||||
}
|
||||
base, err := appURLBase(cfg)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
prefix := strings.Trim(PublicPathPrefix(cfg), "/")
|
||||
rel := strings.TrimPrefix(key, BlobKeyPrefix+"/")
|
||||
if prefix != "" {
|
||||
return base + "/" + prefix + "/" + strings.TrimLeft(rel, "/"), nil
|
||||
}
|
||||
return base + "/" + strings.TrimLeft(rel, "/"), nil
|
||||
}
|
||||
|
||||
func appURLBase(cfg *compass.Config) (string, error) {
|
||||
if cfg == nil {
|
||||
return "", attach.ErrNoAbsoluteURL
|
||||
}
|
||||
raw := strings.TrimSpace(cfg.String("app.url"))
|
||||
if raw == "" {
|
||||
return "", attach.ErrNoAbsoluteURL
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Host == "" || (!strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, "https")) {
|
||||
return "", attach.ErrNoAbsoluteURL
|
||||
}
|
||||
return u.Scheme + "://" + u.Host + strings.TrimRight(u.Path, "/"), nil
|
||||
}
|
||||
|
||||
func isAbsoluteHTTPURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Host == "" {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(u.Scheme, "http") || strings.EqualFold(u.Scheme, "https")
|
||||
}
|
||||
826
modules/album/service.go
Normal file
826
modules/album/service.go
Normal file
@@ -0,0 +1,826 @@
|
||||
package album
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"math/big"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob"
|
||||
"gocloud.dev/gcerrors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
// sniffBytes is how much of an upload Upload peeks ahead for content sniffing
|
||||
// and image header validation (matching attach.Store).
|
||||
sniffBytes = 1 << 20
|
||||
// shortIDLength is the fixed length of generated short_id values.
|
||||
shortIDLength = 12
|
||||
// shortIDAlphabet is the lowercase alphanumeric alphabet for short_id.
|
||||
shortIDAlphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
// maxSlugLength caps sanitized filename/folder slugs.
|
||||
maxSlugLength = 80
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrTooLarge is returned when an upload exceeds its maximum byte limit.
|
||||
ErrTooLarge = errors.New("album: file is too large")
|
||||
// ErrFileType is returned when an upload's extension or sniffed content type is disallowed.
|
||||
ErrFileType = errors.New("album: file type is not allowed")
|
||||
// ErrNotImage is returned when an image upload does not contain a valid allowed raster image.
|
||||
ErrNotImage = errors.New("album: file is not an allowed image")
|
||||
// ErrNotFound is returned when a requested media item does not exist.
|
||||
ErrNotFound = errors.New("album: item not found")
|
||||
// ErrFolderNotFound is returned when a requested media folder does not exist.
|
||||
ErrFolderNotFound = errors.New("album: folder not found")
|
||||
// ErrFolderNotEmpty is returned when attempting to delete a folder that still has items or child folders.
|
||||
ErrFolderNotEmpty = errors.New("album: folder is not empty")
|
||||
// ErrInvalidFolder is returned when a folder name or parent hierarchy is invalid.
|
||||
ErrInvalidFolder = errors.New("album: invalid folder")
|
||||
// ErrInvalidUploadToken is returned when an upload token is missing, unknown, expired, or already used.
|
||||
ErrInvalidUploadToken = errors.New("album: upload token is invalid, expired, or already used")
|
||||
)
|
||||
|
||||
var (
|
||||
extPattern = regexp.MustCompile(`^[a-z0-9]{1,10}$`)
|
||||
disallowedSniffed = []string{
|
||||
"text/html",
|
||||
"application/xhtml+xml",
|
||||
"image/svg+xml",
|
||||
"application/javascript",
|
||||
"text/javascript",
|
||||
"application/ecmascript",
|
||||
"text/xml",
|
||||
"application/xml",
|
||||
}
|
||||
inlineImageMIMEs = []string{
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
"image/avif",
|
||||
}
|
||||
)
|
||||
|
||||
// Service orchestrates Media Library uploads, folder management, queries,
|
||||
// signed upload tokens, and post-commit blob deletion.
|
||||
type Service struct {
|
||||
cfg *compass.Config
|
||||
}
|
||||
|
||||
// NewService constructs a media library Service backed by cfg.
|
||||
// cfg may be nil (defaults apply).
|
||||
func NewService(cfg *compass.Config) *Service {
|
||||
return &Service{cfg: cfg}
|
||||
}
|
||||
|
||||
// Config returns the compass.Config associated with the service (may be nil).
|
||||
func (s *Service) Config() *compass.Config {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s.cfg
|
||||
}
|
||||
|
||||
// UploadInput describes a single file upload to the media library.
|
||||
type UploadInput struct {
|
||||
FileName string
|
||||
Body io.Reader
|
||||
FolderID *uint
|
||||
Alt string
|
||||
Title string
|
||||
Caption string
|
||||
UploadedBy *uint
|
||||
ImageOnly bool
|
||||
// MaxBytes caps this upload; 0 uses MaxBytes(cfg).
|
||||
MaxBytes int64
|
||||
}
|
||||
|
||||
// Upload validates, stores, generates synchronous WebP variants for raster images,
|
||||
// and indexes a media file in summer_media_items.
|
||||
//
|
||||
// It never deduplicates on sha256: every upload produces a fresh Item and
|
||||
// independent blob key under media/<short-id>/<slug>.<ext>. On any error,
|
||||
// all written blobs (original and variants) are deleted before returning.
|
||||
func (s *Service) Upload(ctx context.Context, db *gorm.DB, bucket *blob.Bucket, in UploadInput) (*Item, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
if bucket == nil {
|
||||
return nil, fmt.Errorf("album: bucket is nil")
|
||||
}
|
||||
if in.Body == nil {
|
||||
return nil, fmt.Errorf("album: upload body is nil")
|
||||
}
|
||||
maxBytes := in.MaxBytes
|
||||
if maxBytes <= 0 {
|
||||
maxBytes = MaxBytes(s.Config())
|
||||
}
|
||||
|
||||
if in.FolderID != nil {
|
||||
var count int64
|
||||
if err := db.WithContext(ctx).Model(&Folder{}).Where("id = ?", *in.FolderID).Count(&count).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: check folder: %w", err)
|
||||
}
|
||||
if count == 0 {
|
||||
return nil, ErrFolderNotFound
|
||||
}
|
||||
}
|
||||
|
||||
name := clientBaseName(in.FileName)
|
||||
ext := strings.ToLower(strings.TrimPrefix(path.Ext(name), "."))
|
||||
allowedExts := attach.DefaultFileExtensions
|
||||
if in.ImageOnly {
|
||||
allowedExts = attach.DefaultImageExtensions
|
||||
}
|
||||
if !extPattern.MatchString(ext) || !slices.Contains(allowedExts, ext) {
|
||||
return nil, fmt.Errorf("%w: %q", ErrFileType, ext)
|
||||
}
|
||||
|
||||
br := bufio.NewReaderSize(in.Body, sniffBytes)
|
||||
head, err := br.Peek(sniffBytes)
|
||||
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, bufio.ErrBufferFull) {
|
||||
return nil, fmt.Errorf("album: read upload: %w", err)
|
||||
}
|
||||
if int64(len(head)) > maxBytes {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
|
||||
sniffed := baseMediaType(http.DetectContentType(head))
|
||||
if slices.Contains(disallowedSniffed, sniffed) {
|
||||
return nil, fmt.Errorf("%w: %s", ErrFileType, sniffed)
|
||||
}
|
||||
|
||||
isRasterExt := slices.Contains(attach.DefaultImageExtensions, ext)
|
||||
isRasterSniff := slices.Contains(attach.AllowedImageMIMEs, sniffed)
|
||||
isRaster := in.ImageOnly || isRasterExt || isRasterSniff
|
||||
if isRaster {
|
||||
if !attach.IsAllowedImage(head) {
|
||||
return nil, ErrNotImage
|
||||
}
|
||||
}
|
||||
|
||||
contentType := sniffed
|
||||
if contentType == "application/octet-stream" {
|
||||
if byExt := baseMediaType(mime.TypeByExtension("." + ext)); byExt != "" && !slices.Contains(disallowedSniffed, byExt) {
|
||||
contentType = byExt
|
||||
}
|
||||
}
|
||||
if slices.Contains(disallowedSniffed, contentType) {
|
||||
return nil, fmt.Errorf("%w: %s", ErrFileType, contentType)
|
||||
}
|
||||
|
||||
diskExt := attach.DiskExtension(sniffed, ext)
|
||||
shortID, err := generateUniqueShortID(ctx, db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
baseNameNoExt := strings.TrimSuffix(name, path.Ext(name))
|
||||
slug := SanitizeSlug(baseNameNoExt)
|
||||
blobKey := fmt.Sprintf("%s/%s/%s.%s", BlobKeyPrefix, shortID, slug, diskExt)
|
||||
|
||||
hasher := sha256.New()
|
||||
var imgBuf *bytes.Buffer
|
||||
if isRaster {
|
||||
imgBuf = &bytes.Buffer{}
|
||||
}
|
||||
|
||||
size, err := streamUploadBlob(ctx, bucket, blobKey, br, contentType, maxBytes, hasher, imgBuf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sumHex := hex.EncodeToString(hasher.Sum(nil))
|
||||
|
||||
writtenKeys := []string{blobKey}
|
||||
cleanup := func() {
|
||||
_ = DeleteBlobs(context.WithoutCancel(ctx), bucket, writtenKeys)
|
||||
}
|
||||
|
||||
var widthPtr, heightPtr *int
|
||||
variants := Variants{}
|
||||
|
||||
if isRaster {
|
||||
img, format, decErr := image.Decode(bytes.NewReader(imgBuf.Bytes()))
|
||||
if decErr != nil {
|
||||
cleanup()
|
||||
return nil, ErrNotImage
|
||||
}
|
||||
w := img.Bounds().Dx()
|
||||
h := img.Bounds().Dy()
|
||||
if w <= 0 || h <= 0 || int64(w)*int64(h) > attach.MaxImagePixels {
|
||||
cleanup()
|
||||
return nil, ErrNotImage
|
||||
}
|
||||
widthPtr = &w
|
||||
heightPtr = &h
|
||||
|
||||
genVariants, variantKeys, vErr := GenerateWebPVariants(ctx, s.Config(), bucket, shortID, slug, img, format)
|
||||
if vErr != nil {
|
||||
cleanup()
|
||||
return nil, vErr
|
||||
}
|
||||
variants = Variants(genVariants)
|
||||
writtenKeys = append(writtenKeys, variantKeys...)
|
||||
}
|
||||
|
||||
item := &Item{
|
||||
ShortID: shortID,
|
||||
FolderID: in.FolderID,
|
||||
BlobKey: blobKey,
|
||||
Slug: slug,
|
||||
FileName: name,
|
||||
ContentType: contentType,
|
||||
FileSize: size,
|
||||
Width: widthPtr,
|
||||
Height: heightPtr,
|
||||
SHA256: sumHex,
|
||||
Alt: strings.TrimSpace(in.Alt),
|
||||
Title: strings.TrimSpace(in.Title),
|
||||
Caption: strings.TrimSpace(in.Caption),
|
||||
Variants: variants,
|
||||
UploadedBy: in.UploadedBy,
|
||||
}
|
||||
|
||||
if err := db.WithContext(ctx).Create(item).Error; err != nil {
|
||||
cleanup()
|
||||
return nil, fmt.Errorf("album: insert item: %w", err)
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func streamUploadBlob(
|
||||
ctx context.Context,
|
||||
bucket *blob.Bucket,
|
||||
key string,
|
||||
r io.Reader,
|
||||
contentType string,
|
||||
limit int64,
|
||||
hasher io.Writer,
|
||||
capture *bytes.Buffer,
|
||||
) (int64, error) {
|
||||
writeCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
w, err := bucket.NewWriter(writeCtx, key, attach.UploadWriterOptions(contentType))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("album: blob writer: %w", err)
|
||||
}
|
||||
writers := []io.Writer{w, hasher}
|
||||
if capture != nil {
|
||||
writers = append(writers, capture)
|
||||
}
|
||||
dst := io.MultiWriter(writers...)
|
||||
src := r
|
||||
if limit > 0 {
|
||||
src = io.LimitReader(r, limit+1)
|
||||
}
|
||||
n, copyErr := io.Copy(dst, src)
|
||||
if copyErr == nil && limit > 0 && n > limit {
|
||||
copyErr = ErrTooLarge
|
||||
}
|
||||
if copyErr != nil {
|
||||
cancel()
|
||||
_ = w.Close()
|
||||
_ = DeleteBlobs(context.WithoutCancel(ctx), bucket, []string{key})
|
||||
if errors.Is(copyErr, ErrTooLarge) {
|
||||
return 0, ErrTooLarge
|
||||
}
|
||||
return 0, fmt.Errorf("album: write upload: %w", copyErr)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
_ = DeleteBlobs(context.WithoutCancel(ctx), bucket, []string{key})
|
||||
return 0, fmt.Errorf("album: close upload: %w", err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// EnsureFolder idempotently finds or creates a virtual folder by (parentID, slug).
|
||||
func (s *Service) EnsureFolder(ctx context.Context, db *gorm.DB, slug, name string, parentID *uint) (*Folder, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
cleanSlug := SanitizeSlug(slug)
|
||||
cleanName := strings.TrimSpace(name)
|
||||
if cleanName == "" {
|
||||
cleanName = cleanSlug
|
||||
}
|
||||
|
||||
var existing Folder
|
||||
q := db.WithContext(ctx)
|
||||
if parentID == nil {
|
||||
q = q.Where("parent_id IS NULL AND slug = ?", cleanSlug)
|
||||
} else {
|
||||
q = q.Where("parent_id = ? AND slug = ?", *parentID, cleanSlug)
|
||||
}
|
||||
if err := q.First(&existing).Error; err == nil {
|
||||
return &existing, nil
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("album: lookup folder %q: %w", cleanSlug, err)
|
||||
}
|
||||
|
||||
f := &Folder{
|
||||
ParentID: parentID,
|
||||
Name: cleanName,
|
||||
Slug: cleanSlug,
|
||||
}
|
||||
if err := db.WithContext(ctx).Create(f).Error; err != nil {
|
||||
// Handle concurrent creation race by re-reading.
|
||||
if err2 := q.First(&existing).Error; err2 == nil {
|
||||
return &existing, nil
|
||||
}
|
||||
return nil, fmt.Errorf("album: create folder %q: %w", cleanSlug, err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// ListFolders returns all virtual folders ordered by parent, name, and id.
|
||||
func (s *Service) ListFolders(ctx context.Context, db *gorm.DB) ([]Folder, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
var folders []Folder
|
||||
if err := db.WithContext(ctx).Order("parent_id NULLS FIRST, name ASC, id ASC").Find(&folders).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: list folders: %w", err)
|
||||
}
|
||||
return folders, nil
|
||||
}
|
||||
|
||||
// CreateFolder creates a new virtual folder under parentID (nil for root).
|
||||
func (s *Service) CreateFolder(ctx context.Context, db *gorm.DB, name string, parentID *uint) (*Folder, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
cleanName := strings.TrimSpace(name)
|
||||
if cleanName == "" {
|
||||
return nil, fmt.Errorf("%w: name is required", ErrInvalidFolder)
|
||||
}
|
||||
if parentID != nil {
|
||||
var count int64
|
||||
if err := db.WithContext(ctx).Model(&Folder{}).Where("id = ?", *parentID).Count(&count).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: check parent folder: %w", err)
|
||||
}
|
||||
if count == 0 {
|
||||
return nil, ErrFolderNotFound
|
||||
}
|
||||
}
|
||||
f := &Folder{
|
||||
ParentID: parentID,
|
||||
Name: cleanName,
|
||||
Slug: SanitizeSlug(cleanName),
|
||||
}
|
||||
if err := db.WithContext(ctx).Create(f).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: create folder: %w", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// UpdateFolder renames or moves an existing virtual folder.
|
||||
func (s *Service) UpdateFolder(ctx context.Context, db *gorm.DB, id uint, name string, parentID *uint, setParent bool) (*Folder, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
var f Folder
|
||||
if err := db.WithContext(ctx).First(&f, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrFolderNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("album: load folder: %w", err)
|
||||
}
|
||||
|
||||
updates := map[string]any{}
|
||||
if trimmed := strings.TrimSpace(name); trimmed != "" {
|
||||
updates["name"] = trimmed
|
||||
updates["slug"] = SanitizeSlug(trimmed)
|
||||
}
|
||||
if setParent {
|
||||
if parentID != nil {
|
||||
if *parentID == id {
|
||||
return nil, fmt.Errorf("%w: folder cannot be its own parent", ErrInvalidFolder)
|
||||
}
|
||||
// Walk ancestors to prevent cycles.
|
||||
cur := *parentID
|
||||
for depth := 0; depth < 64; depth++ {
|
||||
var anc Folder
|
||||
if err := db.WithContext(ctx).First(&anc, cur).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrFolderNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("album: check ancestor folder: %w", err)
|
||||
}
|
||||
if anc.ParentID == nil {
|
||||
break
|
||||
}
|
||||
if *anc.ParentID == id {
|
||||
return nil, fmt.Errorf("%w: folder cycle detected", ErrInvalidFolder)
|
||||
}
|
||||
cur = *anc.ParentID
|
||||
}
|
||||
}
|
||||
updates["parent_id"] = parentID
|
||||
}
|
||||
if len(updates) == 0 {
|
||||
return &f, nil
|
||||
}
|
||||
if err := db.WithContext(ctx).Model(&f).Updates(updates).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: update folder: %w", err)
|
||||
}
|
||||
if err := db.WithContext(ctx).First(&f, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: reload folder: %w", err)
|
||||
}
|
||||
return &f, nil
|
||||
}
|
||||
|
||||
// DeleteFolder deletes a virtual folder if it contains no items and no child folders.
|
||||
func (s *Service) DeleteFolder(ctx context.Context, db *gorm.DB, id uint) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return fmt.Errorf("album: db is nil")
|
||||
}
|
||||
var f Folder
|
||||
if err := db.WithContext(ctx).First(&f, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrFolderNotFound
|
||||
}
|
||||
return fmt.Errorf("album: load folder: %w", err)
|
||||
}
|
||||
var childCount int64
|
||||
if err := db.WithContext(ctx).Model(&Folder{}).Where("parent_id = ?", id).Count(&childCount).Error; err != nil {
|
||||
return fmt.Errorf("album: count child folders: %w", err)
|
||||
}
|
||||
if childCount > 0 {
|
||||
return ErrFolderNotEmpty
|
||||
}
|
||||
var itemCount int64
|
||||
if err := db.WithContext(ctx).Model(&Item{}).Where("folder_id = ?", id).Count(&itemCount).Error; err != nil {
|
||||
return fmt.Errorf("album: count folder items: %w", err)
|
||||
}
|
||||
if itemCount > 0 {
|
||||
return ErrFolderNotEmpty
|
||||
}
|
||||
if err := db.WithContext(ctx).Delete(&Folder{}, id).Error; err != nil {
|
||||
return fmt.Errorf("album: delete folder: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListFilter filters and paginates ListItems queries.
|
||||
type ListFilter struct {
|
||||
FolderID *uint
|
||||
RootOnly bool
|
||||
Query string
|
||||
// Type filters by "image" or "file" (empty returns all).
|
||||
Type string
|
||||
SHA256 string
|
||||
Page int
|
||||
PerPage int
|
||||
}
|
||||
|
||||
// ListItems returns a paginated slice of media items and the total matching count.
|
||||
func (s *Service) ListItems(ctx context.Context, db *gorm.DB, filter ListFilter) ([]Item, int64, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, 0, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
page := filter.Page
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
perPage := filter.PerPage
|
||||
if perPage < 1 {
|
||||
perPage = 24
|
||||
}
|
||||
if perPage > 100 {
|
||||
perPage = 100
|
||||
}
|
||||
|
||||
q := db.WithContext(ctx).Model(&Item{})
|
||||
if filter.FolderID != nil {
|
||||
q = q.Where("folder_id = ?", *filter.FolderID)
|
||||
} else if filter.RootOnly {
|
||||
q = q.Where("folder_id IS NULL")
|
||||
}
|
||||
if term := strings.TrimSpace(filter.Query); term != "" {
|
||||
like := "%" + term + "%"
|
||||
q = q.Where("file_name ILIKE ? OR title ILIKE ? OR alt ILIKE ? OR slug ILIKE ?", like, like, like, like)
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(filter.Type)) {
|
||||
case "image":
|
||||
q = q.Where("content_type IN ?", inlineImageMIMEs)
|
||||
case "file":
|
||||
q = q.Where("content_type NOT IN ?", inlineImageMIMEs)
|
||||
}
|
||||
if sha := strings.ToLower(strings.TrimSpace(filter.SHA256)); sha != "" {
|
||||
q = q.Where("sha256 = ?", sha)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("album: count items: %w", err)
|
||||
}
|
||||
var items []Item
|
||||
if err := q.Order("created_at DESC, id DESC").Offset((page - 1) * perPage).Limit(perPage).Find(&items).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("album: list items: %w", err)
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
// GetItem returns a single media item by primary key ID.
|
||||
func (s *Service) GetItem(ctx context.Context, db *gorm.DB, id uint) (*Item, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
var item Item
|
||||
if err := db.WithContext(ctx).First(&item, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("album: get item: %w", err)
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
// GetItemsByShortIDs loads all matching media items in a single batched query,
|
||||
// keyed by short_id. Used for render-time inline srcset enrichment without N+1 queries.
|
||||
func (s *Service) GetItemsByShortIDs(ctx context.Context, db *gorm.DB, shortIDs []string) (map[string]Item, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
out := make(map[string]Item)
|
||||
if len(shortIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
uniq := make([]string, 0, len(shortIDs))
|
||||
seen := make(map[string]struct{}, len(shortIDs))
|
||||
for _, id := range shortIDs {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; !ok {
|
||||
seen[id] = struct{}{}
|
||||
uniq = append(uniq, id)
|
||||
}
|
||||
}
|
||||
if len(uniq) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
var items []Item
|
||||
if err := db.WithContext(ctx).Where("short_id IN ?", uniq).Find(&items).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: get items by short_ids: %w", err)
|
||||
}
|
||||
for _, item := range items {
|
||||
out[item.ShortID] = item
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UpdatePatch describes mutable metadata fields on an Item.
|
||||
// short_id, slug, and blob_key are immutable and never modified.
|
||||
type UpdatePatch struct {
|
||||
Alt *string
|
||||
Title *string
|
||||
Caption *string
|
||||
FolderID *uint
|
||||
ClearFolder bool
|
||||
}
|
||||
|
||||
// UpdateItem updates mutable metadata (alt, title, caption, folder_id) on an Item.
|
||||
func (s *Service) UpdateItem(ctx context.Context, db *gorm.DB, id uint, patch UpdatePatch) (*Item, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
var item Item
|
||||
if err := db.WithContext(ctx).First(&item, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("album: load item: %w", err)
|
||||
}
|
||||
|
||||
updates := map[string]any{}
|
||||
if patch.Alt != nil {
|
||||
updates["alt"] = strings.TrimSpace(*patch.Alt)
|
||||
}
|
||||
if patch.Title != nil {
|
||||
updates["title"] = strings.TrimSpace(*patch.Title)
|
||||
}
|
||||
if patch.Caption != nil {
|
||||
updates["caption"] = strings.TrimSpace(*patch.Caption)
|
||||
}
|
||||
if patch.ClearFolder {
|
||||
updates["folder_id"] = nil
|
||||
} else if patch.FolderID != nil {
|
||||
var count int64
|
||||
if err := db.WithContext(ctx).Model(&Folder{}).Where("id = ?", *patch.FolderID).Count(&count).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: check target folder: %w", err)
|
||||
}
|
||||
if count == 0 {
|
||||
return nil, ErrFolderNotFound
|
||||
}
|
||||
updates["folder_id"] = *patch.FolderID
|
||||
}
|
||||
|
||||
if len(updates) > 0 {
|
||||
if err := db.WithContext(ctx).Model(&item).Updates(updates).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: update item: %w", err)
|
||||
}
|
||||
if err := db.WithContext(ctx).First(&item, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: reload item: %w", err)
|
||||
}
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
// DeleteItemInTx deletes the media item row inside tx and returns the blob keys
|
||||
// (original + variants) that the caller should delete after commit via DeleteBlobs
|
||||
// (for example, inside lagoon.AfterCommit). Rolled-back transactions never touch blobs.
|
||||
func (s *Service) DeleteItemInTx(ctx context.Context, tx *gorm.DB, id uint) ([]string, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if tx == nil {
|
||||
return nil, fmt.Errorf("album: tx is nil")
|
||||
}
|
||||
var item Item
|
||||
if err := tx.WithContext(ctx).First(&item, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("album: load item for delete: %w", err)
|
||||
}
|
||||
if err := tx.WithContext(ctx).Delete(&Item{}, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: delete item: %w", err)
|
||||
}
|
||||
return item.AllBlobKeys(), nil
|
||||
}
|
||||
|
||||
// DeleteItem deletes an item inside a database transaction and removes its
|
||||
// original and variant blobs only after the transaction commits.
|
||||
func (s *Service) DeleteItem(ctx context.Context, db *gorm.DB, bucket *blob.Bucket, id uint) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return fmt.Errorf("album: db is nil")
|
||||
}
|
||||
var keys []string
|
||||
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var txErr error
|
||||
keys, txErr = s.DeleteItemInTx(ctx, tx, id)
|
||||
return txErr
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if bucket != nil && len(keys) > 0 {
|
||||
return DeleteBlobs(ctx, bucket, keys)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteBlobs removes every key in keys from bucket, ignoring NotFound errors.
|
||||
func DeleteBlobs(ctx context.Context, bucket *blob.Bucket, keys []string) error {
|
||||
if bucket == nil || len(keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
var errs []error
|
||||
for _, key := range keys {
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
if err := bucket.Delete(ctx, key); err != nil && gcerrors.Code(err) != gcerrors.NotFound {
|
||||
errs = append(errs, fmt.Errorf("album: delete blob %q: %w", key, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// GenerateShortID returns a cryptographically random 12-character lowercase
|
||||
// alphanumeric identifier suitable for immutable media URLs.
|
||||
func GenerateShortID() (string, error) {
|
||||
maxIdx := big.NewInt(int64(len(shortIDAlphabet)))
|
||||
var b strings.Builder
|
||||
b.Grow(shortIDLength)
|
||||
for i := 0; i < shortIDLength; i++ {
|
||||
n, err := rand.Int(rand.Reader, maxIdx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("album: generate short_id: %w", err)
|
||||
}
|
||||
b.WriteByte(shortIDAlphabet[n.Int64()])
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func generateUniqueShortID(ctx context.Context, db *gorm.DB) (string, error) {
|
||||
for attempt := 0; attempt < 5; attempt++ {
|
||||
id, err := GenerateShortID()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if db == nil {
|
||||
return id, nil
|
||||
}
|
||||
var count int64
|
||||
if err := db.WithContext(ctx).Model(&Item{}).Where("short_id = ?", id).Count(&count).Error; err != nil {
|
||||
return "", fmt.Errorf("album: check short_id collision: %w", err)
|
||||
}
|
||||
if count == 0 {
|
||||
return id, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("album: failed to generate unique short_id")
|
||||
}
|
||||
|
||||
// SanitizeSlug converts raw into a URL-safe lowercase ASCII slug ([a-z0-9-],
|
||||
// max 80 chars, no leading/trailing/repeated hyphens). Falls back to "file"
|
||||
// when no alphanumeric characters remain.
|
||||
func SanitizeSlug(raw string) string {
|
||||
raw = strings.ToLower(strings.TrimSpace(raw))
|
||||
var b strings.Builder
|
||||
lastDash := false
|
||||
for _, r := range raw {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
|
||||
b.WriteRune(r)
|
||||
lastDash = false
|
||||
} else if r == '-' || r == '_' || r == '.' || unicode.IsSpace(r) {
|
||||
if b.Len() > 0 && !lastDash {
|
||||
b.WriteByte('-')
|
||||
lastDash = true
|
||||
}
|
||||
}
|
||||
if b.Len() >= maxSlugLength {
|
||||
break
|
||||
}
|
||||
}
|
||||
out := strings.Trim(b.String(), "-")
|
||||
if out == "" {
|
||||
return "file"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func clientBaseName(name string) string {
|
||||
name = strings.ReplaceAll(name, `\`, "/")
|
||||
if i := strings.LastIndex(name, "/"); i >= 0 {
|
||||
name = name[i+1:]
|
||||
}
|
||||
return strings.TrimSpace(name)
|
||||
}
|
||||
|
||||
func baseMediaType(ct string) string {
|
||||
if ct == "" {
|
||||
return ""
|
||||
}
|
||||
mt, _, err := mime.ParseMediaType(ct)
|
||||
if err != nil {
|
||||
return strings.ToLower(strings.TrimSpace(strings.SplitN(ct, ";", 2)[0]))
|
||||
}
|
||||
return strings.ToLower(mt)
|
||||
}
|
||||
156
modules/album/tokens.go
Normal file
156
modules/album/tokens.go
Normal file
@@ -0,0 +1,156 @@
|
||||
package album
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// PrepareUploadInput describes a request to mint a single-use upload token.
|
||||
type PrepareUploadInput struct {
|
||||
CreatedBy uint
|
||||
FolderID *uint
|
||||
ExpectedFilename string
|
||||
ExpectedContentType string
|
||||
// MaxBytes caps the upload for this token; 0 defaults to MaxBytes(cfg).
|
||||
// Values larger than MaxBytes(cfg) are rejected with ErrTooLarge.
|
||||
MaxBytes int64
|
||||
// TTL overrides DefaultUploadTokenTTL (5 minutes) when positive.
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
// PreparedUpload is returned by PrepareUpload and contains the opaque one-time
|
||||
// token (never stored in plaintext in Postgres) and its constraints.
|
||||
type PreparedUpload struct {
|
||||
Token string `json:"token"`
|
||||
TokenID uint `json:"token_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
MaxBytes int64 `json:"max_bytes"`
|
||||
ExpectedFilename string `json:"expected_filename"`
|
||||
ExpectedContentType string `json:"expected_content_type,omitempty"`
|
||||
FolderID *uint `json:"folder_id,omitempty"`
|
||||
}
|
||||
|
||||
// PrepareUpload validates the expected filename/type/size constraints, generates
|
||||
// a 32-byte cryptographically random base64url token, stores only its SHA-256
|
||||
// hex hash in summer_media_upload_tokens, and returns the opaque token.
|
||||
func (s *Service) PrepareUpload(ctx context.Context, db *gorm.DB, in PrepareUploadInput) (*PreparedUpload, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
|
||||
name := clientBaseName(in.ExpectedFilename)
|
||||
ext := strings.ToLower(strings.TrimPrefix(path.Ext(name), "."))
|
||||
if !extPattern.MatchString(ext) || !slices.Contains(attach.DefaultFileExtensions, ext) {
|
||||
return nil, fmt.Errorf("%w: %q", ErrFileType, ext)
|
||||
}
|
||||
|
||||
expectedCT := baseMediaType(in.ExpectedContentType)
|
||||
if expectedCT != "" && slices.Contains(disallowedSniffed, expectedCT) {
|
||||
return nil, fmt.Errorf("%w: %s", ErrFileType, expectedCT)
|
||||
}
|
||||
|
||||
cfgMax := MaxBytes(s.Config())
|
||||
maxBytes := in.MaxBytes
|
||||
if maxBytes <= 0 {
|
||||
maxBytes = cfgMax
|
||||
}
|
||||
if maxBytes > cfgMax {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
|
||||
if in.FolderID != nil {
|
||||
var count int64
|
||||
if err := db.WithContext(ctx).Model(&Folder{}).Where("id = ?", *in.FolderID).Count(&count).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: check folder: %w", err)
|
||||
}
|
||||
if count == 0 {
|
||||
return nil, ErrFolderNotFound
|
||||
}
|
||||
}
|
||||
|
||||
ttl := in.TTL
|
||||
if ttl <= 0 {
|
||||
ttl = DefaultUploadTokenTTL
|
||||
}
|
||||
|
||||
rawBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(rawBytes); err != nil {
|
||||
return nil, fmt.Errorf("album: generate upload token: %w", err)
|
||||
}
|
||||
rawToken := base64.RawURLEncoding.EncodeToString(rawBytes)
|
||||
expiresAt := time.Now().UTC().Add(ttl)
|
||||
|
||||
row := &UploadToken{
|
||||
TokenHash: hashUploadToken(rawToken),
|
||||
CreatedBy: in.CreatedBy,
|
||||
FolderID: in.FolderID,
|
||||
ExpectedFilename: name,
|
||||
ExpectedContentType: expectedCT,
|
||||
MaxBytes: maxBytes,
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
if err := db.WithContext(ctx).Create(row).Error; err != nil {
|
||||
return nil, fmt.Errorf("album: insert upload token: %w", err)
|
||||
}
|
||||
|
||||
return &PreparedUpload{
|
||||
Token: rawToken,
|
||||
TokenID: row.ID,
|
||||
ExpiresAt: row.ExpiresAt,
|
||||
MaxBytes: row.MaxBytes,
|
||||
ExpectedFilename: row.ExpectedFilename,
|
||||
ExpectedContentType: row.ExpectedContentType,
|
||||
FolderID: row.FolderID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ConsumeUploadToken atomically marks a matching unused, unexpired upload token
|
||||
// as used (used_at = NOW()) in a single SQL UPDATE ... RETURNING statement so
|
||||
// concurrent or replayed requests cannot consume the same token twice.
|
||||
func (s *Service) ConsumeUploadToken(ctx context.Context, db *gorm.DB, rawToken string) (*UploadToken, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("album: db is nil")
|
||||
}
|
||||
rawToken = strings.TrimSpace(rawToken)
|
||||
if rawToken == "" {
|
||||
return nil, ErrInvalidUploadToken
|
||||
}
|
||||
|
||||
var tok UploadToken
|
||||
res := db.WithContext(ctx).Raw(
|
||||
`UPDATE `+UploadTokensTable+`
|
||||
SET used_at = NOW()
|
||||
WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW()
|
||||
RETURNING id, token_hash, created_by, folder_id, expected_filename, expected_content_type, max_bytes, expires_at, used_at, created_at`,
|
||||
hashUploadToken(rawToken),
|
||||
).Scan(&tok)
|
||||
if res.Error != nil {
|
||||
return nil, fmt.Errorf("album: consume upload token: %w", res.Error)
|
||||
}
|
||||
if res.RowsAffected == 0 || tok.ID == 0 {
|
||||
return nil, ErrInvalidUploadToken
|
||||
}
|
||||
return &tok, nil
|
||||
}
|
||||
|
||||
func hashUploadToken(raw string) string {
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
130
modules/album/variants.go
Normal file
130
modules/album/variants.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package album
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/gif"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach/webp"
|
||||
"gocloud.dev/blob"
|
||||
"golang.org/x/image/draw"
|
||||
_ "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
// VariantWidths are the responsive WebP widths generated synchronously on
|
||||
// raster image uploads. Uploads never upscale past the original width.
|
||||
var VariantWidths = []int{480, 960, 1600}
|
||||
|
||||
// GenerateWebPVariants resizes img to each breakpoint in VariantWidths smaller
|
||||
// than its original width (and, when no smaller breakpoint applies and the
|
||||
// original is not already WebP, encodes a single WebP at the original width),
|
||||
// writes each variant to bucket at media/<short-id>/<slug>-<width>w.webp, and
|
||||
// returns the Variant records and written blob keys.
|
||||
//
|
||||
// If any encode or write fails, every variant written so far is deleted before
|
||||
// returning the error.
|
||||
func GenerateWebPVariants(
|
||||
ctx context.Context,
|
||||
cfg *compass.Config,
|
||||
bucket *blob.Bucket,
|
||||
shortID, slug string,
|
||||
img image.Image,
|
||||
origFormat string,
|
||||
) ([]Variant, []string, error) {
|
||||
if bucket == nil {
|
||||
return nil, nil, fmt.Errorf("album: bucket is nil")
|
||||
}
|
||||
if img == nil {
|
||||
return nil, nil, fmt.Errorf("album: image is nil")
|
||||
}
|
||||
bounds := img.Bounds()
|
||||
origW := bounds.Dx()
|
||||
origH := bounds.Dy()
|
||||
if origW <= 0 || origH <= 0 {
|
||||
return nil, nil, fmt.Errorf("album: invalid image dimensions %dx%d", origW, origH)
|
||||
}
|
||||
|
||||
targets := make([]int, 0, len(VariantWidths))
|
||||
for _, w := range VariantWidths {
|
||||
if w < origW {
|
||||
targets = append(targets, w)
|
||||
}
|
||||
}
|
||||
if len(targets) == 0 && origFormat != webp.Format {
|
||||
targets = append(targets, origW)
|
||||
}
|
||||
if len(targets) == 0 {
|
||||
return []Variant{}, nil, nil
|
||||
}
|
||||
|
||||
variants := make([]Variant, 0, len(targets))
|
||||
writtenKeys := make([]string, 0, len(targets))
|
||||
|
||||
cleanup := func() {
|
||||
_ = DeleteBlobs(context.WithoutCancel(ctx), bucket, writtenKeys)
|
||||
}
|
||||
|
||||
for _, targetW := range targets {
|
||||
var dst image.Image
|
||||
var targetH int
|
||||
if targetW == origW {
|
||||
dst = img
|
||||
targetH = origH
|
||||
} else {
|
||||
targetH = max(1, int(math.Round(float64(origH)*float64(targetW)/float64(origW))))
|
||||
rgba := image.NewRGBA(image.Rect(0, 0, targetW, targetH))
|
||||
draw.CatmullRom.Scale(rgba, rgba.Bounds(), img, bounds, draw.Over, nil)
|
||||
dst = rgba
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := webp.Encode(&buf, dst); err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("album: encode %dw webp variant: %w", targetW, err)
|
||||
}
|
||||
|
||||
key := fmt.Sprintf("%s/%s/%s-%sw.webp", BlobKeyPrefix, shortID, slug, strconv.Itoa(targetW))
|
||||
if err := writeBytes(ctx, bucket, key, buf.Bytes(), webp.ContentType); err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("album: write %dw webp variant: %w", targetW, err)
|
||||
}
|
||||
writtenKeys = append(writtenKeys, key)
|
||||
variants = append(variants, Variant{
|
||||
Width: targetW,
|
||||
Height: targetH,
|
||||
Key: key,
|
||||
URL: blobKeyPublicURL(cfg, key),
|
||||
Size: int64(buf.Len()),
|
||||
ContentType: webp.ContentType,
|
||||
})
|
||||
}
|
||||
|
||||
return variants, writtenKeys, nil
|
||||
}
|
||||
|
||||
func writeBytes(ctx context.Context, bucket *blob.Bucket, key string, data []byte, contentType string) error {
|
||||
writeCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
w, err := bucket.NewWriter(writeCtx, key, &blob.WriterOptions{ContentType: contentType})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.Write(data); err != nil {
|
||||
cancel()
|
||||
_ = w.Close()
|
||||
_ = DeleteBlobs(context.WithoutCancel(ctx), bucket, []string{key})
|
||||
return err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
_ = DeleteBlobs(context.WithoutCancel(ctx), bucket, []string{key})
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/album"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
@@ -226,6 +227,7 @@ func migrationSets(gdb *gorm.DB, plugins []party.Plugin) ([]migrationSet, error)
|
||||
sets := []migrationSet{
|
||||
{"summercms.attach", "system_files", attach.Migrations},
|
||||
{"summercms.postcard", "mail", postcard.Migrations},
|
||||
{"summercms.album", "media", album.Migrations},
|
||||
{"summercms.cabana", "backend admin", BackendAdminMigrations},
|
||||
{DeferredHistoryID, "deferred bindings", DeferredBindingMigrations},
|
||||
{QueueHistoryID, "queue", QueueMigrations(sqlDB)},
|
||||
|
||||
120
modules/surf/media.go
Normal file
120
modules/surf/media.go
Normal file
@@ -0,0 +1,120 @@
|
||||
package surf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/album"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gocloud.dev/blob"
|
||||
)
|
||||
|
||||
// mediaPluginID owns the framework media routes in the route table.
|
||||
const mediaPluginID = "summercms.album"
|
||||
|
||||
// mountMedia installs *album.Service on app and mounts the public zero-DB-hit
|
||||
// media static route (GET <prefix>/{short_id}/{file}) when album.ServeEnabled
|
||||
// is true, plus the raw single-use signed upload routes
|
||||
// (PUT and POST <prefix>/upload/{token}) behind an inline rate limit when
|
||||
// media serving, admin backend, or MCP is enabled.
|
||||
//
|
||||
// When static serving is enabled, the route owns the prefix against plugin
|
||||
// route collisions, matching mountUploads.
|
||||
func mountMedia(r *Router, app *backpack.App) error {
|
||||
if r == nil || app == nil {
|
||||
return nil
|
||||
}
|
||||
svc, err := album.Install(app)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if app.Config == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
prefix, err := mediaPrefix(app.Config.String(album.ConfigPublicPathPrefix))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
serveStatic := album.ServeEnabled(app.Config)
|
||||
// When media.serve is not explicitly set and only inherited from
|
||||
// storage.uploads.serve, do not collide if the app explicitly configured
|
||||
// storage.uploads.public_path_prefix to the same path (e.g. /media).
|
||||
if serveStatic && !app.Config.Has(album.ConfigServe) && app.Config.Bool("storage.uploads.serve") {
|
||||
if upPrefix, uErr := uploadsPrefix(app.Config.String("storage.uploads.public_path_prefix")); uErr == nil {
|
||||
if upPrefix == prefix || strings.HasPrefix(upPrefix, prefix+"/") || strings.HasPrefix(prefix, upPrefix+"/") {
|
||||
serveStatic = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mountUpload := serveStatic ||
|
||||
app.Config.Bool("mcp.enabled") ||
|
||||
app.Config.Bool("backend.enabled") ||
|
||||
app.Config.Has(album.ConfigServe) ||
|
||||
app.Config.Has(album.ConfigPublicPathPrefix) ||
|
||||
app.Config.Has(album.ConfigMaxBytes)
|
||||
|
||||
if !serveStatic && !mountUpload {
|
||||
return nil
|
||||
}
|
||||
|
||||
if serveStatic {
|
||||
for _, rt := range r.routes {
|
||||
if rt.path == prefix || strings.HasPrefix(rt.path, prefix+"/") {
|
||||
return fmt.Errorf("surf: route %s %s (plugin %q) is under the media prefix %s %s, which media.serve mounts", rt.method, rt.path, rt.pluginID, album.ConfigPublicPathPrefix, prefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
r.BindPlugin(mediaPluginID)
|
||||
r.GroupRaw(prefix, nil, func(g pact.Router) {
|
||||
if serveStatic {
|
||||
g.Get("/{short_id}/{file}", mediaStaticHandler(app, r.pages, prefix))
|
||||
}
|
||||
if mountUpload {
|
||||
uploadHandler := album.SignedUploadHandler(app, svc).ServeHTTP
|
||||
g.Put("/upload/{token}", uploadHandler, "throttle:60,1")
|
||||
g.Post("/upload/{token}", uploadHandler, "throttle:60,1")
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// mediaPrefix validates media.public_path_prefix with the same rules as uploadsPrefix.
|
||||
func mediaPrefix(raw string) (string, error) {
|
||||
value := strings.TrimSpace(raw)
|
||||
if value == "" {
|
||||
return album.DefaultPublicPathPrefix, nil
|
||||
}
|
||||
prefix := strings.TrimSuffix(value, "/")
|
||||
bad := !strings.HasPrefix(prefix, "/") || strings.ContainsAny(prefix, "{}?# \t\r\n\\")
|
||||
if !bad {
|
||||
for _, seg := range strings.Split(prefix[1:], "/") {
|
||||
if seg == "" || seg == "." || seg == ".." {
|
||||
bad = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if bad {
|
||||
return "", fmt.Errorf("surf: %s must be an absolute URL path such as /media (no scheme, host, query or wildcard), got %q", album.ConfigPublicPathPrefix, raw)
|
||||
}
|
||||
return prefix, nil
|
||||
}
|
||||
|
||||
func mediaStaticHandler(app *backpack.App, pages *errorPages, prefix string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, req *http.Request) {
|
||||
bucket, ok := app.Lookup[*blob.Bucket]()
|
||||
if !ok || bucket == nil {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Security-Policy", album.MediaContentSecurityPolicy)
|
||||
pages.notFound(w, req)
|
||||
return
|
||||
}
|
||||
album.StaticHandler(bucket, prefix).ServeHTTP(w, req)
|
||||
}
|
||||
}
|
||||
@@ -747,6 +747,9 @@ func (r *Router) build(app *backpack.App, plugins []party.Plugin) error {
|
||||
if err := mountUploads(r, app); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mountMedia(r, app); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mountAPIDocs(r, app, plugins); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user