-
Notifications
You must be signed in to change notification settings - Fork 0
/
pull.js
76 lines (60 loc) · 2.04 KB
/
pull.js
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
// @ts-check
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { writeFile, stat, mkdir, copyFile } from "node:fs/promises";
import dotenv from "dotenv";
dotenv.config();
if (!process.env.SESSION_COOKIE) {
throw new Error("SESSION_COOKIE not set");
}
const YEAR = 2022;
const DAY = process.env.DATE ? parseInt(process.env.DATE) : new Date().getDate();
const baseURL = `https://adventofcode.com/${YEAR}/day/${DAY}`;
(async () => {
const date = new Date();
if (date.getMonth() !== 11) {
throw new Error("Not December");
}
const baseDir = join(dirname(fileURLToPath(import.meta.url)), `${DAY < 10 ? `0${DAY}` : DAY}`);
try {
await stat(baseDir);
} catch (err) {
console.log(`Creating ${baseDir}`);
await mkdir(baseDir);
await copyFile(
join(dirname(fileURLToPath(import.meta.url)), "./template/index.js"),
join(baseDir, "index.js")
);
await writeFile(join(baseDir, "input.txt"), "");
await writeFile(join(baseDir, "input_demo.txt"), "");
}
while (true) {
const time = new Date();
if (time.getHours() >= 6) {
const res = await fetch(`${baseURL}/input`, {
headers: { Cookie: `session=${process.env.SESSION_COOKIE}` },
});
if (res.status === 404) {
console.log("Not available yet");
console.log("Wait a sec...");
await new Promise((resolve) => setTimeout(resolve, 1000));
continue;
}
if (res.status !== 200) {
throw new Error(`Unexpected status code: ${res.status}`);
}
const input = await res.text();
await writeFile(join(baseDir, "input.txt"), input.trim(), "utf8");
const demoRes = await fetch(baseURL);
const demoHTML = await demoRes.text();
const demoInput = demoHTML.match(/<pre><code>(.*?)<\/code><\/pre>/s);
if (demoInput) {
await writeFile(join(baseDir, "input_demo.txt"), demoInput[1].trim(), "utf8");
} else {
console.log("No demo input found");
}
console.log("Done");
break;
}
}
})();