Debian Codegraph @

beetsplug/tidal/__init__.py

raw
1 from __future__ import annotations
2
3 import itertools
4 import os
5 import re
6 import time
7 from functools import cached_property
8 from typing import TYPE_CHECKING, ClassVar, Literal, Protocol, overload
9
10 import confuse
11
12 from beets import ui
13 from beets.autotag import AlbumInfo, TrackInfo
14 from beets.dbcore import types
15 from beets.exceptions import UserError
16 from beets.logging import getLogger
17 from beets.metadata_plugins import MetadataSourcePlugin
18
19 from .api import TidalAPI
20
21 if TYPE_CHECKING:
22 from collections.abc import Callable, Iterable, Sequence
23
24 from beets.autotag import Info
25 from beets.importer import ImportSession
26 from beets.library import Album, Item, LibModel, Library
27
28 from .api_types import (
29 AlbumAttributes,
30 MediaAttributes,
31 ResourceIdentifier,
32 TidalAlbum,
33 TidalArtist,
34 TidalArtwork,
35 TidalTrack,
36 )
37
38
39 class TidalCLIOpts(Protocol):
40 auth: bool
41
42
43 class TidalSyncCLIOpts(Protocol):
44 album: bool
45 force: bool
46 write: bool
47
48
49 log = getLogger("beets.tidal")
50
51 _normalize_label_re = re.compile(
52 r"""
53 ^(?:.*(?:©|℗|\([cp]\))\s*)? # optional copyright marker
54 (?:\d{4}\s+)? # optional year
55 (?:.*?\ under\ exclusive\ licen[sc]e\ to\ )? # optional license prefix
56 (.*?) # text to keep
57 (?:,?\ (?:inc|llc|ltd|co)\.?)? # optional legal suffix
58 (?:,\ a\ .*)? # optional corporate clause
59 (?:,?\ for\ the\ united\ states\ and\ .*)? # optional territorial clause
60 $""",
61 re.IGNORECASE | re.VERBOSE,
62 )
63
64
65 class TidalPlugin(MetadataSourcePlugin):
66 item_types: ClassVar[dict[str, types.Type]] = {
67 "tidal_track_id": types.STRING,
68 "tidal_artist_id": types.STRING,
69 "tidal_track_popularity": types.INTEGER,
70 "tidal_updated": types.DATE,
71 }
72
73 album_types: ClassVar[dict[str, types.Type]] = {
74 "tidal_album_id": types.STRING,
75 "tidal_artist_id": types.STRING,
76 "tidal_album_popularity": types.INTEGER,
77 "tidal_updated": types.DATE,
78 }
79
80 def __init__(self) -> None:
81 super().__init__()
82
83 self.config.add(
84 {"client_id": "mcjmpl1bPATJXcBT", "tokenfile": "tidal_token.json"}
85 )
86 self.config["client_id"].redact = True
87
88 # We need to be authenticated if plugin is used to fetch metadata
89 # otherwise the import cannot run.
90 self.register_listener("import_begin", self.require_authentication)
91
92 @cached_property
93 def api(self) -> TidalAPI:
94 return TidalAPI(
95 client_id=self.config["client_id"].as_str(),
96 token_path=self._tokenfile(),
97 )
98
99 def _tokenfile(self) -> str:
100 """Return the configured path to the token file in the app directory."""
101 return self.config["tokenfile"].get(confuse.Filename(in_app_dir=True))
102
103 def require_authentication(self, session: ImportSession) -> None:
104 if not os.path.isfile(self._tokenfile()):
105 raise UserError(
106 "Please login to TIDAL"
107 " using `beet tidal --auth` or disable tidal plugin"
108 )
109
110 def album_for_id(self, album_id: str) -> AlbumInfo | None:
111 if not (tidal_id := self._extract_id(album_id)):
112 return None
113
114 if album := list(self.search_albums_by_ids(tidal_ids=[tidal_id])):
115 return album[0]
116
117 log.warning("Could not find album:{0}", tidal_id)
118 return None
119
120 def albums_for_ids(self, ids: Iterable[str]) -> Iterable[AlbumInfo | None]:
121 yield from self.search_albums_by_ids(ids=ids)
122
123 def track_for_id(self, track_id: str) -> TrackInfo | None:
124 if not (tidal_id := self._extract_id(track_id)):
125 return None
126
127 if track := list(self.search_tracks_by_ids(tidal_ids=[tidal_id])):
128 return track[0]
129
130 log.warning("Could not find track:{0}", tidal_id)
131 return None
132
133 def tracks_for_ids(self, ids: Iterable[str]) -> Iterable[TrackInfo | None]:
134 yield from self.search_tracks_by_ids(ids=ids)
135
136 def candidates(
137 self, items: Sequence[Item], artist: str, album: str, va_likely: bool
138 ) -> Iterable[AlbumInfo]:
139 candidates: list[AlbumInfo] = []
140 # Tidal allows to lookup via isrc and barcode (nice!)
141 # We just return early here as a lookup via isrc should
142 # return a 100% match
143 barcodes: list[str] = list(
144 filter(None, set(i.get("barcode") for i in items))
145 )
146 if barcodes and (
147 candidates := list(
148 filter(None, self.search_albums_by_ids(barcode_ids=barcodes))
149 )
150 ):
151 return candidates
152
153 for query in self._album_queries(items):
154 candidates += self.search_albums_by_query(query)
155
156 log.debug("Found {0} candidates", len(candidates))
157 return candidates
158
159 def item_candidates(
160 self, item: Item, artist: str, title: str
161 ) -> Iterable[TrackInfo]:
162 candidates: list[TrackInfo] = []
163 # Tidal allows to lookup via isrc and barcode (nice!)
164 # We just return early here as a lookup via isrc should
165 # return a 100% match
166 if isrc := item.get("isrc"):
167 if candidates := list(
168 filter(None, self.search_tracks_by_ids(isrcs=[isrc]))
169 ):
170 return candidates
171
172 for query in self._item_queries(item):
173 candidates += self.search_tracks_by_query(query)
174
175 log.debug("Found {0} candidates", len(candidates))
176 return candidates
177
178 @staticmethod
179 def _item_queries(item: Item) -> Iterable[str]:
180 """Search queries for items."""
181 yield item.title
182
183 if item.artist:
184 yield f"{item.artist} {item.title}"
185
186 @staticmethod
187 def _album_queries(items: Sequence[Item]) -> Iterable[str]:
188 """Search queries for albums."""
189
190 album_names = set(i.album for i in items)
191 artist_names = set(i.artist for i in items)
192
193 for album, artist in itertools.product(album_names, artist_names):
194 yield f"{artist} {album}"
195
196 def search_tracks_by_query(self, query: str) -> Iterable[TrackInfo]:
197 """Search for tracks given a string query."""
198 search_doc = self.api.search_results(query, include=["tracks.artists"])
199 if not search_doc["data"]:
200 return
201
202 track_by_id: dict[str, TidalTrack] = {
203 item["id"]: item
204 for item in search_doc.get("included", [])
205 if item["type"] == "tracks"
206 }
207 artist_by_id: dict[str, TidalArtist] = {
208 item["id"]: item
209 for item in search_doc.get("included", [])
210 if item["type"] == "artists"
211 }
212 for track_rel in search_doc["data"][0]["relationships"]["tracks"][
213 "data"
214 ]:
215 if track := track_by_id.get(track_rel["id"]):
216 yield self._get_track_info(track, artist_by_id=artist_by_id)
217 else:
218 log.warning(
219 "Track with id {0} not found in lookup", track_rel["id"]
220 )
221
222 def search_albums_by_query(self, query: str) -> Iterable[AlbumInfo]:
223 """Search for album given a string query."""
224 search_doc = self.api.search_results(
225 query,
226 include=["albums"],
227 # include="albums.items.artists" <- not supported
228 # This is a bit inconvenient, but we fetch the items and artists
229 # for all albums separately.
230 )
231 if not search_doc["data"]:
232 return
233
234 album_ids = [
235 album_rel["id"]
236 for album_rel in search_doc["data"][0]["relationships"]["albums"][
237 "data"
238 ]
239 ]
240 yield from filter(None, self.search_albums_by_ids(tidal_ids=album_ids))
241
242 @overload
243 def search_tracks_by_ids(
244 self, *, ids: Iterable[str]
245 ) -> Iterable[TrackInfo | None]: ...
246
247 @overload
248 def search_tracks_by_ids(
249 self, *, tidal_ids: Iterable[str]
250 ) -> Iterable[TrackInfo | None]: ...
251
252 @overload
253 def search_tracks_by_ids(
254 self, *, isrcs: Iterable[str]
255 ) -> Iterable[TrackInfo | None]: ...
256
257 def search_tracks_by_ids(
258 self,
259 ids: Iterable[str] | None = None,
260 tidal_ids: Iterable[str] | None = None,
261 isrcs: Iterable[str] | None = None,
262 ) -> Iterable[TrackInfo | None]:
263 _ids: list[str | None] = list(tidal_ids or [])
264 isrcs = list(isrcs or [])
265 if ids:
266 _ids = list(map(self._extract_id, ids))
267
268 tracks_doc = self.api.get_tracks(
269 ids=list(filter(None, _ids)), isrcs=isrcs, include=["artists"]
270 )
271 track_by_id: dict[str, TidalTrack] = {
272 item["id"]: item
273 for item in tracks_doc.get("data", [])
274 if item["type"] == "tracks"
275 }
276 artist_by_id: dict[str, TidalArtist] = {
277 item["id"]: item
278 for item in tracks_doc.get("included", [])
279 if item["type"] == "artists"
280 }
281
282 for _id in _ids:
283 if _id is not None and (track := track_by_id.get(_id)):
284 yield self._get_track_info(track, artist_by_id=artist_by_id)
285 else:
286 yield None
287
288 if isrcs:
289 isrc_to_track: dict[str, TidalTrack] = {
290 t["attributes"]["isrc"]: t for t in track_by_id.values()
291 }
292
293 for isrc in isrcs:
294 if track := isrc_to_track.get(isrc):
295 yield self._get_track_info(track, artist_by_id=artist_by_id)
296 else:
297 yield None
298
299 @overload
300 def search_albums_by_ids(
301 self, *, ids: Iterable[str]
302 ) -> Iterable[AlbumInfo | None]: ...
303
304 @overload
305 def search_albums_by_ids(
306 self, *, tidal_ids: Iterable[str]
307 ) -> Iterable[AlbumInfo | None]: ...
308
309 @overload
310 def search_albums_by_ids(
311 self, *, barcode_ids: Iterable[str]
312 ) -> Iterable[AlbumInfo | None]: ...
313
314 def search_albums_by_ids(
315 self,
316 ids: Iterable[str] | None = None,
317 tidal_ids: Iterable[str] | None = None,
318 barcode_ids: Iterable[str] | None = None,
319 ) -> Iterable[AlbumInfo | None]:
320 _ids: list[str | None] = list(tidal_ids or [])
321 barcode_ids = list(barcode_ids or [])
322 if ids:
323 _ids = list(map(self._extract_id, ids))
324
325 albums_doc = self.api.get_albums(
326 ids=list(filter(None, _ids)),
327 barcode_ids=barcode_ids,
328 include=["items.artists", "artists", "coverArt"],
329 )
330 album_by_id: dict[str, TidalAlbum] = {
331 item["id"]: item
332 for item in albums_doc.get("data", [])
333 if item["type"] == "albums"
334 }
335 track_by_id: dict[str, TidalTrack] = {
336 item["id"]: item
337 for item in albums_doc.get("included", [])
338 if item["type"] == "tracks"
339 }
340 artist_by_id: dict[str, TidalArtist] = {
341 item["id"]: item
342 for item in albums_doc.get("included", [])
343 if item["type"] == "artists"
344 }
345 artwork_by_id: dict[str, TidalArtwork] = {
346 item["id"]: item
347 for item in albums_doc.get("included", [])
348 if item["type"] == "artworks"
349 }
350
351 for _id in _ids:
352 if _id is not None and (album := album_by_id.get(_id)):
353 yield self._get_album_info(
354 album,
355 track_by_id=track_by_id,
356 artist_by_id=artist_by_id,
357 artwork_by_id=artwork_by_id,
358 )
359 else:
360 yield None
361
362 if barcode_ids:
363 barcode_to_album: dict[str, TidalAlbum] = {
364 a["attributes"]["barcodeId"]: a for a in album_by_id.values()
365 }
366
367 for barcode in barcode_ids:
368 if album := barcode_to_album.get(barcode):
369 yield self._get_album_info(
370 album,
371 track_by_id=track_by_id,
372 artist_by_id=artist_by_id,
373 artwork_by_id=artwork_by_id,
374 )
375 else:
376 yield None
377
378 def _get_album_info(
379 self,
380 album: TidalAlbum,
381 track_by_id: dict[str, TidalTrack],
382 artist_by_id: dict[str, TidalArtist],
383 artwork_by_id: dict[str, TidalArtwork],
384 ) -> AlbumInfo:
385 track_infos: list[TrackInfo] = []
386 for i, track_rel in enumerate(
387 album["relationships"]["items"]["data"], start=1
388 ):
389 if track := track_by_id.get(track_rel["id"]):
390 track_info = self._get_track_info(track, artist_by_id)
391 track_info.index = i
392 track_infos.append(track_info)
393
394 artist_names, artist_ids = self._parse_artists(
395 album["relationships"]["artists"]["data"], artist_by_id
396 )
397 date_parts = self._parse_release_date(album["attributes"])
398 return AlbumInfo(
399 # Identifier
400 data_source=self.data_source,
401 album_id=album["id"],
402 artists_ids=artist_ids,
403 data_url=self._parse_data_url(album["attributes"]),
404 barcode=album["attributes"]["barcodeId"],
405 cover_art_url=self._parse_artwork_url(album, artwork_by_id),
406 # Meta
407 album=self._parse_title(album["attributes"]),
408 tracks=track_infos,
409 artist=", ".join(artist_names),
410 artists=artist_names,
411 duration=self._duration_to_seconds(album["attributes"]["duration"]),
412 albumtypes=[album["attributes"]["albumType"].lower()],
413 label=self._parse_label(album["attributes"]),
414 year=date_parts[0] if date_parts else None,
415 month=date_parts[1] if date_parts else None,
416 day=date_parts[2] if date_parts else None,
417 # Flexattrs
418 tidal_album_id=album["id"],
419 tidal_artist_id=artist_ids[0] if artist_ids else None,
420 tidal_album_popularity=self._parse_popularity(album["attributes"]),
421 tidal_updated=time.time(),
422 )
423
424 @staticmethod
425 def _normalize_label(text: str) -> str:
426 """Reduce a raw copyright string to a concise label name."""
427 if match := _normalize_label_re.match(text):
428 return match.group(1)
429 return text
430
431 @staticmethod
432 def _parse_artwork_url(
433 album: TidalAlbum, artwork_by_id: dict[str, TidalArtwork]
434 ) -> str | None:
435 cover_rel = album["relationships"].get("coverArt")
436 if cover_rel is None:
437 return None
438 for rel_data in cover_rel["data"]:
439 if (
440 rel_data["type"] == "artworks"
441 and (artwork := artwork_by_id.get(rel_data["id"]))
442 and (files := artwork["attributes"]["files"])
443 ):
444 return files[0]["href"]
445 return None
446
447 def _get_track_info(
448 self, track: TidalTrack, artist_by_id: dict[str, TidalArtist]
449 ) -> TrackInfo:
450 artist_names, artist_ids = self._parse_artists(
451 track["relationships"]["artists"]["data"], artist_by_id
452 )
453
454 return TrackInfo(
455 # Identifier
456 data_source=self.data_source,
457 track_id=track["id"],
458 artists_ids=artist_ids,
459 data_url=self._parse_data_url(track["attributes"]),
460 # Meta
461 title=self._parse_title(track["attributes"]),
462 isrc=track["attributes"]["isrc"],
463 artist=", ".join(artist_names),
464 artists=artist_names,
465 length=self._duration_to_seconds(track["attributes"]["duration"]),
466 label=self._parse_label(track["attributes"]),
467 # Flexattrs
468 tidal_track_id=track["id"],
469 tidal_artist_id=artist_ids[0] if artist_ids else None,
470 tidal_track_popularity=self._parse_popularity(track["attributes"]),
471 tidal_updated=time.time(),
472 )
473
474 @staticmethod
475 def _parse_artists(
476 artist_relationships: list[ResourceIdentifier],
477 artist_by_id: dict[str, TidalArtist],
478 ) -> tuple[list[str], list[str]]:
479 """Extract artists from a relationship.
480
481 Artists are sorted in the track/album response relationship but not in the
482 track/album responses included items.
483 """
484 artist_names = []
485 artist_ids = []
486 for artist_rel in artist_relationships:
487 if artist := artist_by_id.get(artist_rel["id"]):
488 artist_ids.append(artist["id"])
489 artist_names.append(artist["attributes"]["name"])
490 else:
491 log.warning(
492 "Artist with id {0} not found in lookup", artist_rel["id"]
493 )
494
495 return artist_names, artist_ids
496
497 @staticmethod
498 def _parse_title(attributes: MediaAttributes) -> str:
499 """
500 Tidal UIs append the version string at the end of the title. We do the same here
501 by formatting it as ``"{title} ({version})"`` to stay consistent.
502 """
503 if version := attributes.get("version"):
504 return f"{attributes['title']} ({version})"
505 return attributes["title"]
506
507 @staticmethod
508 def _parse_data_url(attributes: MediaAttributes) -> str | None:
509 if external_links := attributes.get("externalLinks"):
510 return external_links[0].get("href")
511 return None
512
513 @staticmethod
514 def _duration_to_seconds(duration: str) -> int | None:
515 """Convert ISO 8601 duration to seconds. E.g. 'PT15M2S' -> 902."""
516 match = ISO_8601_RE.match(duration)
517 if not match:
518 log.warning("Invalid ISO 8601 duration: {0}", duration)
519 return None
520 parts = {k: int(v) if v else 0 for k, v in match.groupdict().items()}
521 return parts["seconds"] + parts["minutes"] * 60 + parts["hours"] * 3600
522
523 @staticmethod
524 def _parse_label(attributes: MediaAttributes) -> str | None:
525 if copyright_ := attributes.get("copyright"):
526 return TidalPlugin._normalize_label(copyright_["text"])
527 return None
528
529 @staticmethod
530 def _parse_release_date(
531 attributes: AlbumAttributes,
532 ) -> tuple[int, int, int] | None:
533 """Returns year, month, day from iso YYYY-MM-DD"""
534
535 if (
536 (release_date := attributes.get("releaseDate"))
537 and (parts := release_date.split("-"))
538 and len(parts) == 3
539 ):
540 return int(parts[0]), int(parts[1]), int(parts[2])
541 return None
542
543 @staticmethod
544 def _parse_popularity(attributes: MediaAttributes) -> int:
545 return round(attributes["popularity"] * 100)
546
547 def sync_item_popularity(
548 self, results: Sequence[Item], write: bool, force: bool = False
549 ) -> None:
550 """Sync Tidal popularity data for library items."""
551 self._sync_popularity(
552 results=results,
553 write=write,
554 force=force,
555 id_field="tidal_track_id",
556 popularity_field="tidal_track_popularity",
557 search=lambda ids: self.search_tracks_by_ids(tidal_ids=ids),
558 label="item",
559 )
560
561 def sync_album_popularity(
562 self, results: Sequence[Album], write: bool, force: bool = False
563 ) -> None:
564 """Sync Tidal popularity data for library albums."""
565 self._sync_popularity(
566 results=results,
567 write=write,
568 force=force,
569 id_field="tidal_album_id",
570 popularity_field="tidal_album_popularity",
571 search=lambda ids: self.search_albums_by_ids(tidal_ids=ids),
572 label="album",
573 )
574
575 def _sync_popularity(
576 self,
577 *,
578 results: Sequence[LibModel],
579 write: bool,
580 force: bool,
581 id_field: str,
582 popularity_field: str,
583 search: Callable[[Iterable[str]], Iterable[Info | None]],
584 label: Literal["item", "album"],
585 ) -> None:
586 """Sync Tidal popularity for a generic model (Item or Album)."""
587 log.info("Syncing popularity for {0} {1}s", len(results), label)
588
589 model_by_id = {
590 tidal_id: model
591 for model in results
592 if (tidal_id := model.get(id_field))
593 and (force or model.get(popularity_field) is None)
594 }
595 total = len(model_by_id)
596 log.debug("{0} {1}s need updates", total, label)
597 processed = 0
598 for model, new_info in zip(
599 model_by_id.values(), search(model_by_id.keys())
600 ):
601 if not new_info:
602 continue
603
604 model[popularity_field] = new_info.get(popularity_field)
605 model["tidal_updated"] = time.time()
606
607 model.store()
608 if write:
609 model.try_write()
610
611 processed += 1
612 if processed % 100 == 0 or processed == total:
613 log.debug("Synced {0}/{1} {2}s", processed, total, label)
614
615 log.info(
616 "Successfully synchronised popularity for {0} {1}s", total, label
617 )
618
619 def commands(self) -> list[ui.Subcommand]:
620 tidal_cmd = ui.Subcommand(
621 "tidal", help="Tidal metadata plugin commands"
622 )
623 tidal_cmd.parser.add_option(
624 "-a",
625 "--auth",
626 action="store_true",
627 help="Authenticate and login to Tidal",
628 default=False,
629 )
630
631 def auth_func(
632 lib: Library, opts: TidalCLIOpts, args: list[str]
633 ) -> None:
634 if opts.auth:
635 self.api.ui_authenticate_flow()
636 else:
637 tidal_cmd.print_help()
638
639 tidal_cmd.func = auth_func
640
641 # It would be nice to combine both auth and sync commands but
642 # currently not really supported in beets. We might be able to
643 # revist this if our subcommand parsing changes
644 sync_help = (
645 "Synchronize Tidal popularity data for library items and albums"
646 )
647 tidalsync_cmd = ui.Subcommand("tidalsync", help=sync_help)
648 tidalsync_cmd.parser.add_album_option()
649 tidalsync_cmd.parser.add_option(
650 "-f",
651 "--force",
652 action="store_true",
653 dest="force",
654 default=False,
655 help=(
656 "re-fetch popularity even if already present (default: False)"
657 ),
658 )
659 tidalsync_cmd.parser.add_option(
660 "-w",
661 "--write",
662 action="store_true",
663 dest="write",
664 default=False,
665 help="write updated tags to media files (default: False)",
666 )
667 tidalsync_cmd.parser.set_usage(
668 "Usage: beet tidalsync <query> [options]"
669 )
670
671 def sync_func(
672 lib: Library, opts: TidalSyncCLIOpts, args: list[str]
673 ) -> None:
674 query = ["data_source:tidal", *args]
675
676 if opts.album:
677 self.sync_album_popularity(
678 lib.albums(query), write=opts.write, force=opts.force
679 )
680 else:
681 self.sync_item_popularity(
682 lib.items(query), write=opts.write, force=opts.force
683 )
684
685 tidalsync_cmd.func = sync_func
686
687 return [tidal_cmd, tidalsync_cmd]
688
689
690 ISO_8601_RE = re.compile(
691 r"^P"
692 r"T"
693 r"(?:(?P<hours>\d+)H)?"
694 r"(?:(?P<minutes>\d+)M)?"
695 r"(?:(?P<seconds>\d+)S)?$"
696 )