Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore/refactor before publish #14

Merged
merged 6 commits into from
Aug 1, 2024
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
2 changes: 1 addition & 1 deletion .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ ignore = E203, E266, E501, W503, F403, F401, F821
max-line-length = 79
max-complexity = 18
select = B,C,E,F,W,T4,B9
exclude = .env, .git, .github, docs, venv
exclude = .env, .git, .github, docs, venv, src/tool
19 changes: 8 additions & 11 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,6 @@ repos:
hooks:
- id: black
args: ['--config=pyproject.toml', '-v']
exclude: |
(?x)^(
.git/.* |
.github/.* |
docs/.* |
venv/.* |
src/tools/templates.*
)$s

- repo: https://github.com/pycqa/flake8
rev: 3.9.2
Expand All @@ -29,7 +21,12 @@ repos:
(?x)^(
.git/.* |
.github/.* |
docs/.* |
venv/.* |
src/tools/templates.*
docs/* |
venv/* |
src/tools/*
)$

exclude: |
(?x)(
^src/tools|
)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ exclude = '''
| \.github
| \docs
| \venv
| \src\tools\templates
| \src\tools
)/
| migrations
)
Expand Down
29 changes: 15 additions & 14 deletions src/iracing_garage/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,21 @@

from iracing_garage.transport import iRacingGarageTransport

from iracing_garage.car.car_client import CarClient
from iracing_garage.carclass.carclass_client import CarClassClient
from iracing_garage.constants.constants_client import ConstantsClient
from iracing_garage.hosted.hosted_client import HostedClient
from iracing_garage.league.league_client import LeagueClient
from iracing_garage.lookup.lookup_client import LookupClient
from iracing_garage.member.member_client import MemberClient
from iracing_garage.results.results_client import ResultsClient
from iracing_garage.season.season_client import SeasonClient
from iracing_garage.series.series_client import SeriesClient
from iracing_garage.stats.stats_client import StatsClient
from iracing_garage.team.team_client import TeamClient
from iracing_garage.time_attack.time_attack_client import TimeAttackClient
from iracing_garage.track.track_client import TrackClient
from iracing_garage.api_clients import ResultsClient
from iracing_garage.api_clients import CarClient
from iracing_garage.api_clients import CarClassClient
from iracing_garage.api_clients import ConstantsClient
from iracing_garage.api_clients import HostedClient
from iracing_garage.api_clients import LeagueClient
from iracing_garage.api_clients import LookupClient
from iracing_garage.api_clients import MemberClient
from iracing_garage.api_clients import SeasonClient
from iracing_garage.api_clients import SeriesClient
from iracing_garage.api_clients import StatsClient
from iracing_garage.api_clients import TeamClient
from iracing_garage.api_clients import TimeAttackClient
from iracing_garage.api_clients import TrackClient


logging.basicConfig(
format="%(asctime)s [%(levelname)s] %(message)s (Line :%(lineno)d [%(filename)s])",
Expand Down
14 changes: 14 additions & 0 deletions src/iracing_garage/api_clients/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from .car_client import CarClient
from .carclass_client import CarClassClient
from .constants_client import ConstantsClient
from .hosted_client import HostedClient
from .league_client import LeagueClient
from .lookup_client import LookupClient
from .member_client import MemberClient
from .results_client import ResultsClient
from .season_client import SeasonClient
from .series_client import SeriesClient
from .stats_client import StatsClient
from .team_client import TeamClient
from .time_attack_client import TimeAttackClient
from .track_client import TrackClient
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,18 @@ def lap_data(
"team_id": team_id,
}

return self._get(
response = self._get(
url=endpoint,
api_group=self.api_group,
func_name=func_name,
params=params,
)

chunks = self._get_chunks(response)
response["chunk_payload"] = chunks

return response

def search_hosted(
self,
start_range_begin: str = None,
Expand Down
1 change: 0 additions & 1 deletion src/iracing_garage/car/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/carclass/__init__.py

This file was deleted.

210 changes: 28 additions & 182 deletions src/iracing_garage/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import inspect
import logging
import json
import requests
Expand All @@ -16,143 +15,55 @@ def _get(
self, url: str, api_group: str, func_name: str, params=None
) -> dict:
response = self.transport.get(url=url, params=params)
response_json = response.json()

if response.status_code == requests.codes.OK:
gateway_response_dict = json.loads(response.text)
api_link = gateway_response_dict.get("link")

# TODO: raise if fails
response_data = self.transport.get(url=api_link)
return response_data.json()

else:
if response.status_code != requests.codes.OK:
self.logger.debug(
f"Error retrieving {api_group} - {func_name}: {self.transport.dump_response(response)}"
)
raise Exception(
f"Error retrieving {api_group} - {func_name}: {response.text}"
)
# TODO:
# payload can either be a dict or a list
# payload can be a dict without link

api_link = response_json.get("link")
api_data_json = self.transport.get(url=api_link).json()
return api_data_json

def _get_chunks(self, payload):
chunks = []
chunk_info = payload.get("chunk_info")
chunk_download_url = chunk_info.get("base_download_url")
chunk_file_names = [x for x in chunk_info.get("chunk_file_names")]

for i, chunk_file_name in enumerate(chunk_file_names):
for chunk_file_name in chunk_file_names:
full_url = chunk_download_url + chunk_file_name
response = self.transport.get(full_url).json()
chunks.extend(response)

try:
response = requests.get(
full_url,
cookies=self.cookies,
allow_redirects=False,
timeout=10.0,
).text
except: # noqa
# TODO: build exceptions
msg = f"API extraction error at {chunk_file_name}, {i}/{len(chunk_file_names)}" # noqa
pass

chunks.append(response)

print()
return chunks

def _get_constants(self):
pass # TODO: constants does not have a gateway

def _wrap_payload(self, payload, method, endpoint, parameters):
## {timestamp, payload, method, endpoint, parameters, username}
record = {
"timestamp": helpers.get_current_utc_time(),
"method": method,
"endpoint": endpoint,
"parameters": parameters,
"username": self.username,
"payload": payload,
}

return record


class Client:
def __init__(self, username: str, password: str):
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
self.username = username
self.password = password
self.cookies = self._login()

def _login(self):
password = helpers.encode_pw(self.username, self.password)
data = {"email": self.username, "password": password}
headers = {"Content-Type": "application/json"}
json_data = json.dumps(data)

login_response = requests.post(
endpoints.URL_LOGIN, data=json_data, headers=headers
)
return login_response.cookies

def _get(self, url: str, params: dict, has_chunks: bool = False):
if not self.cookies:
logging.info("No cookies in cookie jar.")
self.cookies = self._login()

logging.info(f"Request being sent to: {url} with params: {params}")

# TODO: Add a try except raise for failed requests
response = requests.get(
url,
params=params,
cookies=self.cookies,
allow_redirects=False,
timeout=10.0,
)
logging.info(f"Request sent for URL: {response.url}")
logging.info(f"Status code of the response: {response.status_code}")
logging.debug(f"Response object: {response.__dict__}")

response_dict = json.loads(response.text)
link = response_dict.get("link")

# TODO: Add a try except raise for failed requests
response_text = requests.get(link).text

payload_dict = json.loads(response_text)

print()

return payload_dict

def _get_chunks(self, payload):
chunks = []
chunk_info = payload.get("chunk_info")
chunk_download_url = chunk_info.get("base_download_url")
chunk_file_names = [x for x in chunk_info.get("chunk_file_names")]

for i, chunk_file_name in enumerate(chunk_file_names):
full_url = chunk_download_url + chunk_file_name
def _get_entry(
self, url: str, api_group: str, func_name: str, params=None
) -> dict:
response = self.transport.get(url=url, params=params)

try:
response = requests.get(
full_url,
cookies=self.cookies,
allow_redirects=False,
timeout=10.0,
).text
except: # noqa
# TODO: build exceptions
msg = f"API extraction error at {chunk_file_name}, {i}/{len(chunk_file_names)}" # noqa
pass
if response.status_code != requests.codes.OK:
self.logger.debug(
f"Error retrieving {api_group} - {func_name}: {self.transport.dump_response(response)}"
)
raise Exception(
f"Error retrieving {api_group} - {func_name}: {response.text}"
)

chunks.append(response)
gateway_response_dict = json.loads(response.text)
api_link = gateway_response_dict.get("link")

print()
return chunks
# TODO: raise if fails
response_data = self.transport.get(url=api_link)
return response_data.json()

def _wrap_payload(self, payload, method, endpoint, parameters):
## {timestamp, payload, method, endpoint, parameters, username}
Expand All @@ -164,70 +75,5 @@ def _wrap_payload(self, payload, method, endpoint, parameters):
"username": self.username,
"payload": payload,
}
return record

def member_bests(self, customer_id, car_id):
params = {"cust_id": customer_id, "car_id": car_id}
endpoint = endpoints.URL_STATS_MEMBER_BESTS
func_name = inspect.stack()[0][3]

results_response = self._get(endpoint, params)
record = self._wrap_payload(
results_response, func_name, endpoint, params
)
return record

def member_career(self, customer_id):
params = {"cust_id": customer_id}
endpoint = endpoints.URL_STATS_MEMBER_CAREER
func_name = inspect.stack()[0][3]

results_response = self._get(endpoint, params)
record = self._wrap_payload(
results_response, func_name, endpoint, params
)
return record

def member_recent_races(self, customer_id):
params = {"cust_id": customer_id}
endpoint = endpoints.URL_STATS_MEMBER_RECENT_RACES
func_name = inspect.stack()[0][3]

results_response = self._get(endpoint, params)
record = self._wrap_payload(
results_response, func_name, endpoint, params
)
return record

def member_summary(self, customer_id):
params = {"cust_id": customer_id}
endpoint = endpoints.URL_STATS_MEMBER_SUMMARY
func_name = inspect.stack()[0][3]

results_response = self._get(endpoint, params)
record = self._wrap_payload(
results_response, func_name, endpoint, params
)
return record

def member_yearly(self, customer_id):
params = {"cust_id": customer_id}
endpoint = endpoints.URL_STATS_MEMBER_YEARLY
func_name = inspect.stack()[0][3]

results_response = self._get(endpoint, params)
record = self._wrap_payload(
results_response, func_name, endpoint, params
)
return record

def membership(self, customer_id: int):
params = {"customer_id": customer_id}
endpoint = endpoints.URL_MEMBERSHIP
func_name = inspect.stack()[0][3]

results_response = self._get(endpoint, params)
record = self._wrap_payload(
results_response, func_name, endpoint, params
)
return record
1 change: 0 additions & 1 deletion src/iracing_garage/constants/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/hosted/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/league/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/lookup/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/member/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/results/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/season/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/series/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/stats/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/team/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/time_attack/__init__.py

This file was deleted.

1 change: 0 additions & 1 deletion src/iracing_garage/track/__init__.py

This file was deleted.

Loading