advent_input/
lib.rs

1//! Advent Input
2//!
3//! `advent_input` provides a function to easily retrieve Advent of Code input for a given date.
4extern crate reqwest;
5use std::{io::Read, path::Path, fs, env, error::Error};
6
7struct Day {
8    num: u8
9}
10
11impl Day {
12    fn new(num: u8) -> Day {
13        if num < 1 || num > 25 {
14            panic!("Invalid day specified.");
15        }
16        Day { num }
17    }
18}
19
20struct Year {
21    num : u16
22}
23
24impl Year {
25    fn new(num: u16) -> Year {
26        if num < 2015 {
27            panic!("Invalid year specified.");
28        }
29        Year { num }
30    }
31}
32
33/// Gets input of specified year and day, writing to given path.
34/// Reads from environment variable for authentication. Set ADVENT_COOKIE to your session value in
35/// your environment variables to configure.
36///
37/// # Examples
38///
39/// ```
40/// advent_input::get_input(2017, 16, "sixteen.txt").unwrap(); // Writes input for Day 16, 2017 to sixteen.txt
41/// ```
42pub fn get_input(year: u16, day: u8, path: &str) -> Result<(), Box<dyn Error>> {
43    let y = Year::new(year);
44    let d = Day::new(day);
45
46    let path = Path::new(path);
47    if path.exists() {
48        return Ok(());
49    }
50
51    let client = reqwest::blocking::Client::new();
52    let url = format!("https://adventofcode.com/{}/day/{}/input", y.num, d.num);
53    let cookie = env::var("ADVENT_COOKIE")?;
54    let mut res = client.get(url)
55        .header("Cookie", format!("session={}", cookie)).send()?;
56    let mut body = String::new();
57    res.read_to_string(&mut body)?;
58
59    fs::write(path, body)?;
60
61    Ok(())
62}