import pickle
from collections.abc import Callable
from contextlib import suppress
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from enum import StrEnum
from typing import TYPE_CHECKING, ParamSpec, TypeVar, cast
-from music_assistant_models.config_entries import ConfigEntry, ConfigValueOption, ConfigValueType
+from music_assistant_models.config_entries import (
+ ConfigEntry,
+ ConfigValueOption,
+ ConfigValueType,
+)
from music_assistant_models.enums import (
AlbumType,
CacheCategory,
from music_assistant.helpers.auth import AuthenticationHelper
from music_assistant.helpers.tags import AudioTags, async_parse_tags
-from music_assistant.helpers.throttle_retry import ThrottlerManager, throttle_with_retries
+from music_assistant.helpers.throttle_retry import (
+ ThrottlerManager,
+ throttle_with_retries,
+)
from music_assistant.models.music_provider import MusicProvider
from .helpers import (
library_items_add_remove,
remove_playlist_tracks,
search,
+ token_refresh,
)
if TYPE_CHECKING:
async def _get_tidal_session(self) -> TidalSession:
"""Ensure the current token is valid and return a tidal session."""
+ token_expiry = datetime.fromisoformat(str(self.config.get_value(CONF_EXPIRY_TIME)))
+ token_expiry_with_tz = token_expiry.replace(tzinfo=UTC)
+ utc_now_plus_one_hour = datetime.now(UTC) + timedelta(hours=1)
if (
self._tidal_session
and self._tidal_session.access_token
- and datetime.fromisoformat(str(self.config.get_value(CONF_EXPIRY_TIME)))
- > (datetime.now() + timedelta(days=1))
+ and token_expiry_with_tz > utc_now_plus_one_hour
):
return self._tidal_session
refresh_token=str(self.config.get_value(CONF_REFRESH_TOKEN)),
expiry_time=datetime.fromisoformat(str(self.config.get_value(CONF_EXPIRY_TIME))),
)
+ await token_refresh(self._tidal_session)
+
except Exception as err:
if "401 Client Error: Unauthorized" in str(err):
err_msg = "Credentials expired, you need to re-setup"
# Cache the mapping for future use
await self.mass.cache.set(
- cache_key, tracks[0].id, category=CacheCategory.DEFAULT, base_key=self.lookup_key
+ cache_key,
+ tracks[0].id,
+ category=CacheCategory.DEFAULT,
+ base_key=self.lookup_key,
)
return tracks[0]