rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! Alerts from the HIM messages of RMV. Their texts are HTML; the output
//! has plain text.

use crate::model::{Alert, Period, non_empty, truncate};
use crate::time;

impl Alert {
    /// The alert of a message, `None` if it is not active or says nothing.
    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,
        })
    }
}

/// The alerts of several lists, each once.
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
}

/// HTML as plain text: tags dropped, line breaks at `<br>` and the ends of
/// blocks, entities decoded, spaces collapsed.
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 {
            // An unclosed `<` is text.
            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")
}

/// Decodes the named entities HIM texts use and numeric ones.
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
}

/// The named entities HIM texts use.
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&auml;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 &amp; y &lt;z&gt; &#252; &#xE4; &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; &#99999999;"), "&#xZZ; &#99999999;");
    }
}