Skip to content

Commit

Permalink
fix: media_player.py: Prevent access to non-existent accounts data …
Browse files Browse the repository at this point in the history
…during updates.

- **Purpose**: Prevent access to non-existent `accounts` data during updates.
- **Changes**:
  - **`async_update` Method**:
    - Introduced checks using the `get` method to safely access nested dictionary keys.
    - Added warnings and early returns if required data structures are missing.
  - **Other Methods (`async_select_source`, etc.)**:
    - Applied similar conditional checks to ensure robust data access.
  - **Comments**:
    - Updated all comments to English for consistency and clarity.
  - **Best Practices**:
    - Adhered to Python 3.12 best practices, including the use of `is None` instead of `== None`, proper type annotations, and structured logging.
  • Loading branch information
jleinenbach authored Oct 2, 2024
1 parent 81e2c81 commit 7025624
Showing 1 changed file with 35 additions and 22 deletions.
57 changes: 35 additions & 22 deletions custom_components/alexa_media/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -776,8 +776,12 @@ async def async_select_source(self, source):
else:
await self.alexa_api.set_bluetooth(devices["address"])
self._source = source
# Safely access 'http2' setting
if not (
self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["http2"]
self.hass.data.get(DATA_ALEXAMEDIA, {})
.get("accounts", {})
.get(self._login.email, {})
.get("http2")
):
await self.async_update()

Expand Down Expand Up @@ -922,35 +926,45 @@ async def async_update(self):
except AttributeError:
pass
email = self._login.email

# Check if DATA_ALEXAMEDIA and 'accounts' exist
accounts_data = self.hass.data.get(DATA_ALEXAMEDIA, {}).get("accounts", {})
if (
self.entity_id is None # Device has not initialized yet
or email not in self.hass.data[DATA_ALEXAMEDIA]["accounts"]
or email not in accounts_data
or self._login.session.closed
):
self._assumed_state = True
self.available = False
return
device = self.hass.data[DATA_ALEXAMEDIA]["accounts"][email]["devices"][
"media_player"
][self.device_serial_number]

# Safely access the device
device = accounts_data[email]["devices"]["media_player"].get(self.device_serial_number)
if not device:
_LOGGER.warning(
"Device serial number %s not found for account %s. Skipping update.",
self.device_serial_number,
hide_email(email),
)
self.available = False
return

# Safely access websocket_commands
seen_commands = (
self.hass.data[DATA_ALEXAMEDIA]["accounts"][email][
"websocket_commands"
].keys()
if "websocket_commands"
in (self.hass.data[DATA_ALEXAMEDIA]["accounts"][email])
accounts_data[email]["websocket_commands"].keys()
if "websocket_commands" in accounts_data[email]
else None
)
await self.refresh( # pylint: disable=unexpected-keyword-arg
device, no_throttle=True
)
push_enabled = (
self.hass.data[DATA_ALEXAMEDIA]["accounts"].get(email, {}).get("http2")
)

await self.refresh(device, no_throttle=True)

# Safely access 'http2' setting
push_enabled = accounts_data[email].get("http2")

if (
self.state in [MediaPlayerState.PLAYING]
and
# only enable polling if websocket not connected
# Only enable polling if websocket not connected
(
not push_enabled
or not seen_commands
Expand All @@ -970,7 +984,7 @@ async def async_update(self):
):
_LOGGER.debug(
"%s: %s playing; scheduling update in %s seconds",
hide_email(self._login.email),
hide_email(email),
self.name,
PLAY_SCAN_INTERVAL,
)
Expand All @@ -983,9 +997,8 @@ async def async_update(self):
self._should_poll = False
if not push_enabled:
_LOGGER.debug(
"%s: Disabling polling and scheduling last update in"
" 300 seconds for %s",
hide_email(self._login.email),
"%s: Disabling polling and scheduling last update in 300 seconds for %s",
hide_email(email),
self.name,
)
async_call_later(
Expand All @@ -996,7 +1009,7 @@ async def async_update(self):
else:
_LOGGER.debug(
"%s: Disabling polling for %s",
hide_email(self._login.email),
hide_email(email),
self.name,
)
self._last_update = util.utcnow()
Expand Down

0 comments on commit 7025624

Please sign in to comment.