1use axum::http::HeaderMap;
5use jiff::Timestamp;
6use jiff::tz::TimeZone;
7use schedr_client::times::{show, show_seconds};
8
9#[cfg(test)]
10mod tests;
11
12pub const PREFIX_HEADER: &str = "x-forwarded-prefix";
14
15pub const ZONE_COOKIE: &str = "schedr_tz";
17
18#[derive(Debug, Clone)]
20pub struct Page {
21 pub base: String,
23 pub zone: Option<TimeZone>,
25 pub docs: bool,
27 pub events: String,
30 pub refresh: String,
33}
34
35impl Page {
36 #[must_use]
38 pub fn new(headers: &HeaderMap, docs: bool) -> Self {
39 Self {
40 base: prefix(headers),
41 zone: zone(headers),
42 docs,
43 events: String::new(),
44 refresh: String::new(),
45 }
46 }
47
48 #[must_use]
51 pub fn live(self, follow: &str, refresh: &str) -> Self {
52 Self {
53 events: format!(
56 "{}/events?{follow}{}since={}",
57 self.base,
58 if follow.is_empty() { "" } else { "&" },
59 Timestamp::now().as_millisecond()
60 ),
61 refresh: format!("{}{refresh}", self.base),
62 ..self
63 }
64 }
65
66 #[must_use]
68 pub const fn is_live(&self) -> bool {
69 !self.events.is_empty()
70 }
71
72 #[must_use]
74 pub const fn has_zone(&self) -> bool {
75 self.zone.is_some()
76 }
77
78 #[must_use]
81 pub fn time(&self, at: &Timestamp) -> String {
82 show(*at, self.zone.as_ref().unwrap_or(&TimeZone::UTC))
83 }
84
85 #[must_use]
87 pub fn column_time(&self, at: &Timestamp) -> String {
88 show_seconds(*at, self.zone.as_ref().unwrap_or(&TimeZone::UTC))
89 }
90
91 #[must_use]
95 pub fn narrow_time(&self, at: &Timestamp) -> String {
96 let text = self.time(at);
97 let (utc, local) = text.split_once(" (").unwrap_or((&text, ""));
98 let (date, clock) = utc.split_once(' ').unwrap_or((utc, ""));
99 let keep = |part: &str| part.replace(' ', "\u{a0}");
100 let mut lines = vec![date.to_owned(), keep(clock)];
101 if !local.is_empty() {
102 lines.push(format!("({}", keep(local)));
103 }
104 lines.join("\n")
105 }
106}
107
108#[must_use]
112pub fn prefix(headers: &HeaderMap) -> String {
113 let Some(value) = headers.get(PREFIX_HEADER).and_then(|v| v.to_str().ok()) else {
114 return String::new();
115 };
116 let plain = value.starts_with('/')
117 && !value.contains("..")
118 && !value.contains("//")
119 && value
120 .bytes()
121 .all(|b| b.is_ascii_alphanumeric() || b"/-_.~".contains(&b));
122 if plain {
123 value.trim_end_matches('/').to_owned()
124 } else {
125 String::new()
126 }
127}
128
129pub const DAGS_VIEW_COOKIE: &str = "schedr_dags_view";
132
133pub const DAGS_TRIGGER_COOKIE: &str = "schedr_dags_trigger";
136
137#[must_use]
139pub fn cookie(headers: &HeaderMap, name: &str) -> Option<String> {
140 headers
141 .get_all(axum::http::header::COOKIE)
142 .iter()
143 .filter_map(|v| v.to_str().ok())
144 .flat_map(|cookies| cookies.split(';'))
145 .filter_map(|cookie| cookie.trim().strip_prefix(name)?.strip_prefix('='))
146 .find_map(percent_decoded)
147}
148
149#[must_use]
151pub fn zone(headers: &HeaderMap) -> Option<TimeZone> {
152 headers
153 .get_all(axum::http::header::COOKIE)
154 .iter()
155 .filter_map(|v| v.to_str().ok())
156 .flat_map(|cookies| cookies.split(';'))
157 .filter_map(|cookie| cookie.trim().strip_prefix(ZONE_COOKIE)?.strip_prefix('='))
158 .find_map(|name| TimeZone::get(&percent_decoded(name)?).ok())
159}
160
161pub(crate) fn percent_decoded(text: &str) -> Option<String> {
164 let bytes = text.as_bytes();
165 let mut out = Vec::with_capacity(bytes.len());
166 let mut i = 0;
167 while i < bytes.len() {
168 if bytes[i] == b'%' {
169 let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?;
170 out.push(u8::from_str_radix(hex, 16).ok()?);
171 i += 3;
172 } else {
173 out.push(bytes[i]);
174 i += 1;
175 }
176 }
177 String::from_utf8(out).ok()
178}