Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
):
serial = (json_payload["key"]["entryId"]).split("#")[2]
json_payload["key"]["serialNumber"] = serial
else:
serial = None
if command == "PUSH_ACTIVITY":
# Last_Alexa Updated
last_called = {
"serialNumber": serial,
"timestamp": json_payload["timestamp"],
}
if serial and serial in existing_serials:
await update_last_called(login_obj, last_called)
async_dispatcher_send(
hass,
f"{DOMAIN}_{hide_email(email)}"[0:32],
{"push_activity": json_payload},
)
elif command in (
"PUSH_AUDIO_PLAYER_STATE",
"PUSH_MEDIA_CHANGE",
"PUSH_MEDIA_PROGRESS_CHANGE",
):
# Player update/ Push_media from tune_in
if serial and serial in existing_serials:
_LOGGER.debug(
"Updating media_player: %s", hide_serial(json_payload)
)
async_dispatcher_send(
hass,
f"{DOMAIN}_{hide_email(email)}"[0:32],
{"player_state": json_payload},
async def close_connections(hass, email: Text) -> None:
"""Clear open aiohttp connections for email."""
if (
email not in hass.data[DATA_ALEXAMEDIA]["accounts"]
or "login_obj" not in hass.data[DATA_ALEXAMEDIA]["accounts"][email]
):
return
account_dict = hass.data[DATA_ALEXAMEDIA]["accounts"][email]
login_obj = account_dict["login_obj"]
await login_obj.close()
_LOGGER.debug(
"%s: Connection closed: %s", hide_email(email), login_obj.session.closed
)
await clear_configurator(hass, email)
async def ws_connect() -> WebsocketEchoClient:
"""Open WebSocket connection.
This will only attempt one login before failing.
"""
websocket: Optional[WebsocketEchoClient] = None
try:
if login_obj.session.closed:
_LOGGER.debug(
"%s: Websocket creation aborted. Session is closed.",
hide_email(email),
)
return
websocket = WebsocketEchoClient(
login_obj,
ws_handler,
ws_open_handler,
ws_close_handler,
ws_error_handler,
)
_LOGGER.debug("%s: Websocket created: %s", hide_email(email), websocket)
await websocket.async_run()
except BaseException as exception_: # pylint: disable=broad-except
_LOGGER.debug(
"%s: Websocket creation failed: %s", hide_email(email), exception_
)
return
websocket: Optional[WebsocketEchoClient] = None
try:
if login_obj.session.closed:
_LOGGER.debug(
"%s: Websocket creation aborted. Session is closed.",
hide_email(email),
)
return
websocket = WebsocketEchoClient(
login_obj,
ws_handler,
ws_open_handler,
ws_close_handler,
ws_error_handler,
)
_LOGGER.debug("%s: Websocket created: %s", hide_email(email), websocket)
await websocket.async_run()
except BaseException as exception_: # pylint: disable=broad-except
_LOGGER.debug(
"%s: Websocket creation failed: %s", hide_email(email), exception_
)
return
return websocket
hide_email(email),
len(devices) if devices is not None else "",
len(bluetooth.get("bluetoothStates", []))
if bluetooth is not None
else "",
)
except (AlexapyLoginError, JSONDecodeError):
_LOGGER.debug(
"%s: Alexa API disconnected; attempting to relogin : status %s",
hide_email(email),
login_obj.status,
)
if login_obj.status:
await hass.bus.async_fire(
"alexa_media_player/relogin_required",
event_data={"email": hide_email(email), "url": login_obj.url},
)
await login_obj.reset()
await login_obj.login()
await test_login_status(hass, config_entry, login_obj, setup_alexa)
return
except BaseException as err:
raise UpdateFailed(f"Error communicating with API: {err}")
await process_notifications(login_obj, raw_notifications)
# Process last_called data to fire events
await update_last_called(login_obj)
new_alexa_clients = [] # list of newly discovered device names
exclude_filter = []
include_filter = []
)
json_payload = (
message_obj.json_payload["payload"]
if isinstance(message_obj.json_payload, dict)
and "payload" in message_obj.json_payload
else None
)
existing_serials = _existing_serials(hass, login_obj)
seen_commands = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
"websocket_commands"
]
if command and json_payload:
_LOGGER.debug(
"%s: Received websocket command: %s : %s",
hide_email(email),
command,
hide_serial(json_payload),
)
serial = None
if command not in seen_commands:
seen_commands[command] = time.time()
_LOGGER.debug("Adding %s to seen_commands: %s", command, seen_commands)
if (
"dopplerId" in json_payload
and "deviceSerialNumber" in json_payload["dopplerId"]
):
serial = json_payload["dopplerId"]["deviceSerialNumber"]
elif (
"key" in json_payload
and "entryId" in json_payload["key"]
and json_payload["key"]["entryId"].find("#") != -1
async def close_connections(hass, email: Text) -> None:
"""Clear open aiohttp connections for email."""
if (
email not in hass.data[DATA_ALEXAMEDIA]["accounts"]
or "login_obj" not in hass.data[DATA_ALEXAMEDIA]["accounts"][email]
):
return
account_dict = hass.data[DATA_ALEXAMEDIA]["accounts"][email]
login_obj = account_dict["login_obj"]
await login_obj.close()
_LOGGER.debug(
"%s: Connection closed: %s", hide_email(email), login_obj.session.closed
)
hide_email(email),
len(devices) if devices is not None else "",
len(bluetooth.get("bluetoothStates", []))
if bluetooth is not None
else "",
)
except (AlexapyLoginError, JSONDecodeError):
_LOGGER.debug(
"%s: Alexa API disconnected; attempting to relogin : status %s",
hide_email(email),
login_obj.status,
)
if login_obj.status:
await hass.bus.async_fire(
"alexa_media_player/relogin_required",
event_data={"email": hide_email(email), "url": login_obj.url},
)
await login_obj.reset()
await login_obj.login()
await test_login_status(hass, config_entry, login_obj, setup_alexa)
return
except BaseException as err:
raise UpdateFailed(f"Error communicating with API: {err}")
await process_notifications(login_obj, raw_notifications)
# Process last_called data to fire events
await update_last_called(login_obj)
new_alexa_clients = [] # list of newly discovered device names
exclude_filter = []
include_filter = []
async def test_login_status(hass, config_entry, login,
setup_platform_callback) -> None:
"""Test the login status and spawn requests for info."""
_LOGGER.debug("Testing login status: %s", login.status)
if 'login_successful' in login.status and login.status['login_successful']:
_LOGGER.debug("Setting up Alexa devices for %s",
hide_email(login.email))
await hass.async_add_job(setup_alexa, hass, config_entry,
login)
return
if ('captcha_required' in login.status and
login.status['captcha_required']):
_LOGGER.debug("Creating configurator to request captcha")
elif ('securitycode_required' in login.status and
login.status['securitycode_required']):
_LOGGER.debug("Creating configurator to request 2FA")
elif ('claimspicker_required' in login.status and
login.status['claimspicker_required']):
_LOGGER.debug("Creating configurator to select verification option")
elif ('authselect_required' in login.status and
login.status['authselect_required']):
_LOGGER.debug("Creating configurator to select OTA option")
elif ('verificationcode_required' in login.status and
"""Unload a config entry."""
hass.services.async_remove(DOMAIN, SERVICE_UPDATE_LAST_CALLED)
hass.services.async_remove(DOMAIN, SERVICE_CLEAR_HISTORY)
for component in ALEXA_COMPONENTS:
await hass.config_entries.async_forward_entry_unload(entry, component)
# notify has to be handled manually as the forward does not work yet
from .notify import async_unload_entry as notify_async_unload_entry
await notify_async_unload_entry(hass, entry)
email = entry.data["email"]
await close_connections(hass, email)
await clear_configurator(hass, email)
for listener in hass.data[DATA_ALEXAMEDIA]["accounts"][email][DATA_LISTENER]:
listener()
hass.data[DATA_ALEXAMEDIA]["accounts"].pop(email)
_LOGGER.debug("Unloaded entry for %s", hide_email(email))
return True