AoC-Client.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import * as https from 'https';
  2. import { resolve } from 'path';
  3. export class AoCClient {
  4. /** The base URL for Advent of Code */
  5. hostname = "adventofcode.com";
  6. private now = new Date();
  7. /**
  8. * The year the client is set to work with
  9. *
  10. * Initializes to the current year
  11. */
  12. year: number = -1;
  13. /**
  14. * The session cookie for the user to access the Advent of Code
  15. */
  16. private sessionCookie: string|undefined;
  17. /**
  18. * A client for connecting to the Advent of Code website
  19. */
  20. constructor() {
  21. this.LoadConfig();
  22. if (this.year == -1) {
  23. this.year = this.now.getFullYear();
  24. }
  25. }
  26. LoadConfig() {
  27. return;
  28. }
  29. async SaveInput(day: number, year: number|undefined = undefined) {
  30. // Check that the day value is within bounds
  31. if (day < 1 || day > 25) {
  32. throw new RangeError("The day requested must be between 1 and 25");
  33. }
  34. // If the year is unset, set it to the client's value
  35. if (!year) {
  36. year = this.year;
  37. }
  38. // Check that the year is within bounds
  39. if (year < 2013 || year > this.now.getFullYear()) {
  40. throw new RangeError(`The year must be between 2013 and ${this.now.getFullYear()}`);
  41. }
  42. // Check that the input is ready
  43. if (year == this.now.getFullYear() && day > this.now.getDate()) {
  44. throw new RangeError(`The input for day ${day} is not ready yet. Please try again later`);
  45. }
  46. // Get the contents of the input
  47. this.GET(`${year}/day/${day}/input`).then((fileContents) => {
  48. console.log("Input loaded!");
  49. console.log(fileContents);
  50. });
  51. }
  52. private async GET(uri: string): Promise<string> {
  53. return new Promise((resolve, reject) => {
  54. https.get({
  55. hostname: this.hostname,
  56. path: `/${uri}`,
  57. headers: {
  58. "Cookie": `session=${this.sessionCookie}`
  59. }
  60. }, (resp) => {
  61. if (resp.statusCode == 200) {
  62. resp.on("data", (data) => {
  63. return resolve(data.toString());
  64. });
  65. }
  66. else {
  67. return reject(new Error(`BAD_CODE=${resp.statusCode}`));
  68. }
  69. }).on("error", (err) => {
  70. console.error(err);
  71. })
  72. });
  73. }
  74. }