Handle LastFM unavailable (#94456)

pull/95115/head
Joost Lekkerkerker 2023-06-23 15:34:37 +02:00 committed by GitHub
parent 4255cd6bbc
commit 8fd930ba87
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 20 additions and 16 deletions

View File

@ -3,7 +3,7 @@ from __future__ import annotations
import hashlib import hashlib
from pylast import LastFMNetwork, Track, User, WSError from pylast import LastFMNetwork, PyLastError, Track, User
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
@ -104,26 +104,30 @@ class LastFmSensor(SensorEntity):
def update(self) -> None: def update(self) -> None:
"""Update device state.""" """Update device state."""
self._attr_native_value = STATE_NOT_SCROBBLING
try: try:
self._user.get_playcount() play_count = self._user.get_playcount()
except WSError as exc: 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 self._attr_available = False
LOGGER.error("Failed to load LastFM user `%s`: %r", self._user.name, exc) LOGGER.error("Failed to load LastFM user `%s`: %r", self._user.name, exc)
return return
self._attr_entity_picture = self._user.get_image() self._attr_available = True
if now_playing := self._user.get_now_playing(): if now_playing:
self._attr_native_value = format_track(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 = { self._attr_extra_state_attributes = {
ATTR_LAST_PLAYED: last_played,
ATTR_PLAY_COUNT: play_count, 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
)