diff --git a/aiotractive/api.py b/aiotractive/api.py index e7d82c8..b502b1e 100644 --- a/aiotractive/api.py +++ b/aiotractive/api.py @@ -2,6 +2,7 @@ import asyncio import json +import time import aiohttp from aiohttp.client_exceptions import ClientResponseError @@ -42,11 +43,11 @@ def __init__( # pylint: disable=too-many-arguments self._auth_headers = None async def user_id(self): - await self._authenticate() + await self.authenticate() return self._user_credentials["user_id"] async def auth_headers(self): - await self._authenticate() + await self.authenticate() return {**self.BASE_HEADERS, **self._auth_headers} async def request(self, *args, **kwargs): @@ -76,9 +77,12 @@ async def raw_request(self, uri, params=None, data=None, method="GET"): return await response.json() return await response.read() - async def _authenticate(self): + async def authenticate(self): """Perform authenticateion.""" - # TODO: update credentials if expired + if self._user_credentials is not None and self._user_credentials["expires_at"] - time.time() < 3600: + self._user_credentials = None + self._auth_headers = None + if self._user_credentials is not None: return self._user_credentials diff --git a/aiotractive/channel.py b/aiotractive/channel.py index f3dc0d3..ed5e323 100644 --- a/aiotractive/channel.py +++ b/aiotractive/channel.py @@ -3,7 +3,7 @@ import time from asyncio.exceptions import TimeoutError as AIOTimeoutError -from .exceptions import DisconnectedError +from .exceptions import DisconnectedError, TractiveError class Channel: @@ -34,7 +34,7 @@ async def listen(self): self._check_connection_task.cancel() await self._check_connection_task - raise event["error"] + raise TractiveError() from event["error"] if event["type"] == "cancelled": self._listen_task.cancel() diff --git a/aiotractive/tractive.py b/aiotractive/tractive.py index d59d6a5..81a2d29 100644 --- a/aiotractive/tractive.py +++ b/aiotractive/tractive.py @@ -11,6 +11,9 @@ def __init__(self, *args, **kwargs): """Initialize the client.""" self._api = API(*args, **kwargs) + async def authenticate(self): + return await self._api.authenticate() + async def trackers(self): trackers = await self._api.request(f"user/{await self._api.user_id()}/trackers") return [Tracker(self._api, t) for t in trackers] diff --git a/setup.py b/setup.py index fac5d4c..d7c700c 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ setup( name="aiotractive", - version="0.3.0", + version="0.4.0", author="Gleb Sinyavskiy", author_email="zhulik.gleb@gmail.com", description="Asynchronous Python client for the Tractive REST API",