feat(media): unify uploads onto modules/album, add batched srcset enrichment and Media Library picker
This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"git.golem15.com/golem15/sm-journal-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/album"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
@@ -461,6 +462,32 @@ func uploadBlogImage(app func() *backpack.App) func(context.Context, pact.FormFi
|
||||
if folder == "" {
|
||||
folder = blogUploadFolder
|
||||
}
|
||||
if db, hasDB := a.Lookup[*gorm.DB](); hasDB && db != nil {
|
||||
svc, ok := album.ServiceFrom(a)
|
||||
if !ok {
|
||||
svc = album.NewService(a.Config)
|
||||
}
|
||||
if targetFolder, fErr := EnsureJournalMediaFolder(ctx, svc, db, folder); fErr == nil {
|
||||
folderID := targetFolder.ID
|
||||
item, uErr := svc.Upload(ctx, db, bucket, album.UploadInput{
|
||||
FileName: name,
|
||||
Body: io.MultiReader(bytes.NewReader(head), in.Body),
|
||||
FolderID: &folderID,
|
||||
ImageOnly: true,
|
||||
MaxBytes: MediaMaxBytes,
|
||||
})
|
||||
if uErr != nil {
|
||||
switch {
|
||||
case errors.Is(uErr, album.ErrTooLarge):
|
||||
return pact.FormFieldUploadResult{}, &pact.FormFieldError{Messages: []string{"The file may not be greater than 10240 kilobytes."}}
|
||||
case errors.Is(uErr, album.ErrFileType), errors.Is(uErr, album.ErrNotImage):
|
||||
return pact.FormFieldUploadResult{}, &pact.FormFieldError{Messages: []string{editorImageInvalid}}
|
||||
}
|
||||
return pact.FormFieldUploadResult{}, uErr
|
||||
}
|
||||
return pact.FormFieldUploadResult{URL: item.PublicURL(a.Config)}, nil
|
||||
}
|
||||
}
|
||||
stored, err := StoreMedia(ctx, bucket, folder, name, io.MultiReader(bytes.NewReader(head), in.Body))
|
||||
if err != nil {
|
||||
var refused *MediaError
|
||||
|
||||
276
classes/enrich_media.go
Normal file
276
classes/enrich_media.go
Normal file
@@ -0,0 +1,276 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"html"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/album"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
xhtml "golang.org/x/net/html"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DefaultInlineImageSizes is the default sizes attribute injected on enriched
|
||||
// inline /media/<short-id>/... images when the tag does not already specify one.
|
||||
const DefaultInlineImageSizes = "(max-width: 768px) 100vw, 800px"
|
||||
|
||||
var mediaShortIDPattern = regexp.MustCompile(`^[a-z0-9]{10,16}$`)
|
||||
|
||||
// EnsureJournalMediaFolder ensures the root "journal" virtual folder exists in
|
||||
// album, and creates any sanitized subfolder hierarchy requested under it.
|
||||
// Empty, ".", "..", and a redundant leading "journal" segment are skipped.
|
||||
func EnsureJournalMediaFolder(ctx context.Context, svc *album.Service, db *gorm.DB, folder string) (*album.Folder, error) {
|
||||
if svc == nil {
|
||||
svc = album.NewService(nil)
|
||||
}
|
||||
root, err := svc.EnsureFolder(ctx, db, "journal", "Journal", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
segments := make([]string, 0, 4)
|
||||
for _, part := range strings.Split(strings.Trim(folder, "/"), "/") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" || part == "." || part == ".." {
|
||||
continue
|
||||
}
|
||||
segments = append(segments, part)
|
||||
}
|
||||
if len(segments) > 0 && strings.EqualFold(segments[0], "journal") {
|
||||
segments = segments[1:]
|
||||
}
|
||||
cur := root
|
||||
for _, seg := range segments {
|
||||
parentID := cur.ID
|
||||
next, err := svc.EnsureFolder(ctx, db, seg, seg, &parentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cur = next
|
||||
}
|
||||
return cur, nil
|
||||
}
|
||||
|
||||
// ExtractMediaShortIDs scans htmlDoc using golang.org/x/net/html and returns
|
||||
// the deduplicated slice of album short_id values referenced by <img src="...">
|
||||
// tags pointing to /media/<short-id>/<file> (or an absolute URL ending in
|
||||
// /media/<short-id>/<file>). Non-media images (such as legacy /uploads/...)
|
||||
// are ignored.
|
||||
func ExtractMediaShortIDs(htmlDoc string) []string {
|
||||
return ExtractMediaShortIDsWithConfig(htmlDoc, nil)
|
||||
}
|
||||
|
||||
// ExtractMediaShortIDsWithConfig is like ExtractMediaShortIDs but respects a
|
||||
// custom media.public_path_prefix configured on cfg.
|
||||
func ExtractMediaShortIDsWithConfig(htmlDoc string, cfg *compass.Config) []string {
|
||||
if !strings.Contains(htmlDoc, "<") || !strings.Contains(strings.ToLower(htmlDoc), "<img") {
|
||||
return nil
|
||||
}
|
||||
prefix := mediaPrefixPath(cfg)
|
||||
z := xhtml.NewTokenizer(strings.NewReader(htmlDoc))
|
||||
var ids []string
|
||||
seen := make(map[string]struct{})
|
||||
for {
|
||||
tt := z.Next()
|
||||
if tt == xhtml.ErrorToken {
|
||||
break
|
||||
}
|
||||
if tt != xhtml.StartTagToken && tt != xhtml.SelfClosingTagToken {
|
||||
continue
|
||||
}
|
||||
name, hasAttr := z.TagName()
|
||||
if !hasAttr || !strings.EqualFold(string(name), "img") {
|
||||
continue
|
||||
}
|
||||
for {
|
||||
k, v, more := z.TagAttr()
|
||||
if strings.EqualFold(string(k), "src") {
|
||||
if shortID, ok := parseMediaShortID(string(v), prefix); ok {
|
||||
if _, dup := seen[shortID]; !dup {
|
||||
seen[shortID] = struct{}{}
|
||||
ids = append(ids, shortID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// EnrichMediaHTML rewrites matching <img src="/media/<short-id>/..."> start
|
||||
// tags in htmlDoc to add srcset (from item.Srcset(cfg)), sizes (when absent),
|
||||
// and width/height (when absent and known on item). All other tokens,
|
||||
// including legacy /uploads/... images and external images, are emitted
|
||||
// byte-for-byte unchanged.
|
||||
func EnrichMediaHTML(htmlDoc string, items map[string]album.Item, cfg *compass.Config) string {
|
||||
if htmlDoc == "" || len(items) == 0 {
|
||||
return htmlDoc
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(htmlDoc), "<img") {
|
||||
return htmlDoc
|
||||
}
|
||||
prefix := mediaPrefixPath(cfg)
|
||||
z := xhtml.NewTokenizer(strings.NewReader(htmlDoc))
|
||||
var out strings.Builder
|
||||
out.Grow(len(htmlDoc) + 128)
|
||||
|
||||
for {
|
||||
tt := z.Next()
|
||||
if tt == xhtml.ErrorToken {
|
||||
// Preserve any trailing raw bytes on non-EOF tokenization edge cases.
|
||||
if raw := z.Raw(); len(raw) > 0 {
|
||||
out.Write(raw)
|
||||
}
|
||||
break
|
||||
}
|
||||
if tt != xhtml.StartTagToken && tt != xhtml.SelfClosingTagToken {
|
||||
out.Write(z.Raw())
|
||||
continue
|
||||
}
|
||||
raw := append([]byte(nil), z.Raw()...)
|
||||
tok := z.Token()
|
||||
if !strings.EqualFold(tok.Data, "img") {
|
||||
out.Write(raw)
|
||||
continue
|
||||
}
|
||||
|
||||
var src string
|
||||
var hasSrcset, hasSizes, hasWidth, hasHeight bool
|
||||
for _, a := range tok.Attr {
|
||||
switch strings.ToLower(a.Key) {
|
||||
case "src":
|
||||
src = a.Val
|
||||
case "srcset":
|
||||
hasSrcset = true
|
||||
case "sizes":
|
||||
hasSizes = true
|
||||
case "width":
|
||||
hasWidth = true
|
||||
case "height":
|
||||
hasHeight = true
|
||||
}
|
||||
}
|
||||
|
||||
shortID, ok := parseMediaShortID(src, prefix)
|
||||
if !ok {
|
||||
out.Write(raw)
|
||||
continue
|
||||
}
|
||||
item, found := items[shortID]
|
||||
if !found {
|
||||
out.Write(raw)
|
||||
continue
|
||||
}
|
||||
|
||||
srcset := item.Srcset(cfg)
|
||||
var additions strings.Builder
|
||||
if !hasSrcset && srcset != "" {
|
||||
additions.WriteString(` srcset="`)
|
||||
additions.WriteString(html.EscapeString(srcset))
|
||||
additions.WriteByte('"')
|
||||
}
|
||||
if !hasSizes && (srcset != "" || hasSrcset) {
|
||||
additions.WriteString(` sizes="`)
|
||||
additions.WriteString(DefaultInlineImageSizes)
|
||||
additions.WriteByte('"')
|
||||
}
|
||||
if !hasWidth && item.Width != nil && *item.Width > 0 {
|
||||
additions.WriteString(` width="`)
|
||||
additions.WriteString(strconv.Itoa(*item.Width))
|
||||
additions.WriteByte('"')
|
||||
}
|
||||
if !hasHeight && item.Height != nil && *item.Height > 0 {
|
||||
additions.WriteString(` height="`)
|
||||
additions.WriteString(strconv.Itoa(*item.Height))
|
||||
additions.WriteByte('"')
|
||||
}
|
||||
|
||||
if additions.Len() == 0 {
|
||||
out.Write(raw)
|
||||
continue
|
||||
}
|
||||
|
||||
out.Write(injectImgAttrs(raw, additions.String()))
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
// injectImgAttrs inserts extra (already leading-space prefixed) immediately
|
||||
// before the closing ">" or "/>" of raw, preserving all existing attributes
|
||||
// and quoting byte-for-byte.
|
||||
func injectImgAttrs(raw []byte, extra string) []byte {
|
||||
s := string(raw)
|
||||
if !strings.HasSuffix(s, ">") {
|
||||
return raw
|
||||
}
|
||||
body := s[:len(s)-1]
|
||||
closing := ">"
|
||||
if strings.HasSuffix(body, "/") {
|
||||
body = body[:len(body)-1]
|
||||
trimmed := strings.TrimRight(body, " \t\r\n")
|
||||
ws := body[len(trimmed):]
|
||||
if ws == "" {
|
||||
ws = " "
|
||||
}
|
||||
return []byte(trimmed + extra + ws + "/>")
|
||||
}
|
||||
return []byte(body + extra + closing)
|
||||
}
|
||||
|
||||
func mediaPrefixPath(cfg *compass.Config) string {
|
||||
p := strings.TrimSpace(album.PublicPathPrefix(cfg))
|
||||
if p == "" {
|
||||
p = album.DefaultPublicPathPrefix
|
||||
}
|
||||
if !strings.HasPrefix(p, "/") {
|
||||
p = "/" + p
|
||||
}
|
||||
return strings.TrimRight(p, "/") + "/"
|
||||
}
|
||||
|
||||
// parseMediaShortID extracts <short-id> from a relative or absolute URL whose
|
||||
// path contains <prefix><short-id>/<file> (default prefix "/media/").
|
||||
func parseMediaShortID(rawSrc, prefix string) (string, bool) {
|
||||
rawSrc = strings.TrimSpace(rawSrc)
|
||||
if rawSrc == "" {
|
||||
return "", false
|
||||
}
|
||||
pathPart := rawSrc
|
||||
if strings.Contains(rawSrc, "://") || strings.HasPrefix(rawSrc, "//") {
|
||||
u, err := url.Parse(rawSrc)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
pathPart = u.Path
|
||||
} else {
|
||||
if idx := strings.IndexAny(pathPart, "?#"); idx >= 0 {
|
||||
pathPart = pathPart[:idx]
|
||||
}
|
||||
}
|
||||
|
||||
var rest string
|
||||
if strings.HasPrefix(pathPart, prefix) {
|
||||
rest = strings.TrimPrefix(pathPart, prefix)
|
||||
} else if idx := strings.Index(pathPart, prefix); idx >= 0 {
|
||||
// Supports sub-path deployments (e.g. https://example.com/blog/media/<short-id>/<file>)
|
||||
// and CDN URLs ending in /media/<short-id>/<file>.
|
||||
rest = pathPart[idx+len(prefix):]
|
||||
} else {
|
||||
return "", false
|
||||
}
|
||||
|
||||
shortID, file, hasSlash := strings.Cut(rest, "/")
|
||||
if !hasSlash || file == "" || strings.Contains(file, "/") {
|
||||
return "", false
|
||||
}
|
||||
if !mediaShortIDPattern.MatchString(shortID) {
|
||||
return "", false
|
||||
}
|
||||
return shortID, true
|
||||
}
|
||||
85
classes/enrich_media_test.go
Normal file
85
classes/enrich_media_test.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/album"
|
||||
)
|
||||
|
||||
func TestExtractMediaShortIDs(t *testing.T) {
|
||||
doc := `<p>Intro</p>` +
|
||||
`<img src="/media/abc123456789/lion-mane.jpg" alt="Lion">` +
|
||||
`<img src="/uploads/public/012/345/678/legacy.png" alt="Legacy">` +
|
||||
`<img src="https://example.com/media/xyz987654321/chart.png?v=1" alt="Full URL">` +
|
||||
`<img src="/media/abc123456789/lion-mane.jpg" alt="Duplicate">` +
|
||||
`<img src="/media/short/too-short.jpg" alt="Invalid short id">` +
|
||||
`<img src="https://cdn.example.com/assets/media/qwe123456789/diagram.webp" alt="CDN">`
|
||||
|
||||
got := ExtractMediaShortIDs(doc)
|
||||
want := []string{"abc123456789", "xyz987654321", "qwe123456789"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("ExtractMediaShortIDs() = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrichMediaHTML(t *testing.T) {
|
||||
w, h := 1600, 900
|
||||
items := map[string]album.Item{
|
||||
"abc123456789": {
|
||||
ShortID: "abc123456789",
|
||||
BlobKey: "media/abc123456789/hero.jpg",
|
||||
Width: &w,
|
||||
Height: &h,
|
||||
Variants: album.Variants{
|
||||
{Width: 480, Height: 270, Key: "media/abc123456789/hero-480w.webp", URL: "/media/abc123456789/hero-480w.webp"},
|
||||
{Width: 960, Height: 540, Key: "media/abc123456789/hero-960w.webp", URL: "/media/abc123456789/hero-960w.webp"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
t.Run("enriches matching media img and preserves legacy uploads byte-identically", func(t *testing.T) {
|
||||
legacy := `<img src="/uploads/public/1/2/3/old.jpg" alt="Old" class="keep" />`
|
||||
in := `<p>Hello</p>` + legacy + `<figure><img src="/media/abc123456789/hero.jpg" alt="Hero"><figcaption>Cap</figcaption></figure>`
|
||||
out := EnrichMediaHTML(in, items, nil)
|
||||
|
||||
if !strings.Contains(out, legacy) {
|
||||
t.Fatalf("legacy img mutated:\ngot: %s\nwant: %s", out, legacy)
|
||||
}
|
||||
wantSrcset := `srcset="/media/abc123456789/hero-480w.webp 480w, /media/abc123456789/hero-960w.webp 960w"`
|
||||
if !strings.Contains(out, wantSrcset) {
|
||||
t.Fatalf("missing srcset in %s", out)
|
||||
}
|
||||
if !strings.Contains(out, `sizes="(max-width: 768px) 100vw, 800px"`) {
|
||||
t.Fatalf("missing sizes in %s", out)
|
||||
}
|
||||
if !strings.Contains(out, `width="1600" height="900"`) {
|
||||
t.Fatalf("missing width/height in %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("does not overwrite existing sizes width height or srcset", func(t *testing.T) {
|
||||
in := `<img src="/media/abc123456789/hero.jpg" sizes="50vw" width="600" height="338" />`
|
||||
out := EnrichMediaHTML(in, items, nil)
|
||||
if strings.Count(out, "sizes=") != 1 || !strings.Contains(out, `sizes="50vw"`) {
|
||||
t.Fatalf("existing sizes overwritten: %s", out)
|
||||
}
|
||||
if strings.Count(out, "width=") != 1 || !strings.Contains(out, `width="600"`) {
|
||||
t.Fatalf("existing width overwritten: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "srcset=") {
|
||||
t.Fatalf("expected srcset added: %s", out)
|
||||
}
|
||||
if !strings.HasSuffix(out, "/>") {
|
||||
t.Fatalf("expected self-closing syntax preserved: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty items returns input byte-identical", func(t *testing.T) {
|
||||
in := `<p><img src="/media/abc123456789/hero.jpg" alt="A"></p>`
|
||||
if got := EnrichMediaHTML(in, nil, nil); got != in {
|
||||
t.Fatalf("got %q, want %q", got, in)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user