Skip to main content

rustango_cms/
media.rs

1//! `Media` — per-tenant uploaded files (images + documents).
2//!
3//! Single table with a `kind` discriminator so the admin can show
4//! two filtered views ("Media" for images, "Documents" for the
5//! rest) over the same storage backend.
6
7use chrono::{DateTime, Utc};
8use rustango::sql::Auto;
9use rustango::Model;
10use serde::{Deserialize, Serialize};
11
12/// One row per uploaded file. Bytes live behind the per-tenant
13/// `Storage` trait, keyed by `storage_key`. Resized variants live in
14/// `cms_media_rendition` (see `crate::rendition`); this table is just the
15/// upload surface.
16#[derive(Model, Debug, Clone, Serialize, Deserialize)]
17#[rustango(
18    table = "cms_media",
19    app = "cms",
20    display = "title",
21    admin(
22        list_display = "title, filename, kind, mime, size, uploaded_at",
23        search_fields = "title, filename, alt_text, description",
24        ordering = "-uploaded_at",
25        list_filter = "kind",
26    )
27)]
28pub struct Media {
29    #[rustango(primary_key)]
30    pub id: Auto<i64>,
31
32    /// Sanitized original filename.
33    #[rustango(max_length = 255)]
34    pub filename: String,
35
36    /// SHA-256 hex of the file contents. Used for rendition cache
37    /// keys + cross-tenant dedup (not implemented in this slice).
38    #[rustango(max_length = 64, index)]
39    pub content_hash: String,
40
41    /// MIME type detected at upload time.
42    #[rustango(max_length = 128)]
43    pub mime: String,
44
45    /// Size in bytes.
46    pub size: i64,
47
48    /// Discriminator: `"image"`, `"document"`, or `"other"`.
49    #[rustango(max_length = 16, index)]
50    pub kind: String,
51
52    /// Image-only: pixel width.
53    pub width: Option<i32>,
54
55    /// Image-only: pixel height.
56    pub height: Option<i32>,
57
58    /// Opaque key inside the tenant's `Storage` backend.
59    #[rustango(max_length = 512)]
60    pub storage_key: String,
61
62    /// Friendly title shown in the admin picker. Defaults to the
63    /// filename without extension.
64    #[rustango(max_length = 255)]
65    pub title: String,
66
67    /// Alt text — the contextual accessibility string for images.
68    /// Optional on non-image kinds. Distinct from [`Self::description`].
69    #[rustango(max_length = 1024)]
70    pub alt_text: String,
71
72    /// Decorative / editorial description — longer metadata about the
73    /// asset (credit, context, usage notes). NOT used as the image
74    /// `alt`: `alt_text` carries the accessibility string, this is
75    /// human-facing metadata only.
76    ///
77    /// `default = "''"` so the AddColumn migration can backfill
78    /// existing `cms_media` rows — a NOT NULL column added to a table
79    /// with data needs a default (SQLite rejects it outright; the
80    /// framework's migration guard rejects it on every dialect).
81    #[rustango(max_length = 1024, default = "''")]
82    pub description: String,
83
84    /// FK to `rustango_users.id` of the operator who uploaded — left
85    /// as a plain `Option<i64>` (no compile-time FK) so the cms crate
86    /// doesn't have to depend on the tenant-user model shape.
87    pub uploaded_by: Option<i64>,
88
89    /// FK to the collection this row belongs to. NULL means
90    /// "uncategorized" — render as the root collection in the admin.
91    /// The seed pass creates a default "Root" collection per tenant
92    /// so most rows land there.
93    #[rustango(fk = "cms_media_collection", on = "id", index)]
94    pub collection_id: Option<i64>,
95
96    /// Focal point — normalized x coordinate (0.0 = left edge,
97    /// 1.0 = right edge). When NULL, `fill-*` renditions crop
98    /// around the geometric center.
99    pub focal_point_x: Option<f32>,
100
101    /// Focal point — normalized y coordinate (0.0 = top, 1.0 = bottom).
102    pub focal_point_y: Option<f32>,
103
104    #[rustango(auto_now_add)]
105    pub uploaded_at: Auto<DateTime<Utc>>,
106}
107
108// Built-in "media" chooser so `WidgetKind::MediaPicker` renders the shared
109// chooser overlay (thumbnails + search + selected-image preview) instead of a
110// bare <select>. Backs `/cms-admin/__chooser/media`; rows carry `kind`, so the
111// overlay shows image thumbnails.
112crate::register_chooser!(crate::media::Media, "media", "Image", "title", "filename");
113
114/// Editor-curated folder for media. Tree-shaped (`parent_id` FK to
115/// self) so sites can group assets per team / per campaign / per
116/// product, with sub-folders for finer-grain organization.
117///
118/// One "Root" collection is auto-seeded per tenant on first boot so
119/// every upload has somewhere to land. Hosts can rename or delete
120/// the root — the `Media.collection_id` FK is nullable, so orphan
121/// rows just show under the root view.
122#[derive(Model, Debug, Clone, Serialize, Deserialize)]
123#[rustango(
124    table = "cms_media_collection",
125    app = "cms",
126    display = "name",
127    admin(
128        list_display = "name, parent_id, sort_order, created_at",
129        ordering = "parent_id, sort_order, name",
130    )
131)]
132pub struct MediaCollection {
133    #[rustango(primary_key)]
134    pub id: Auto<i64>,
135
136    /// Display name. Unique within a parent so the breadcrumb path
137    /// reads cleanly.
138    #[rustango(max_length = 100)]
139    pub name: String,
140
141    /// Tree parent — None for the root collection per tenant.
142    #[rustango(fk = "cms_media_collection", on = "id", index)]
143    pub parent_id: Option<i64>,
144
145    /// Sibling order — editors drag to reorder; rendered in
146    /// ascending sort_order.
147    pub sort_order: i32,
148
149    #[rustango(auto_now_add)]
150    pub created_at: Auto<DateTime<Utc>>,
151}
152
153impl Media {
154    /// Public download URL — serves the original bytes regardless of
155    /// kind (image, document, file). Use in `<img src>`, `<a href>`,
156    /// or anywhere a stable URL for the raw file is needed. The
157    /// underlying route is `/__media__/raw/{id}`, mounted by
158    /// [`crate::rendition_route::router`].
159    #[must_use]
160    pub fn public_url(&self) -> String {
161        match self.id.get() {
162            Some(id) => format!("/__media__/raw/{id}"),
163            None => String::new(),
164        }
165    }
166
167    /// Sized-image URL via the rendition pipeline (image-only).
168    /// `filter` is a pipeline spec, e.g. `"fill-300x200"`,
169    /// `"width-800"`, `"max-1200x800|format-webp"`. Returns empty
170    /// for non-image rows so callers can fall back to
171    /// [`Self::public_url`].
172    #[must_use]
173    pub fn image_url(&self, filter: &str) -> String {
174        if self.kind != "image" {
175            return String::new();
176        }
177        // Signed like every CMS-rendered image URL (#643); an unknown
178        // filter yields an empty URL.
179        match self.id.get() {
180            Some(id) => crate::rendition::rendition_url_for(*id, filter, None).unwrap_or_default(),
181            None => String::new(),
182        }
183    }
184
185    /// Classify a MIME type into the storage `kind` discriminator.
186    pub fn classify_mime(mime: &str) -> &'static str {
187        if mime.starts_with("image/") {
188            "image"
189        } else if mime.starts_with("video/")
190            || mime.starts_with("audio/")
191            || mime == "application/pdf"
192            || mime.starts_with("application/vnd.")
193            || mime.starts_with("application/msword")
194            || mime.starts_with("application/x-")
195            || mime == "text/plain"
196            || mime == "text/csv"
197        {
198            "document"
199        } else {
200            "other"
201        }
202    }
203}