Skip to content

Commit

Permalink
(0.1.4) better session handling
Browse files Browse the repository at this point in the history
  • Loading branch information
pantherale0 committed Jul 16, 2023
1 parent 75482f6 commit 43f430a
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 19 deletions.
53 changes: 49 additions & 4 deletions pyroostermoney/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,23 @@ def __init__(self, username: str, password: str) -> None:

async def async_login(self):
"""Logs into RoosterMoney and starts a new active session."""
if self._session is not None:
if self._session.get("expiry_time") > datetime.now():
_LOGGER.debug("Not logging in again, session already active.")
return True

req_body = LOGIN_BODY
req_body["username"] = self._username
req_body["password"] = self._password
auth = aiohttp.BasicAuth(self._username, self._password)

login_response = await self.internal_request_handler(url=URLS.get("login"),
if "Authorization" in self._headers:
self._headers.pop("Authorization")

login_response = await self.request_handler(url=URLS.get("login"),
body=req_body,
auth=auth,
headers=HEADERS)
headers=self._headers)

if login_response["status"] == 401:
raise InvalidAuthError(self._username, login_response["status"])
Expand All @@ -79,12 +87,13 @@ async def async_login(self):

return True

async def internal_request_handler(self,
async def _internal_request_handler(self,
url,
body=None,
headers=None,
auth=None,
method="GET"):
method="GET",
login_request=False):
"""Handles all incoming requests to make sure that the session is active."""
if self._session is None and self._logged_in:
raise RuntimeError("Invalid state. Missing session data yet currently logged in?")
Expand All @@ -100,6 +109,10 @@ async def internal_request_handler(self,

# Check if auth has expired

if login_request:
_LOGGER.debug("Login request.")
return await _post_request(url, body, auth, headers)

if self._session["expiry_time"] < datetime.now():
raise AuthenticationExpired()

Expand All @@ -112,3 +125,35 @@ async def internal_request_handler(self,
return await _post_request(url, body=body, headers=headers)
else:
raise ValueError("Invalid type argument.")

async def request_handler(self,
url,
body=None,
headers=None,
auth=None,
method="GET",
login_request=False):
"""Public calls for the private _internal_request_handler."""
try:
return await self._internal_request_handler(
url=url,
body=body,
headers=headers,
auth=auth,
method=method,
login_request=login_request
)
except AuthenticationExpired:
await self.async_login()
return await self._internal_request_handler(
url=url,
body=body,
headers=headers,
auth=auth,
method=method,
login_request=login_request
)
except NotLoggedIn:
raise NotLoggedIn()
except Exception as err:
_LOGGER.error(err)
10 changes: 5 additions & 5 deletions pyroostermoney/child/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def __init__(self, raw_response: dict, session: RoosterSession) -> None:

async def update(self):
"""Updates the cached data for this child."""
response = await self._session.internal_request_handler(
response = await self._session.request_handler(
url=URLS.get("get_child").format(user_id=self.user_id))
self._parse_response(response)

Expand All @@ -34,7 +34,7 @@ def _parse_response(self, raw_response:dict):

async def get_active_allowance_period(self):
"""Returns the current active allowance period."""
allowance_periods = await self._session.internal_request_handler(
allowance_periods = await self._session.request_handler(
url=URLS.get("get_child_allowance_periods").format(user_id=self.user_id))
allowance_periods = allowance_periods["response"]
active_periods = [p for p in allowance_periods
Expand All @@ -51,7 +51,7 @@ async def get_spend_history(self, count=10):
user_id=self.user_id,
count=count
)
response = await self._session.internal_request_handler(url=url)
response = await self._session.request_handler(url=url)

return response["response"]

Expand All @@ -61,7 +61,7 @@ async def get_allowance_period_jobs(self, allowance_period_id):
user_id=self.user_id,
allowance_period_id=allowance_period_id
)
response = await self._session.internal_request_handler(url)
response = await self._session.request_handler(url)

return response["response"]

Expand All @@ -70,7 +70,7 @@ async def get_pocket_money(self):
url = URLS.get("get_child_pocket_money").format(
user_id=self.user_id
)
response = await self._session.internal_request_handler(url)
response = await self._session.request_handler(url)

return response["response"]

Expand Down
2 changes: 1 addition & 1 deletion pyroostermoney/const.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Static Rooster Money variables"""

VERSION="0.1.3"
VERSION="0.1.4"
BASE_URL="https://api.rooster.money"
LANGUAGE="en-GB"
COUNTRY="gb"
Expand Down
8 changes: 4 additions & 4 deletions pyroostermoney/family_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def _parse_response(self, raw_response: dict):

async def update(self):
"""Updates the FamilyAccount object data."""
response = await self._session.internal_request_handler(
response = await self._session.request_handler(
url=URLS.get("get_family_account"))
self._parse_response(response)

Expand Down Expand Up @@ -55,7 +55,7 @@ async def create_payment(self,
request_body["paymentMethod"]["holderName"] = holder_name
## TODO request_body["shopperEmail"] = self.account_info.email

response = await self._session.internal_request_handler(
response = await self._session.request_handler(
url=URLS.get("create_payment"),
body=request_body,
method="POST"
Expand All @@ -65,7 +65,7 @@ async def create_payment(self,

async def get_available_cards(self):
"""Gets available top up payment cards"""
response = await self._session.internal_request_handler(
response = await self._session.request_handler(
url=URLS.get("get_available_cards")
)

Expand All @@ -76,7 +76,7 @@ async def get_top_up_methods(self, currency=None):
if currency is None:
currency=CURRENCY

response = await self._session.internal_request_handler(
response = await self._session.request_handler(
url=URLS.get("get_top_up_methods").format(
currency=currency
)
Expand Down
8 changes: 4 additions & 4 deletions pyroostermoney/roostermoney.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,26 +29,26 @@ async def get_children(self) -> list[ChildAccount]:

async def get_account_info(self) -> dict:
"""Returns the account info for the current user."""
return await self.internal_request_handler(url=URLS.get("get_account_info"))
return await self.request_handler(url=URLS.get("get_account_info"))

async def get_child_account(self, user_id) -> ChildAccount:
"""Fetches and returns a given child account details."""
response = await self.internal_request_handler(
response = await self.request_handler(
url=URLS.get("get_child").format(user_id=user_id))

return ChildAccount(response, self)

async def get_master_job_list(self):
"""Gets master job list (/parent/master-jobs)"""
response = await self.internal_request_handler(
response = await self.request_handler(
url=URLS.get("get_master_job_list")
)

return response

async def get_family_account(self) -> FamilyAccount:
"""Gets family account details (/parent/family/account)"""
response = await self.internal_request_handler(
response = await self.request_handler(
url=URLS.get("get_family_account")
)

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from setuptools import setup

setup(name="pyroostermoney",
version="0.1.3",
version="0.1.4",
description="A RoosterMoney integration for Python.",
url="https://github.com/pantherale0/pyroostermoney",
author="pantherale0",
Expand Down

0 comments on commit 43f430a

Please sign in to comment.