-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPuzzleInputProvider.cs
66 lines (56 loc) · 1.8 KB
/
PuzzleInputProvider.cs
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System.Net;
using Microsoft.Extensions.Configuration;
namespace AdventOfCode.Runner;
public sealed class PuzzleInputProvider
{
public static PuzzleInputProvider Instance { get; } = new();
private readonly HttpClient _httpClient;
private PuzzleInputProvider()
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var sessionId = configuration["sessionId"];
var baseAddress = new Uri("https://adventofcode.com");
var cookieContainer = new CookieContainer();
cookieContainer.Add(baseAddress, new Cookie("session", sessionId));
_httpClient = new HttpClient(
new HttpClientHandler
{
CookieContainer = cookieContainer,
AutomaticDecompression = DecompressionMethods.All,
})
{
BaseAddress = baseAddress,
DefaultRequestHeaders =
{
{ "User-Agent", ".NET/9.0 (https://github.com/viceroypenguin/adventofcode by stuart@turner-isageek.com)" },
},
};
}
public PuzzleInput GetRawInput(int year, int day)
{
var inputFile = $"Inputs/{year}/day{day:00}.input.txt";
_ = Directory.CreateDirectory(Path.GetDirectoryName(inputFile)!);
if (!File.Exists(inputFile))
{
if (DateTimeOffset.Now < new DateTimeOffset(year, 12, day, 0, 0, 0, TimeSpan.FromHours(-5)))
throw new InvalidOperationException("Puzzle has not been released yet.");
var response = _httpClient.GetAsync($"{year}/day/{day}/input")
.GetAwaiter()
.GetResult();
var text = response
.EnsureSuccessStatusCode()
.Content.ReadAsStringAsync()
.GetAwaiter()
.GetResult();
File.WriteAllText(inputFile, text);
}
return new(
File.ReadAllBytes(inputFile),
File.ReadAllText(inputFile),
File.ReadAllLines(inputFile));
}
}