use crate::model::{Alert, Period, non_empty, truncate};
use crate::time;
impl Alert {
pub(crate) fn of(message: &hafas::Message) -> Option<Self> {
if !message.act {
return None;
}
let head = message
.head
.as_deref()
.map(text)
.and_then(|t| non_empty(Some(&t)));
let lead = message
.lead
.as_deref()
.map(text)
.and_then(|t| non_empty(Some(&t)));
let body = message
.text
.as_deref()
.map(text)
.and_then(|t| non_empty(Some(&t)));
let (header, description) = match (head, body.or(lead.clone())) {
(Some(head), description) => (head, description.unwrap_or_default()),
(None, Some(description)) => (lead.unwrap_or(description.clone()), description),
(None, None) => return None,
};
let header = truncate(&header);
let description = if description == header {
String::new()
} else {
truncate(&description)
};
let start = message
.s_date
.as_deref()
.and_then(|date| time::parse(date, message.s_time.as_deref().unwrap_or("00:00")));
let end = message
.e_date
.as_deref()
.and_then(|date| time::parse(date, message.e_time.as_deref().unwrap_or("23:59")));
let periods = if start.is_some() || end.is_some() {
vec![Period {
start: start.map(time::format),
end: end.map(time::format),
}]
} else {
Vec::new()
};
Some(Self {
header,
description,
effect: None,
severity: None,
url: None,
periods,
})
}
}
pub(crate) fn alerts<'a>(lists: impl IntoIterator<Item = &'a Vec<hafas::Message>>) -> Vec<Alert> {
let mut out: Vec<Alert> = Vec::new();
for alert in lists.into_iter().flatten().filter_map(Alert::of) {
if !out.contains(&alert) {
out.push(alert);
}
}
out
}
pub(crate) fn text(html: &str) -> String {
let mut out = String::with_capacity(html.len());
let mut rest = html;
while let Some(start) = rest.find('<') {
out.push_str(&rest[..start]);
let Some(end) = rest[start..].find('>') else {
out.push_str(&rest[start..]);
rest = "";
break;
};
let tag = rest[start + 1..start + end].trim().to_ascii_lowercase();
let name = tag.trim_start_matches('/');
let name = name
.split(|c: char| c.is_whitespace() || c == '/')
.next()
.unwrap_or_default();
if matches!(name, "br" | "p" | "div" | "li" | "tr" | "ul" | "ol") {
out.push('\n');
} else {
out.push(' ');
}
rest = &rest[start + end + 1..];
}
out.push_str(rest);
decode(&out)
.lines()
.map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join("\n")
}
fn decode(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(start) = rest.find('&') {
out.push_str(&rest[..start]);
rest = &rest[start..];
let entity = rest[1..]
.find(';')
.filter(|end| *end <= 10)
.and_then(|end| Some((entity(&rest[1..=end])?, end + 2)));
let (c, length) = entity.unwrap_or(('&', 1));
out.push(c);
rest = &rest[length..];
}
out.push_str(rest);
out
}
const ENTITIES: &[(&str, char)] = &[
("amp", '&'),
("lt", '<'),
("gt", '>'),
("quot", '"'),
("apos", '\''),
("nbsp", ' '),
("auml", 'ä'),
("ouml", 'ö'),
("uuml", 'ü'),
("Auml", 'Ä'),
("Ouml", 'Ö'),
("Uuml", 'Ü'),
("szlig", 'ß'),
("euro", '€'),
("ndash", '–'),
("mdash", '—'),
("bdquo", '„'),
("ldquo", '“'),
("rdquo", '”'),
];
fn entity(name: &str) -> Option<char> {
if let Some((_, c)) = ENTITIES.iter().find(|(entity, _)| *entity == name) {
return Some(*c);
}
let number = name.strip_prefix('#')?;
let code = match number.strip_prefix(['x', 'X']) {
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
None => number.parse().ok()?,
};
char::from_u32(code)
}
#[cfg(test)]
mod tests {
use super::*;
fn message() -> hafas::Message {
hafas::Message {
id: "1".into(),
act: true,
head: Some("Bauarbeiten".into()),
lead: Some("Kurz".into()),
text: Some("Wegen <b>Bauarbeiten</b> fällt die S2 aus.<br/>Ersatz: Bus".into()),
s_date: Some("2026-11-28".into()),
s_time: Some("04:00:00".into()),
..hafas::Message::default()
}
}
#[test]
fn reads_a_message() {
let alert = Alert::of(&message()).unwrap();
assert_eq!(alert.header, "Bauarbeiten");
assert_eq!(
alert.description,
"Wegen Bauarbeiten fällt die S2 aus.\nErsatz: Bus"
);
assert_eq!(
alert.periods,
[Period {
start: Some("2026-11-28T04:00:00+01:00".into()),
end: None
}]
);
}
#[test]
fn falls_back_to_the_lead() {
let alert = Alert::of(&hafas::Message {
head: None,
text: None,
s_date: None,
e_date: Some("2026-11-29".into()),
..message()
})
.unwrap();
assert_eq!(alert.header, "Kurz");
assert_eq!(alert.description, "");
assert_eq!(
alert.periods[0].end.as_deref(),
Some("2026-11-29T23:59:00+01:00")
);
let alert = Alert::of(&hafas::Message {
head: Some(" ".into()),
lead: None,
..message()
})
.unwrap();
assert!(alert.header.starts_with("Wegen"), "{}", alert.header);
assert_eq!(alert.description, "");
assert_eq!(
Alert::of(&hafas::Message {
head: None,
lead: None,
text: None,
..message()
}),
None
);
}
#[test]
fn a_message_without_dates_has_no_period() {
let alert = Alert::of(&hafas::Message {
s_date: None,
..message()
})
.unwrap();
assert_eq!(alert.periods, []);
}
#[test]
fn skips_inactive_messages_and_duplicates() {
let inactive = hafas::Message {
act: false,
..message()
};
assert_eq!(Alert::of(&inactive), None);
let list = vec![message(), inactive];
assert_eq!(alerts([&list, &list]).len(), 1);
}
#[test]
fn turns_html_into_text() {
assert_eq!(text("a<p>b</p>c"), "a\nb\nc");
assert_eq!(
text("x & y <z> ü ä &bogus; &"),
"x & y <z> ü ä &bogus; &"
);
assert_eq!(text("1 < 2"), "1 < 2");
assert_eq!(text("<a href=\"x\">Link</a> mehr"), "Link mehr");
assert_eq!(text("&#xZZ; �"), "&#xZZ; �");
}
}