From 8fd930ba872e147be73b042ec985ac29100caf5a Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Fri, 23 Jun 2023 15:34:37 +0200 Subject: [PATCH] Handle LastFM unavailable (#94456) --- homeassistant/components/lastfm/sensor.py | 36 +++++++++++++---------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/homeassistant/components/lastfm/sensor.py b/homeassistant/components/lastfm/sensor.py index d8cf96be5ac..08179df5b7e 100644 --- a/homeassistant/components/lastfm/sensor.py +++ b/homeassistant/components/lastfm/sensor.py @@ -3,7 +3,7 @@ from __future__ import annotations import hashlib -from pylast import LastFMNetwork, Track, User, WSError +from pylast import LastFMNetwork, PyLastError, Track, User import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity @@ -104,26 +104,30 @@ class LastFmSensor(SensorEntity): def update(self) -> None: """Update device state.""" + self._attr_native_value = STATE_NOT_SCROBBLING try: - self._user.get_playcount() - except WSError as exc: + play_count = self._user.get_playcount() + self._attr_entity_picture = self._user.get_image() + now_playing = self._user.get_now_playing() + top_tracks = self._user.get_top_tracks(limit=1) + last_tracks = self._user.get_recent_tracks(limit=1) + except PyLastError as exc: self._attr_available = False LOGGER.error("Failed to load LastFM user `%s`: %r", self._user.name, exc) return - self._attr_entity_picture = self._user.get_image() - if now_playing := self._user.get_now_playing(): + self._attr_available = True + if now_playing: self._attr_native_value = format_track(now_playing) - else: - self._attr_native_value = STATE_NOT_SCROBBLING - top_played = None - if top_tracks := self._user.get_top_tracks(limit=1): - top_played = format_track(top_tracks[0].item) - last_played = None - if last_tracks := self._user.get_recent_tracks(limit=1): - last_played = format_track(last_tracks[0].track) - play_count = self._user.get_playcount() self._attr_extra_state_attributes = { - ATTR_LAST_PLAYED: last_played, ATTR_PLAY_COUNT: play_count, - ATTR_TOP_PLAYED: top_played, + ATTR_LAST_PLAYED: None, + ATTR_TOP_PLAYED: None, } + if len(last_tracks) > 0: + self._attr_extra_state_attributes[ATTR_LAST_PLAYED] = format_track( + last_tracks[0].track + ) + if len(top_tracks) > 0: + self._attr_extra_state_attributes[ATTR_TOP_PLAYED] = format_track( + top_tracks[0].item + )