use super::error::ClientError;
use super::http::AocHttpClient;
use super::{cache, session};
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputSource {
Cached,
Downloaded,
}
pub struct InputStore {
root: PathBuf,
download_lock: PathBuf,
token: String,
http: Option<AocHttpClient>,
}
impl InputStore {
fn new(root: &Path, account_id: u64, token: String) -> Self {
Self {
root: root.join("inputs").join(account_id.to_string()),
download_lock: root.join("download.lock"),
token,
http: None,
}
}
pub fn global() -> Result<Self, ClientError> {
let root = cache::root()?;
let token = session::get_session()?;
let (account_id, http) =
if let Some(account_id) = session::SessionStore::known_account(&root, &token)? {
(account_id, None)
} else {
let http = AocHttpClient::new()?;
let account_id = http.verify_session_at(&root, &token)?;
session::SessionStore::remember_account_at(&root, &token, account_id)?;
(account_id, Some(http))
};
let mut store = Self::new(&root, account_id, token);
store.http = http;
Ok(store)
}
#[cfg(feature = "cli")]
pub(crate) fn account_root(&self) -> &Path {
&self.root
}
pub fn get(&mut self, year: usize, day: usize) -> Result<String, ClientError> {
self.get_with_source(year, day).map(|(input, _)| input)
}
pub fn get_with_source(
&mut self,
year: usize,
day: usize,
) -> Result<(String, InputSource), ClientError> {
let path = self.input_path(year, day);
if let Some(cached) = Self::read_cached(&path)? {
return Ok((cached, InputSource::Cached));
}
let _guard = cache::lock(&self.download_lock)?;
if let Some(cached) = Self::read_cached(&path)? {
return Ok((cached, InputSource::Cached));
}
cache::with_request_cooldown(|| {
let input = self.download(year, day)?;
cache::store(&path, &input)?;
Ok((input, InputSource::Downloaded))
})
}
pub fn global_cache_root() -> Result<PathBuf, ClientError> {
Ok(cache::root()?.join("inputs"))
}
fn input_path(&self, year: usize, day: usize) -> PathBuf {
self.root.join(year.to_string()).join(format!("{day}.txt"))
}
fn read_cached(path: &Path) -> Result<Option<String>, ClientError> {
match fs::read_to_string(path) {
Ok(input) if input.trim().is_empty() => Ok(None),
Ok(input) => Ok(Some(input)),
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(source) => Err(cache::io_error(path, source)),
}
}
fn download(&mut self, year: usize, day: usize) -> Result<String, ClientError> {
let http = match &self.http {
Some(http) => http,
None => self.http.insert(AocHttpClient::new()?),
};
http.fetch_input(year, day, &self.token)
}
}
#[cfg(test)]
mod tests;