Skip to main content

aoc_toolkit/client/
inputs.rs

1use super::error::ClientError;
2use super::http::AocHttpClient;
3use super::{cache, session};
4use std::fs;
5use std::io::ErrorKind;
6use std::path::{Path, PathBuf};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum InputSource {
10    Cached,
11    Downloaded,
12}
13
14pub struct InputStore {
15    root: PathBuf,
16    download_lock: PathBuf,
17    token: String,
18    http: Option<AocHttpClient>,
19}
20
21impl InputStore {
22    fn new(root: &Path, account_id: u64, token: String) -> Self {
23        Self {
24            root: root.join("inputs").join(account_id.to_string()),
25            download_lock: root.join("download.lock"),
26            token,
27            http: None,
28        }
29    }
30
31    /// Creates an account-specific global input store.
32    ///
33    /// # Errors
34    ///
35    /// Returns an error if the cache directory, session
36    /// or account identity cannot be resolved.
37    pub fn global() -> Result<Self, ClientError> {
38        let root = cache::root()?;
39        let token = session::get_session()?;
40
41        let (account_id, http) =
42            if let Some(account_id) = session::SessionStore::known_account(&root, &token)? {
43                (account_id, None)
44            } else {
45                let http = AocHttpClient::new()?;
46
47                let account_id = http.verify_session_at(&root, &token)?;
48
49                session::SessionStore::remember_account_at(&root, &token, account_id)?;
50
51                (account_id, Some(http))
52            };
53
54        let mut store = Self::new(&root, account_id, token);
55
56        store.http = http;
57
58        Ok(store)
59    }
60
61    #[cfg(feature = "cli")]
62    pub(crate) fn account_root(&self) -> &Path {
63        &self.root
64    }
65
66    /// Returns cached puzzle input or downloads it from Advent of Code.
67    ///
68    /// # Errors
69    ///
70    /// Returns an error if the input cannot be read,
71    /// downloaded, or stored in the cache.
72    pub fn get(&mut self, year: usize, day: usize) -> Result<String, ClientError> {
73        self.get_with_source(year, day).map(|(input, _)| input)
74    }
75
76    /// Returns puzzle input together with its acquisition source.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error if the input cannot be read,
81    /// downloaded, or stored in the cache.
82    pub fn get_with_source(
83        &mut self,
84        year: usize,
85        day: usize,
86    ) -> Result<(String, InputSource), ClientError> {
87        let path = self.input_path(year, day);
88
89        if let Some(cached) = Self::read_cached(&path)? {
90            return Ok((cached, InputSource::Cached));
91        }
92
93        let _guard = cache::lock(&self.download_lock)?;
94
95        // Another process may have downloaded the input
96        // while we were waiting for the lock.
97        if let Some(cached) = Self::read_cached(&path)? {
98            return Ok((cached, InputSource::Cached));
99        }
100
101        cache::with_request_cooldown(|| {
102            let input = self.download(year, day)?;
103
104            cache::store(&path, &input)?;
105
106            Ok((input, InputSource::Downloaded))
107        })
108    }
109
110    /// Returns the platform-specific global input cache directory.
111    ///
112    /// # Errors
113    ///
114    /// Returns an error if the system cache directory
115    /// cannot be determined.
116    pub fn global_cache_root() -> Result<PathBuf, ClientError> {
117        Ok(cache::root()?.join("inputs"))
118    }
119
120    fn input_path(&self, year: usize, day: usize) -> PathBuf {
121        self.root.join(year.to_string()).join(format!("{day}.txt"))
122    }
123
124    fn read_cached(path: &Path) -> Result<Option<String>, ClientError> {
125        match fs::read_to_string(path) {
126            Ok(input) if input.trim().is_empty() => Ok(None),
127
128            Ok(input) => Ok(Some(input)),
129
130            Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
131
132            Err(source) => Err(cache::io_error(path, source)),
133        }
134    }
135
136    fn download(&mut self, year: usize, day: usize) -> Result<String, ClientError> {
137        let http = match &self.http {
138            Some(http) => http,
139            None => self.http.insert(AocHttpClient::new()?),
140        };
141
142        http.fetch_input(year, day, &self.token)
143    }
144}
145
146#[cfg(test)]
147mod tests;