Code for the Advent of Code event
aoc
advent-of-code
1# frozen_string_literal: true
2
3require 'cgi'
4require 'net/http'
5
6require_relative 'version'
7require_relative 'logging'
8
9module AoC
10 # Helper functions to interact with the AoC "API".
11 module API
12 include Logging
13
14 # User-Agent used for calls to the AoC "API".
15 # @return [String]
16 USER_AGENT = "Sharparam-AoC/#{AoC::VERSION} (github.com/Sharparam/advent-of-code)".freeze
17
18 # Email address used for the "From" header when calling the AoC "API".
19 # @return [String]
20 FROM = 'sharparam@sharparam.com'
21
22 # Fetches the input data (string) for a given year and day.
23 # @param year [Integer] The year to fetch.
24 # @param day [Integer] The day to fetch.
25 # @param session_id [String] Session ID for authentication.
26 # @param dry_run [Boolean] If dry run is enabled, no HTTP calls will be made and dummy data will be returned.
27 # @return [String]
28 def self.input(year, day, session_id, dry_run: false)
29 url = "https://adventofcode.com/#{year}/day/#{day}/input"
30 if dry_run
31 log.warn('DRY RUN DOWNLOAD', url:)
32 return 'DRY RUN DOWNLOAD CONTENT'
33 end
34 uri = URI(url)
35 Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
36 log.debug('Downloading input', url:)
37 request = Net::HTTP::Get.new(uri)
38 request['User-Agent'] = USER_AGENT
39 request['From'] = FROM
40 request['Cookie'] = "session=#{CGI.escape session_id}"
41 response = http.request request
42 log.debug 'Got response', status_code: response.code, message: response.message
43 raise "Input download request failed (#{response.code} #{response.message})" unless response.code == '200'
44 response.body
45 end
46 end
47 end
48end