Skip to content

Commit

Permalink
images: more robust to bad/weird/changing response format
Browse files Browse the repository at this point in the history
  • Loading branch information
kingosticks committed Dec 20, 2023
1 parent 24430a2 commit 23dd688
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
27 changes: 20 additions & 7 deletions mopidy_spotify/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ def _parse_uri(uri):

def _process_uri(web_client, uri):
data = web_client.get(f"{uri['type']}s/{uri['id']}")
_cache[uri["key"]] = tuple(_translate_image(i) for i in data["images"])
_cache[uri["key"]] = tuple(
_translate_image(i) for i in data.get("images") or []
)
return {uri["uri"]: _cache[uri["key"]]}


Expand All @@ -72,29 +74,40 @@ def _process_uris(web_client, uri_type, uris):
return result

data = web_client.get(uri_type + "s", params={"ids": ",".join(ids)})
for item in data.get(uri_type + "s", []):
for item in (
data.get(
uri_type + "s",
)
or []
):
if not item:
continue

if "linked_from" in item:
uri = ids_to_uris[item["linked_from"]["id"]]
item_id = item["linked_from"].get("id")
else:
uri = ids_to_uris[item["id"]]
item_id = item.get("id")
uri = ids_to_uris.get(item_id)
if not uri:
continue

if uri["key"] not in _cache:
if uri_type == "track":
album = _parse_uri(item["album"]["uri"])
if "album" not in item:
continue
album = _parse_uri(item["album"].get("uri"))
if not album:
continue
album_key = album["key"]
if album_key not in _cache:
_cache[album_key] = tuple(
_translate_image(i) for i in item["album"]["images"]
_translate_image(i)
for i in item["album"].get("images") or []
)
_cache[uri["key"]] = _cache[album_key]
else:
_cache[uri["key"]] = tuple(
_translate_image(i) for i in item["images"]
_translate_image(i) for i in item.get("images") or []
)
result[uri["uri"]] = _cache[uri["key"]]

Expand Down
18 changes: 18 additions & 0 deletions tests/test_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,21 @@ def test_service_returns_empty_result(web_client_mock, img_provider):
result = img_provider.get_images(["spotify:track:41shEpOKyyadtG6lDclooa"])

assert result == {}


def test_service_returns_none_result(web_client_mock, img_provider):
web_client_mock.get.return_value = {"tracks": None}

result = img_provider.get_images(["spotify:track:41shEpOKyyadtG6lDclooa"])

assert result == {}


def test_service_returns_none_result_playlist(web_client_mock, img_provider):
web_client_mock.get.return_value = {"images": None}

result = img_provider.get_images(
["spotify:playlist:41shEpOKyyadtG6lDclooa"]
)

assert result == {"spotify:playlist:41shEpOKyyadtG6lDclooa": ()}

0 comments on commit 23dd688

Please sign in to comment.