feat(media): unify uploads onto modules/album, add batched srcset enrichment and Media Library picker
This commit is contained in:
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
|
||||
}
|
||||
Reference in New Issue
Block a user