Fix: some small typos and optimizations
authorMarcel van der Veldt <m.vanderveldt@outlook.com>
Sat, 23 Nov 2024 01:10:10 +0000 (02:10 +0100)
committerMarcel van der Veldt <m.vanderveldt@outlook.com>
Sat, 23 Nov 2024 01:10:10 +0000 (02:10 +0100)
music_assistant/providers/airplay/provider.py
music_assistant/providers/spotify/__init__.py
music_assistant/providers/spotify/helpers.py [new file with mode: 0644]

index 0ed4a1e74eccbff4b01bb693135de1ce00b0485e..b1beb7af7f1b8f86b7a439181f59c06651d6c1c5 100644 (file)
@@ -298,7 +298,7 @@ class AirplayProvider(PlayerProvider):
                 output_format=AIRPLAY_PCM_FORMAT,
                 use_pre_announce=media.custom_data["use_pre_announce"],
             )
-        elif media.queue_id.startswith("ugp_"):
+        elif media.queue_id and media.queue_id.startswith("ugp_"):
             # special case: UGP stream
             ugp_provider: PlayerGroupProvider = self.mass.get_provider("player_group")
             ugp_stream = ugp_provider.ugp_streams[media.queue_id]
@@ -320,7 +320,7 @@ class AirplayProvider(PlayerProvider):
             input_format = AIRPLAY_PCM_FORMAT
             audio_source = get_ffmpeg_stream(
                 audio_input=media.uri,
-                input_format=AudioFormat(ContentType.try_parse(media.uri)),
+                input_format=AudioFormat(content_type=ContentType.try_parse(media.uri)),
                 output_format=AIRPLAY_PCM_FORMAT,
             )
         # setup RaopStreamSession for player (and its sync childs if any)
index a45adc905461033f1bbdce94038fef86e291488f..fb67a9214dd84fb68dc3844ec3c5e1e16e2a5a02 100644 (file)
@@ -5,7 +5,6 @@ from __future__ import annotations
 import asyncio
 import contextlib
 import os
-import platform
 import time
 from typing import TYPE_CHECKING, Any, cast
 from urllib.parse import urlencode
@@ -51,6 +50,8 @@ from music_assistant.helpers.throttle_retry import ThrottlerManager, throttle_wi
 from music_assistant.helpers.util import lock, parse_title_and_version
 from music_assistant.models.music_provider import MusicProvider
 
+from .helpers import get_librespot_binary
+
 if TYPE_CHECKING:
     from collections.abc import AsyncGenerator
 
@@ -252,7 +253,7 @@ class SpotifyProvider(MusicProvider):
             self.throttler.rate_limit = 45
             self.throttler.period = 30
         # check if we have a librespot binary for this arch
-        await self.get_librespot_binary()
+        self._librespot_bin = await get_librespot_binary()
         # try login which will raise if it fails
         await self.login()
 
@@ -553,11 +554,10 @@ class SpotifyProvider(MusicProvider):
         self, streamdetails: StreamDetails, seek_position: int = 0
     ) -> AsyncGenerator[bytes, None]:
         """Return the audio stream for the provider item."""
-        librespot = await self.get_librespot_binary()
         spotify_uri = f"spotify://track:{streamdetails.item_id}"
         self.logger.log(VERBOSE_LOG_LEVEL, f"Start streaming {spotify_uri} using librespot")
         args = [
-            librespot,
+            self._librespot_bin,
             "--cache",
             self.cache_dir,
             "--cache-size-limit",
@@ -820,9 +820,8 @@ class SpotifyProvider(MusicProvider):
             self.instance_id, CONF_REFRESH_TOKEN, auth_info["refresh_token"], encrypted=True
         )
         # check if librespot still has valid auth
-        librespot = await self.get_librespot_binary()
         args = [
-            librespot,
+            self._librespot_bin,
             "--cache",
             self.cache_dir,
             "--check-auth",
@@ -982,33 +981,6 @@ class SpotifyProvider(MusicProvider):
             response.raise_for_status()
             return await response.json(loads=json_loads)
 
-    async def get_librespot_binary(self):
-        """Find the correct librespot binary belonging to the platform."""
-        # ruff: noqa: SIM102
-        if self._librespot_bin is not None:
-            return self._librespot_bin
-
-        async def check_librespot(librespot_path: str) -> str | None:
-            try:
-                returncode, output = await check_output(librespot_path, "--version")
-                if returncode == 0 and b"librespot" in output:
-                    self._librespot_bin = librespot_path
-                    return librespot_path
-            except OSError:
-                return None
-
-        base_path = os.path.join(os.path.dirname(__file__), "bin")
-        system = platform.system().lower().replace("darwin", "macos")
-        architecture = platform.machine().lower()
-
-        if bridge_binary := await check_librespot(
-            os.path.join(base_path, f"librespot-{system}-{architecture}")
-        ):
-            return bridge_binary
-
-        msg = f"Unable to locate Librespot for {system}/{architecture}"
-        raise RuntimeError(msg)
-
     def _fix_create_playlist_api_bug(self, playlist_obj: dict[str, Any]) -> None:
         """Fix spotify API bug where incorrect owner id is returned from Create Playlist."""
         if playlist_obj["owner"]["id"] != self._sp_user["id"]:
diff --git a/music_assistant/providers/spotify/helpers.py b/music_assistant/providers/spotify/helpers.py
new file mode 100644 (file)
index 0000000..4675d14
--- /dev/null
@@ -0,0 +1,33 @@
+"""Helpers/utils for the Spotify musicprovider."""
+
+from __future__ import annotations
+
+import os
+import platform
+
+from music_assistant.helpers.process import check_output
+
+
+async def get_librespot_binary():
+    """Find the correct librespot binary belonging to the platform."""
+
+    # ruff: noqa: SIM102
+    async def check_librespot(librespot_path: str) -> str | None:
+        try:
+            returncode, output = await check_output(librespot_path, "--version")
+            if returncode == 0 and b"librespot" in output:
+                return librespot_path
+        except OSError:
+            return None
+
+    base_path = os.path.join(os.path.dirname(__file__), "bin")
+    system = platform.system().lower().replace("darwin", "macos")
+    architecture = platform.machine().lower()
+
+    if bridge_binary := await check_librespot(
+        os.path.join(base_path, f"librespot-{system}-{architecture}")
+    ):
+        return bridge_binary
+
+    msg = f"Unable to locate Librespot for {system}/{architecture}"
+    raise RuntimeError(msg)