Browse Source

Begin work on AoC Client

Beginning work on a client that can fetch my input, and submit solutions
for me.
ApisNecros 1 year ago
parent
commit
ed8870cec5
1 changed files with 83 additions and 0 deletions
  1. 83 0
      AoC-Client/AoC-Client.ts

+ 83 - 0
AoC-Client/AoC-Client.ts

@@ -0,0 +1,83 @@
+import * as https from 'https';
+import { resolve } from 'path';
+
+export class AoCClient {
+    /** The base URL for Advent of Code */
+    hostname = "adventofcode.com";
+    private now = new Date();
+    /**
+     * The year the client is set to work with
+     * 
+     * Initializes to the current year
+     */
+    year: number = -1;
+    /**
+     * The session cookie for the user to access the Advent of Code
+     */
+    private sessionCookie: string|undefined;
+
+    /**
+     * A client for connecting to the Advent of Code website
+     */
+    constructor() {
+        this.LoadConfig();
+        if (this.year == -1) {
+            this.year = this.now.getFullYear();
+        }
+    }
+
+    LoadConfig() {
+        return;
+    }
+
+    async SaveInput(day: number, year: number|undefined = undefined) {
+        // Check that the day value is within bounds
+        if (day < 1 || day > 25) {
+            throw new RangeError("The day requested must be between 1 and 25");
+        }
+
+        // If the year is unset, set it to the client's value
+        if (!year) {
+            year = this.year;
+        }
+
+        // Check that the year is within bounds
+        if (year < 2013 || year > this.now.getFullYear()) {
+            throw new RangeError(`The year must be between 2013 and ${this.now.getFullYear()}`);
+        }
+
+        // Check that the input is ready
+        if (year == this.now.getFullYear() && day > this.now.getDate()) {
+            throw new RangeError(`The input for day ${day} is not ready yet. Please try again later`);
+        }
+
+        // Get the contents of the input
+        this.GET(`${year}/day/${day}/input`).then((fileContents) => {
+            console.log("Input loaded!");
+            console.log(fileContents);
+        });
+    }
+
+    private async GET(uri: string): Promise<string> {
+        return new Promise((resolve, reject) => {
+            https.get({
+                hostname: this.hostname,
+                path: `/${uri}`,
+                headers: {
+                    "Cookie": `session=${this.sessionCookie}`
+                }
+            },  (resp) => {
+                if (resp.statusCode == 200) {
+                    resp.on("data", (data) => {
+                        return resolve(data.toString());
+                    });
+                }
+                else {
+                    return reject(new Error(`BAD_CODE=${resp.statusCode}`));
+                }
+            }).on("error", (err) => {
+                console.error(err);
+            })
+        });
+    }
+}