827 lines
23 KiB
Go
827 lines
23 KiB
Go
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)
|
|
}
|