Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

18.4 KB
Raw Blame

Media Library

Status: Implemented Target: Spree 6.0 Depends on: 5.4-6.0-product-media-system.md (shipped data model: Spree::Media, spree_variant_media, media types, focal point, external video) Author: Damian Legawiec Last updated: 2026-08-24

Summary

Give merchants a store-wide media library in the dashboard: browse and search every uploaded image and video in one place, upload files before deciding where they go, reuse a file on another product without re-uploading it, and see where a file is used before deleting it. On top of the library, the rich text editor gains image embedding — images in product, category and collection descriptions come from the library instead of not existing at all.

This is deliberately the small version of a media library. Spree::Media keeps its current shape — one row owned by one viewable (product or variant), with per-row position, alt text, focal point and variant links. Reuse is implemented by duplicating the row while sharing the underlying ActiveStorage::Blob: a copy is a new Media row plus a new attachment row pointing at the same blob, so there is no second file in storage, every already-processed rendition is reused, and the copy still gets its own alt text and position in its new context. A shared-asset model with attachment join tables (one asset row referenced from many products) was considered and rejected — it would rework everything that hangs off the polymorphic viewable (list scoping, counter caches, thumbnail denormalization, the variant-link security boundary) for a benefit blob sharing already provides at the storage level.

Key Decisions (do not deviate without discussion)

  • Blob sharing is the reuse mechanism, not a shared asset entity. "Use this file on another product" creates a new Spree::Media row and attaches the existing blob. Deletion safety comes from the standard Rails foreign key from active_storage_attachments to active_storage_blobs: purging a copy's blob raises a foreign-key violation while other attachments reference it, and ActiveStorage::PurgeJob discards on exactly that error, so the file survives until the last reference is gone. That FK is load-bearing — the "no foreign key constraints" rule covers Spree's own tables, and this Rails table must keep its constraint.
  • spree_media gains a store_id column (2026-08-24). An unattached library upload has no viewable to derive tenancy from, so the library cannot be scoped through products. belongs_to :store becomes required on new rows; existing rows are backfilled from their viewable's product store by an upgrade task in the 5.6→6.0 manifest. Store-owned means the StoreScopeGuard tripwires apply to every new media query.
  • The library lists every Spree::Media row in the store, attached or not. "In the library" is not a flag — an unattached row is simply viewable_id: nil (already legal today; session uploads rely on it). No second bucket, no folders. Organization is search and filters (type, attachment state, filename); anything richer waits for demonstrated need.
  • Reuse rides the existing nested create (2026-08-24). POST /products/:id/media (and the variant twin) accepts source_media_id as a third transport shape beside signed_id and url — "create this product's media from that library row". Copies attachment blob, poster blob, alt and focal point; position and variant links are the new context's own. No separate duplicate endpoint.
  • Media is its own permission resource (2026-08-24). Spree::Media used to be a subject of products, which was right while a file belonged to one product. Now that a row can be placed on a category or collection, the library lists, traces and deletes across all three — so read_products alone could name a category and write_products could strip its image. Media is registered as read_media/write_media in the catalog group, and the split follows Shopify's: reaching a file through a product stays products (the nested gallery is that product's own media, reached through a product the caller can already see), while enumerating the library, asking where a file is used, or deleting one everywhere needs media. A grouped read_catalog was considered and rejected — it would have removed the boundary rather than fixed it, and cost the ability to grant categories without products. Constraint: every path that creates an attachment must check the media key, not just the endpoints — WooCommerce ships this bug today, where its URL-ingest helper creates attachments under the product capability while the media endpoint requires the upload one.
  • The library picker serves every attachment field, not just product media (2026-08-24). Picking an existing file yields the blob's signed_id, which any has_one_attached writer accepts — so category, collection, store and seller image fields get "choose from library" through their existing endpoints, with the same blob-sharing economics.
  • Category and Collection are real Media viewables (2026-08-24, supersedes the "those fields stay bare attachments" clause above for these two models; implemented same day). A file uploaded to a category or collection image slot was invisible to the library — no Media row meant no grid entry, no search, no reuse. Rather than mirror it as an unplaced row (which would have made the placement filter lie: "not used yet" about a file on a category), the slots reconcile into actual placements: Spree::HasLibraryMedia (has_library_media :image, :square_image on both models) creates Media rows with viewable: category sharing the slot blobs on save, and clearing a slot unplaces the row (back to the library pool) rather than destroying it — destroying would take the file with it. Spree.media_viewable_types is now a registry (Product, Variant, Category, Collection); ensure_store reads the viewable's own store first. The named image/square_image attachments remain the operational storage every existing serializer and storefront reads; the placements are the library's view of them, and the future category gallery is additive rows on the same has_many :media association (dependent: :nullify — deleting the category returns its files to the library). Until that gallery exists, reconciliation owns every placement on these records — do not create Media rows on a category by another path, they will be unplaced on the next slot change. Sellers and stores stay bare — logos are branding, not merchandising media. Existing images backfill via spree:upgrade:backfill_library_media_placements in the 5.6→6.0 manifest.
  • Library delete detaches on confirmation (2026-08-24, revised the same day from "refuse until the merchant clears each use"). DELETE /admin/media/:id on a file in use returns 422 with the usage list; passing detach=true — which the dashboard sends after a confirmation naming the count — runs Spree::Media::Destroy, removing the file from every placement and plain attachment in its store, then deleting the row so the blob purges. Clearing each use by hand was busywork the usage list already knew how to do; the refusal survives as the default so an API client cannot pull a file out from under a catalog by accident. Rich text embeds are plain URLs with nothing to detach, so those descriptions lose the image — the confirmation says so. The product-nested destroy is untouched: removing a file from one gallery is not deleting the file.
  • Rich text embeds are plain <img> URLs, not tracked references (2026-08-24). The editor inserts a URL to a non-cropping rendition of a library file. No join rows track which descriptions use which media; "where used" for rich text is a best-effort blob-key search and deletion warns generically. Tracked content references are a follow-up if merchants hit broken images in practice.
  • The sanitizer widens in the same change that gives the editor the image node — per the doctrine written into Spree::RichTextSanitizer: img joins allowed_tags and src, alt, width, height join allowed_attributes exactly when the Tiptap Image extension lands. src must survive only with https or relative URLs — data: and javascript: URIs are stripped (add an explicit scrubber if the stock protocol filtering proves not to cover it).
  • Deleting a library row that is in use requires seeing the usage. The dashboard delete flow shows where the row and its blob are referenced (products, variants, and other attachments sharing the blob) before the destructive confirm.
  • A copy takes the target's store, never the source's (2026-08-24, found in implementation). duplicate_for leaves store_id unset so SingleStoreResource resolves it from the new owner's product — media follows the thing it is a picture of. Copying the source's store instead would have written a row into the wrong tenant whenever a placement crossed stores; the controller's scoped lookup hides that, but the model has to be right on its own.
  • Reuse works on both product write paths (2026-08-24). source_media_id is accepted by the nested media create and by the inline media: list on the product itself — the dashboard's product Save uses the latter, so supporting only the endpoint would have left the picker silently dropping its files.
  • acts_as_list is scoped by store_id too (2026-08-24, review). An unplaced row has no viewable, so with only [viewable_id, viewable_type] in the scope every store's library uploads shared one list — positions bleeding across tenants, and a store-less position query that the store-scope guard rightly refuses.
  • The library lists files, not placements (2026-08-24). Reuse shares a blob across rows, so one picture on three products is three rows — listing them all showed the same image repeatedly. The index groups by blob (Media.distinct_by_file), but only the index: a hidden row is still a real record a client holds the id of, so member actions resolve any row.
  • Usage includes the row's own placement (2026-08-24). Excluding it — on the reasoning that "its own placement is not news" — meant a file sitting on a product reported "not used anywhere", which is worst in the case the panel exists for. A video's file and poster are two blobs on one row, so the result is deduplicated by owner.
  • One preview component, two surfaces (2026-08-24). MediaPreview renders a file by kind — external video as its provider embed, uploaded video as a player, image with its focal point marker — and is used by both the product gallery's edit sheet and the library's detail panel, so a file looks and behaves the same in both. It lives in dashboard-ui (ui/media-preview.tsx) and is headless per that package's rule: everything arrives as props, so the same component serves a saved record and a form row that has only blob URLs because it is not saved yet. Provider links are parsed by the caller — it takes a ready embedUrl, which keeps the app's parseVideoUrl out of the design system and matches the server being the authority on embeddability (the library passes the serializer's video_embed_url; the product form passes what it already parsed for its own validation). The grid keeps its own still-only tile — dozens of video players in one view is not a gallery. Poster upload now appears in both places too; the library saves it immediately (no surrounding form), the product sheet carries it on the form. Without it the picker had nothing to hand a plain attachment field, and the "generic image fields adopt library files" decision below was unimplementable.
  • Usage is scoped to the file's own store (2026-08-24, review). A shared blob can reach another tenant's records; reporting them named that tenant's data to a merchant who cannot see it anywhere else. All three sources filter by the media's store_id, and the rich text search covers content models only — order and customer internal notes are staff correspondence on the two largest tables, and no merchant embeds a library image in one.

Design Details

Model

Spree::Media changes are additive:

  • store_id column, belongs_to :store, required on create for new rows (validation, not a DB null: false, until the 6.1 cleanup — legacy rows backfill first). Uniqueness/scoping and the library index key off it.
  • A library scope is unnecessary — the library IS store.media. New scopes: attached / unattached (on viewable_id presence), filename search via a join to the attachment blob.
  • Duplication: Spree::Media#duplicate_for(viewable) builds the copy — attaches attachment.blob and (when present) poster.blob, copies media_type, alt, focal_point_x/y, external_video_url; leaves position to acts_as_list in the new scope and copies no variant links. Counter caches and thumbnail denormalization fire through the existing callbacks because the copy is an ordinary create.

Blob-level usage lookup (for the delete flow and the media detail panel): given a row, find all active_storage_attachments sharing its blob ids, resolve to owner records, and present them grouped. This is a read-side service — Spree::Media::Usage — not columns.

Admin API

  • GET /api/v3/admin/media — new top-level, store-scoped index (the library). Filters: media_type, attached/unattached, filename q, product. Existing nested indexes stay for the product/variant galleries.
  • POST /api/v3/admin/media — top-level create for upload-first: accepts the same signed_id / url / external-video shapes as the nested create but builds an unattached, store-owned row.
  • PATCH /api/v3/admin/media/:id, DELETE /api/v3/admin/media/:id — manage library rows (rename alt, delete). Delete responds with usage info on the serializer so the dashboard confirm can show it.
  • POST /api/v3/admin/products/:id/media gains source_media_id (and the variant-nested twin) — the reuse path. The source must resolve through current_store.media, same IDOR rule as every other lookup.
  • Scopes: rides the existing read_products / write_products pair — media is product imagery, not a new sensitive resource.
  • Serializer: admin media serializer gains attached?/owner summary and usage counts where cheap; the event serializer is unchanged.

Dashboard

  • New Media page (nav: under Products) — grid of thumbnails with type badges, filters, search, upload dropzone (direct upload → top-level create), bulk delete with usage-aware confirm, detail side panel (preview, alt, file facts, usage list, "add to product…").
  • Library picker sheet (dashboard-core-level component): browse/search the library, multi-select, returns either media ids (product media reuse) or blob signed ids (generic attachment fields). Product media card gains "Add from library" beside upload; category/collection/store/seller image fields gain "Choose from library".
  • Rich text editor: Tiptap Image extension + toolbar button opening the picker (upload tab included — uploads land in the library as unattached rows, then embed). Inserted src is the non-cropping embed rendition URL.

Renditions

Product image variants are resize_to_fill — cropped to exact dimensions, wrong for editorial images inside descriptions. Add one embed rendition (resize_to_limit, WebP, same saver options) used by rich text embeds; the grid reuses the existing small/thumbnail renditions.

Migration Path

  1. Migration: add store_id to spree_media (nullable, indexed). Schema only — the data step is a rake task, per the repo's migration rules.
  2. Upgrade task spree:upgrade:backfill_media_store_ids, in the 5.6→6.0 manifest after migrate_master_images_to_product_media (that step moves media between viewables, and a row re-homed afterwards would keep the wrong store). Resumable by where(store_id: nil); rows whose viewable is gone fall to the default store rather than staying unreachable.
  3. Model changes + top-level API + source_media_id on both product write paths.
  4. Dashboard library page + picker; wire picker into product media card and generic attachment fields.
  5. Tiptap Image + sanitizer widening + embed rendition, in one change.
  6. 6.1 cleanup: null: false on spree_media.store_id.

Constraints on Current Work

  • Never strip or "align" the active_storage_attachments → blobs foreign key with the no-FK convention — blob-sharing deletion safety depends on it.
  • Spree::Media::Usage must stay store-scoped on every one of its three sources (attachments, placements, rich text) — a blob can be shared, but a file's reported uses are its own store's rows.
  • Which editors can embed a file is a dashboard decision: MediaRichTextEditor is opt-in per call site and only product, category and collection descriptions use it. The usage search covers every model declaring rich text rather than restating that list on the server.
  • A controller action outside index/show needs its CanCanCan action mapped as well as its key scope declared: read_actions settles the API-key gate, but the :read alias covers only those two, so a custom read action refuses JWT staff until it is mapped. Test it with a JWT alone — the shared spec headers also carry a full-scope secret key, which authorizes on its own and hides the refusal.
  • New media queries must scope through current_store.media once store_id lands; until then, keep scoping through the product as today.
  • Do not add an img tag to RichTextSanitizer.allowed_tags ahead of the editor gaining the image node — the allowlist and the editor move together.
  • Do not build attachment-style join tables between Spree::Media and new owners; a new context that needs a file gets its own row sharing the blob.
  • attachment.purge / blob.purge must never be called directly on media paths — always purge_later, so the foreign-key discard path can do its job.

Open Questions

None — resolved 2026-08-24 (see Key Decisions).

References

  • docs/plans/5.4-6.0-product-media-system.md — the shipped media data model
  • docs/plans/6.0-rich-text-descriptions.md — sanitizer doctrine this plan extends
  • spree/core/app/models/spree/rich_text_sanitizer.rb — allowlist + widening note
  • spree/core/app/models/spree/media.rb, spree/core/app/models/spree/variant_media.rb