-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interface.rs
477 lines (456 loc) · 15.5 KB
/
interface.rs
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use std::collections::HashMap;
use std::fmt::Display;
use std::fs;
use std::time::Duration;
use chrono::{DateTime, Datelike, TimeZone, Utc};
use crossterm::style::{style, Stylize};
use super::internal_util::{
calculate_practice_result,
get,
load_token_from_stdin,
make,
post,
practice_result_for,
wait,
work,
};
use crate::data::{base_url, DATA_DIR, WAIT_TIME};
use crate::internal_util::{
is_practice_mode,
message_from_body,
must_run_solutions,
open_page,
pretty_print,
print_rank,
strip_trailing_nl,
Submissions,
};
use crate::MaybeDisplay;
/// Fetch and return the input for `day` of `year`.
///
/// If `--practice` is provided on the command line, pretend that today is the
/// day of the puzzle and wait for puzzle unlock accordingly. 'today' is
/// determined in UTC; from 0:00 to 5:00 UTC, this will block until 5:00 UTC.
/// After that, until 0:00 UTC the next day, input fetching will be instant.
///
/// All inputs are cached in the data directory.
///
/// # Panics
///
/// If the day and year do not correspond to a
/// valid puzzle.
#[must_use]
pub fn fetch(day: u32, year: i32, never_print: bool) -> String {
assert!(year >= 2015, "Invalid year");
assert!((1..=25).contains(&day), "Invalid day");
let in_folder = &*DATA_DIR / year.to_string();
make(&in_folder);
let in_file = &in_folder / format!("{day}.in");
let wait_for_unlock = |now: DateTime<Utc>, unlock: DateTime<Utc>| {
if now < unlock {
wait(
"Waiting for puzzle unlock".yellow(),
(unlock - now)
.to_std()
.unwrap_or_else(|_| unreachable!("Should always be positive")),
);
println!("{}", "Fetching input!".green());
open_page(base_url(year, day).as_str());
true
} else {
false
}
};
if in_file.exists() {
let should_print = if is_practice_mode() {
let now = Utc::now();
let unlock = Utc
.with_ymd_and_hms(now.year(), now.month(), now.day(), 5, 0, 0)
.single()
.unwrap_or_else(|| unreachable!("Today at 5AM is always valid"));
wait_for_unlock(now, unlock)
} else {
false
};
let input = fs::read_to_string(&in_file).unwrap_or_else(|_| {
fs::remove_file(in_file).expect("Removing the input file should not fail");
fetch(day, year, true)
});
if should_print && !never_print && is_practice_mode() {
println!("{input}");
}
input
} else {
let mut unlock = Utc
.with_ymd_and_hms(year, 12, day, 5, 0, 0)
.single()
.unwrap_or_else(|| unreachable!("December days at 5AM are always valid"));
let mut now = Utc::now();
if is_practice_mode() {
unlock = Utc
.with_ymd_and_hms(now.year(), now.month(), now.day(), 5, 0, 0)
.single()
.unwrap_or_else(|| unreachable!("Today at 5AM is always valid"));
}
if now < unlock {
// On the first day, run a stray request to validate the user's token
if day == 1 {
let resp = get(&(base_url(year, day) + "/input"), true);
if resp.status().is_client_error() {
load_token_from_stdin(
"Your token has expired. Please enter your new token.".red(),
);
return fetch(day, year, never_print);
}
now = Utc::now();
}
wait_for_unlock(now, unlock);
}
let resp = get(&(base_url(year, day) + "/input"), true);
if !resp.status().is_success() {
if resp.status().is_client_error() {
load_token_from_stdin(
"Your token has expired. Please enter your new token.".red(),
);
return fetch(day, year, never_print);
}
panic!("Received bad response from server: {}", resp.status());
}
let input = strip_trailing_nl(
resp.text()
.unwrap_or_else(|_| unreachable!("Response should be text")),
);
fs::write(in_file, &input).unwrap_or_else(|_| {
eprintln!(
"{}",
"Warning: Failed to cache input file. Please check your permissions."
.red()
);
});
if !never_print {
println!("{input}");
}
input
}
}
/// Submit a solution.
///
/// Submissions are cached; submitting an already-submitted solution will return
/// the previous response.
///
/// # Panics
///
/// If the day and year do not correspond to a valid puzzle.
pub fn submit(day: u32, part: u32, year: i32, answer: impl Display) {
submit_impl(day, part, year, answer.to_string());
}
fn submit_already_solved(
solution: &str,
answer: &str,
day: u32,
part: u32,
year: i32,
part_solutions: &HashMap<String, String>,
) {
if is_practice_mode() {
println!(
"Submitting {} as the solution to part {}...",
answer.blue(),
style(part).blue()
);
return if solution == answer {
calculate_practice_result(day, part, year);
} else if part_solutions.contains_key(solution) {
pretty_print(&part_solutions[solution]);
} else {
println!("{}", "That's not the right answer".red());
};
}
println!(
"Day {} part {} has already been solved.\nThe solution was: {}",
style(day).blue(),
style(part).blue(),
solution.blue(),
);
print_rank(&part_solutions[solution]);
}
fn delay(msg: &str) -> bool {
if msg.starts_with("You gave") {
println!("{}", msg.red());
let wait_match = WAIT_TIME.captures(msg).expect(
"Found a message that appeared to be a submission delay, that wasn't a \
submission delay",
);
let pause =
60 * wait_match.get(1).map_or(0, |m| {
m.as_str().parse::<u64>().expect("Failed to parse minutes")
}) + wait_match.get(2).map_or(0, |m| {
m.as_str().parse::<u64>().expect("Failed to parse seconds")
});
wait(
format!(
"{} {} {}",
"Waiting".yellow(),
style(pause).blue(),
"seconds to retry...".yellow()
),
Duration::from_secs(pause),
);
true
} else {
false
}
}
fn submit_impl(day: u32, part: u32, year: i32, answer: String) {
let submission_dir = &*DATA_DIR / year.to_string() / day.to_string();
make(&submission_dir);
let submissions = &submission_dir / "submissions.txt";
let mut solutions = if submissions.exists() {
serde_json::from_reader(
fs::File::open(&submissions)
.unwrap_or_else(|_| unreachable!("File should exist")),
)
.unwrap_or_else(|_| unreachable!("File should be valid"))
} else {
Submissions {
part_1: HashMap::new(),
part_2: HashMap::new(),
}
};
let part_solutions = match part {
1 => &mut solutions.part_1,
2 => &mut solutions.part_2,
_ => unreachable!("Part should be 1 or 2"),
};
let solution_file = &submission_dir / format!("{part}.solution");
#[allow(clippy::map_entry)]
if solution_file.exists() {
let solution = fs::read_to_string(solution_file)
.unwrap_or_else(|_| panic!("Solution file was corrupt"));
submit_already_solved(&solution, &answer, day, part, year, part_solutions);
} else if part_solutions.contains_key(&answer) {
println!(
"{} {} {} {} {}",
"Solution: ".yellow(),
answer.as_str().blue(),
"to part".yellow(),
style(part).blue(),
"has already been submitted.\nResponse was:".yellow(),
);
pretty_print(part_solutions[&answer].as_str());
} else {
let mut msg;
loop {
println!(
"Submitting {} as the solution to part {}...",
answer.as_str().blue(),
style(part).blue()
);
let resp = post(
&(base_url(year, day) + "/answer"),
true,
HashMap::from([
("level", part.to_string()),
("answer", answer.to_string()),
]),
);
if !resp.status().is_success() {
if resp.status().is_client_error() {
load_token_from_stdin(
"Your token has expired. Please enter your new token.".red(),
);
continue;
}
panic!("Received bad response from server: {}", resp.status());
}
let resp_text = resp
.text()
.unwrap_or_else(|_| unreachable!("Response should be text"));
msg = message_from_body(&resp_text);
if !delay(&msg) {
break;
}
}
if msg.starts_with("That's the") {
print_rank(&msg);
fs::write(solution_file, &answer).expect("Writing solution cache failed");
calculate_practice_result(day, part, year);
if part == 1 {
open_page(&(base_url(year, day) + "#part2"));
}
} else {
pretty_print(&msg);
}
part_solutions.insert(answer, msg);
fs::write(submissions, serde_json::to_string(&solutions).unwrap())
.expect("Writing submissions cache failed");
}
}
fn submit_25(year: &str) {
let resp = loop {
println!(
"{} {}{}",
"Finishing Advent of Code".green(),
year.blue(),
'!'.green(),
);
let resp = post(
&(base_url(year, 25) + "/answer"),
true,
HashMap::from([("level", "2"), ("answer", "0")]),
);
if resp.status().is_success() {
break resp;
} else if resp.status().is_client_error() {
load_token_from_stdin(
"Your token has expired. Please enter your new token.".red(),
);
} else {
panic!("Received bad response from server: {}", resp.status());
}
};
println!("Response from the server:");
println!(
"{}",
message_from_body(&resp.text().expect("Response should be text")),
);
}
/// Run the functions only if we haven't seen a solution.
///
/// Will also run solutions if `--force-run` or `--practice` is passed on the
/// command line.
///
/// The solution for part 2 will be ignored if day is 25.
pub fn lazy_submit<U, S1: MaybeDisplay, S2: MaybeDisplay>(
day: u32,
year: i32,
solution_part_1: impl FnOnce(U) -> S1,
solution_part_2: impl FnOnce(U) -> S2,
mut parse_raw: impl FnMut(&str) -> U,
) {
lazy_submit_part(day, year, 1, solution_part_1, &mut parse_raw);
lazy_submit_part(day, year, 2, solution_part_2, &mut parse_raw);
}
/// Run the function only if we haven't seen a solution.
///
/// Will also run solution if `--force-run` or `--practice` is passed on the
/// command line.
///
/// If the day is 25 and the part is 2, will ignore the solution.
pub fn lazy_submit_part<U, M: MaybeDisplay>(
day: u32,
year: i32,
part: u32,
solution_part_1: impl FnOnce(U) -> M,
parse_raw: impl FnOnce(&str) -> U,
) {
let submission_dir = &*DATA_DIR / year.to_string() / day.to_string();
make(&submission_dir);
if day == 25 && part == 2 {
// don't try to submit part 2 if part 1 isn't solved
if (&submission_dir / "1.solution").exists() {
submit_25(&year.to_string());
} else {
return;
}
}
let solution_file = &submission_dir / format!("{part}.solution");
if !solution_file.exists()
|| must_run_solutions()
|| (is_practice_mode()
&& practice_result_for(day, year).1.len() < part as usize)
{
let answer = work(
format!(
"{} {} {}",
"Running part".yellow(),
style(part).blue(),
"solution".yellow(),
),
|| {
let raw = fetch(day, year, false);
solution_part_1(parse_raw(&raw))
},
)
.into_solution();
if let Some(answer) = answer {
submit(day, part, year, answer);
}
} else {
// load cached solutions
let submissions = submission_dir / "submissions.json";
let solutions: Submissions = serde_json::from_str(
&fs::read_to_string(submissions).unwrap_or_else(|_| {
unreachable!(
"Failed to read submission cache, which must exist as this part \
has already been solved"
)
}),
)
.unwrap_or_else(|_| unreachable!("Failed to parse submission cache"));
let solution = fs::read_to_string(solution_file)
.unwrap_or_else(|_| unreachable!("Solution file was corrupt"));
let response = match part {
1 => &solutions.part_1[&solution],
2 => &solutions.part_2[&solution],
_ => unreachable!("Part should be 1 or 2"),
};
println!(
"Day {} part {} has already been solved.\nThe solution was {}",
style(day).blue(),
style(part).blue(),
solution.blue(),
);
print_rank(response);
}
}
/// Retrieve the example input and answer for the specified puzzle.
///
/// This is provided on a best-effort basis; not all puzzles have example
/// inputs, and some puzzles that do have example inputs have example inputs
/// that are difficult to determine programmatically.
#[allow(unused_variables)]
#[must_use]
pub fn get_sample_input(day: u32, part: u32, year: i32) -> Option<(String, String)> {
// unimplemented
None
// let testing_dir = &*DATA_DIR / year.to_string() / day.to_string();
// make(&testing_dir);
// let testing_file = testing_dir / "tests.json";
// let test_info = if testing_file.exists() {
// serde_json::from_str(&fs::read_to_string(testing_file).
// unwrap_or_else(|_| { unreachable!(
// "Failed to read test cache"
// )
// }))
// .unwrap_or(TestInfo {
// part_1: None,
// part_2: None,
// })
// } else {
// TestInfo {
// part_1: None,
// part_2: None,
// }
// };
// let part_tests = match part {
// 1 => &test_info.part_1,
// 2 => &test_info.part_2,
// _ => unreachable!("Part should be 1 or 2"),
// };
// if let Some(part_tests) = part_tests {
// return part_tests.clone();
// }
// let resp = get_text(&(base_url(year, day) + "/input"), true);
// let soup = tl::parse(&resp, tl::ParserOptions::new()).unwrap_or_else(|_|
// { unreachable!("Advent of Code server returned a bad response")
// });
// let possible_test_inputs = soup
// .query_selector("pre")
// .unwrap_or_else(|| unreachable!("Selector 'pre' is always valid"))
// .map(|node| {
// let node = node
// .get(soup.parser())
// .unwrap_or_else(|| unreachable!("Node is from this parser"));
// });
}