feat(media): unify uploads onto modules/album, add batched srcset enrichment and Media Library picker

This commit is contained in:
Jakub Zych
2026-11-27 13:26:59 +01:00
parent f61c90a326
commit ccd8dc85aa
14 changed files with 781 additions and 79 deletions

View File

@@ -212,7 +212,8 @@ Every entry of `featured_images` (on `GET /posts`, `GET /posts/{slug}` and the a
- **When they are made.** `POST /_journal/api/v1/posts/{id}/featured-images` stores the original and queues the conga job `golem15.journal.image_variants` (`classes.ImageVariantsArgs`, three attempts) after the row is written; the request itself never resizes or encodes, and a queue that cannot take the job is logged without failing the upload. An admin save of a post queues the job, after the save commits, for its featured images that lack a width.
- **What is made.** For each width of `golem15.journal.image_widths` no larger than the original, `classes.GenerateImageVariants` writes the thumbnail (`attach.File.ThumbKey`, mode `exact`, the original's aspect ratio) and its WebP copy (`webp.Variant` of the framework's `modules/lagoon/attach/webp`). A width that has its row is skipped, so the job and the command can run any number of times. A missing or undecodable original, or one over the thumbnailer's 4096 by 4096 pixel limit, is skipped and logged.
- **Backfill.** `journal:image-variants` takes the images that lack a width no larger than their original; `--all` checks every featured image. It runs from the application's CLI too: without a running server it opens `database.dsn` and `storage.uploads.bucket_url` itself.
- **Not made.** AVIF (deferred). Images inserted into a post body keep their original file.
- **Not made.** AVIF (deferred). Legacy `/uploads/...` images in a post body keep their original file untouched.
- **Inline Media Library (`modules/album`) uploads & render-time `srcset` enrichment.** `POST /_journal/api/v1/media/upload` and the Blog Editor's direct image upload store new raster images through the framework's `modules/album` Media Library (into the virtual folder `journal`, or a sanitized subfolder beneath `journal`), generating synchronous WebP width variants (`480w`, `960w`, `1600w`) and returning `{data: {url, path, id, short_id, width, height, variants, srcset}}`. Stored post `content` and `content_html` remain clean `<img src="/media/<short-id>/<slug>.<ext>" ...>` tags. During `GET /_journal/api/v1/posts`, `GET /_journal/api/v1/posts/{slug}`, and `GET /_journal/api/v1/authors/{author}/posts` serialization, `classes.EnrichMediaHTML` enriches matching `/media/<short-id>/...` `<img>` tags in serialized `content_html` (and translations) with `srcset`, `sizes="(max-width: 768px) 100vw, 800px"`, and `width`/`height` using a single batched `WHERE short_id IN ?` query per request (zero N+1), while leaving legacy `/uploads/...` images byte-identical.
- **Server.** WebP is encoded in Go. With the system libwebp installed (`libwebp.so` and `libwebpdemux.so`, Debian `libwebp-dev`) it is about five times faster. A binary that mounts this plugin is dynamically linked against glibc, unless it is built with `-tags nodynamic` (see the framework's attachments documentation).
### Personal API tokens

File diff suppressed because one or more lines are too long

View File

@@ -13,6 +13,8 @@ export const TAG = 'golem15-journal-blogeditor'
export const CHANGE_EVENT = 'summer-change'
export const UPLOAD_EVENT = 'summer-upload'
export const UPLOAD_RESULT_EVENT = 'summer-upload-result'
export const MEDIA_PICK_EVENT = 'summer-media-pick'
export const MEDIA_PICK_RESULT_EVENT = 'summer-media-pick-result'
/** The image types the picker offers and the editor uploads (D-18). */
export const IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
@@ -110,6 +112,7 @@ export class BlogEditorElement extends HTMLElement {
#options: EditorOptions = readOptions(null)
#showingSource = false
#pending = new Map<string, { name: string; choice: ImageChoice; timer: ReturnType<typeof setTimeout> }>()
#pendingMediaPick = new Set<string>()
/** The picked files waiting for their image form (J4). */
#queue: File[] = []
/** Whether this element shows the preview pane (per instance, off by default). */
@@ -172,6 +175,7 @@ export class BlogEditorElement extends HTMLElement {
openLink: () => this.#openLink(),
openEmbed: () => this.#openEmbed(),
pickImage: () => this.#fileInput?.click(),
pickFromMediaLibrary: () => this.#pickFromMediaLibrary(),
insertRawHtml: () => this.#insertRawHtml(),
showSource: (on) => this.showSource(on),
togglePreview: () => this.showPreview(!this.#previewOn),
@@ -263,6 +267,7 @@ export class BlogEditorElement extends HTMLElement {
)
this.addEventListener(UPLOAD_RESULT_EVENT, this.#onUploadResult)
this.addEventListener(MEDIA_PICK_RESULT_EVENT, this.#onMediaPickResult)
this.addEventListener(EDIT_HTML_EVENT, this.#onEditHtml)
const initial = this.value
@@ -301,9 +306,11 @@ export class BlogEditorElement extends HTMLElement {
disconnectedCallback(): void {
this.removeEventListener(UPLOAD_RESULT_EVENT, this.#onUploadResult)
this.removeEventListener(MEDIA_PICK_RESULT_EVENT, this.#onMediaPickResult)
this.removeEventListener(EDIT_HTML_EVENT, this.#onEditHtml)
for (const { timer } of this.#pending.values()) clearTimeout(timer)
this.#pending.clear()
this.#pendingMediaPick.clear()
clearTimeout(this.#previewTimer)
this.#previewTimer = undefined
this.#outline?.stop()
@@ -723,6 +730,50 @@ export class BlogEditorElement extends HTMLElement {
if (this.#imageForm) this.#imageForm.root.hidden = true
this.#showImageForm()
}
// Media Library Picker (Phase 37, D-05) -------------------------------------
#pickFromMediaLibrary(): void {
if (!this.#editor?.isEditable) return
const id = uploadRequestId()
this.#pendingMediaPick.add(id)
this.dispatchEvent(
new CustomEvent(MEDIA_PICK_EVENT, {
bubbles: true,
composed: true,
detail: { id, mode: 'image', defaultFolder: 'journal', showAlt: true },
}),
)
}
#onMediaPickResult = (event: Event): void => {
const detail = (
event as CustomEvent<{
id?: unknown
cancelled?: unknown
item?: { url?: unknown; alt?: unknown; caption?: unknown; width?: unknown; height?: unknown }
}>
).detail ?? {}
const id = typeof detail.id === 'string' ? detail.id : ''
if (!this.#pendingMediaPick.delete(id)) return
if (detail.cancelled === true || !detail.item) return
const url = typeof detail.item.url === 'string' ? detail.item.url.trim() : ''
if (!url || !isPolicyUrl(url)) return
const editor = this.#editor
if (!editor) return
const alt = typeof detail.item.alt === 'string' ? detail.item.alt : ''
const caption = typeof detail.item.caption === 'string' ? detail.item.caption.trim() : ''
const width = typeof detail.item.width === 'number' && detail.item.width > 0 ? String(detail.item.width) : null
const height = typeof detail.item.height === 'number' && detail.item.height > 0 ? String(detail.item.height) : null
if (caption) {
editor.chain().focus().setFigure({ src: url, alt, caption, width, height }).run()
} else {
const attrs: Record<string, unknown> = { src: url, alt }
if (width) attrs.width = width
if (height) attrs.height = height
editor.chain().focus().setImage(attrs as { src: string; alt?: string }).run()
}
}
}
function isImage(file: File): boolean {

View File

@@ -222,7 +222,7 @@ declare module '@tiptap/core' {
}
figure: {
/** Inserts an image with a caption as figure, img and figcaption. */
setFigure: (attributes: { src: string; alt: string; caption: string }) => ReturnType
setFigure: (attributes: { src: string; alt: string; caption: string; width?: number | string | null; height?: number | string | null }) => ReturnType
}
}
}
@@ -452,9 +452,12 @@ export const Figure = Node.create({
addCommands() {
return {
setFigure:
({ src, alt, caption }) =>
({ src, alt, caption, width, height }) =>
({ commands }) => {
const content: Record<string, unknown>[] = [{ type: 'figureImage', attrs: { src, alt } }]
const imgAttrs: Record<string, unknown> = { src, alt }
if (width != null && width !== '') imgAttrs.width = String(width)
if (height != null && height !== '') imgAttrs.height = String(height)
const content: Record<string, unknown>[] = [{ type: 'figureImage', attrs: imgAttrs }]
if (caption) content.push({ type: 'figcaption', content: [{ type: 'text', text: caption }] })
return commands.insertContent({ type: this.name, content })
},
@@ -572,6 +575,17 @@ export const HeadingOneAsTwo = Node.create({
* the preservation nodes and marks. headingLevels are the offered heading
* levels (J1): without 1, an h1 is parsed as a level 2 heading.
*/
/** Inline image with optional width/height attributes preserved for Media Library picks. */
const SizedImage = Image.extend({
addAttributes() {
return {
...this.parent?.(),
width: { default: null },
height: { default: null },
}
},
})
export function preservationExtensions(labels: Labels = labelsFor('en'), headingLevels: readonly number[] = DEFAULT_HEADING_LEVELS): AnyExtension[] {
const levels = schemaHeadingLevels(headingLevels)
return [
@@ -585,7 +599,7 @@ export function preservationExtensions(labels: Labels = labelsFor('en'), heading
},
}),
...(levels.includes(1) ? [] : [HeadingOneAsTwo]),
Image.configure({ inline: true, allowBase64: false }),
SizedImage.configure({ inline: true, allowBase64: false }),
PlainTable,
TableRow,
PlainTableHeader,

View File

@@ -28,6 +28,7 @@ export interface Labels {
deleteColumn: string
deleteTable: string
image: string
mediaLibrary: string
embed: string
rawHtml: string
undo: string
@@ -102,6 +103,7 @@ const en: Labels = {
deleteColumn: 'Delete column',
deleteTable: 'Delete table',
image: 'Image',
mediaLibrary: 'Choose from Media Library',
embed: 'Embed video',
rawHtml: 'HTML block',
undo: 'Undo',
@@ -173,6 +175,7 @@ const pl: Labels = {
deleteColumn: 'Usuń kolumnę',
deleteTable: 'Usuń tabelę',
image: 'Obraz',
mediaLibrary: 'Wybierz z biblioteki mediów',
embed: 'Osadź wideo',
rawHtml: 'Blok HTML',
undo: 'Cofnij',

View File

@@ -8,6 +8,7 @@ export interface ToolbarHost {
openLink: () => void
openEmbed: () => void
pickImage: () => void
pickFromMediaLibrary: () => void
insertRawHtml: () => void
showSource: (on: boolean) => void
/** Switches the preview pane on or off. */
@@ -91,6 +92,7 @@ const GROUPS: ButtonSpec[][] = [
],
[
{ command: 'image', glyph: 'Image', label: 'image', run: (_e, h) => h.pickImage(), host: true },
{ command: 'mediaLibrary', glyph: 'Library', label: 'mediaLibrary', run: (_e, h) => h.pickFromMediaLibrary(), host: true },
{ command: 'embed', glyph: 'Video', label: 'embed', run: (_e, h) => h.openEmbed(), host: true },
{ command: 'rawHtml', glyph: 'HTML', label: 'rawHtml', run: (_e, h) => h.insertRawHtml(), host: true },
],

View File

@@ -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
View 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
}

View 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)
}
})
}

View File

@@ -202,8 +202,15 @@ func AuthorPosts(app *backpack.App) http.HandlerFunc {
return
}
rows := make([]map[string]any, 0, len(posts))
postPtrs := make([]*models.Post, len(posts))
trs := make([]any, len(posts))
for i := range posts {
rows = append(rows, serializePost(&posts[i], db))
postPtrs[i] = &posts[i]
trs[i] = translationsOf(db, &posts[i])
}
media := batchLoadPostMedia(r.Context(), db, app, postPtrs, trs)
for i := range posts {
rows = append(rows, serializePostWithMedia(&posts[i], db, trs[i], media))
}
wire.WriteJSON(w, http.StatusOK, lagoon.Paginate(rows, page, perPage, total))
}

View File

@@ -6,15 +6,18 @@ import (
"strings"
"git.golem15.com/golem15/sm-journal-plugin/classes"
"git.golem15.com/golem15/summercms/modules/album"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/wire"
"gocloud.dev/blob"
)
// UploadMedia is POST /_journal/api/v1/media/upload (JOURNAL-006). The
// route authenticates, checks permissions, the folder and the form, then
// stores the file with classes.StoreMedia, which the Blog Editor's image
// upload shares.
// route authenticates, checks permissions, validates the folder and file,
// and stores new uploads via modules/album (under the virtual "journal"
// folder, or a sanitized subfolder beneath it) while preserving the
// backward-compatible {data: {url, path}} keys and additively returning
// id, short_id, width, height, variants, and srcset.
func UploadMedia(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r, pr, ok := requireBackendPrincipal(app, w, r)
@@ -35,29 +38,84 @@ func UploadMedia(app *backpack.App) http.HandlerFunc {
return
}
defer file.Close()
db, err := gdb(app)
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "Internal server error")
return
}
bucket, _ := app.Lookup[*blob.Bucket]()
stored, err := classes.StoreMedia(r.Context(), bucket, folder, header.Filename, file)
if bucket == nil {
writeAPIError(w, http.StatusInternalServerError, "Internal server error")
return
}
svc, ok := album.ServiceFrom(app)
if !ok {
svc = album.NewService(appConfig(app))
}
targetFolder, err := classes.EnsureJournalMediaFolder(r.Context(), svc, db, folder)
if err != nil {
writeMediaStoreError(w, err)
return
}
folderID := targetFolder.ID
var uploadedBy *uint
if pr != nil && pr.ID > 0 {
id := pr.ID
uploadedBy = &id
}
item, err := svc.Upload(r.Context(), db, bucket, album.UploadInput{
FileName: classes.MediaFileName(header.Filename),
Body: file,
FolderID: &folderID,
UploadedBy: uploadedBy,
ImageOnly: true,
MaxBytes: classes.MediaMaxBytes,
})
if err != nil {
writeMediaStoreError(w, err)
return
}
cfg := appConfig(app)
variants := item.Variants
if variants == nil {
variants = album.Variants{}
}
wire.WriteJSON(w, http.StatusCreated, map[string]any{
"data": map[string]any{
"url": stored.URL,
"path": stored.Path,
"url": item.PublicURL(cfg),
"path": "/" + strings.TrimLeft(item.BlobKey, "/"),
"id": item.ID,
"short_id": item.ShortID,
"width": item.Width,
"height": item.Height,
"variants": variants,
"srcset": item.Srcset(cfg),
},
})
}
}
// writeMediaStoreError answers a StoreMedia failure as the route always
// has: a classes.MediaError is a 422 on its field with its message, any
// other error the opaque 500.
// writeMediaStoreError answers a media upload failure with the route's
// backward-compatible 422 validation bodies (for *classes.MediaError and
// album validation errors), and an opaque 500 for any other error.
func writeMediaStoreError(w http.ResponseWriter, err error) {
var refused *classes.MediaError
if errors.As(err, &refused) && refused != nil {
writeValidation(w, map[string][]string{refused.Field: {refused.Message}})
return
}
switch {
case errors.Is(err, album.ErrTooLarge):
writeValidation(w, map[string][]string{"file": {"The file may not be greater than 10240 kilobytes."}})
return
case errors.Is(err, album.ErrFileType), errors.Is(err, album.ErrNotImage):
writeValidation(w, map[string][]string{"file": {"The file must be an image."}})
return
case errors.Is(err, album.ErrInvalidFolder):
writeValidation(w, map[string][]string{"folder": {"The folder format is invalid."}})
return
}
writeAPIError(w, http.StatusInternalServerError, "Internal server error")
}

View File

@@ -12,6 +12,7 @@ import (
"git.golem15.com/golem15/sm-journal-plugin/classes"
"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/bouncer"
"git.golem15.com/golem15/summercms/modules/cabana"
@@ -128,11 +129,21 @@ func Index(app *backpack.App) http.HandlerFunc {
return
}
rows := make([]map[string]any, 0, len(posts))
for i := range posts {
if suggest {
rows = append(rows, serializeSuggestion(&posts[i], db.WithContext(r.Context())))
} else {
rows = append(rows, serializePost(&posts[i], db.WithContext(r.Context())))
dbCtx := db.WithContext(r.Context())
if suggest {
for i := range posts {
rows = append(rows, serializeSuggestion(&posts[i], dbCtx))
}
} else {
postPtrs := make([]*models.Post, len(posts))
trs := make([]any, len(posts))
for i := range posts {
postPtrs[i] = &posts[i]
trs[i] = translationsOf(dbCtx, &posts[i])
}
media := batchLoadPostMedia(r.Context(), dbCtx, app, postPtrs, trs)
for i := range posts {
rows = append(rows, serializePostWithMedia(&posts[i], dbCtx, trs[i], media))
}
}
wire.WriteJSON(w, http.StatusOK, lagoon.Paginate(rows, page, perPage, total))
@@ -166,29 +177,47 @@ func Show(app *backpack.App) http.HandlerFunc {
writeAPIError(w, http.StatusInternalServerError, "Internal server error")
return
}
payload := serializePost(post, db)
payload["previous_post"] = serializeSibling(previousPost(db, post))
payload["next_post"] = serializeSibling(nextPost(db, post))
// golem15.journal.related_mode: the default category mode answers as
// it always has; scored (opt-in, P33-44) ranks the related posts by
// shared tags and categories and adds the neighbours within the
// post's first category (additive keys, scored mode only).
relatedCfg := classes.ReadRelatedSettings(appConfig(app))
var related []models.Post
var prevInCat, nextInCat any
if relatedCfg.Scored() {
related, err = classes.ScoredRelatedPosts(r.Context(), db, post, relatedCfg.Count, isEditor(pr))
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "Internal server error")
return
}
payload["previous_in_category"] = serializeSibling(classes.CategoryNeighbour(r.Context(), db, post, true))
payload["next_in_category"] = serializeSibling(classes.CategoryNeighbour(r.Context(), db, post, false))
prevInCat = serializeSibling(classes.CategoryNeighbour(r.Context(), db, post, true))
nextInCat = serializeSibling(classes.CategoryNeighbour(r.Context(), db, post, false))
} else {
related = relatedPosts(db, post, isEditor(pr))
}
// Batch-load all inline /media/<short-id>/... items across the post,
// its translations, and all related posts in a single DB query (D-14).
allPosts := make([]*models.Post, 0, 1+len(related))
allPosts = append(allPosts, post)
for i := range related {
allPosts = append(allPosts, &related[i])
}
allTrs := make([]any, len(allPosts))
for i, p := range allPosts {
allTrs[i] = translationsOf(db, p)
}
media := batchLoadPostMedia(r.Context(), db, app, allPosts, allTrs)
payload := serializePostWithMedia(post, db, allTrs[0], media)
payload["previous_post"] = serializeSibling(previousPost(db, post))
payload["next_post"] = serializeSibling(nextPost(db, post))
if relatedCfg.Scored() {
payload["previous_in_category"] = prevInCat
payload["next_in_category"] = nextInCat
}
rows := make([]map[string]any, 0, len(related))
for i := range related {
rows = append(rows, serializePost(&related[i], db))
rows = append(rows, serializePostWithMedia(&related[i], db, allTrs[i+1], media))
}
payload["related_posts"] = rows
// Additive (2026-10-28 Journal H1 setting): whether H1 in post
@@ -294,7 +323,10 @@ func Store(app *backpack.App) http.HandlerFunc {
return
}
purgeSiteCache(r, app, post)
wire.WriteJSON(w, http.StatusCreated, h1.answer(r, app, map[string]any{"data": serializePost(post, db.WithContext(r.Context()))}))
dbCtx := db.WithContext(r.Context())
tr := translationsOf(dbCtx, post)
media := batchLoadPostMedia(r.Context(), dbCtx, app, []*models.Post{post}, []any{tr})
wire.WriteJSON(w, http.StatusCreated, h1.answer(r, app, map[string]any{"data": serializePostWithMedia(post, dbCtx, tr, media)}))
}
}
@@ -369,7 +401,10 @@ func Update(app *backpack.App) http.HandlerFunc {
return
}
purgeSiteCache(r, app, post)
wire.WriteJSON(w, http.StatusOK, h1.answer(r, app, map[string]any{"data": serializePost(post, db.WithContext(r.Context()))}))
dbCtx := db.WithContext(r.Context())
tr := translationsOf(dbCtx, post)
media := batchLoadPostMedia(r.Context(), dbCtx, app, []*models.Post{post}, []any{tr})
wire.WriteJSON(w, http.StatusOK, h1.answer(r, app, map[string]any{"data": serializePostWithMedia(post, dbCtx, tr, media)}))
}
}
@@ -642,7 +677,97 @@ func applyTagFilter(q, db *gorm.DB, input string) *gorm.DB {
return q.Where("id IN (SELECT post_id FROM golem15_journal_posts_tags WHERE tag_id = ?)", tag.ID)
}
type postMediaContext struct {
items map[string]album.Item
cfg *compass.Config
}
func batchLoadPostMedia(ctx context.Context, db *gorm.DB, app *backpack.App, posts []*models.Post, translations []any) postMediaContext {
cfg := appConfig(app)
if db == nil || len(posts) == 0 {
return postMediaContext{cfg: cfg}
}
var allIDs []string
seen := make(map[string]struct{})
collect := func(htmlDoc string) {
for _, id := range classes.ExtractMediaShortIDsWithConfig(htmlDoc, cfg) {
if _, ok := seen[id]; !ok {
seen[id] = struct{}{}
allIDs = append(allIDs, id)
}
}
}
for _, p := range posts {
if p == nil {
continue
}
collect(p.ContentHTML)
}
for _, tr := range translations {
m, ok := tr.(map[string]any)
if !ok {
continue
}
for _, rawAttrs := range m {
attrs, ok := rawAttrs.(map[string]any)
if !ok {
continue
}
if s, ok := attrs["content_html"].(string); ok {
collect(s)
}
}
}
if len(allIDs) == 0 {
return postMediaContext{cfg: cfg}
}
svc, ok := album.ServiceFrom(app)
if !ok {
svc = album.NewService(cfg)
}
items, err := svc.GetItemsByShortIDs(ctx, db, allIDs)
if err != nil {
pluginLog.Warn("journal: load inline media items", "error", err)
return postMediaContext{cfg: cfg}
}
return postMediaContext{items: items, cfg: cfg}
}
func enrichTranslationsMedia(tr any, media postMediaContext) any {
if len(media.items) == 0 {
return tr
}
m, ok := tr.(map[string]any)
if !ok || len(m) == 0 {
return tr
}
out := make(map[string]any, len(m))
for loc, rawAttrs := range m {
attrs, ok := rawAttrs.(map[string]any)
if !ok {
out[loc] = rawAttrs
continue
}
cloned := make(map[string]any, len(attrs))
for k, v := range attrs {
if k == "content_html" {
if s, isStr := v.(string); isStr {
cloned[k] = classes.EnrichMediaHTML(s, media.items, media.cfg)
continue
}
}
cloned[k] = v
}
out[loc] = cloned
}
return out
}
func serializePost(p *models.Post, db *gorm.DB) map[string]any {
return serializePostWithMedia(p, db, nil, postMediaContext{})
}
func serializePostWithMedia(p *models.Post, db *gorm.DB, preloadedTranslations any, media postMediaContext) map[string]any {
if p == nil {
return map[string]any{}
}
@@ -656,13 +781,22 @@ func serializePost(p *models.Post, db *gorm.DB) map[string]any {
}
featured := featuredImages(db, p)
featuredURL := firstImageURL(featured)
tr := preloadedTranslations
if tr == nil {
tr = translationsOf(db, p)
}
contentHTML := p.ContentHTML
if len(media.items) > 0 {
contentHTML = classes.EnrichMediaHTML(contentHTML, media.items, media.cfg)
tr = enrichTranslationsMedia(tr, media)
}
row := map[string]any{
"id": p.ID,
"title": p.Title,
"slug": p.Slug,
"excerpt": p.Excerpt,
"content": p.Content,
"content_html": p.ContentHTML,
"content_html": contentHTML,
"reading_time": readingTime(p.ContentHTML),
"published": p.Published,
"published_at": carbonTime(p.PublishedAt),
@@ -674,7 +808,7 @@ func serializePost(p *models.Post, db *gorm.DB) map[string]any {
"tags": tags,
"featured_images": featured,
"featured_image_url": featuredURL,
"translations": translationsOf(db, p),
"translations": tr,
"created_at": carbonTime(p.CreatedAt),
"updated_at": carbonTime(p.UpdatedAt),
}

View File

@@ -76,15 +76,24 @@ func TestJournal006MediaUpload(t *testing.T) {
}
var body struct {
Data struct {
URL string `json:"url"`
Path string `json:"path"`
URL string `json:"url"`
Path string `json:"path"`
ID uint `json:"id"`
ShortID string `json:"short_id"`
Width *int `json:"width"`
Height *int `json:"height"`
Variants []any `json:"variants"`
Srcset string `json:"srcset"`
} `json:"data"`
}
if err := json.Unmarshal(created.Body.Bytes(), &body); err != nil {
t.Fatalf("upload json: %s err=%v", created.Body.String(), err)
}
if !strings.HasPrefix(body.Data.Path, "/journal/") {
t.Fatalf("path = %q, want prefix /journal/", body.Data.Path)
if !strings.HasPrefix(body.Data.Path, "/media/") {
t.Fatalf("path = %q, want prefix /media/", body.Data.Path)
}
if body.Data.ID == 0 || body.Data.ShortID == "" || body.Data.Width == nil || body.Data.Height == nil {
t.Fatalf("expected additive album metadata (id, short_id, width, height), got %+v", body.Data)
}
trav := env.callMultipart(t, http.MethodPost, "/_journal/api/v1/media/upload", okTok, map[string]string{"folder": "../etc"}, "file", "cover.png", png1x1)

View File

@@ -108,3 +108,38 @@ describe('untouched value (D-03)', () => {
expect(changes).toEqual([edited])
})
})
describe('Media Library picker (Phase 37, D-05)', () => {
it('dispatches summer-media-pick and inserts clean /media/ img with dimensions on result', () => {
const { el, changes } = mount('<p>Intro</p>')
const picks: CustomEvent[] = []
el.addEventListener('summer-media-pick', (event) => picks.push(event as CustomEvent))
click(button(el, 'mediaLibrary'))
expect(picks).toHaveLength(1)
const { id, mode, defaultFolder } = picks[0]!.detail as { id: string; mode: string; defaultFolder: string }
expect(typeof id).toBe('string')
expect(mode).toBe('image')
expect(defaultFolder).toBe('journal')
el.dispatchEvent(
new CustomEvent('summer-media-pick-result', {
detail: {
id,
item: {
url: '/media/abc123456789/lion-mane.jpg',
alt: 'Lion mane infographic',
width: 1200,
height: 800,
},
},
}),
)
expect(el.value).toContain('src="/media/abc123456789/lion-mane.jpg"')
expect(el.value).toContain('alt="Lion mane infographic"')
expect(el.value).toContain('width="1200"')
expect(el.value).toContain('height="800"')
expect(changes.length).toBeGreaterThan(0)
})
})