Skip to content

Commit 7e95e3e

Browse files
fix: send user agent with input retrieval request
1 parent aabb214 commit 7e95e3e

File tree

4 files changed

+31
-10
lines changed

4 files changed

+31
-10
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,5 +132,5 @@ dmypy.json
132132
.idea
133133

134134
# Advent of code related
135-
.session
135+
.setup.json
136136
src/adventofcode/inputs

.session.template

Whitespace-only changes.

.setup.json.template

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"user_agent": "github.com/your-username/your-repo",
3+
"session_cookie": "session cookie value"
4+
}
Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,36 @@
1+
import json
12
import os
3+
from typing import Required, TypedDict
24

35
from httpx import get
46

57
from adventofcode.config import ROOT_DIR
68

79

10+
class Setup(TypedDict):
11+
user_agent: Required[str]
12+
session_cookie: Required[str]
13+
14+
815
def get_input(year: int, day: int):
9-
session = _read_session()
10-
data = _download_input(year, day, session)
16+
"""
17+
Retrieves input from the Advent of Code website for the given year/day.
18+
After retrieving the input, the input is stored in the project.
19+
"""
20+
setup = _read_setup()
21+
data = _download_input(year, day, setup)
1122
_save_input(data, year, day)
1223

1324

14-
def _download_input(year: int, day: int, session: str) -> bytes:
25+
def _download_input(year: int, day: int, setup: Setup) -> bytes:
1526
"""
1627
Downloads the input as text from the advent of code site
1728
"""
18-
cookies = {"session": session}
29+
cookies = {"session": setup["session_cookie"]}
1930
url = f"https://adventofcode.com/{year}/day/{day}/input"
20-
resp = get(url, cookies=cookies)
31+
resp = get(url, cookies=cookies, headers={"User-Agent": setup["user_agent"]})
2132
resp.raise_for_status()
22-
return resp.content # type: ignore
33+
return resp.content
2334

2435

2536
def _save_input(data: bytes, year: int, day: int) -> None:
@@ -32,9 +43,15 @@ def _save_input(data: bytes, year: int, day: int) -> None:
3243
file.write(data)
3344

3445

35-
def _read_session():
36-
target = os.path.join(ROOT_DIR, "../../.session")
46+
def _read_setup() -> Setup:
47+
"""
48+
Reads .setup.json from the projects' root directory
49+
50+
Returns:
51+
Setup: a typed dict
52+
"""
53+
target = os.path.join(ROOT_DIR, "../../.setup.json")
3754
path = os.path.abspath(target)
3855

3956
with open(path) as f:
40-
return f.read()
57+
return json.load(f)

0 commit comments

Comments
 (0)