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