83 lines
2.0 KiB
Rust
83 lines
2.0 KiB
Rust
use std::{
|
|
fs::File,
|
|
io::{self, Read as _},
|
|
path::Path,
|
|
time::Duration,
|
|
};
|
|
|
|
#[derive(serde::Deserialize, Debug, Clone)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct AdventConfig {
|
|
pub year: u16,
|
|
pub leaderboard: u32,
|
|
pub session: String,
|
|
|
|
#[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 {
|
|
use reqwest::header;
|
|
|
|
let res = reqwest::Client::new()
|
|
.get(format!(
|
|
"https://adventofcode.com/{YEAR}/leaderboard/private/view/{ID}.json",
|
|
YEAR = self.year,
|
|
ID = self.leaderboard
|
|
))
|
|
.header(header::COOKIE, format!("session={}", self.session))
|
|
.send()
|
|
.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)
|
|
}
|
|
}
|