aoc-toolkit 0.1.0-alpha.4

A toolkit for solving Advent of Code problems
Documentation
use scraper::{Html, Selector};

use super::{StarSnapshot, StarStoreError};
use crate::application::calendar::CalendarDate;
use crate::client::http::has_logout_link;

#[derive(Debug, thiserror::Error)]
pub enum CalendarHtmlError {
    #[error("The Advent of Code calendar does not show a signed-in session")]
    NotAuthenticated,

    #[error("Unexpected Advent of Code calendar structure")]
    InvalidCalendar,

    #[error("Expected {expected} unlocked calendar days, found {actual}")]
    UnexpectedDays { expected: usize, actual: usize },

    #[error(transparent)]
    Snapshot(#[from] StarStoreError),
}

impl StarSnapshot {
    /// Builds a snapshot from a signed-in edition calendar.
    ///
    /// `unlocked_days` is the expected number of unlocked days at sync time.
    ///
    /// # Errors
    ///
    /// Returns an error if authentication or calendar coverage cannot be
    /// established, or if the resulting snapshot is invalid.
    pub fn from_calendar_html(
        document: &Html,
        year: usize,
        unlocked_days: usize,
        synced_at_unix_seconds: u64,
    ) -> Result<Self, CalendarHtmlError> {
        if !has_logout_link(document) {
            return Err(CalendarHtmlError::NotAuthenticated);
        }

        if !(1..=CalendarDate::edition_days(year)).contains(&unlocked_days) {
            return Err(CalendarHtmlError::InvalidCalendar);
        }

        let calendar_selector =
            Selector::parse("pre.calendar").map_err(|_| CalendarHtmlError::InvalidCalendar)?;
        let link_selector = Selector::parse("a").map_err(|_| CalendarHtmlError::InvalidCalendar)?;

        let mut calendars = document.select(&calendar_selector);
        let calendar = calendars.next().ok_or(CalendarHtmlError::InvalidCalendar)?;
        if calendars.next().is_some() {
            return Err(CalendarHtmlError::InvalidCalendar);
        }

        let mut stars = Vec::with_capacity(unlocked_days);

        for (index, link) in calendar.select(&link_selector).enumerate() {
            let day = index + 1;
            let href = format!("/{year}/day/{day}");
            let day_class = format!("calendar-day{day}");
            let element = link.value();

            if element.attr("href") != Some(href.as_str())
                || !element.classes().any(|class| class == day_class)
            {
                return Err(CalendarHtmlError::InvalidCalendar);
            }

            let count = if element
                .classes()
                .any(|class| class == "calendar-verycomplete")
            {
                2
            } else {
                element
                    .classes()
                    .any(|class| class == "calendar-complete")
                    .into()
            };

            stars.push(count);
        }

        if stars.len() != unlocked_days {
            return Err(CalendarHtmlError::UnexpectedDays {
                expected: unlocked_days,
                actual: stars.len(),
            });
        }

        Ok(Self::new(year, synced_at_unix_seconds, stars)?)
    }
}

#[cfg(test)]
mod tests {
    use scraper::Html;

    use super::{CalendarHtmlError, StarSnapshot};
    use crate::application::progress::VerifiedStar;

    const SIGNED_IN_CALENDAR: &str = r#"
        <header><a href="/2025/auth/logout">Log Out</a></header>
        <pre class="calendar">
            <a href="/2025/day/1" class="calendar-day1 calendar-complete calendar-verycomplete">
                <span class="calendar-mark-verycomplete">*</span>
            </a>
            <a href="/2025/day/2" class="calendar-day2 calendar-complete">
                <span class="calendar-mark-complete">*</span>
            </a>
            <a href="/2025/day/3" class="calendar-day3">
                <span class="calendar-mark-complete">*</span>
                <span class="calendar-mark-verycomplete">*</span>
            </a>
            <span class="calendar-day4">4</span>
        </pre>
    "#;

    #[test]
    fn reads_star_classes_from_day_links_and_ignores_child_markers() {
        let document = Html::parse_document(SIGNED_IN_CALENDAR);
        let snapshot = StarSnapshot::from_calendar_html(&document, 2025, 3, 100).unwrap();

        assert_eq!(snapshot.star(1, 2), VerifiedStar::Earned);
        assert_eq!(snapshot.star(2, 1), VerifiedStar::Earned);
        assert_eq!(snapshot.star(2, 2), VerifiedStar::Missing);
        assert_eq!(snapshot.star(3, 1), VerifiedStar::Missing);
        assert_eq!(snapshot.star(4, 1), VerifiedStar::Unknown);
        assert_eq!(snapshot.synced_at_unix_seconds(), 100);
    }

    #[test]
    fn accepts_a_signed_in_calendar_with_zero_stars() {
        let html = SIGNED_IN_CALENDAR
            .replace(" calendar-complete", "")
            .replace(" calendar-verycomplete", "");
        let document = Html::parse_document(&html);
        let snapshot = StarSnapshot::from_calendar_html(&document, 2025, 3, 100).unwrap();

        for day in 1..=3 {
            assert_eq!(snapshot.star(day, 1), VerifiedStar::Missing);
            assert_eq!(snapshot.star(day, 2), VerifiedStar::Missing);
        }
    }

    #[test]
    fn rejects_a_logged_out_calendar() {
        let html = SIGNED_IN_CALENDAR.replace("/2025/auth/logout", "/2025/auth/login");
        let document = Html::parse_document(&html);

        assert!(matches!(
            StarSnapshot::from_calendar_html(&document, 2025, 3, 100),
            Err(CalendarHtmlError::NotAuthenticated),
        ));
    }

    #[test]
    fn rejects_incomplete_duplicate_and_wrong_edition_links() {
        let document = Html::parse_document(SIGNED_IN_CALENDAR);
        assert!(matches!(
            StarSnapshot::from_calendar_html(&document, 2025, 4, 100),
            Err(CalendarHtmlError::UnexpectedDays {
                expected: 4,
                actual: 3,
            }),
        ));

        for href in ["/2025/day/1", "/2024/day/2"] {
            let html = SIGNED_IN_CALENDAR.replace("/2025/day/2", href);
            let document = Html::parse_document(&html);

            assert!(matches!(
                StarSnapshot::from_calendar_html(&document, 2025, 3, 100),
                Err(CalendarHtmlError::InvalidCalendar),
            ));
        }
    }
}