1use crate::api::query::{Path, Query};
16use axum::http::{HeaderMap, StatusCode};
17use axum::response::{IntoResponse, Response};
18use axum::Json;
19use rustango::core::Column as _;
20use rustango::extractors::{SessionUser, Tenant};
21use rustango::sql::FetcherPool as _;
22use serde::Deserialize;
23
24use super::query as q;
25use crate::page::{Page, PageStatus};
26use crate::page_type::{find_handler, PageTypeHandler};
27use crate::page_type_model::PageType;
28
29#[derive(Debug, Default, Deserialize)]
31pub struct PageFilters {
32 #[serde(default, deserialize_with = "q::empty_string_as_none")]
34 pub r#type: Option<String>,
35 #[serde(default, deserialize_with = "q::empty_as_none")]
37 pub child_of: Option<i64>,
38 #[serde(default, deserialize_with = "q::empty_as_none")]
40 pub descendant_of: Option<i64>,
41 #[serde(default, deserialize_with = "q::empty_as_none")]
43 pub ancestor_of: Option<i64>,
44 #[serde(default, deserialize_with = "q::empty_as_none")]
46 pub translation_of: Option<i64>,
47 #[serde(default, deserialize_with = "q::empty_string_as_none")]
49 pub locale: Option<String>,
50 #[serde(default, deserialize_with = "q::empty_string_as_none")]
52 pub tag: Option<String>,
53 #[serde(default, deserialize_with = "q::empty_string_as_none")]
61 pub id_in: Option<String>,
62}
63
64#[derive(Debug, Default, Deserialize)]
66pub struct PageListQuery {
67 #[serde(flatten)]
68 pub list: q::ListQuery,
69 #[serde(flatten)]
70 pub filters: PageFilters,
71}
72
73#[derive(Debug, Default, Deserialize)]
75pub struct FindQuery {
76 #[serde(default, deserialize_with = "q::empty_string_as_none")]
79 pub html_path: Option<String>,
80}
81
82#[derive(Default, Deserialize)]
84pub struct DetailQuery {
85 #[serde(default, deserialize_with = "q::empty_string_as_none")]
90 pub preview_token: Option<String>,
91 #[serde(default, deserialize_with = "q::empty_string_as_none")]
100 pub locale: Option<String>,
101 #[serde(default, deserialize_with = "q::empty_string_as_none")]
106 pub fields: Option<String>,
107}
108
109pub async fn list(
111 tenant: Tenant,
112 SessionUser(session_user): SessionUser,
113 rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
114 crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
115 Query(qs): Query<PageListQuery>,
116) -> Response {
117 let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
120 match list_inner(tenant.pool(), &tenant.org.slug, viewer, &qs).await {
121 Ok(resp) => resp,
122 Err(e) => {
123 tracing::error!(target: "rustango_cms::api", error = %e, "pages list failed");
124 crate::api::error::ApiError::internal().into_response()
125 }
126 }
127}
128
129struct PageScope {
133 translation_of: Option<i64>,
136 type_id: Option<i64>,
137 updated_since: Option<chrono::DateTime<chrono::Utc>>,
138 id_in: Option<Vec<i64>>,
139 child_of: Option<i64>,
140 descendant_prefix: Option<String>,
142 ancestor_paths: Option<Vec<String>>,
144 variants_only: bool,
146 tag: Option<String>,
148 matches_nothing: bool,
151}
152
153impl PageScope {
154 fn base(&self) -> rustango::query::QuerySet<Page> {
160 let mut qs = Page::objects().where_(Page::status.is_in([
161 PageStatus::Published.as_str().to_owned(),
162 PageStatus::Archived.as_str().to_owned(),
163 ]));
164 if self.translation_of.is_none() {
165 qs = qs.where_(Page::locale_variant_of.is_null());
166 }
167 if let Some(tid) = self.type_id {
168 qs = qs.where_(Page::page_type_id.eq(tid));
169 }
170 if let Some(since) = self.updated_since {
171 qs = qs.where_(Page::updated_at.gte(since));
172 }
173 if let Some(ids) = &self.id_in {
174 qs = qs.where_(Page::id.is_in(ids.iter().copied()));
175 }
176 if let Some(parent) = self.child_of {
177 qs = qs.where_(Page::parent_id.eq(parent));
178 }
179 qs
180 }
181
182 fn narrowed(&self) -> Result<rustango::query::QuerySet<Page>, rustango::sql::ExecError> {
184 let mut qs = self.base();
185 if let Some(prefix) = &self.descendant_prefix {
186 qs = qs.where_(Page::path.like(format!("{prefix}%")));
189 qs = qs.where_(Page::path.ne(prefix.clone()));
190 }
191 if let Some(paths) = &self.ancestor_paths {
192 qs = qs.where_(Page::path.is_in(paths.iter().cloned()));
193 }
194 if let Some(canon) = self.translation_of {
195 qs = qs.where_(Page::locale_variant_of.eq(canon));
196 }
197 if self.variants_only {
198 qs = qs.where_(Page::locale_variant_of.is_not_null());
199 }
200 if let Some(tag) = &self.tag {
201 let tagged = crate::page_tag::PageTag::objects()
204 .where_(crate::page_tag::PageTag::name.eq(tag.clone()))
205 .values_list_flat("page_id")
206 .compile()?;
207 qs = qs.where_(rustango::core::TypedExpr::from_where_expr(
208 rustango::core::subquery::in_subquery("id", tagged),
209 ));
210 }
211 Ok(qs)
212 }
213}
214
215enum SqlOrder {
217 Default,
219 Keys(Vec<(&'static str, bool, rustango::core::NullsOrder)>),
221}
222
223fn sql_order(orderings: &[q::OrderSpec]) -> Option<SqlOrder> {
227 use rustango::core::NullsOrder;
228 if orderings.is_empty() {
229 return Some(SqlOrder::Default);
230 }
231 let mut keys = Vec::with_capacity(orderings.len() + 1);
232 for o in orderings {
233 if o.random {
234 return None;
235 }
236 let col = match o.field.as_str() {
237 "published_at" => "published_at",
238 "updated_at" => "updated_at",
239 "created_at" => "created_at",
240 "depth" => "depth",
241 "sort_order" => "sort_order",
242 _ => return None,
243 };
244 let nulls = if col != "published_at" {
246 NullsOrder::Default
247 } else if o.descending {
248 NullsOrder::Last
249 } else {
250 NullsOrder::First
251 };
252 keys.push((col, o.descending, nulls));
253 }
254 keys.push(("id", false, NullsOrder::Default));
255 Some(SqlOrder::Keys(keys))
256}
257
258fn compare_default(a: &Page, b: &Page) -> std::cmp::Ordering {
261 b.published_at
262 .cmp(&a.published_at)
263 .then_with(|| a.title.cmp(&b.title))
264 .then_with(|| a.id.get().cmp(&b.id.get()))
268}
269
270const MAX_ID_IN: usize = 200;
279
280async fn default_order_window(
287 pool: &rustango::sql::Pool,
288 scope: &PageScope,
289 limit: usize,
290 offset: usize,
291) -> Result<Vec<Page>, rustango::sql::ExecError> {
292 use rustango::core::NullsOrder;
293 use rustango::sql::CounterPool as _;
294 let sql_window: Vec<Page> = scope
295 .narrowed()?
296 .order_by_with_nulls(&[
297 ("published_at", true, NullsOrder::Last),
298 ("id", false, NullsOrder::Default),
299 ])
300 .limit(i64::try_from(limit).unwrap_or(i64::MAX))
301 .offset(i64::try_from(offset).unwrap_or(i64::MAX))
303 .fetch(pool)
304 .await?;
305 let (Some(first), Some(last)) = (sql_window.first(), sql_window.last()) else {
306 return Ok(Vec::new());
307 };
308 let (first_key, last_key) = (first.published_at, last.published_at);
309 let ahead = match first_key {
310 Some(t) => scope.narrowed()?.where_(Page::published_at.gt(t)).count(pool).await?,
311 None => scope.narrowed()?.where_(Page::published_at.is_not_null()).count(pool).await?,
313 };
314 let group = |key: Option<chrono::DateTime<chrono::Utc>>| -> Result<_, rustango::sql::ExecError> {
315 Ok(match key {
316 Some(t) => scope.narrowed()?.where_(Page::published_at.eq(t)),
317 None => scope.narrowed()?.where_(Page::published_at.is_null()),
318 })
319 };
320 let mut run: Vec<Page> = group(first_key)?.fetch(pool).await?;
321 if last_key != first_key {
322 run.extend(
323 sql_window
324 .into_iter()
325 .filter(|p| p.published_at != first_key && p.published_at != last_key),
326 );
327 run.extend(group(last_key)?.fetch(pool).await?);
328 }
329 run.sort_by(compare_default);
330 let skip = offset.saturating_sub(usize::try_from(ahead).unwrap_or_default());
331 Ok(run.into_iter().skip(skip).take(limit).collect())
332}
333
334async fn visible_anchor_path(
340 pool: &rustango::sql::Pool,
341 base: rustango::query::QuerySet<Page>,
342 access: &crate::view_restriction::AccessContext,
343 id: i64,
344) -> Result<Option<String>, rustango::sql::ExecError> {
345 let anchor: Option<Page> = base.where_(Page::id.eq(id)).first(pool).await?;
346 Ok(anchor
347 .filter(|p| access.can_view(&p.path, p.page_type_id))
348 .map(|p| p.path))
349}
350
351pub async fn list_inner(
365 pool: &rustango::sql::Pool,
366 tenant_slug: &str,
367 viewer: Option<&rustango::tenancy::auth::User>,
368 qs: &PageListQuery,
369) -> Result<Response, rustango::sql::ExecError> {
370 let (limit, offset) = q::paginate(&qs.list);
371 let fields = q::field_set(&qs.list);
372 let orderings = match q::parse_order_in(&qs.list, &PAGE_ORDER_FIELDS) {
373 Ok(v) => v,
374 Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
375 };
376 let updated_since = match crate::api::query::parse_updated_since(&qs.list) {
379 Ok(v) => v,
380 Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
381 };
382 let mut id_in: Option<Vec<i64>> = None;
391 if let Some(raw) = qs.filters.id_in.as_deref() {
392 let mut wanted = std::collections::BTreeSet::new();
393 for seg in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
394 match seg.parse::<i64>() {
395 Ok(id) => {
396 wanted.insert(id);
397 }
398 Err(_) => {
399 return Ok(crate::api::error::ApiError::bad_request(format!(
400 "`id_in` expects comma-separated integers; `{seg}` is not one",
401 ))
402 .into_response())
403 }
404 }
405 }
406 if wanted.len() > MAX_ID_IN {
409 return Ok(crate::api::error::ApiError::bad_request(format!(
410 "`id_in` takes at most {MAX_ID_IN} ids; got {}",
411 wanted.len()
412 ))
413 .into_response());
414 }
415 id_in = Some(wanted.into_iter().collect());
416 }
417
418 if orderings.iter().any(|o| o.random) && offset > 0 {
422 return Ok(crate::api::error::ApiError::bad_request(
423 "`order=random` cannot be paged — omit `offset`, or order by a field",
424 )
425 .into_response());
426 }
427 let mut scope = PageScope {
437 translation_of: qs.filters.translation_of,
438 type_id: None,
439 updated_since,
440 matches_nothing: id_in.as_ref().is_some_and(Vec::is_empty),
441 id_in,
442 child_of: qs.filters.child_of,
443 descendant_prefix: None,
444 ancestor_paths: None,
445 variants_only: false,
446 tag: None,
447 };
448
449 if let Some(type_name) = qs.filters.r#type.as_deref().filter(|s| !s.is_empty()) {
451 let bare = type_name.rsplit('.').next().unwrap_or(type_name);
456 match lookup_page_type(pool, bare).await? {
457 Some(pt) => scope.type_id = Some(pt.id.get().copied().unwrap_or_default()),
458 None => scope.matches_nothing = true,
459 }
460 }
461
462 let access = crate::view_restriction::access_context(pool, viewer).await;
468
469 let mut descendant_prefix = None;
475 let mut ancestor_paths = None;
476 if !scope.matches_nothing {
477 if let Some(root_id) = qs.filters.descendant_of {
478 descendant_prefix = visible_anchor_path(pool, scope.base(), &access, root_id).await?;
479 if descendant_prefix.is_none() {
480 scope.matches_nothing = true;
481 }
482 }
483 if let Some(leaf_id) = qs.filters.ancestor_of {
484 match visible_anchor_path(pool, scope.base(), &access, leaf_id).await? {
485 Some(path) => {
486 let paths: Vec<String> = ancestor_paths_of(&path).into_iter().collect();
487 if paths.is_empty() {
488 scope.matches_nothing = true;
489 }
490 ancestor_paths = Some(paths);
491 }
492 None => scope.matches_nothing = true,
493 }
494 }
495 }
496 scope.descendant_prefix = descendant_prefix;
497 scope.ancestor_paths = ancestor_paths;
498
499 if let Some(code) = qs.filters.locale.as_deref().filter(|s| !s.is_empty()) {
501 let locale = crate::translation::resolve_locale(pool, Some(code)).await?;
509 scope.variants_only = locale.is_some_and(|loc| !loc.is_default);
510 }
511
512 if let Some(raw) = qs.filters.tag.as_deref().filter(|s| !s.is_empty()) {
514 scope.tag = Some(crate::page_tag::normalize_name(raw));
515 }
516
517 let search_needle = qs.list.search.as_deref().filter(|s| !s.trim().is_empty());
520
521 let fast = if search_needle.is_some() || !access.denies_nothing() {
523 None
524 } else {
525 sql_order(&orderings)
526 };
527 let mut fts_ordered = false;
528 let (window, total_count): (Vec<Page>, usize) = if scope.matches_nothing && fast.is_some() {
529 (Vec::new(), 0)
530 } else if let Some(order) = fast {
531 use rustango::sql::CounterPool as _;
532 let total = usize::try_from(scope.narrowed()?.count(pool).await?).unwrap_or_default();
533 let rows = match order {
534 SqlOrder::Default => default_order_window(pool, &scope, limit, offset).await?,
535 SqlOrder::Keys(keys) => {
536 scope
537 .narrowed()?
538 .order_by_with_nulls(&keys)
539 .limit(i64::try_from(limit).unwrap_or(i64::MAX))
540 .offset(i64::try_from(offset).unwrap_or(i64::MAX))
542 .fetch(pool)
543 .await?
544 }
545 };
546 (rows, total)
547 } else {
548 let mut pages: Vec<Page> = if scope.matches_nothing {
549 Vec::new()
550 } else {
551 scope
552 .narrowed()?
553 .order_by(&[("id", false)])
558 .fetch(pool)
559 .await?
560 };
561 if !access.is_unrestricted() {
562 pages.retain(|p| access.can_view(&p.path, p.page_type_id));
563 }
564
565 if let Some(needle) = search_needle {
571 crate::search_promotion::log_public_query(pool, needle, offset);
572 let ranked =
573 crate::search::ranked_public_page_ids(pool, tenant_slug, needle, 1000).await;
574 let rank: Option<std::collections::HashMap<i64, usize>> =
581 ranked.map(|r| r.iter().enumerate().map(|(i, id)| (*id, i)).collect());
582 let n = crate::api::search::fold(needle);
583 pages.retain(|p| {
584 rank.as_ref()
585 .is_some_and(|r| p.id.get().copied().is_some_and(|id| r.contains_key(&id)))
586 || crate::api::search::contains_folded(&p.title, &n)
587 || crate::api::search::contains_folded(&p.slug, &n)
588 || crate::api::search::contains_folded(&p.url_path, &n)
589 });
590 if let Some(rank) = &rank {
591 pages.sort_by_key(|p| {
592 p.id.get()
593 .copied()
594 .and_then(|id| rank.get(&id).copied())
595 .unwrap_or(usize::MAX)
596 });
597 fts_ordered = true;
598 }
599 }
600
601 if fts_ordered && orderings.is_empty() {
604 } else if orderings.iter().any(|o| o.random) {
606 use rand::seq::SliceRandom as _;
608 pages.shuffle(&mut rand::rng());
609 } else if !orderings.is_empty() {
610 pages.sort_by(|a, b| compare_pages(a, b, &orderings));
611 } else {
612 pages.sort_by(compare_default);
613 }
614
615 if let Some(needle) = search_needle {
627 if let Ok(Some(q)) = crate::search_promotion::find_by_query(pool, needle).await {
628 let query_id = q.id.get().copied().unwrap_or_default();
629 if query_id != 0 {
630 if let Ok(promos) =
631 crate::search_promotion::promotions_for_query(pool, query_id).await
632 {
633 let mut pinned: Vec<Page> = Vec::with_capacity(promos.len());
639 for p in &promos {
640 if let Some(pos) = pages
641 .iter()
642 .position(|page| page.id.get().copied() == Some(p.page_id))
643 {
644 pinned.push(pages.remove(pos));
645 }
646 }
647 for (i, page) in pinned.into_iter().enumerate() {
648 pages.insert(i, page);
649 }
650 }
651 }
652 }
653 }
654
655 let total = pages.len();
656 (pages.into_iter().skip(offset).take(limit).collect(), total)
657 };
658
659 let did_you_mean = match (fts_ordered, total_count, search_needle) {
665 (true, 0, Some(needle)) => match crate::search::did_you_mean(pool, needle, 0.3).await {
666 Some(title) => visible_title(pool, viewer, &title).await,
667 None => None,
668 },
669 _ => None,
670 };
671
672 let type_names = page_type_names(pool).await?;
674 let mut items = Vec::with_capacity(window.len());
675 for p in &window {
676 let mut obj = serialize_summary(p, &type_names);
677 if let Err(msg) = q::validate_fields(fields.as_ref(), &obj) {
680 return Ok(crate::api::error::ApiError::bad_request(msg).into_response());
681 }
682 q::apply_fields(&mut obj, fields.as_ref());
683 items.push(serde_json::Value::Object(obj));
684 }
685
686 let envelope = q::ListEnvelope {
687 meta: q::ListMeta {
688 did_you_mean,
689 ..q::ListMeta::paged(total_count, limit, offset)
690 },
691 items,
692 };
693 Ok(Json(envelope).into_response())
694}
695
696pub async fn detail(
698 tenant: Tenant,
699 SessionUser(session_user): SessionUser,
700 rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
701 crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
702 headers: HeaderMap,
703 Path(id): Path<i64>,
704 Query(qs): Query<DetailQuery>,
705) -> Response {
706 let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
708 let allow_draft = qs
710 .preview_token
711 .as_deref()
712 .zip(rustango::tenancy::TenantSlug::of(&tenant.org))
713 .and_then(|(t, org)| crate::preview_token::verify(&org, t, chrono::Utc::now().timestamp()))
714 == Some(id);
715 match detail_inner(
716 &tenant,
717 viewer,
718 &headers,
719 id,
720 allow_draft,
721 qs.locale.as_deref(),
722 qs.fields.as_deref(),
723 )
724 .await
725 {
726 Ok(resp) => resp,
727 Err(e) => {
728 tracing::error!(target: "rustango_cms::api", error = %e, "page detail failed");
729 crate::api::error::ApiError::internal().into_response()
730 }
731 }
732}
733
734pub async fn find(
739 tenant: Tenant,
740 SessionUser(session_user): SessionUser,
741 rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
742 crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
743 axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
744 Query(qs): Query<FindQuery>,
745) -> Response {
746 let Some(html_path) = qs.html_path.filter(|p| !p.is_empty()) else {
747 return crate::api::error::ApiError::bad_request("missing `html_path` query parameter")
748 .into_response();
749 };
750 let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
751 let carry = carried_query(raw_query.as_deref());
752 match find_inner(&tenant, viewer, &html_path, &carry).await {
753 Ok(resp) => resp,
754 Err(e) => {
755 tracing::error!(target: "rustango_cms::api", error = %e, "page find failed");
756 crate::api::error::ApiError::internal().into_response()
757 }
758 }
759}
760
761fn carried_query(raw: Option<&str>) -> String {
776 let Some(raw) = raw.filter(|r| !r.is_empty()) else {
777 return String::new();
778 };
779 let kept: Vec<&str> = raw
780 .split('&')
781 .filter(|pair| !pair.is_empty())
782 .filter(|pair| {
783 let name = pair.split('=').next().unwrap_or("");
784 name != "html_path"
785 })
786 .collect();
787 if kept.is_empty() {
788 String::new()
789 } else {
790 format!("?{}", kept.join("&"))
791 }
792}
793
794async fn find_inner(
795 tenant: &Tenant,
796 viewer: Option<&rustango::tenancy::auth::User>,
797 html_path: &str,
798 carry: &str,
799) -> Result<Response, rustango::sql::ExecError> {
800 let pool = tenant.pool();
801 let mut rows: Vec<Page> = Page::objects()
804 .where_(Page::url_path.eq(html_path))
805 .fetch(pool)
806 .await?;
807 if rows.is_empty() {
808 let alt = if let Some(stripped) = html_path.strip_suffix('/') {
809 stripped.to_owned()
810 } else {
811 format!("{html_path}/")
812 };
813 rows = Page::objects()
814 .where_(Page::url_path.eq(alt))
815 .fetch(pool)
816 .await?;
817 }
818 let hit = rows
825 .into_iter()
826 .find(|p| PageStatus::str_is_public(&p.status));
827
828 let id = match hit {
834 Some(p) => {
835 let pid = p.id.get().copied().unwrap_or_default();
836 let denied = crate::view_restriction::denied_page_ids(
837 pool,
838 viewer,
839 &[(pid, p.path.clone(), p.page_type_id)],
840 )
841 .await;
842 if denied.contains(&pid) {
843 None
844 } else {
845 Some(pid)
846 }
847 }
848 None => None,
849 };
850 match id {
851 Some(id) => Ok((
853 StatusCode::FOUND,
854 [(
855 axum::http::header::LOCATION,
856 format!("/api/v2/pages/{id}/{carry}"),
857 )],
858 )
859 .into_response()),
860 None => Ok(crate::api::error::ApiError::not_found("page").into_response()),
865 }
866}
867
868async fn detail_inner(
869 tenant: &Tenant,
870 viewer: Option<&rustango::tenancy::auth::User>,
871 headers: &HeaderMap,
872 id: i64,
873 allow_draft: bool,
874 locale_code: Option<&str>,
875 fields: Option<&str>,
876) -> Result<Response, rustango::sql::ExecError> {
877 let pool = tenant.pool();
878 let Some(page) = lookup_page(pool, id).await? else {
879 return Ok(crate::api::error::ApiError::not_found("page").into_response());
880 };
881 let is_public = PageStatus::str_is_public(&page.status);
888 if !is_public && !allow_draft {
889 return Ok(crate::api::error::ApiError::not_found("page").into_response());
890 }
891 if let Some(denial) =
900 crate::view_restriction_guard::decide(tenant, &page, viewer, headers).await
901 {
902 use crate::view_restriction_guard::Denial;
903 return Ok(match denial {
904 Denial::NeedsLogin => crate::api::error::ApiError::unauthenticated(),
905 Denial::Forbidden => crate::api::error::ApiError::forbidden(),
906 Denial::NeedsPassword { .. } => crate::api::error::ApiError::password_required(),
907 }
908 .into_response());
909 }
910
911 let mut alias_owned = None;
917 if let Some(source_id) = page.alias_of {
918 match lookup_page(pool, source_id).await? {
919 Some(src) => alias_owned = Some(crate::page::alias_hybrid(&page, &src)),
920 None => tracing::warn!(
921 target: "rustango_cms::api",
922 alias_id = ?page.id.get().copied(),
923 source_id,
924 "alias source missing — serving the alias row verbatim",
925 ),
926 }
927 }
928 let page = alias_owned.as_ref().unwrap_or(&page);
929
930 let type_name = page_type_names(pool)
931 .await?
932 .get(&page.page_type_id)
933 .cloned()
934 .unwrap_or_default();
935 let locale = crate::translation::resolve_locale(pool, locale_code)
938 .await
939 .ok()
940 .flatten();
941 let locale_id = locale
944 .as_ref()
945 .filter(|l| !l.is_default)
946 .and_then(|l| l.id.get().copied());
947 let mut obj =
948 detail_object_with_type(pool, page, &type_name, None, None, locale_id, viewer).await;
949
950 echo_locale(&mut obj, locale.as_ref());
951
952 let keep = fields.map(|raw| -> std::collections::HashSet<String> {
954 raw.split(',')
955 .map(str::trim)
956 .filter(|s| !s.is_empty())
957 .map(str::to_owned)
958 .collect()
959 });
960 q::apply_fields(&mut obj, keep.as_ref());
961
962 Ok(Json(serde_json::Value::Object(obj)).into_response())
963}
964
965async fn visible_title(
972 pool: &rustango::sql::Pool,
973 viewer: Option<&rustango::tenancy::auth::User>,
974 title: &str,
975) -> Option<String> {
976 let matches: Vec<Page> = Page::objects()
977 .where_(Page::title.eq(title.to_owned()))
978 .where_(Page::status.eq(PageStatus::Published.as_str().to_owned()))
979 .fetch(pool)
980 .await
981 .ok()?;
982 if matches.is_empty() {
983 return None;
984 }
985 let triples: Vec<(i64, String, i64)> = matches
986 .iter()
987 .map(|p| {
988 (
989 p.id.get().copied().unwrap_or_default(),
990 p.path.clone(),
991 p.page_type_id,
992 )
993 })
994 .collect();
995 let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;
996 triples
997 .iter()
998 .any(|(id, _, _)| !denied.contains(id))
999 .then(|| title.to_owned())
1000}
1001
1002pub(crate) fn echo_locale(
1008 obj: &mut serde_json::Map<String, serde_json::Value>,
1009 locale: Option<&crate::locale::Locale>,
1010) {
1011 if let Some(meta) = obj.get_mut("meta").and_then(|m| m.as_object_mut()) {
1012 meta.insert(
1013 "locale".to_owned(),
1014 locale.map_or(serde_json::Value::Null, |l| serde_json::Value::String(l.code.clone())),
1015 );
1016 }
1017}
1018
1019pub async fn detail_object_with_type(
1045 pool: &rustango::sql::Pool,
1046 page: &Page,
1047 type_name: &str,
1048 extension_override: Option<serde_json::Value>,
1049 builder_override: Option<serde_json::Value>,
1050 locale_id: Option<i64>,
1051 viewer: Option<&rustango::tenancy::auth::User>,
1052) -> serde_json::Map<String, serde_json::Value> {
1053 let id = page.id.get().copied().unwrap_or_default();
1054 let content_id = page.alias_of.unwrap_or(id);
1058 let mut type_names = std::collections::HashMap::new();
1059 type_names.insert(page.page_type_id, type_name.to_owned());
1060 let mut obj = serialize_summary(page, &type_names);
1061
1062 let handler: Option<Box<dyn PageTypeHandler>> = find_handler(type_name);
1065 if let Some(h) = handler {
1066 let routes = h.routes();
1070 if !routes.is_empty() {
1071 let arr: Vec<serde_json::Value> = routes
1072 .iter()
1073 .map(|r| serde_json::json!({ "name": r.name, "pattern": r.pattern.as_str() }))
1074 .collect();
1075 obj.insert("routes".to_owned(), serde_json::Value::Array(arr));
1076 }
1077 let streams = stream_field_names(h.as_ref(), pool, content_id).await;
1078 match extension_override {
1079 Some(mut ext) => {
1080 if !ext.is_null() {
1081 decode_stream_fields(&mut ext, &streams);
1082 obj.insert("extension".to_owned(), ext);
1083 }
1084 }
1085 None => match h.load_extension(pool, content_id).await {
1086 Ok(mut ext) if !ext.is_null() => {
1087 decode_stream_fields(&mut ext, &streams);
1088 obj.insert("extension".to_owned(), ext);
1089 }
1090 Ok(_) => {}
1091 Err(e) => {
1092 tracing::warn!(
1093 target: "rustango_cms::api",
1094 page_id = id,
1095 error = %e,
1096 "load_extension failed in api detail",
1097 );
1098 }
1099 },
1100 }
1101 }
1102
1103 let mut compiled_schema = None;
1112 match builder_override {
1113 Some(values) => {
1114 obj.insert("builder".to_owned(), values);
1115 if locale_id.is_some() {
1116 compiled_schema = crate::page_builder::values::values_for(
1117 pool,
1118 content_id,
1119 page.page_type_id,
1120 None,
1121 )
1122 .await
1123 .map(|(_, c)| c);
1124 }
1125 }
1126 None => {
1127 if let Some((values, compiled)) =
1128 crate::page_builder::values::values_for(pool, content_id, page.page_type_id, None)
1129 .await
1130 {
1131 obj.insert("builder".to_owned(), values);
1132 compiled_schema = Some(compiled);
1133 }
1134 }
1135 }
1136
1137 if let Some(lid) = locale_id {
1138 localize_detail_object(pool, id, type_name, lid, &mut obj, compiled_schema.as_ref()).await;
1139 }
1140
1141 obj.insert(
1145 "children".to_owned(),
1146 serde_json::Value::Array(child_summaries(pool, page, viewer, locale_id).await),
1147 );
1148
1149 obj
1150}
1151
1152pub const MAX_CHILDREN: usize = 100;
1160
1161async fn child_summaries(
1175 pool: &rustango::sql::Pool,
1176 page: &Page,
1177 viewer: Option<&rustango::tenancy::auth::User>,
1178 locale_id: Option<i64>,
1179) -> Vec<serde_json::Value> {
1180 let Some(&parent_id) = page.id.get() else {
1182 return Vec::new();
1183 };
1184 if page.path.is_empty() {
1185 return Vec::new();
1186 }
1187
1188 let statuses = [
1192 PageStatus::Published.as_str().to_owned(),
1193 PageStatus::Archived.as_str().to_owned(),
1194 ];
1195 let mut rows: Vec<Page> = match Page::objects()
1196 .where_(Page::path.like(crate::tree::descendants_like(&page.path)))
1197 .where_(Page::depth.is_in([page.depth + 1, page.depth + 2]))
1198 .where_(Page::status.is_in(statuses))
1199 .order_by(&[("path", false)])
1200 .fetch(pool)
1201 .await
1202 {
1203 Ok(rows) => rows,
1204 Err(e) => {
1205 tracing::warn!(
1206 target: "rustango_cms::api",
1207 page_id = parent_id,
1208 error = %e,
1209 "child summaries lookup failed",
1210 );
1211 return Vec::new();
1212 }
1213 };
1214
1215 let error_tid = crate::error_pages::error_page_type_id(pool).await;
1219 rows.retain(|p| error_tid.is_none_or(|tid| p.page_type_id != tid));
1220
1221 let triples: Vec<(i64, String, i64)> = rows
1224 .iter()
1225 .map(|p| {
1226 (
1227 p.id.get().copied().unwrap_or_default(),
1228 p.path.clone(),
1229 p.page_type_id,
1230 )
1231 })
1232 .collect();
1233 let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;
1234
1235 let visible: Vec<&Page> = rows
1236 .iter()
1237 .filter(|p| !denied.contains(&p.id.get().copied().unwrap_or_default()))
1238 .filter(|p| p.locale_variant_of.is_none())
1242 .collect();
1243
1244 let mut grandchildren: std::collections::HashSet<i64> = std::collections::HashSet::new();
1245 for p in visible.iter().filter(|p| p.depth == page.depth + 2) {
1246 if let Some(pid) = p.parent_id {
1247 grandchildren.insert(pid);
1248 }
1249 }
1250
1251 let mut children: Vec<&&Page> = visible
1252 .iter()
1253 .filter(|p| p.depth == page.depth + 1)
1254 .collect();
1255 children.sort_by_key(|p| (p.sort_order, p.id.get().copied().unwrap_or_default()));
1258 if children.is_empty() {
1259 return Vec::new();
1260 }
1261
1262 let translations = match locale_id {
1264 Some(lid) => {
1265 let ids: Vec<i64> = children.iter().filter_map(|p| p.id.get().copied()).collect();
1266 crate::translation::fetch_for_pages(pool, &ids, lid)
1267 .await
1268 .unwrap_or_default()
1269 }
1270 None => std::collections::HashMap::new(),
1271 };
1272
1273 children
1274 .into_iter()
1275 .take(MAX_CHILDREN)
1276 .map(|p| {
1277 let id = p.id.get().copied().unwrap_or_default();
1278 let title = translations
1279 .get(&id)
1280 .and_then(|m| m.get("title"))
1281 .filter(|s| !s.is_empty())
1282 .cloned()
1283 .unwrap_or_else(|| p.title.clone());
1284 serde_json::json!({
1285 "id": id,
1286 "title": title,
1287 "slug": p.slug,
1288 "url": if p.url_path.is_empty() { "/" } else { p.url_path.as_str() },
1289 "has_children": grandchildren.contains(&id),
1290 "detail_url": format!("/api/v2/pages/{id}/"),
1291 })
1292 })
1293 .collect()
1294}
1295
1296async fn stream_field_names(
1301 h: &dyn PageTypeHandler,
1302 pool: &rustango::sql::Pool,
1303 page_id: i64,
1304) -> Vec<String> {
1305 h.widgets(pool, page_id)
1306 .await
1307 .unwrap_or_default()
1308 .into_iter()
1309 .filter(|w| w.kind == crate::widget::WidgetKind::Stream)
1310 .map(|w| w.name)
1311 .collect()
1312}
1313
1314fn decode_stream_fields(ext: &mut serde_json::Value, names: &[String]) {
1319 let Some(map) = ext.as_object_mut() else {
1320 return;
1321 };
1322 for name in names {
1323 let Some(serde_json::Value::String(raw)) = map.get(name) else {
1324 continue;
1325 };
1326 let decoded = if raw.trim().is_empty() {
1327 serde_json::Value::Array(Vec::new())
1328 } else {
1329 match serde_json::from_str::<serde_json::Value>(raw) {
1330 Ok(v @ serde_json::Value::Array(_)) => v,
1331 _ => continue,
1332 }
1333 };
1334 map.insert(name.clone(), decoded);
1335 }
1336}
1337
1338async fn localize_detail_object(
1357 pool: &rustango::sql::Pool,
1358 page_id: i64,
1359 type_name: &str,
1360 locale_id: i64,
1361 obj: &mut serde_json::Map<String, serde_json::Value>,
1362 compiled: Option<&crate::page_builder::compile::CompiledSchema>,
1363) {
1364 let by_page = crate::translation::fetch_for_pages(pool, &[page_id], locale_id)
1365 .await
1366 .unwrap_or_default();
1367 let Some(here) = by_page.get(&page_id) else {
1368 return; };
1370
1371 let mut value = serde_json::Value::Object(std::mem::take(obj));
1372 crate::translation::overlay_translations(&mut value, &by_page);
1373
1374 if let Some(h) = find_handler(type_name) {
1379 let stream_fields = stream_field_names(h.as_ref(), pool, page_id).await;
1380 if let Some(ext) = value.get_mut("extension") {
1381 decode_stream_fields(ext, &stream_fields);
1384 for name in stream_fields {
1385 if let Some(raw) = ext.get(&name).cloned() {
1386 let localized =
1387 crate::block::translate::apply_translatable_overrides(&name, &raw, here);
1388 if let Some(m) = ext.as_object_mut() {
1389 m.insert(name, localized);
1390 }
1391 }
1392 }
1393 }
1394 }
1395
1396 if let (Some(compiled), Some(builder)) = (compiled, value.get_mut("builder")) {
1397 if let Some(map) = builder.as_object_mut() {
1398 crate::page_builder::values::apply_builder_translations(compiled, map, here);
1399 }
1400 }
1401
1402 if let serde_json::Value::Object(m) = value {
1403 *obj = m;
1404 }
1405}
1406
1407async fn lookup_page(
1412 pool: &rustango::sql::Pool,
1413 id: i64,
1414) -> Result<Option<Page>, rustango::sql::ExecError> {
1415 let mut rows: Vec<Page> = Page::objects().where_(Page::id.eq(id)).fetch(pool).await?;
1416 Ok(rows.pop())
1417}
1418
1419async fn lookup_page_type(
1420 pool: &rustango::sql::Pool,
1421 type_name: &str,
1422) -> Result<Option<PageType>, rustango::sql::ExecError> {
1423 let mut rows: Vec<PageType> = PageType::objects()
1424 .where_(PageType::type_name.eq(type_name.to_owned()))
1425 .fetch(pool)
1426 .await?;
1427 Ok(rows.pop())
1428}
1429
1430pub(crate) async fn page_type_names(
1433 pool: &rustango::sql::Pool,
1434) -> Result<std::collections::HashMap<i64, String>, rustango::sql::ExecError> {
1435 let rows: Vec<PageType> = PageType::objects().fetch(pool).await?;
1436 Ok(rows
1437 .into_iter()
1438 .filter_map(|pt| pt.id.get().copied().map(|id| (id, pt.type_name)))
1439 .collect())
1440}
1441
1442fn serialize_summary(
1443 p: &Page,
1444 type_names: &std::collections::HashMap<i64, String>,
1445) -> serde_json::Map<String, serde_json::Value> {
1446 let id = p.id.get().copied().unwrap_or_default();
1447 let type_name = type_names.get(&p.page_type_id).cloned().unwrap_or_default();
1448 let mut obj = serde_json::Map::new();
1449 obj.insert("id".to_owned(), serde_json::json!(id));
1450 obj.insert(
1451 "meta".to_owned(),
1452 serde_json::json!({
1453 "type": type_name,
1454 "detail_url": format!("/api/v2/pages/{id}/"),
1455 "html_url": p.url_path,
1456 "slug": p.slug,
1457 "depth": p.depth,
1458 "parent_id": p.parent_id,
1459 "alias_of": p.alias_of,
1460 "first_published_at": p.published_at,
1461 "updated_at": p.updated_at.get().copied(),
1462 }),
1463 );
1464 obj.insert("title".to_owned(), serde_json::json!(p.title));
1465 obj.insert(
1471 "url".to_owned(),
1472 serde_json::json!(if p.url_path.is_empty() {
1473 "/"
1474 } else {
1475 p.url_path.as_str()
1476 }),
1477 );
1478 obj.insert("seo_title".to_owned(), serde_json::json!(p.seo_title));
1479 obj.insert(
1480 "seo_description".to_owned(),
1481 serde_json::json!(p.seo_description),
1482 );
1483 obj.insert("robots_index".to_owned(), serde_json::json!(p.robots_index));
1484 obj.insert(
1485 "sitemap_priority".to_owned(),
1486 serde_json::json!(p.sitemap_priority),
1487 );
1488 obj.insert(
1489 "show_in_menus".to_owned(),
1490 serde_json::json!(p.show_in_menus),
1491 );
1492 obj
1493}
1494
1495fn ancestor_paths_of(path: &str) -> std::collections::HashSet<String> {
1499 let mut out = std::collections::HashSet::new();
1500 let mut acc = String::new();
1501 for seg in path.split('/').filter(|s| !s.is_empty()) {
1502 acc.push_str(seg);
1503 acc.push('/');
1504 if acc != path {
1505 out.insert(acc.clone());
1506 }
1507 }
1508 out
1509}
1510
1511const PAGE_ORDER_FIELDS: [&str; 8] = [
1514 "title",
1515 "slug",
1516 "url_path",
1517 "depth",
1518 "sort_order",
1519 "published_at",
1520 "updated_at",
1521 "created_at",
1522];
1523
1524fn compare_pages(a: &Page, b: &Page, specs: &[q::OrderSpec]) -> std::cmp::Ordering {
1525 for spec in specs {
1526 let ord = match spec.field.as_str() {
1527 "title" => a.title.cmp(&b.title),
1528 "slug" => a.slug.cmp(&b.slug),
1529 "url_path" => a.url_path.cmp(&b.url_path),
1530 "depth" => a.depth.cmp(&b.depth),
1531 "sort_order" => a.sort_order.cmp(&b.sort_order),
1532 "published_at" => a.published_at.cmp(&b.published_at),
1533 "updated_at" => a.updated_at.get().cmp(&b.updated_at.get()),
1534 "created_at" => a.created_at.get().cmp(&b.created_at.get()),
1535 _ => continue,
1536 };
1537 if ord != std::cmp::Ordering::Equal {
1538 return if spec.descending { ord.reverse() } else { ord };
1539 }
1540 }
1541 a.id.get().cmp(&b.id.get())
1544}
1545
1546#[cfg(test)]
1547mod tests {
1548 use super::carried_query;
1549
1550 #[test]
1551 fn the_resolved_path_is_not_carried_onto_the_detail_url() {
1552 assert_eq!(carried_query(Some("html_path=%2Fabout")), "");
1555 assert_eq!(carried_query(None), "");
1556 assert_eq!(carried_query(Some("")), "");
1557 }
1558
1559 #[test]
1560 fn everything_else_survives_the_redirect() {
1561 assert_eq!(carried_query(Some("html_path=%2F&locale=fr")), "?locale=fr");
1564 assert_eq!(
1565 carried_query(Some("locale=fr&html_path=%2F&fields=title")),
1566 "?locale=fr&fields=title",
1567 );
1568 }
1569
1570 #[test]
1571 fn a_parameter_this_endpoint_never_heard_of_is_still_forwarded() {
1572 assert_eq!(carried_query(Some("html_path=%2F&whatever=1")), "?whatever=1");
1575 }
1576
1577 #[test]
1578 fn values_are_forwarded_verbatim_not_re_encoded() {
1579 assert_eq!(
1581 carried_query(Some("html_path=%2Fx&preview_token=7.123.ab%2Fcd")),
1582 "?preview_token=7.123.ab%2Fcd",
1583 );
1584 }
1585}