Skip to content

Commit e268b95

Browse files
authored
Merge pull request #121 from droans/next
Cache encoded images to avoid redownloading
2 parents d0f6c3c + fd05108 commit e268b95

7 files changed

Lines changed: 29 additions & 15 deletions

File tree

custom_components/mass_queue/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# ty:ignore[unresolved-import]
12
"""Initialize component."""
23

34
from __future__ import annotations

custom_components/mass_queue/config_flow.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# ty:ignore[unresolved-import]
12
"""Config flow for integration."""
23

34
from __future__ import annotations
@@ -67,12 +68,13 @@ def _parse_zeroconf_server_info(properties: dict[str, str]) -> ServerInfoMessage
6768
)
6869

6970

70-
def get_manual_schema(user_input: dict[str, Any]) -> vol.Schema:
71+
def get_manual_schema(user_input: dict[str, Any] | None) -> vol.Schema:
7172
"""Return a schema for the manual step."""
72-
if type(user_input) is dict:
73-
default_url = user_input.get(CONF_URL, DEFAULT_URL)
74-
else:
75-
default_url = DEFAULT_URL
73+
default_url = (
74+
user_input.get(CONF_URL, DEFAULT_URL)
75+
if type(user_input) is dict
76+
else DEFAULT_URL
77+
)
7678
return vol.Schema(
7779
{
7880
vol.Required(CONF_URL, default=default_url): str,

custom_components/mass_queue/controller.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# ty:ignore[unresolved-import]
12
"""Controller for queues, players cache."""
23

34
from __future__ import annotations
@@ -141,7 +142,7 @@ def update_player_queue(self, player_id: str):
141142

142143
async def send_command(self, command: str, data: dict | None = None):
143144
"""Sends command to Music Assistant and returns response."""
144-
data = data if data else {}
145+
data = data or {}
145146
return await self._client.send_command(command, require_schema=None, **data)
146147

147148
async def get_recommendations(self, providers: list | None = None):
@@ -378,7 +379,7 @@ async def process_image_single_item(self, queue_item: dict):
378379
img_data = queue_item["media_item"]["metadata"]["images"][0]
379380
url = generate_image_url_from_image_data(img_data, self._client)
380381
LOGGER.debug(f"Downloading URL {url}")
381-
result = await download_and_encode_image(url, self._hass)
382+
result = await download_and_encode_image(url)
382383
LOGGER.debug("Downloaded and setting")
383384
queue_item["local_image_encoded"] = result
384385
except Exception as e: # noqa: BLE001

custom_components/mass_queue/schemas.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# ty:ignore[unresolved-import]
12
"""Schemas."""
23

34
from __future__ import annotations

custom_components/mass_queue/services.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# ty:ignore[unresolved-import]
12
"""Service actions for mass_queue."""
23

34
from __future__ import annotations

custom_components/mass_queue/utils.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# ty:ignore[unresolved-import]
12
"""Utilities."""
23

34
from __future__ import annotations
@@ -6,8 +7,10 @@
67
import urllib.parse
78
from typing import TYPE_CHECKING
89

10+
from aiocache import cached
11+
from aiocache.serializers import PickleSerializer
912
from homeassistant.config_entries import ConfigEntryState
10-
from homeassistant.core import callback
13+
from homeassistant.core import async_get_hass, callback
1114
from homeassistant.exceptions import ServiceValidationError
1215
from homeassistant.helpers import aiohttp_client
1316
from homeassistant.helpers import device_registry as dr
@@ -118,7 +121,7 @@ def get_queue_id_from_player_data(player_data):
118121
return current_media.get("queue_id")
119122

120123

121-
def return_image_or_none(img_data: dict, remotely_accessible: bool):
124+
def return_image_or_none(img_data: dict | None, remotely_accessible: bool):
122125
"""Returns None if image is not present or not remotely accessible."""
123126
if type(img_data) is dict:
124127
img = img_data.get("path")
@@ -168,10 +171,12 @@ def find_image_from_artists(data: dict, remotely_accessible: bool):
168171
"""Attempts to find the image via the artists key."""
169172
artist = data.get("artist", {})
170173
img_data = artist.get("image") or []
171-
img_data += artist.get("metadata") or []
174+
img_data += artist.get("metadata", {})
172175
if len(img_data):
173176
return search_image_list(img_data, remotely_accessible)
174-
return return_image_or_none(img_data, remotely_accessible)
177+
if isinstance(img_data, dict):
178+
return return_image_or_none(img_data, remotely_accessible)
179+
return None
175180

176181

177182
def find_image(data: dict, remotely_accessible: bool = True):
@@ -233,7 +238,7 @@ def process_recommendation_section_items(items: list):
233238
return [process_recommendation_section_item(item) for item in items]
234239

235240

236-
def process_recommendation_section(section: dict):
241+
def process_recommendation_section(section):
237242
"""Process and reformat a single recommendation section."""
238243
LOGGER.debug(f"Got section: {section}")
239244
section = section.to_dict()
@@ -287,8 +292,10 @@ async def download_single_image_from_image_data(
287292
return None
288293

289294

290-
async def download_and_encode_image(url: str, hass: HomeAssistant):
295+
@cached(serializer=PickleSerializer())
296+
async def download_and_encode_image(url: str):
291297
"""Downloads and encodes a single image from the given URL."""
298+
hass = async_get_hass()
292299
session = aiohttp_client.async_get_clientsession(hass)
293300
req = await session.get(url)
294301
read = await req.content.read()

custom_components/mass_queue/websocket_commands.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# ty:ignore[unresolved-import]
12
"""Music Assistant Queue Actions Websocket Commands."""
23

34
from __future__ import annotations
@@ -47,14 +48,14 @@ def api_get_entity_info(
4748
)
4849
@websocket_api.async_response
4950
async def api_download_and_encode_image(
50-
hass: HomeAssistant,
51+
hass: HomeAssistant, # noqa: ARG001
5152
connection: websocket_api.ActiveConnection,
5253
msg: dict,
5354
) -> None:
5455
"""Download images and return them as b64 encoded."""
5556
LOGGER.debug(f"Got message: {msg}")
5657
url = msg["url"]
57-
result = await download_and_encode_image(url, hass)
58+
result = await download_and_encode_image(url)
5859
connection.send_result(msg["id"], result)
5960

6061

0 commit comments

Comments
 (0)