276 lines
9.4 KiB
Go
276 lines
9.4 KiB
Go
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")
|
|
}
|