Skip to main content

rustango_cms/api/
images.rs

1//! `GET /api/v2/images/` + `GET /api/v2/images/{id}/`.
2//!
3//! Read-only image metadata for headless consumers. Bytes still
4//! flow through [`crate::rendition_route`] — the API exposes
5//! `download_url_template` so clients can build the URL for any
6//! filter spec.
7
8// Our extractors, not axum's: they refuse a malformed value in the same
9// JSON envelope as everything else. See `query::Query`.
10use crate::api::query::{Path, Query};
11use axum::response::{IntoResponse, Response};
12use axum::Json;
13use rustango::core::Column as _;
14use rustango::extractors::{SessionUser, Tenant};
15use rustango::sql::FetcherPool as _;
16use serde::Deserialize;
17
18use super::query as q;
19use crate::media::Media;
20
21#[derive(Debug, Default, Deserialize)]
22pub struct ImageListQuery {
23    #[serde(flatten)]
24    pub list: q::ListQuery,
25    /// Optional collection scope: `?collection=N`.
26    #[serde(default, deserialize_with = "crate::api::query::empty_as_none")]
27    pub collection: Option<i64>,
28}
29
30/// `GET /api/v2/images/`
31pub async fn list(
32    tenant: Tenant,
33    SessionUser(session_user): SessionUser,
34    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
35    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
36    Query(qs): Query<ImageListQuery>,
37) -> Response {
38    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
39    match list_inner(&tenant, viewer, &qs).await {
40        Ok(resp) => resp,
41        Err(e) => {
42            tracing::error!(target: "rustango_cms::api", error = %e, "images list failed");
43            crate::api::error::ApiError::internal().into_response()
44        }
45    }
46}
47
48async fn list_inner(
49    tenant: &Tenant,
50    viewer: Option<&rustango::tenancy::auth::User>,
51    qs: &ImageListQuery,
52) -> Result<Response, rustango::sql::ExecError> {
53    let pool = tenant.pool();
54    let (limit, offset) = q::paginate(&qs.list);
55    let fields = q::field_set(&qs.list);
56    let orderings = match q::parse_order_in(&qs.list, &MEDIA_ORDER_FIELDS) {
57        Ok(v) => v,
58        Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
59    };
60
61    let updated_since = match crate::api::query::parse_updated_since(&qs.list) {
62        Ok(v) => v,
63        Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
64    };
65    let (window, total_count) = list_media(
66        pool,
67        viewer,
68        MediaFilter {
69            images: true,
70            collection: qs.collection,
71            search: qs.list.search.as_deref(),
72            search_alt_text: true,
73            updated_since,
74        },
75        &orderings,
76        limit,
77        offset,
78    )
79    .await?;
80
81    let mut items = Vec::with_capacity(window.len());
82    for m in &window {
83        let mut obj = serialize_image(m);
84        // Validated against the first serialized row rather than a
85        // hand-written list, so it cannot drift from what we return.
86        if let Err(msg) = q::validate_fields(fields.as_ref(), &obj) {
87            return Ok(crate::api::error::ApiError::bad_request(msg).into_response());
88        }
89        q::apply_fields(&mut obj, fields.as_ref());
90        items.push(serde_json::Value::Object(obj));
91    }
92
93    Ok(Json(q::ListEnvelope {
94        meta: q::ListMeta::paged(total_count, limit, offset),
95        items,
96    })
97    .into_response())
98}
99
100/// `GET /api/v2/images/{id}/`
101pub async fn detail(
102    tenant: Tenant,
103    SessionUser(session_user): SessionUser,
104    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
105    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
106    Path(id): Path<i64>,
107    Query(q): Query<crate::api::query::DetailFields>,
108) -> Response {
109    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
110    match detail_inner(&tenant, viewer, id, &q).await {
111        Ok(resp) => resp,
112        Err(e) => {
113            tracing::error!(target: "rustango_cms::api", error = %e, "image detail failed");
114            crate::api::error::ApiError::internal().into_response()
115        }
116    }
117}
118
119async fn detail_inner(
120    tenant: &Tenant,
121    viewer: Option<&rustango::tenancy::auth::User>,
122    id: i64,
123    q: &crate::api::query::DetailFields,
124) -> Result<Response, rustango::sql::ExecError> {
125    let row: Option<Media> = Media::objects()
126        .where_(Media::id.eq(id))
127        .where_(Media::kind.eq("image".to_owned()))
128        .first(tenant.pool())
129        .await?;
130    match row {
131        // A gated collection answers exactly as a missing asset does —
132        // otherwise this endpoint tells an anonymous caller which ids
133        // exist behind the gate.
134        Some(m) if !gated_for(tenant, viewer, &m).await => {
135            let mut obj = serialize_image(&m);
136            crate::api::query::apply_fields(&mut obj, q.keep().as_ref());
137            Ok(Json(serde_json::Value::Object(obj)).into_response())
138        }
139        _ => Ok(crate::api::error::ApiError::not_found("image").into_response()),
140    }
141}
142
143/// Is this asset's collection closed to `viewer`?
144async fn gated_for(
145    tenant: &Tenant,
146    viewer: Option<&rustango::tenancy::auth::User>,
147    media: &Media,
148) -> bool {
149    let Some(cid) = media.collection_id else {
150        return false;
151    };
152    !crate::collection_view_restriction::denied_collection_ids(tenant.pool(), viewer, &[cid])
153        .await
154        .is_empty()
155}
156
157pub(super) fn serialize_image(m: &Media) -> serde_json::Map<String, serde_json::Value> {
158    let id = m.id.get().copied().unwrap_or_default();
159    let hash_v: String = m.content_hash.chars().take(12).collect();
160    let mut obj = serde_json::Map::new();
161    obj.insert("id".to_owned(), serde_json::json!(id));
162    obj.insert(
163        "meta".to_owned(),
164        serde_json::json!({
165            "type": "cms.Image",
166            "detail_url": format!("/api/v2/images/{id}/"),
167            "download_url_template": format!(
168                "/__media__/{{filter_spec}}/{id}?v={hash_v}"
169            ),
170        }),
171    );
172    // #431 — concrete rendition URLs for common sizes. Built (and
173    // signed, when #425 signing is on) server-side so clients get
174    // ready-to-use URLs — unlike `download_url_template`, which a
175    // client can't sign.
176    let hash = m.content_hash.as_str();
177    obj.insert(
178        "renditions".to_owned(),
179        serde_json::json!({
180            "thumbnail": crate::rendition::rendition_url_for(id, "fill-100x100", Some(hash)),
181            "medium": crate::rendition::rendition_url_for(id, "width-800", Some(hash)),
182            "large": crate::rendition::rendition_url_for(id, "width-1600", Some(hash)),
183        }),
184    );
185    obj.insert("title".to_owned(), serde_json::json!(m.title));
186    obj.insert("filename".to_owned(), serde_json::json!(m.filename));
187    obj.insert("alt_text".to_owned(), serde_json::json!(m.alt_text));
188    obj.insert("description".to_owned(), serde_json::json!(m.description));
189    obj.insert("mime".to_owned(), serde_json::json!(m.mime));
190    obj.insert("size".to_owned(), serde_json::json!(m.size));
191    obj.insert("width".to_owned(), serde_json::json!(m.width));
192    obj.insert("height".to_owned(), serde_json::json!(m.height));
193    obj.insert(
194        "focal_point_x".to_owned(),
195        serde_json::json!(m.focal_point_x),
196    );
197    obj.insert(
198        "focal_point_y".to_owned(),
199        serde_json::json!(m.focal_point_y),
200    );
201    obj.insert(
202        "collection_id".to_owned(),
203        serde_json::json!(m.collection_id),
204    );
205    obj.insert(
206        "uploaded_at".to_owned(),
207        serde_json::json!(m.uploaded_at.get().copied()),
208    );
209    obj
210}
211
212/// What a media listing is narrowed by.
213pub(super) struct MediaFilter<'a> {
214    /// Images (`kind = image`) or documents (every other kind).
215    pub images: bool,
216    pub collection: Option<i64>,
217    pub search: Option<&'a str>,
218    /// Whether the search also reads `alt_text` (images only).
219    pub search_alt_text: bool,
220    pub updated_since: Option<chrono::DateTime<chrono::Utc>>,
221}
222
223/// One page of the media the viewer may see, and the total match count
224/// (#655). Exact filters always run in SQL. Without a text search and
225/// with a date/size order, counting and paging run there too; a search
226/// (accent-folded, in Rust) or a text/random order reads the narrowed
227/// set and pages it in memory.
228pub(super) async fn list_media(
229    pool: &rustango::sql::Pool,
230    viewer: Option<&rustango::tenancy::auth::User>,
231    f: MediaFilter<'_>,
232    orderings: &[q::OrderSpec],
233    limit: usize,
234    offset: usize,
235) -> Result<(Vec<Media>, usize), rustango::sql::ExecError> {
236    // #members — a gated collection's catalogue (titles, filenames, alt
237    // text) is as private as its files. The collections table is small.
238    let collection_ids: Vec<i64> = crate::media::MediaCollection::objects()
239        .fetch(pool)
240        .await?
241        .iter()
242        .filter_map(|c| c.id.get().copied())
243        .collect();
244    let denied: Vec<i64> =
245        crate::collection_view_restriction::denied_collection_ids(pool, viewer, &collection_ids)
246            .await
247            .into_iter()
248            .collect();
249    let narrowed = || {
250        let mut qs = if f.images {
251            Media::objects().where_(Media::kind.eq("image".to_owned()))
252        } else {
253            Media::objects().where_(Media::kind.ne("image".to_owned()))
254        };
255        if !denied.is_empty() {
256            qs = qs.where_(
257                Media::collection_id
258                    .is_null()
259                    .or(Media::collection_id.not_in(denied.iter().copied())),
260            );
261        }
262        if let Some(cid) = f.collection {
263            qs = qs.where_(Media::collection_id.eq(cid));
264        }
265        if let Some(since) = f.updated_since {
266            qs = qs.where_(Media::uploaded_at.gte(since));
267        }
268        qs
269    };
270    let search = f.search.map(str::trim).filter(|s| !s.is_empty());
271    let sql_order: Option<Vec<(&'static str, bool)>> = if search.is_some() {
272        None
273    } else if orderings.is_empty() {
274        Some(vec![("uploaded_at", true)])
275    } else {
276        orderings
277            .iter()
278            .map(|o| match o.field.as_str() {
279                _ if o.random => None,
280                "uploaded_at" => Some(("uploaded_at", o.descending)),
281                "size" => Some(("size", o.descending)),
282                // Text orders stay in Rust: SQL collations differ per
283                // backend, Rust's byte order does not.
284                _ => None,
285            })
286            .collect()
287    };
288    if let Some(mut order) = sql_order {
289        use rustango::sql::CounterPool as _;
290        order.push(("id", true));
291        let total = usize::try_from(narrowed().count(pool).await?).unwrap_or_default();
292        let rows = narrowed()
293            .order_by(&order)
294            .limit(limit as i64)
295            // A huge `?offset=` must not wrap negative (backends differ).
296            .offset(i64::try_from(offset).unwrap_or(i64::MAX))
297            .fetch(pool)
298            .await?;
299        return Ok((rows, total));
300    }
301    let mut rows: Vec<Media> = narrowed().order_by(&[("id", true)]).fetch(pool).await?;
302    if let Some(needle) = search {
303        let n = crate::api::search::fold(needle);
304        rows.retain(|m| {
305            crate::api::search::contains_folded(&m.title, &n)
306                || crate::api::search::contains_folded(&m.filename, &n)
307                || (f.search_alt_text && crate::api::search::contains_folded(&m.alt_text, &n))
308        });
309    }
310    if orderings.iter().any(|o| o.random) {
311        use rand::seq::SliceRandom as _;
312        rows.shuffle(&mut rand::rng());
313    } else if !orderings.is_empty() {
314        rows.sort_by(|a, b| compare_media(a, b, orderings));
315    } else {
316        rows.sort_by(|a, b| b.uploaded_at.get().cmp(&a.uploaded_at.get()));
317    }
318    let total = rows.len();
319    Ok((rows.into_iter().skip(offset).take(limit).collect(), total))
320}
321
322/// Fields `?order=` accepts on the media endpoints. Must match the arms
323/// of `compare_media` below: a field listed here but not handled there
324/// would sort by nothing, which is the bug this list exists to prevent.
325/// Shared with `documents`, which sorts the same rows.
326pub(super) const MEDIA_ORDER_FIELDS: [&str; 4] = ["title", "filename", "size", "uploaded_at"];
327
328pub(super) fn compare_media(a: &Media, b: &Media, specs: &[q::OrderSpec]) -> std::cmp::Ordering {
329    for spec in specs {
330        let ord = match spec.field.as_str() {
331            "title" => a.title.cmp(&b.title),
332            "filename" => a.filename.cmp(&b.filename),
333            "size" => a.size.cmp(&b.size),
334            "uploaded_at" => a.uploaded_at.get().cmp(&b.uploaded_at.get()),
335            _ => continue,
336        };
337        if ord != std::cmp::Ordering::Equal {
338            return if spec.descending { ord.reverse() } else { ord };
339        }
340    }
341    std::cmp::Ordering::Equal
342}