1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- 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);
- })
- });
- }
- }
|