aoc_toolkit/application/progress/
calendar_html.rs1use scraper::{Html, Selector};
2
3use super::{StarSnapshot, StarStoreError};
4use crate::application::calendar::CalendarDate;
5use crate::client::http::has_logout_link;
6
7#[derive(Debug, thiserror::Error)]
8pub enum CalendarHtmlError {
9 #[error("The Advent of Code calendar does not show a signed-in session")]
10 NotAuthenticated,
11
12 #[error("Unexpected Advent of Code calendar structure")]
13 InvalidCalendar,
14
15 #[error("Expected {expected} unlocked calendar days, found {actual}")]
16 UnexpectedDays { expected: usize, actual: usize },
17
18 #[error(transparent)]
19 Snapshot(#[from] StarStoreError),
20}
21
22impl StarSnapshot {
23 pub fn from_calendar_html(
32 document: &Html,
33 year: usize,
34 unlocked_days: usize,
35 synced_at_unix_seconds: u64,
36 ) -> Result<Self, CalendarHtmlError> {
37 if !has_logout_link(document) {
38 return Err(CalendarHtmlError::NotAuthenticated);
39 }
40
41 if !(1..=CalendarDate::edition_days(year)).contains(&unlocked_days) {
42 return Err(CalendarHtmlError::InvalidCalendar);
43 }
44
45 let calendar_selector =
46 Selector::parse("pre.calendar").map_err(|_| CalendarHtmlError::InvalidCalendar)?;
47 let link_selector = Selector::parse("a").map_err(|_| CalendarHtmlError::InvalidCalendar)?;
48
49 let mut calendars = document.select(&calendar_selector);
50 let calendar = calendars.next().ok_or(CalendarHtmlError::InvalidCalendar)?;
51 if calendars.next().is_some() {
52 return Err(CalendarHtmlError::InvalidCalendar);
53 }
54
55 let mut stars = Vec::with_capacity(unlocked_days);
56
57 for (index, link) in calendar.select(&link_selector).enumerate() {
58 let day = index + 1;
59 let href = format!("/{year}/day/{day}");
60 let day_class = format!("calendar-day{day}");
61 let element = link.value();
62
63 if element.attr("href") != Some(href.as_str())
64 || !element.classes().any(|class| class == day_class)
65 {
66 return Err(CalendarHtmlError::InvalidCalendar);
67 }
68
69 let count = if element
70 .classes()
71 .any(|class| class == "calendar-verycomplete")
72 {
73 2
74 } else {
75 element
76 .classes()
77 .any(|class| class == "calendar-complete")
78 .into()
79 };
80
81 stars.push(count);
82 }
83
84 if stars.len() != unlocked_days {
85 return Err(CalendarHtmlError::UnexpectedDays {
86 expected: unlocked_days,
87 actual: stars.len(),
88 });
89 }
90
91 Ok(Self::new(year, synced_at_unix_seconds, stars)?)
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use scraper::Html;
98
99 use super::{CalendarHtmlError, StarSnapshot};
100 use crate::application::progress::VerifiedStar;
101
102 const SIGNED_IN_CALENDAR: &str = r#"
103 <header><a href="/2025/auth/logout">Log Out</a></header>
104 <pre class="calendar">
105 <a href="/2025/day/1" class="calendar-day1 calendar-complete calendar-verycomplete">
106 <span class="calendar-mark-verycomplete">*</span>
107 </a>
108 <a href="/2025/day/2" class="calendar-day2 calendar-complete">
109 <span class="calendar-mark-complete">*</span>
110 </a>
111 <a href="/2025/day/3" class="calendar-day3">
112 <span class="calendar-mark-complete">*</span>
113 <span class="calendar-mark-verycomplete">*</span>
114 </a>
115 <span class="calendar-day4">4</span>
116 </pre>
117 "#;
118
119 #[test]
120 fn reads_star_classes_from_day_links_and_ignores_child_markers() {
121 let document = Html::parse_document(SIGNED_IN_CALENDAR);
122 let snapshot = StarSnapshot::from_calendar_html(&document, 2025, 3, 100).unwrap();
123
124 assert_eq!(snapshot.star(1, 2), VerifiedStar::Earned);
125 assert_eq!(snapshot.star(2, 1), VerifiedStar::Earned);
126 assert_eq!(snapshot.star(2, 2), VerifiedStar::Missing);
127 assert_eq!(snapshot.star(3, 1), VerifiedStar::Missing);
128 assert_eq!(snapshot.star(4, 1), VerifiedStar::Unknown);
129 assert_eq!(snapshot.synced_at_unix_seconds(), 100);
130 }
131
132 #[test]
133 fn accepts_a_signed_in_calendar_with_zero_stars() {
134 let html = SIGNED_IN_CALENDAR
135 .replace(" calendar-complete", "")
136 .replace(" calendar-verycomplete", "");
137 let document = Html::parse_document(&html);
138 let snapshot = StarSnapshot::from_calendar_html(&document, 2025, 3, 100).unwrap();
139
140 for day in 1..=3 {
141 assert_eq!(snapshot.star(day, 1), VerifiedStar::Missing);
142 assert_eq!(snapshot.star(day, 2), VerifiedStar::Missing);
143 }
144 }
145
146 #[test]
147 fn rejects_a_logged_out_calendar() {
148 let html = SIGNED_IN_CALENDAR.replace("/2025/auth/logout", "/2025/auth/login");
149 let document = Html::parse_document(&html);
150
151 assert!(matches!(
152 StarSnapshot::from_calendar_html(&document, 2025, 3, 100),
153 Err(CalendarHtmlError::NotAuthenticated),
154 ));
155 }
156
157 #[test]
158 fn rejects_incomplete_duplicate_and_wrong_edition_links() {
159 let document = Html::parse_document(SIGNED_IN_CALENDAR);
160 assert!(matches!(
161 StarSnapshot::from_calendar_html(&document, 2025, 4, 100),
162 Err(CalendarHtmlError::UnexpectedDays {
163 expected: 4,
164 actual: 3,
165 }),
166 ));
167
168 for href in ["/2025/day/1", "/2024/day/2"] {
169 let html = SIGNED_IN_CALENDAR.replace("/2025/day/2", href);
170 let document = Html::parse_document(&html);
171
172 assert!(matches!(
173 StarSnapshot::from_calendar_html(&document, 2025, 3, 100),
174 Err(CalendarHtmlError::InvalidCalendar),
175 ));
176 }
177 }
178}