Skip to content

Commit

Permalink
feat: add automatic relogin
Browse files Browse the repository at this point in the history
  • Loading branch information
alandtse committed Nov 27, 2020
1 parent a025774 commit 23c44c3
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 20 deletions.
25 changes: 19 additions & 6 deletions custom_components/alexa_media/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,12 @@ async def relogin(event=None) -> None:
)
if login_obj is None:
login_obj = AlexaLogin(
url, email, password, hass.config.path, account.get(CONF_DEBUG)
url,
email,
password,
hass.config.path,
account.get(CONF_DEBUG),
account.get(CONF_OTPSECRET, ""),
)
hass.data[DATA_ALEXAMEDIA]["accounts"][email][
"login_obj"
Expand Down Expand Up @@ -1055,6 +1060,19 @@ async def test_login_status(hass, config_entry, login) -> bool:
return True
account = config_entry.data
_LOGGER.debug("Logging in: %s %s", obfuscate(account), in_progess_instances(hass))
_LOGGER.debug("Login stats: %s", login.stats)
message: Text = (
"Reauthenticate on the [Integrations](/config/integrations) page. "
)
if login.stats.get("login_timestamp") != datetime(1, 1, 1):
elaspsed_time: str = str(datetime.now() - login.stats.get("login_timestamp"))
api_calls: int = login.stats.get("api_calls")
message += f"Relogin required after {elaspsed_time} and {api_calls} api calls."
hass.components.persistent_notification.async_create(
title="Alexa Media Reauthentication Required",
message=message,
notification_id="alexa_media_relogin_required",
)
flow = hass.data[DATA_ALEXAMEDIA]["config_flows"].get(
f"{account[CONF_EMAIL]} - {account[CONF_URL]}"
)
Expand Down Expand Up @@ -1090,9 +1108,4 @@ async def test_login_status(hass, config_entry, login) -> bool:
CONF_OTPSECRET: account.get(CONF_OTPSECRET, ""),
},
)
hass.components.persistent_notification.async_create(
title="Alexa Media Reauthentication Required",
message=("Reauthenticate on the [Integrations](/config/integrations) page."),
notification_id="alexa_media_relogin_required",
)
return False
46 changes: 35 additions & 11 deletions custom_components/alexa_media/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from datetime import timedelta
from functools import reduce
import logging
import datetime
from typing import Any, Optional, Text
import re

Expand Down Expand Up @@ -160,10 +161,13 @@ async def async_step_user(self, user_input=None):
description_placeholders={"message": ""},
)

if f"{user_input[CONF_EMAIL]} - {user_input[CONF_URL]}" in configured_instances(
self.hass
) and not self.hass.data[DATA_ALEXAMEDIA]["config_flows"].get(
f"{user_input[CONF_EMAIL]} - {user_input[CONF_URL]}"
if (
not self.config.get("reauth")
and f"{user_input[CONF_EMAIL]} - {user_input[CONF_URL]}"
in configured_instances(self.hass)
and not self.hass.data[DATA_ALEXAMEDIA]["config_flows"].get(
f"{user_input[CONF_EMAIL]} - {user_input[CONF_URL]}"
)
):
_LOGGER.debug("Existing account found")
self.automatic_steps = 0
Expand Down Expand Up @@ -301,20 +305,40 @@ async def async_step_reauth(self, user_input=None):
"Creating reauth form with %s", obfuscate(self.config),
)
self.automatic_steps = 0
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(reauth_schema),
description_placeholders={"message": "REAUTH"},
)
if self.login is None:
try:
self.login = self.hass.data[DATA_ALEXAMEDIA]["accounts"][
self.config[CONF_EMAIL]
].get("login_obj")
except KeyError:
self.login = None
seconds_since_login: int = (
datetime.datetime.now() - self.login.stats["login_timestamp"]
).seconds if self.login else 60
if seconds_since_login < 60:
_LOGGER.debug(
"Relogin requested within %s seconds; manual login required",
seconds_since_login,
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(reauth_schema),
description_placeholders={"message": "REAUTH"},
)
_LOGGER.debug("Attempting automatic relogin")
await sleep(15)
return await self.async_step_user(self.config)

async def _test_login(self):
login = self.login
email = login.email
_LOGGER.debug("Testing login status: %s", login.status)
if login.status and login.status.get("login_successful"):
existing_entry = await self.async_set_unique_id(f"{email} - {login.url}")
self.config.pop("reauth")
self.config.pop(CONF_SECURITYCODE)
if self.config.get("reauth"):
self.config.pop("reauth")
if self.config.get(CONF_SECURITYCODE):
self.config.pop(CONF_SECURITYCODE)
if existing_entry:
self.hass.config_entries.async_update_entry(
existing_entry, data=self.config
Expand Down
11 changes: 9 additions & 2 deletions custom_components/alexa_media/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,18 @@ def report_relogin_required(hass, login, email) -> bool:
if hass and login and email:
if login.status:
_LOGGER.debug(
"Reporting need to relogin to %s with %s", login.url, hide_email(email)
"Reporting need to relogin to %s with %s stats: %s",
login.url,
hide_email(email),
login.stats,
)
hass.bus.async_fire(
"alexa_media_relogin_required",
event_data={"email": hide_email(email), "url": login.url},
event_data={
"email": hide_email(email),
"url": login.url,
"stats": login.stats,
},
)
return True
return False
Expand Down
2 changes: 1 addition & 1 deletion custom_components/alexa_media/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
"issue_tracker": "https://github.com/custom-components/alexa_media_player/issues",
"dependencies": ["persistent_notification"],
"codeowners": ["@keatontaylor", "@alandtse"],
"requirements": ["alexapy==1.15.2", "packaging~=20.3", "wrapt~=1.12.1"]
"requirements": ["alexapy==1.16.0", "packaging~=20.3", "wrapt~=1.12.1"]
}

0 comments on commit 23c44c3

Please sign in to comment.