Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,24 @@ jobs:

- name: Run unit tests
run: python -m unittest discover -s tests -v

mypy:
name: mypy
runs-on: ubuntu-latest

steps:
- name: Check out repository
uses: actions/checkout@v7

- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.14"
cache: pip
cache-dependency-path: requirements.txt

- name: Install dependencies
run: python -m pip install -r requirements.txt "mypy>=2.4.1,<3" types-requests

- name: Type-check
run: mypy
12 changes: 4 additions & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,10 @@ repos:
- id: flake8

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.961
rev: v2.4.1
hooks:
- id: mypy
args:
- --ignore-missing-imports
- auto.py
- common.py
- migrations.py
- query.py
- shift.py
additional_dependencies:
- types-requests
- beautifulsoup4>=4.15.0,<5
pass_filenames: false
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Follow PEP 8 conventions: four-space indentation, `snake_case` for functions and

```sh
flake8 *.py
mypy *.py
mypy # files and options come from [tool.mypy] in pyproject.toml
```

## Testing Guidelines
Expand Down
Empty file removed __init__.py
Empty file.
4 changes: 2 additions & 2 deletions migrations.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import re
import sqlite3
from typing import List, Union
from typing import Callable, Dict, List, Union
from common import DIRNAME, _L

try:
Expand Down Expand Up @@ -54,7 +54,7 @@ def migrate_shift_codes():

# --- Versioned schema migrations ---

migrationFunctions = {}
migrationFunctions: Dict[int, Callable[..., bool]] = {}


def register(version: int):
Expand Down
368 changes: 321 additions & 47 deletions poetry.lock

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,18 @@ requests = "^2.34.2"
flake8 = "^7.5.0"
ipdb = "^0.13.13"
jedi = "^0.18.1"
mypy = "^0.961"
mypy = "^2.4.1"
types-requests = "^2.33.0"
debugpy = "^1.8.22"
pylint = "^4.1.4"
Flask = "^3.1.3"
autoflake = "^2.4.0"

[tool.mypy]
python_version = "3.11"
files = ["auto.py", "common.py", "migrations.py", "query.py", "shift.py"]
ignore_missing_imports = true

[build-system]
requires = ["poetry-core>=2.4,<3.0"]
build-backend = "poetry.core.masonry.api"
35 changes: 25 additions & 10 deletions query.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import sqlite3
from os import makedirs, path
from typing import (
Any,
Callable,
ContextManager,
Dict,
Expand Down Expand Up @@ -86,7 +87,7 @@ def without(self, *args):


### games used to help find the correct shift redemption forms
known_games = SymmetricDict(
known_games: SymmetricDict[str, str] = SymmetricDict(
{
"bl1": "Borderlands: Game of the Year Edition",
"bl2": "Borderlands 2",
Expand All @@ -99,7 +100,7 @@ def without(self, *args):
)

### platforms that are used to find the correct input values in the shift redemption forms
known_platforms = SymmetricDict(
known_platforms: SymmetricDict[str, str] = SymmetricDict(
{
"steam": "steam",
"epic": "epic",
Expand Down Expand Up @@ -212,6 +213,19 @@ class Key:
"expired",
)

# Declared for the type checker; values are assigned via set()/setattr.
id: Optional[int]
reward: str
code: str
game: str
platform: str
redeemed: bool
type: Any
archived: Any
expires: Any
link: Any
expired: Any

def __init__(self, **kwargs):
self.redeemed = False
self.id = None
Expand Down Expand Up @@ -261,9 +275,8 @@ def __enter__(self):
self.__open_db()
return self

def __exit__(self, *_) -> Optional[bool]:
def __exit__(self, *_) -> None:
self.close_db()
return False

def execute(self, sql, parameters=None):
if not self.__updated:
Expand Down Expand Up @@ -443,6 +456,10 @@ def set_shift_source(source: str):
_L.info(f"Using SHiFT source: {SHIFT_SOURCE}")


# Print the source banner only on the first fetch.
_first_parse = True


def parse_shift_orcicorn():
import json

Expand Down Expand Up @@ -484,8 +501,9 @@ def parse_shift_orcicorn():
else:
valid_codes.append(code_data)

if parse_shift_orcicorn.first_parse:
parse_shift_orcicorn.first_parse = False
global _first_parse
if _first_parse:
_first_parse = False
print_banner(data)

for code_data in valid_codes:
Expand Down Expand Up @@ -514,13 +532,10 @@ def parse_shift_orcicorn():
yield from keys


parse_shift_orcicorn.first_parse = True


def update_keys():
from collections import Counter

if not parse_shift_orcicorn.first_parse:
if not _first_parse:
_L.info("Checking for new keys!")

keys = list(parse_shift_orcicorn())
Expand Down
25 changes: 17 additions & 8 deletions shift.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ def __init__(self, s: str):
self.msg = s

@classmethod
def _missing_(cls, value: str):
def _missing_(cls, value: object):
obj = object.__new__(cls)
obj._value_ = value
obj.__init__(value)
obj._value_ = cast(str, value)
obj.__init__(obj._value_) # type: ignore[misc]
cls._value2member_map_[value] = obj # type: ignore # these bindings are wrong..
return obj

Expand Down Expand Up @@ -183,7 +183,7 @@ def input_pw(qry):


class ShiftClient:
def __init__(self, user: str = None, pw: str = None):
def __init__(self, user: Optional[str] = None, pw: Optional[str] = None):
from os import path

self.client = requests.session()
Expand Down Expand Up @@ -304,7 +304,7 @@ def __get_token(
meta = soup.find("meta", attrs=dict(name="csrf-token"))
if not meta:
return r.status_code, None
return r.status_code, meta["content"]
return r.status_code, cast(str, meta["content"])

def __login(self, user, pw):
"""Login with user/pw"""
Expand Down Expand Up @@ -392,10 +392,15 @@ def __get_redemption_form(

forms = title.find_all_next("form", id="new_archway_code_redemption")
for form in forms:
service: bs4.element.Tag = form.find(id="archway_code_redemption_service")
service = cast(
bs4.element.Tag, form.find(id="archway_code_redemption_service")
)
if platform not in service["value"]:
continue
form_data = {inp["name"]: inp["value"] for inp in form.find_all("input")}
form_data = {
cast(str, inp["name"]): cast(str, inp["value"])
for inp in form.find_all("input")
}
return True, r.status_code, form_data

return (False, r.status_code, "This code is not available for your platform")
Expand All @@ -416,7 +421,11 @@ def __get_redemption_status(self, r: Response) -> tuple[str, str, str]:
div = soup.find("div", id="check_redemption_status")
if div:
_L.debug(f"Result Check Redemption Status: {div.text.strip()}")
return (div.text.strip(), div["data-url"], div["data-fallback-url"])
return (
div.text.strip(),
cast(str, div["data-url"]),
cast(str, div["data-fallback-url"]),
)
div = soup.find("div", class_="alert notice")
if div:
_L.debug(f"Result Alert Notice: {div.text.strip()}")
Expand Down