| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import webbrowser |
| 4 |
from contextlib import suppress |
| 5 |
from functools import cached_property |
| 6 |
from itertools import islice, zip_longest |
| 7 |
from typing import TYPE_CHECKING, Any, TypeVar |
| 8 |
|
| 9 |
from beets import ui |
| 10 |
from beets.logging import getLogger |
| 11 |
from beetsplug._utils.requests import RequestHandler |
| 12 |
from beetsplug.tidal.session import TidalSession |
| 13 |
|
| 14 |
if TYPE_CHECKING: |
| 15 |
from collections.abc import Iterable |
| 16 |
|
| 17 |
from .api_types import ( |
| 18 |
AlbumDocument, |
| 19 |
Document, |
| 20 |
SearchDocument, |
| 21 |
TrackDocument, |
| 22 |
) |
| 23 |
|
| 24 |
T = TypeVar("T") |
| 25 |
|
| 26 |
log = getLogger("beets.tidal") |
| 27 |
|
| 28 |
|
| 29 |
API_BASE = "https://openapi.tidal.com/v2" |
| 30 |
MAX_FILTER_SIZE = 20 |
| 31 |
|
| 32 |
|
| 33 |
def _batched(iterable: Iterable[T], n: int) -> Iterable[list[T]]: |
| 34 |
# FIXME: Replace with itertools.batched once |
| 35 |
# we upgrade to python > 3.12 |
| 36 |
it = iter(iterable) |
| 37 |
while batch := list(islice(it, n)): |
| 38 |
yield batch |
| 39 |
|
| 40 |
|
| 41 |
class TidalAPI(RequestHandler): |
| 42 |
def __init__(self, client_id: str, token_path: str) -> None: |
| 43 |
self.client_id = client_id |
| 44 |
self.token_path = token_path |
| 45 |
|
| 46 |
@cached_property |
| 47 |
def session(self) -> TidalSession: |
| 48 |
return TidalSession(self.client_id, self.token_path) |
| 49 |
|
| 50 |
def search_results( |
| 51 |
self, |
| 52 |
query: str, |
| 53 |
*, |
| 54 |
explicit_filter: str = "INCLUDE", |
| 55 |
include: list[str] | None = None, |
| 56 |
country_code: str = "US", |
| 57 |
) -> SearchDocument: |
| 58 |
"""Search results for a query. |
| 59 |
|
| 60 |
https://tidal-music.github.io/tidal-api-reference/#/searchResults |
| 61 |
""" |
| 62 |
params = { |
| 63 |
"filter[query]": query, |
| 64 |
"explicitFilter": explicit_filter, |
| 65 |
"countryCode": country_code, |
| 66 |
"include": include or [], |
| 67 |
} |
| 68 |
|
| 69 |
return self.get_json(f"{API_BASE}/searchResults", params=params) |
| 70 |
|
| 71 |
def get_tracks( |
| 72 |
self, |
| 73 |
ids: list[str] | None = None, |
| 74 |
isrcs: list[str] | None = None, |
| 75 |
include: list[str] | None = None, |
| 76 |
country_code: str = "US", |
| 77 |
) -> TrackDocument: |
| 78 |
"""Fetch tracks resolving pagination and included items. |
| 79 |
|
| 80 |
https://tidal-music.github.io/tidal-api-reference/#/tracks/get_tracks |
| 81 |
""" |
| 82 |
ids = ids or [] |
| 83 |
isrcs = isrcs or [] |
| 84 |
|
| 85 |
# Tidal allows at max 20 filters per request. This needs a bit of extra |
| 86 |
# logic sadly. |
| 87 |
doc: TrackDocument = {"data": [], "included": []} |
| 88 |
for id_batch, isrc_batch in zip_longest( |
| 89 |
_batched(ids, MAX_FILTER_SIZE), |
| 90 |
_batched(isrcs, MAX_FILTER_SIZE), |
| 91 |
fillvalue=(), |
| 92 |
): |
| 93 |
params: dict[str, Any] = {"countryCode": country_code} |
| 94 |
if id_batch: |
| 95 |
params["filter[id]"] = id_batch |
| 96 |
if isrc_batch: |
| 97 |
params["filter[isrc]"] = isrc_batch |
| 98 |
|
| 99 |
doc = self.merge_multiresource_pagination( |
| 100 |
doc, |
| 101 |
self.get_paginated( |
| 102 |
f"{API_BASE}/tracks", include, params=params |
| 103 |
), |
| 104 |
) |
| 105 |
|
| 106 |
return doc |
| 107 |
|
| 108 |
def get_albums( |
| 109 |
self, |
| 110 |
ids: list[str] | None = None, |
| 111 |
barcode_ids: list[str] | None = None, |
| 112 |
include: list[str] | None = None, |
| 113 |
country_code: str = "US", |
| 114 |
) -> AlbumDocument: |
| 115 |
"""Fetch Albums resolving pagination and included items. |
| 116 |
|
| 117 |
https://tidal-music.github.io/tidal-api-reference/#/albums/get_albums |
| 118 |
""" |
| 119 |
ids = ids or [] |
| 120 |
barcode_ids = barcode_ids or [] |
| 121 |
|
| 122 |
# Tidal allows at max 20 filters per request. This needs a bit of extra |
| 123 |
# logic sadly. |
| 124 |
doc: AlbumDocument = {"data": [], "included": []} |
| 125 |
for id_batch, barcode_batch in zip_longest( |
| 126 |
_batched(ids, MAX_FILTER_SIZE), |
| 127 |
_batched(barcode_ids, MAX_FILTER_SIZE), |
| 128 |
fillvalue=(), |
| 129 |
): |
| 130 |
params: dict[str, Any] = {"countryCode": country_code} |
| 131 |
if id_batch: |
| 132 |
params["filter[id]"] = id_batch |
| 133 |
if barcode_batch: |
| 134 |
params["filter[barcodeId]"] = barcode_batch |
| 135 |
|
| 136 |
doc = self.merge_multiresource_pagination( |
| 137 |
doc, |
| 138 |
self.get_paginated( |
| 139 |
f"{API_BASE}/albums", include, params=params |
| 140 |
), |
| 141 |
) |
| 142 |
|
| 143 |
return doc |
| 144 |
|
| 145 |
def ui_authenticate_flow(self) -> None: |
| 146 |
"""Interactive first-time authentication (PKCE flow). |
| 147 |
|
| 148 |
1. Visit generated URL |
| 149 |
2. Paste full redirect URL (with ?code=...) |
| 150 |
3. Token auto-saved for future use |
| 151 |
""" |
| 152 |
auth_url, _ = self.session.authorization_url( |
| 153 |
"https://login.tidal.com/authorize" |
| 154 |
) |
| 155 |
ui.print_(f"Visit: {auth_url}") |
| 156 |
with suppress(webbrowser.Error): |
| 157 |
webbrowser.open(auth_url) |
| 158 |
redirect_url = ui.input_("Paste redirected URL: ") |
| 159 |
self.session.fetch_token( |
| 160 |
"https://auth.tidal.com/v1/oauth2/token", |
| 161 |
authorization_response=redirect_url, |
| 162 |
include_client_id=True, |
| 163 |
) |
| 164 |
self.session.save_token(self.session.token) |
| 165 |
ui.print_(f"Saved tidal token in {self.session.token_path}") |
| 166 |
|
| 167 |
@staticmethod |
| 168 |
def merge_multiresource_pagination( |
| 169 |
a: Document[list[T]], b: Document[list[T]] |
| 170 |
) -> Document[list[T]]: |
| 171 |
""" |
| 172 |
Merge of b into a, following JSON:API spec rules. |
| 173 |
|
| 174 |
- Appends data arrays |
| 175 |
- Deduplicates included by (type, id) |
| 176 |
- Updates links (b overrides a) |
| 177 |
""" |
| 178 |
a["included"] = a.get("included", []) |
| 179 |
a["links"] = a.get("links", {}) |
| 180 |
|
| 181 |
a["data"].extend(b["data"]) |
| 182 |
|
| 183 |
# Merge included with deduplication |
| 184 |
seen = {(item["type"], item["id"]) for item in a["included"]} |
| 185 |
for item in b.get("included", []): |
| 186 |
key = (item["type"], item["id"]) |
| 187 |
if key not in seen: |
| 188 |
seen.add(key) |
| 189 |
a["included"].append(item) |
| 190 |
|
| 191 |
# Update pagination links (final state wins) |
| 192 |
a["links"] = b.get("links", {}) |
| 193 |
return a |
| 194 |
|
| 195 |
def get_paginated( |
| 196 |
self, |
| 197 |
url: str, |
| 198 |
include: list[str] | str | None = None, |
| 199 |
params: dict[str, Any] | None = None, |
| 200 |
**kwargs, |
| 201 |
) -> Document[list[Any]]: |
| 202 |
""" |
| 203 |
Perform a GET request to the Tidal API with pagination resolution. |
| 204 |
""" |
| 205 |
include = include or [] |
| 206 |
params = params or {} |
| 207 |
|
| 208 |
doc: Document[list[Any]] = { |
| 209 |
"data": [], |
| 210 |
"included": [], |
| 211 |
"links": {"next": url}, |
| 212 |
} |
| 213 |
|
| 214 |
while next_ := doc.get("links", {}).get("next"): |
| 215 |
page_doc = self.get_json( |
| 216 |
url=next_, params={**params, "include": include}, **kwargs |
| 217 |
) |
| 218 |
doc = self.merge_multiresource_pagination(doc, page_doc) |
| 219 |
|
| 220 |
# Dedupe include |
| 221 |
doc["included"] = list( |
| 222 |
{ |
| 223 |
(item["type"], item["id"]): item |
| 224 |
for item in doc.get("included", []) |
| 225 |
}.values() |
| 226 |
) |
| 227 |
return doc |