1use rustango::core::Column as _;
23use rustango::extractors::Tenant;
24use rustango::sql::FetcherPool as _;
25
26use crate::page::Page;
27use crate::tree_ops::TreeError;
28
29#[must_use]
38pub fn served_statuses() -> [String; 3] {
39 [
40 crate::page::PageStatus::Published.as_str().to_owned(),
41 crate::page::PageStatus::Archived.as_str().to_owned(),
42 crate::page::PageStatus::Scheduled.as_str().to_owned(),
43 ]
44}
45
46#[must_use]
50pub fn visible_now(page: &Page, now: chrono::DateTime<chrono::Utc>) -> bool {
51 use crate::page::PageStatus;
52 let status = page.status.as_str();
53 if status == PageStatus::Archived.as_str() {
54 true
55 } else if status == PageStatus::Published.as_str() {
56 !page.expire_at.is_some_and(|t| t <= now)
57 } else if status == PageStatus::Scheduled.as_str() {
58 page.go_live_at.is_some_and(|t| t <= now)
59 && !page.expire_at.is_some_and(|t| t <= now)
60 } else {
61 false
62 }
63}
64
65pub fn canonical_request_path(raw: &str) -> String {
70 let trimmed = raw.trim();
71 if trimmed.is_empty() || trimmed == "/" {
72 return "/".to_owned();
73 }
74 let with_leading = if trimmed.starts_with('/') {
75 trimmed.to_owned()
76 } else {
77 format!("/{trimmed}")
78 };
79 let trailing_stripped = with_leading.trim_end_matches('/').to_owned();
80 if trailing_stripped.is_empty() {
81 "/".to_owned()
82 } else {
83 trailing_stripped
84 }
85}
86
87pub async fn resolve_by_url_path(t: &Tenant, url_path: &str) -> Result<Option<Page>, TreeError> {
92 let canon = canonical_request_path(url_path);
93 let hits: Vec<Page> = Page::objects()
96 .where_(Page::url_path.eq(canon))
97 .where_(Page::status.is_in(served_statuses()))
98 .order_by(&[("id", false)])
99 .fetch(t.pool())
100 .await?;
101 let now = chrono::Utc::now();
102 Ok(hits.into_iter().find(|p| visible_now(p, now)))
103}
104
105pub async fn resolve_by_walk(t: &Tenant, url_path: &str) -> Result<Option<Page>, TreeError> {
110 let segments: Vec<&str> = url_path.split('/').filter(|s| !s.is_empty()).collect();
111
112 let roots: Vec<Page> = Page::objects()
113 .where_(Page::parent_id.is_null())
114 .where_(Page::slug.eq(String::new()))
115 .where_(Page::status.is_in(served_statuses()))
116 .order_by(&[("id", false)])
117 .fetch(t.pool())
118 .await?;
119 let now = chrono::Utc::now();
120 let Some(mut current) = roots.into_iter().find(|p| visible_now(p, now)) else {
121 return Ok(None);
122 };
123
124 for seg in segments {
125 let parent_id = match current.id.get().copied() {
126 Some(id) => id,
127 None => return Ok(None),
128 };
129 let hits: Vec<Page> = Page::objects()
130 .where_(Page::parent_id.eq(parent_id))
131 .where_(Page::slug.eq(seg.to_string()))
132 .where_(Page::status.is_in(served_statuses()))
133 .order_by(&[("id", false)])
134 .fetch(t.pool())
135 .await?;
136 let Some(child) = hits.into_iter().find(|p| visible_now(p, now)) else {
137 return Ok(None);
138 };
139 current = child;
140 }
141 Ok(Some(current))
142}
143
144pub async fn resolve_path(t: &Tenant, url_path: &str) -> Result<Option<Page>, TreeError> {
154 if let Some(page) = resolve_by_url_path(t, url_path).await? {
155 return Ok(Some(page));
156 }
157 resolve_by_walk(t, url_path).await
158}
159
160pub async fn resolve_routable(
174 t: &Tenant,
175 request_path: &str,
176) -> Result<Option<(Page, crate::routable::RouteMatch)>, TreeError> {
177 let canon = canonical_request_path(request_path);
178 for ancestor in crate::routable::ancestor_prefixes(&canon) {
179 let Some(page) = resolve_by_url_path(t, &ancestor).await? else {
180 continue;
181 };
182 let Some(pt_row) = crate::page_type_model::PageType::objects()
187 .where_(crate::page_type_model::PageType::id.eq(page.page_type_id))
188 .first(t.pool())
189 .await?
190 else {
191 continue;
192 };
193 let Some(handler) = crate::page_type::find_handler(&pt_row.type_name) else {
194 continue;
195 };
196 let routes = handler.routes();
197 if routes.is_empty() {
198 continue;
199 }
200 let suffix = if ancestor == "/" {
204 canon.trim_start_matches('/')
205 } else {
206 canon
207 .strip_prefix(&ancestor)
208 .unwrap_or("")
209 .trim_start_matches('/')
210 };
211 if let Some(matched) = crate::routable::match_routes(&routes, suffix) {
212 return Ok(Some((page, matched)));
213 }
214 }
215 Ok(None)
216}
217
218#[cfg(test)]
219mod visible_now_tests {
220 use super::visible_now;
221 use crate::page::{Page, PageStatus};
222 use chrono::{Duration, Utc};
223
224 fn page(status: PageStatus) -> Page {
225 use rustango::sql::Auto;
226 Page {
227 id: Auto::Unset,
228 page_type_id: 1,
229 title: "t".to_owned(),
230 slug: "t".to_owned(),
231 path: "0001/".to_owned(),
232 url_path: "/t".to_owned(),
233 preview_path: String::new(),
234 template_override: String::new(),
235 depth: 1,
236 parent_id: None,
237 locale_variant_of: None,
238 alias_of: None,
239 theme_id: None,
240 sort_order: 0,
241 status: status.as_str().to_owned(),
242 published_at: None,
243 last_published_at: None,
244 go_live_at: None,
245 expire_at: None,
246 seo_title: String::new(),
247 seo_description: String::new(),
248 robots_index: true,
249 sitemap_priority: 0.5,
250 show_in_menus: true,
251 og_title: String::new(),
252 og_description: String::new(),
253 og_image_media_id: None,
254 twitter_card: "summary".to_owned(),
255 notification_pre_published_sent: false,
256 created_at: Auto::Unset,
257 updated_at: Auto::Unset,
258 }
259 }
260
261 #[test]
262 fn a_scheduled_page_is_public_once_its_go_live_time_passes() {
263 let now = Utc::now();
264 let mut p = page(PageStatus::Scheduled);
265 assert!(!visible_now(&p, now), "no go-live time: not public");
266 p.go_live_at = Some(now + Duration::minutes(5));
267 assert!(!visible_now(&p, now));
268 p.go_live_at = Some(now - Duration::minutes(5));
269 assert!(visible_now(&p, now), "due but not yet swept: public");
270 }
271
272 #[test]
273 fn a_published_page_comes_down_at_its_expiry() {
274 let now = Utc::now();
275 let mut p = page(PageStatus::Published);
276 assert!(visible_now(&p, now));
277 p.expire_at = Some(now - Duration::seconds(1));
278 assert!(!visible_now(&p, now), "expired but not yet swept: hidden");
279 }
280
281 #[test]
282 fn drafts_and_expired_pages_are_never_public() {
283 let now = Utc::now();
284 assert!(!visible_now(&page(PageStatus::Draft), now));
285 assert!(!visible_now(&page(PageStatus::Expired), now));
286 assert!(visible_now(&page(PageStatus::Archived), now));
287 }
288}