aoc-template/src/bin/download.rs

62 lines
1.7 KiB
Rust
Raw Normal View History

2023-01-31 19:54:16 +01:00
use dotenvy::dotenv;
use reqwest::{header, Client};
2022-11-28 21:59:26 +01:00
use std::{env, fs::OpenOptions, io::Write, process};
#[tokio::main]
async fn main() {
2022-11-28 21:59:26 +01:00
let day: u8 = match aoc::parse_args() {
Ok(day) => day,
Err(_) => {
eprintln!("Need to specify a day (as integer). example: `cargo download 7`");
process::exit(1);
}
};
dotenv().ok();
2022-12-06 21:48:14 +01:00
let day_padded = format!("{day:02}");
2022-11-28 21:59:26 +01:00
let token = env::var("TOKEN").expect("$TOKEN is not set");
let year = env::var("YEAR")
.expect("$YEAR is not set")
.parse::<u32>()
.expect("$YEAR must be a number");
let mut headers = header::HeaderMap::new();
2022-12-06 21:48:14 +01:00
let mut session_header = header::HeaderValue::from_str(format!("session={token}").as_str())
2022-11-28 21:59:26 +01:00
.expect("Error building cookie header");
session_header.set_sensitive(true);
headers.insert(header::COOKIE, session_header);
let client = Client::builder().default_headers(headers).build().unwrap();
let res = client
2022-12-12 22:41:35 +01:00
.get(format!("https://adventofcode.com/{year}/day/{day}/input"))
2022-11-28 21:59:26 +01:00
.send()
.await
2022-11-28 21:59:26 +01:00
.unwrap()
.text()
.await
2022-11-28 21:59:26 +01:00
.unwrap();
2022-12-06 21:48:14 +01:00
let input_path = format!("src/inputs/{day_padded}.txt");
2022-11-28 21:59:26 +01:00
let mut file = match OpenOptions::new()
.write(true)
.create(true)
.open(&input_path)
{
Ok(file) => file,
Err(e) => {
2022-12-06 21:48:14 +01:00
eprintln!("Failed to create module file: {e}");
2022-11-28 21:59:26 +01:00
process::exit(1);
}
};
match file.write_all(res.as_bytes()) {
Ok(_) => {
println!("Downloaded input file \"{}\"", &input_path);
}
Err(e) => {
2022-12-06 21:48:14 +01:00
eprintln!("Failed to write module contents: {e}");
2022-11-28 21:59:26 +01:00
process::exit(1);
}
}
}