initial commit (backend) (pending TODOs, will amend)
This commit is contained in:
77
src/config.rs
Normal file
77
src/config.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, Read as _},
|
||||
path::Path,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
#[derive(serde::Deserialize, Debug, Clone, Copy)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AdventConfig {
|
||||
pub year: u16,
|
||||
pub leaderboard: u32,
|
||||
|
||||
#[serde(with = "humantime_serde")]
|
||||
#[serde(default = "AdventConfig::default_validity")]
|
||||
pub validity: Duration,
|
||||
|
||||
#[serde(with = "humantime_serde")]
|
||||
#[serde(default = "AdventConfig::default_fail_validity")]
|
||||
pub fail_validity: Duration,
|
||||
}
|
||||
|
||||
impl AdventConfig {
|
||||
const fn default_validity() -> Duration {
|
||||
Duration::from_mins(15)
|
||||
}
|
||||
|
||||
const fn default_fail_validity() -> Duration {
|
||||
Duration::from_secs(30)
|
||||
}
|
||||
|
||||
pub async fn fetch(&self) -> reqwest::Result<String> {
|
||||
if let Some(data) = option_env!("AOC_TEST_DATA") {
|
||||
Ok(data.to_string())
|
||||
} else {
|
||||
// TODO: we are missing session cookies for aoc to reply
|
||||
let res = reqwest::get(format!(
|
||||
"https://adventofcode.com/{YEAR}/leaderboard/private/view/{ID}.json",
|
||||
YEAR = self.year,
|
||||
ID = self.leaderboard
|
||||
))
|
||||
.await?;
|
||||
|
||||
let res = res.error_for_status()?;
|
||||
|
||||
res.text().await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
pub advent: AdventConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum OpenConfigError {
|
||||
#[error("opening: {0}")]
|
||||
Open(io::Error),
|
||||
#[error("reading: {0}")]
|
||||
Read(io::Error),
|
||||
#[error("parsing: {0}")]
|
||||
Parse(toml::de::Error),
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, OpenConfigError> {
|
||||
use OpenConfigError as E;
|
||||
|
||||
let mut file = File::open(path).map_err(E::Open)?;
|
||||
let mut contents = Vec::new();
|
||||
file.read_to_end(&mut contents).map_err(E::Read)?;
|
||||
|
||||
toml::from_slice(&contents).map_err(E::Parse)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user