fix(tidal): adapt to current search API (#6990)

## Problem

TIDAL album and track searches fail with HTTP 400 even after successful
authentication.

The plugin currently sends search queries as part of the URL path:

```text
GET /v2/searchResults/{query}
```

TIDAL’s current API requires the query through the `filter[query]`
parameter:

```text
GET /v2/searchResults?filter[query]={query}
```

The response format has also changed: `data` is now an array containing
the search-results resource rather than the resource object itself.

Fixes #6989.

## Fix

- Send search requests to `/v2/searchResults`.
- Pass the query using the required `filter[query]` parameter.
- Update the `SearchDocument` type for the new `data` array.
- Parse album and track relationships from the first search-results
resource.
- Handle empty search responses without raising an exception.
- Add regression coverage using a query that previously produced HTTP
400.
This commit is contained in:
Šarūnas Nejus
2026-09-05 00:25:35 +01:00
committed by GitHub
5 changed files with 79 additions and 22 deletions
+10 -2
View File
@@ -196,6 +196,9 @@ class TidalPlugin(MetadataSourcePlugin):
def search_tracks_by_query(self, query: str) -> Iterable[TrackInfo]:
"""Search for tracks given a string query."""
search_doc = self.api.search_results(query, include=["tracks.artists"])
if not search_doc["data"]:
return
track_by_id: dict[str, TidalTrack] = {
item["id"]: item
for item in search_doc.get("included", [])
@@ -206,7 +209,9 @@ class TidalPlugin(MetadataSourcePlugin):
for item in search_doc.get("included", [])
if item["type"] == "artists"
}
for track_rel in search_doc["data"]["relationships"]["tracks"]["data"]:
for track_rel in search_doc["data"][0]["relationships"]["tracks"][
"data"
]:
if track := track_by_id.get(track_rel["id"]):
yield self._get_track_info(track, artist_by_id=artist_by_id)
else:
@@ -223,9 +228,12 @@ class TidalPlugin(MetadataSourcePlugin):
# This is a bit inconvenient, but we fetch the items and artists
# for all albums separately.
)
if not search_doc["data"]:
return
album_ids = [
album_rel["id"]
for album_rel in search_doc["data"]["relationships"]["albums"][
for album_rel in search_doc["data"][0]["relationships"]["albums"][
"data"
]
]
+2 -5
View File
@@ -1,6 +1,5 @@
from __future__ import annotations
import urllib.parse
import webbrowser
from contextlib import suppress
from functools import cached_property
@@ -61,15 +60,13 @@ class TidalAPI(RequestHandler):
https://tidal-music.github.io/tidal-api-reference/#/searchResults
"""
params = {
"filter[query]": query,
"explicitFilter": explicit_filter,
"countryCode": country_code,
"include": include or [],
}
return self.get_json(
f"{API_BASE}/searchResults/{urllib.parse.quote(query)}",
params=params,
)
return self.get_json(f"{API_BASE}/searchResults", params=params)
def get_tracks(
self,
+1 -1
View File
@@ -204,4 +204,4 @@ class Document(TypedDict, Generic[T]):
AlbumDocument = Document[list[TidalAlbum]]
TrackDocument = Document[list[TidalTrack]]
SearchDocument = Document[TidalSearch]
SearchDocument = Document[list[TidalSearch]]
+3
View File
@@ -101,6 +101,9 @@ Bug fixes
- :doc:`plugins/tidal`: Pass the converted track duration as ``length`` so it
contributes to the autotagging track-length distance instead of being silently
stored as a ``duration`` flexible attribute.
- :doc:`plugins/tidal`: Restore catalog searches after TIDAL moved search
queries from the request path to the required ``filter[query]`` parameter.
:bug:`6989`
..
For plugin developers
+63 -14
View File
@@ -12,12 +12,14 @@ import pytest
from beets.library import Item
from beets.test.helper import PluginTestHelper
from beetsplug.tidal import TidalPlugin
from beetsplug.tidal.api import API_BASE, TidalAPI
if TYPE_CHECKING:
from beetsplug.tidal.api_types import (
AlbumAttributes,
RelationshipData,
ResourceIdentifier,
SearchDocument,
TidalAlbum,
TidalArtist,
TidalArtwork,
@@ -28,6 +30,29 @@ if TYPE_CHECKING:
CURRENT_TS = 150000000
def _make_search_doc(
resource_type: str, resource_ids: list[str]
) -> SearchDocument:
return {
"data": [
{
"id": "search-result",
"type": "searchResults",
"attributes": {"trackingId": "tracking-id"},
"relationships": {
resource_type: {
"data": [
{"id": id_, "type": resource_type}
for id_ in resource_ids
],
"links": {},
}
},
}
]
}
def _make_artwork(id_: str, href: str = "") -> TidalArtwork:
return {
"id": id_,
@@ -149,6 +174,26 @@ class TidalPluginTest(PluginTestHelper):
self.tidal = TidalPlugin()
class TestAPI:
def test_search_results_uses_query_filter(self):
api = TidalAPI("client-id", "token.json")
response = {"data": []}
api.get_json = Mock(return_value=response)
result = api.search_results("My Artist My Album", include=["albums"])
assert result == response
api.get_json.assert_called_once_with(
f"{API_BASE}/searchResults",
params={
"filter[query]": "My Artist My Album",
"explicitFilter": "INCLUDE",
"countryCode": "US",
"include": ["albums"],
},
)
class TestParsing(TidalPluginTest):
"""High-level tests for album parsing."""
@@ -640,13 +685,7 @@ class TestCandidates(TidalPluginTest):
# Mock search returning album IDs
self.tidal.api.search_results = Mock(
return_value={
"data": {
"relationships": {
"albums": {"data": [{"id": "1", "type": "albums"}]}
}
}
}
return_value=_make_search_doc("albums", ["1"])
)
# Mock album lookup by ID
@@ -670,6 +709,15 @@ class TestCandidates(TidalPluginTest):
assert len(candidates) == 1
assert candidates[0].album == "Query Album"
def test_album_search_handles_empty_response(self):
self.tidal.api.search_results = Mock(return_value={"data": []})
self.tidal.api.get_albums = Mock()
candidates = list(self.tidal.search_albums_by_query("missing album"))
assert candidates == []
self.tidal.api.get_albums.assert_not_called()
class TestItemCandidates(TidalPluginTest):
"""Tests for item_candidates method."""
@@ -699,13 +747,7 @@ class TestItemCandidates(TidalPluginTest):
self.tidal.api.search_results = Mock(
return_value={
"data": {
"relationships": {
"tracks": {
"data": [{"id": "490839595", "type": "tracks"}]
}
}
},
**_make_search_doc("tracks", ["490839595"]),
"included": [
_make_track(
"490839595", "Query Track", "PT3M", "ISRC002", ["1001"]
@@ -722,6 +764,13 @@ class TestItemCandidates(TidalPluginTest):
assert self.tidal.api.search_results.called
assert results[0].title == "Query Track"
def test_track_search_handles_empty_response(self):
self.tidal.api.search_results = Mock(return_value={"data": []})
candidates = list(self.tidal.search_tracks_by_query("missing track"))
assert candidates == []
class TestStaticHelpers:
"""Tests for static helper methods."""