Skip to content

Commit

Permalink
feat: expose expiration for oauth
Browse files Browse the repository at this point in the history
  • Loading branch information
alandtse committed Feb 28, 2020
1 parent 249a25c commit 0e116c3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
24 changes: 16 additions & 8 deletions teslajsonpy/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def __init__(
password: Text = None,
access_token: Text = None,
refresh_token: Text = None,
expiration: int = 0,
) -> None:
"""Initialize connection object."""
self.user_agent: Text = "Model S 2.1.79 (SM-G900V; Android REL 4.4.4; en_US"
Expand All @@ -45,15 +46,15 @@ def __init__(
self.websocket_url: Text = "wss://streaming.vn.teslamotors.com/streaming"
self.api: Text = "/api/1/"
self.oauth: Dict[Text, Text] = {}
self.expiration: int = 0
self.access_token = None
self.expiration: int = expiration
self.access_token = access_token
self.head = None
self.refresh_token = refresh_token
self.websession = websession
self.token_refreshed = False
self.generate_oauth(email, password, refresh_token)
if access_token:
self.__sethead(access_token)
if self.access_token:
self.__sethead(access_token=self.access_token, expiration=self.expiration)
_LOGGER.debug("Connecting with existing access token")
self.websocket = None

Expand Down Expand Up @@ -104,19 +105,26 @@ async def post(self, command, method="post", data=None):
"Requesting new oauth token using %s", self.oauth["grant_type"]
)
auth = await self.__open("/oauth/token", "post", data=self.oauth)
self.__sethead(auth["access_token"], auth["expires_in"])
self.__sethead(
access_token=auth["access_token"], expires_in=auth["expires_in"]
)
self.refresh_token = auth["refresh_token"]
self.generate_oauth()
self.token_refreshed = True
return await self.__open(
f"{self.api}{command}", method=method, headers=self.head, data=data
)

def __sethead(self, access_token: Text, expires_in: int = 1800):
def __sethead(
self, access_token: Text, expires_in: int = 1800, expiration: int = 0
):
"""Set HTTP header."""
self.access_token = access_token
now = calendar.timegm(datetime.datetime.now().timetuple())
self.expiration = now + expires_in
if expiration > 0:
self.expiration = expiration
else:
now = calendar.timegm(datetime.datetime.now().timetuple())
self.expiration = now + expires_in
self.head = {
"Authorization": f"Bearer {access_token}",
"User-Agent": self.user_agent,
Expand Down
16 changes: 14 additions & 2 deletions teslajsonpy/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ def __init__(
password: Text = None,
access_token: Text = None,
refresh_token: Text = None,
expiration: int = 0,
update_interval: int = 300,
enable_websocket: bool = False,
) -> None:
Expand All @@ -210,13 +211,14 @@ def __init__(
password (Text, optional): Password. Defaults to None.
access_token (Text, optional): Access token. Defaults to None.
refresh_token (Text, optional): Refresh token. Defaults to None.
expiration (int, optional): Timestamp when access_token expires. Defaults to 0
update_interval (int, optional): Seconds between allowed updates to the API. This is to prevent
being blocked by Tesla. Defaults to 300.
enable_websocket (bool, optional): Whether to connect with websockets. Defaults to False.
"""
self.__connection = Connection(
websession, email, password, access_token, refresh_token
websession, email, password, access_token, refresh_token, expiration
)
self.__components = []
self._update_interval: int = update_interval
Expand Down Expand Up @@ -303,6 +305,7 @@ async def connect(
tasks = [
self.update(car["id"], wake_if_asleep=wake_if_asleep) for car in cars
]
_LOGGER.debug("tasks %s %s", tasks, wake_if_asleep)
try:
await asyncio.gather(*tasks)
except (TeslaException, RetryLimitError):
Expand Down Expand Up @@ -330,6 +333,15 @@ def get_tokens(self) -> Tuple[Text, Text]:
self.__connection.token_refreshed = False
return (self.__connection.refresh_token, self.__connection.access_token)

def get_expiration(self) -> int:
"""Return expiration for oauth.
Returns
int: Returns timestamp when oauth expires
"""
return self.__connection.expiration

def register_websocket_callback(self, callback) -> int:
"""Register callback for websocket messages.
Expand Down Expand Up @@ -601,7 +613,7 @@ def _calculate_next_interval(vin: int) -> int:
async with self.__lock[vin]:
car_state = self.car_state[vin].get("state")
if (
(online or (wake_if_asleep and car_state == "asleep"))
(online or (wake_if_asleep and car_state in ["asleep", "offline"]))
and ( # pylint: disable=too-many-boolean-expressions
self.__update.get(vin)
)
Expand Down

0 comments on commit 0e116c3

Please sign in to comment.