1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
pub use adventage_macros::{day, part1demo, part2demo};

use reqwest::blocking::Client;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use dirs::home_dir;

fn fetch_from_file() -> io::Result<String> {
    let mut file = File::open("input")?;
    let mut contents = String::new();

    file.read_to_string(&mut contents)?;

    Ok(contents)
}

fn fetch_token() -> String {
    let mut path = home_dir().unwrap();
    path.push(".aoc-token");
    let mut file = File::open(path.to_str().unwrap()).unwrap();
    let mut contents = String::new();

    file.read_to_string(&mut contents).unwrap();
    String::from(contents.trim())
}

fn write_to_file(contents: &str) -> io::Result<()> {
    let mut file = File::create("input")?;
    file.write_all(contents.as_bytes())?;

    Ok(())
}

pub fn fetch_day(year: u32, day: u32) -> String {
    if let Ok(input) = fetch_from_file() {
        input 
    } else {
        let client = Client::new();
        let uri = format!("https://adventofcode.com/{year}/day/{day}/input");
        let session = format!("session={};", fetch_token());

        let contents = client.get(uri)
            .header("Cookie", &session)
            .send().unwrap()
            .text().unwrap();

        let _ = write_to_file(&contents);
        contents
    }
}