beets-tidalv1 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- beets_tidalv1-0.1.0.dist-info/METADATA +124 -0
- beets_tidalv1-0.1.0.dist-info/RECORD +10 -0
- beets_tidalv1-0.1.0.dist-info/WHEEL +5 -0
- beets_tidalv1-0.1.0.dist-info/licenses/LICENSE +21 -0
- beets_tidalv1-0.1.0.dist-info/top_level.txt +1 -0
- beetsplug/tidalv1/__init__.py +89 -0
- beetsplug/tidalv1/auth.py +498 -0
- beetsplug/tidalv1/client.py +371 -0
- beetsplug/tidalv1/http_types.py +24 -0
- beetsplug/tidalv1/sources.py +90 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: beets-tidalv1
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: beets plugin sources for TIDAL v1 lyrics and album art
|
|
5
|
+
Author: Trey Turner
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/treyturner/beets-plugins
|
|
8
|
+
Project-URL: Source, https://github.com/treyturner/beets-plugins/tree/main/plugins/tidalv1
|
|
9
|
+
Keywords: beets,tidal,lyrics,album-art
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Framework :: Pytest
|
|
13
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Multimedia :: Sound/Audio
|
|
21
|
+
Requires-Python: <3.15,>=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: beets>=2.7
|
|
25
|
+
Requires-Dist: beautifulsoup4>=4.12
|
|
26
|
+
Requires-Dist: requests>=2.31
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# beets-tidalv1
|
|
30
|
+
|
|
31
|
+
`tidalv1` adds TIDAL v1 sources to the built-in beets `lyrics` and `fetchart` plugins.
|
|
32
|
+
|
|
33
|
+
The lyrics endpoint used is the legacy v1 endpoint:
|
|
34
|
+
|
|
35
|
+
```text
|
|
36
|
+
GET https://api.tidal.com/v1/tracks/{track_id}/lyrics
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
TIDAL v2 does not currently expose the same lyrics payload.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
`beets-tidalv1` requires Beets 2.7 or newer and Python 3.10–3.14.
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
python -m pip install "beets-tidalv1 @ git+https://github.com/treyturner/beets-plugins.git#subdirectory=plugins/tidalv1"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Configure beets
|
|
50
|
+
|
|
51
|
+
Enable this plugin before `lyrics` and `fetchart` so it registers before beets builds the source lists:
|
|
52
|
+
|
|
53
|
+
```yaml
|
|
54
|
+
plugins:
|
|
55
|
+
- tidalv1
|
|
56
|
+
- lyrics
|
|
57
|
+
- fetchart
|
|
58
|
+
|
|
59
|
+
lyrics:
|
|
60
|
+
sources:
|
|
61
|
+
- tidalv1
|
|
62
|
+
- lrclib
|
|
63
|
+
|
|
64
|
+
fetchart:
|
|
65
|
+
sources:
|
|
66
|
+
- filesystem
|
|
67
|
+
- tidalv1
|
|
68
|
+
- coverart
|
|
69
|
+
|
|
70
|
+
tidalv1:
|
|
71
|
+
v1_client_id: YOUR_TIDAL_V1_APP_CLIENT_ID
|
|
72
|
+
v1_client_secret: YOUR_TIDAL_V1_APP_CLIENT_SECRET
|
|
73
|
+
country_code: US
|
|
74
|
+
prefer_synced: yes
|
|
75
|
+
art_size: 1280
|
|
76
|
+
match_threshold: 0.78
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
A **legacy v1 client ID and secret** are required. If you have a credential pair in the same format used by `tiddl`, you can provide a Base64-encoded `<v1_client_id>;<v1_client_secret>` value instead:
|
|
80
|
+
|
|
81
|
+
```yaml
|
|
82
|
+
tidalv1:
|
|
83
|
+
v1_client_id_secret_b64: BASE64_ENCODED_PAIR
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
If left empty, a best-effort attempt will be made to find it for you.
|
|
87
|
+
|
|
88
|
+
Run `beet tidalv1 --auth` once to authorize a TIDAL account, mirroring the official
|
|
89
|
+
`tidal` plugin's `beet tidal --auth` interface. The command opens the authorization
|
|
90
|
+
URL in your browser and stores a refreshable token cache named `tidalv1_token.json`
|
|
91
|
+
in beets' application config directory.
|
|
92
|
+
|
|
93
|
+
## Usage
|
|
94
|
+
|
|
95
|
+
Fetch lyrics through the normal beets command:
|
|
96
|
+
|
|
97
|
+
```sh
|
|
98
|
+
beet lyrics artist:"Daft Punk"
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Fetch album art through the normal fetchart command:
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
beet fetchart -f album:"Discovery"
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
During imports, the built-in `lyrics` and `fetchart` plugins handle automatic updates when their own `auto` settings are enabled.
|
|
108
|
+
|
|
109
|
+
## Development
|
|
110
|
+
|
|
111
|
+
Run tests:
|
|
112
|
+
|
|
113
|
+
```sh
|
|
114
|
+
uv sync
|
|
115
|
+
uv run pytest
|
|
116
|
+
uv run mypy
|
|
117
|
+
uv run pyright
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Run a single module:
|
|
121
|
+
|
|
122
|
+
```sh
|
|
123
|
+
uv run pytest tests/test_client.py
|
|
124
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
beets_tidalv1-0.1.0.dist-info/licenses/LICENSE,sha256=ntjwUm1y8dnmZJ2PrnpJooZtQij7X-0155XKEofnl2U,1068
|
|
2
|
+
beetsplug/tidalv1/__init__.py,sha256=9FBd-tWvGbOhz32h7FJ96-wcF-QxjfFBlhCTu_Bk5ak,2698
|
|
3
|
+
beetsplug/tidalv1/auth.py,sha256=OPomsnqLDD7vBYQGT31rwRYXRKTE0o90gSmFiY4LNBQ,18340
|
|
4
|
+
beetsplug/tidalv1/client.py,sha256=JmrXC4gbs6Mo_9CBCGayfTg0QnGJSw1j0uldLXNL7U8,11461
|
|
5
|
+
beetsplug/tidalv1/http_types.py,sha256=gBTR2XrWyhKmTnsmdK-s6rTzSrcsyOyUPrX3RUKQIQI,482
|
|
6
|
+
beetsplug/tidalv1/sources.py,sha256=b5CKCJojAbzNtL4_Drl5odsDlo0HVvXcG5qQC0CzrQ0,3035
|
|
7
|
+
beets_tidalv1-0.1.0.dist-info/METADATA,sha256=hGDgWD030OJLmC2MJW7Oc6oCO_-_hfxOfnVPSRY-LLo,3186
|
|
8
|
+
beets_tidalv1-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
9
|
+
beets_tidalv1-0.1.0.dist-info/top_level.txt,sha256=za8u6CXAGbgac8cUyn9NlsgXqqq-_4HHZcNmJnfmyWc,10
|
|
10
|
+
beets_tidalv1-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Trey Turner
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
beetsplug
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
import webbrowser
|
|
5
|
+
from contextlib import suppress
|
|
6
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
7
|
+
from typing import Any, cast
|
|
8
|
+
|
|
9
|
+
from beets import ui
|
|
10
|
+
from beets.plugins import BeetsPlugin
|
|
11
|
+
|
|
12
|
+
from .auth import (
|
|
13
|
+
DEFAULT_AUTH_BASE,
|
|
14
|
+
DEFAULT_AUTH_CACHE_FILENAME,
|
|
15
|
+
AuthManager,
|
|
16
|
+
)
|
|
17
|
+
from .client import DEFAULT_API_BASE
|
|
18
|
+
from .sources import register_sources
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
__version__ = version("beets-tidalv1")
|
|
22
|
+
except PackageNotFoundError: # pragma: no cover - source tree without installation
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
|
|
25
|
+
DEFAULT_CONFIG: dict[str, str | int | float | bool | None] = {
|
|
26
|
+
"api_base": DEFAULT_API_BASE,
|
|
27
|
+
"auth_base": DEFAULT_AUTH_BASE,
|
|
28
|
+
"v1_client_id": None,
|
|
29
|
+
"v1_client_secret": None,
|
|
30
|
+
"v1_client_id_secret_b64": None,
|
|
31
|
+
"access_token": None,
|
|
32
|
+
"refresh_token": None,
|
|
33
|
+
"token_expires_at": None,
|
|
34
|
+
"country_code": "US",
|
|
35
|
+
"auth_cache": DEFAULT_AUTH_CACHE_FILENAME,
|
|
36
|
+
"request_timeout": 15.0,
|
|
37
|
+
"search_limit": 10,
|
|
38
|
+
"match_threshold": 0.78,
|
|
39
|
+
"prefer_synced": True,
|
|
40
|
+
"art_size": 1280,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
register_sources()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class TidalV1Plugin(BeetsPlugin):
|
|
47
|
+
def __init__(self) -> None:
|
|
48
|
+
super().__init__()
|
|
49
|
+
self.config.add(DEFAULT_CONFIG)
|
|
50
|
+
for key in (
|
|
51
|
+
"v1_client_id",
|
|
52
|
+
"v1_client_secret",
|
|
53
|
+
"v1_client_id_secret_b64",
|
|
54
|
+
"access_token",
|
|
55
|
+
"refresh_token",
|
|
56
|
+
):
|
|
57
|
+
self.config[key].redact = True
|
|
58
|
+
register_sources()
|
|
59
|
+
|
|
60
|
+
def commands(self) -> list[Any]:
|
|
61
|
+
cmd = cast(Any, ui.Subcommand)("tidalv1", help="TIDAL v1 plugin commands")
|
|
62
|
+
cmd.parser.add_option(
|
|
63
|
+
"-a",
|
|
64
|
+
"--auth",
|
|
65
|
+
action="store_true",
|
|
66
|
+
default=False,
|
|
67
|
+
help="authenticate and log in to TIDAL",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def func(lib: Any, opts: Any, args: Any) -> None:
|
|
71
|
+
if not opts.auth:
|
|
72
|
+
cmd.print_help()
|
|
73
|
+
return
|
|
74
|
+
|
|
75
|
+
manager = AuthManager.from_config(self.config)
|
|
76
|
+
device = manager.start_device_authorization()
|
|
77
|
+
url = device.verification_uri_complete or device.verification_uri
|
|
78
|
+
ui.print_("OAuth login started; waiting for a response.")
|
|
79
|
+
ui.print_(f"Open this TIDAL authorization URL: {url}")
|
|
80
|
+
ui.print_(f"If not auto-filled, use code: {device.user_code}")
|
|
81
|
+
with suppress(webbrowser.Error):
|
|
82
|
+
webbrowser.open(url)
|
|
83
|
+
|
|
84
|
+
token = manager.poll_device_authorization(device, sleep=time.sleep)
|
|
85
|
+
manager.save_token(token)
|
|
86
|
+
ui.print_(f"TIDAL authorization saved to {manager.cache_path}")
|
|
87
|
+
|
|
88
|
+
cmd.func = func
|
|
89
|
+
return [cmd]
|
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import binascii
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import tempfile
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import asdict, dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, cast
|
|
15
|
+
|
|
16
|
+
import confuse
|
|
17
|
+
import requests
|
|
18
|
+
from beets import config as beets_config
|
|
19
|
+
|
|
20
|
+
from .http_types import HTTPSession, ResponseLike
|
|
21
|
+
|
|
22
|
+
DEFAULT_AUTH_BASE = "https://auth.tidal.com/v1/oauth2"
|
|
23
|
+
DEFAULT_SCOPE = "r_usr+w_usr+w_sub"
|
|
24
|
+
DEFAULT_AUTH_CACHE_FILENAME = "tidalv1_token.json"
|
|
25
|
+
|
|
26
|
+
_discovered_app_credentials: tuple[str, str] | None = None
|
|
27
|
+
_discovered_app_credentials_lock = threading.Lock()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TidalAuthError(RuntimeError):
|
|
31
|
+
"""Base exception for TIDAL auth failures."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AuthRequired(TidalAuthError):
|
|
35
|
+
"""Raised when a user-scoped token is required but unavailable."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AppCredentialsRequired(TidalAuthError):
|
|
39
|
+
"""Raised when app client credentials are required but unavailable."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class DeviceAuthExpired(TidalAuthError):
|
|
43
|
+
"""Raised when the device authorization window expires."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class DeviceAuthDenied(TidalAuthError):
|
|
47
|
+
"""Raised when the user denies device authorization."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class DeviceCode:
|
|
52
|
+
device_code: str
|
|
53
|
+
user_code: str
|
|
54
|
+
verification_uri: str
|
|
55
|
+
expires_in: int
|
|
56
|
+
interval: int = 5
|
|
57
|
+
verification_uri_complete: str | None = None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class TokenSet:
|
|
62
|
+
access_token: str
|
|
63
|
+
token_type: str = "Bearer"
|
|
64
|
+
refresh_token: str | None = None
|
|
65
|
+
expires_at: int | None = None
|
|
66
|
+
scope: str | None = None
|
|
67
|
+
user_id: str | None = None
|
|
68
|
+
country_code: str | None = None
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def from_oauth_payload(cls, payload: dict[str, Any]) -> TokenSet:
|
|
72
|
+
expires_at = None
|
|
73
|
+
if payload.get("expires_in") is not None:
|
|
74
|
+
expires_at = int(time.time()) + int(payload["expires_in"])
|
|
75
|
+
|
|
76
|
+
user_payload = payload.get("user")
|
|
77
|
+
user = cast(dict[str, Any], user_payload) if isinstance(user_payload, dict) else {}
|
|
78
|
+
return cls(
|
|
79
|
+
access_token=str(payload["access_token"]),
|
|
80
|
+
token_type=str(payload.get("token_type", "Bearer")),
|
|
81
|
+
refresh_token=optional_str(payload.get("refresh_token")),
|
|
82
|
+
expires_at=expires_at,
|
|
83
|
+
scope=optional_str(payload.get("scope")),
|
|
84
|
+
user_id=str(user.get("userId")) if user.get("userId") else None,
|
|
85
|
+
country_code=optional_str(user.get("countryCode") or payload.get("countryCode")),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def from_mapping(cls, payload: dict[str, Any]) -> TokenSet | None:
|
|
90
|
+
token = payload.get("access_token")
|
|
91
|
+
if not token:
|
|
92
|
+
return None
|
|
93
|
+
return cls(
|
|
94
|
+
access_token=str(token),
|
|
95
|
+
token_type=str(payload.get("token_type", "Bearer")),
|
|
96
|
+
refresh_token=optional_str(payload.get("refresh_token")),
|
|
97
|
+
expires_at=optional_int(payload.get("expires_at")),
|
|
98
|
+
scope=optional_str(payload.get("scope")),
|
|
99
|
+
user_id=optional_str(payload.get("user_id")),
|
|
100
|
+
country_code=optional_str(payload.get("country_code")),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def is_valid(self, skew_seconds: int = 60) -> bool:
|
|
104
|
+
return self.expires_at is None or self.expires_at > int(time.time()) + skew_seconds
|
|
105
|
+
|
|
106
|
+
def has_scope(self, scope: str) -> bool:
|
|
107
|
+
if self.scope is None:
|
|
108
|
+
return True
|
|
109
|
+
return scope in self.scope.replace("+", " ").split()
|
|
110
|
+
|
|
111
|
+
def to_json(self) -> dict[str, Any]:
|
|
112
|
+
return {key: value for key, value in asdict(self).items() if value is not None}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def default_auth_cache_path() -> Path:
|
|
116
|
+
return Path(cast(Any, beets_config).config_dir()) / DEFAULT_AUTH_CACHE_FILENAME
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class AuthManager:
|
|
120
|
+
def __init__(
|
|
121
|
+
self,
|
|
122
|
+
*,
|
|
123
|
+
v1_client_id: str | None = None,
|
|
124
|
+
v1_client_secret: str | None = None,
|
|
125
|
+
auth_base: str = DEFAULT_AUTH_BASE,
|
|
126
|
+
access_token: str | None = None,
|
|
127
|
+
refresh_token: str | None = None,
|
|
128
|
+
token_expires_at: int | None = None,
|
|
129
|
+
country_code: str = "US",
|
|
130
|
+
cache_path: str | Path | None = None,
|
|
131
|
+
request_timeout: float = 15.0,
|
|
132
|
+
session: HTTPSession | None = None,
|
|
133
|
+
) -> None:
|
|
134
|
+
self.v1_client_id = v1_client_id
|
|
135
|
+
self.v1_client_secret = v1_client_secret
|
|
136
|
+
self.auth_base = auth_base.rstrip("/")
|
|
137
|
+
self.country_code = country_code
|
|
138
|
+
self.request_timeout = request_timeout
|
|
139
|
+
self.session: HTTPSession = session or cast(HTTPSession, requests.Session())
|
|
140
|
+
self.cache_path = Path(cache_path).expanduser() if cache_path else default_auth_cache_path()
|
|
141
|
+
self._memory_token: TokenSet | None = None
|
|
142
|
+
self._configured_token = (
|
|
143
|
+
TokenSet(
|
|
144
|
+
access_token=access_token,
|
|
145
|
+
refresh_token=refresh_token,
|
|
146
|
+
expires_at=token_expires_at,
|
|
147
|
+
country_code=country_code,
|
|
148
|
+
)
|
|
149
|
+
if access_token
|
|
150
|
+
else None
|
|
151
|
+
)
|
|
152
|
+
self._configured_refresh_token = refresh_token
|
|
153
|
+
|
|
154
|
+
@classmethod
|
|
155
|
+
def from_config(
|
|
156
|
+
cls,
|
|
157
|
+
config: Any,
|
|
158
|
+
*,
|
|
159
|
+
session: HTTPSession | None = None,
|
|
160
|
+
) -> AuthManager:
|
|
161
|
+
request_timeout = _config_value(config, "request_timeout", 15.0, float)
|
|
162
|
+
v1_client_id = os.environ.get("TIDAL_V1_CLIENT_ID") or _config_value(
|
|
163
|
+
config, "v1_client_id", None, str
|
|
164
|
+
)
|
|
165
|
+
v1_client_secret = os.environ.get("TIDAL_V1_CLIENT_SECRET") or _config_value(
|
|
166
|
+
config, "v1_client_secret", None, str
|
|
167
|
+
)
|
|
168
|
+
if not (v1_client_id and v1_client_secret):
|
|
169
|
+
v1_client_id_secret_b64 = os.environ.get(
|
|
170
|
+
"TIDAL_V1_CLIENT_ID_SECRET_B64"
|
|
171
|
+
) or _config_value(config, "v1_client_id_secret_b64", None, str)
|
|
172
|
+
if v1_client_id_secret_b64:
|
|
173
|
+
v1_client_id, v1_client_secret = decode_v1_client_id_secret_b64(
|
|
174
|
+
v1_client_id_secret_b64
|
|
175
|
+
)
|
|
176
|
+
else:
|
|
177
|
+
credential_session = session or cast(HTTPSession, requests.Session())
|
|
178
|
+
discovered_credentials = _discover_app_credentials(
|
|
179
|
+
credential_session, request_timeout
|
|
180
|
+
)
|
|
181
|
+
if discovered_credentials:
|
|
182
|
+
v1_client_id, v1_client_secret = discovered_credentials
|
|
183
|
+
|
|
184
|
+
if not (v1_client_id and v1_client_secret):
|
|
185
|
+
raise AppCredentialsRequired(
|
|
186
|
+
"TIDAL v1 app client ID and secret are required. Configure "
|
|
187
|
+
"`tidalv1.v1_client_id` and `tidalv1.v1_client_secret`"
|
|
188
|
+
"or set `tidalv1.v1_client_id_secret_b64`."
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
return cls(
|
|
192
|
+
v1_client_id=v1_client_id,
|
|
193
|
+
v1_client_secret=v1_client_secret,
|
|
194
|
+
auth_base=_config_value(config, "auth_base", DEFAULT_AUTH_BASE, str),
|
|
195
|
+
access_token=os.environ.get("TIDAL_ACCESS_TOKEN")
|
|
196
|
+
or _config_value(config, "access_token", None, str),
|
|
197
|
+
refresh_token=os.environ.get("TIDAL_REFRESH_TOKEN")
|
|
198
|
+
or _config_value(config, "refresh_token", None, str),
|
|
199
|
+
token_expires_at=_config_value(config, "token_expires_at", None, int),
|
|
200
|
+
country_code=os.environ.get("TIDAL_COUNTRY_CODE")
|
|
201
|
+
or _config_value(config, "country_code", "US", str),
|
|
202
|
+
cache_path=_config_filename(config, "auth_cache"),
|
|
203
|
+
request_timeout=request_timeout,
|
|
204
|
+
session=session,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
def start_device_authorization(self) -> DeviceCode:
|
|
208
|
+
client_id = self.require_client_id()
|
|
209
|
+
response = self.session.post(
|
|
210
|
+
f"{self.auth_base}/device_authorization",
|
|
211
|
+
data={"client_id": client_id, "scope": DEFAULT_SCOPE},
|
|
212
|
+
timeout=self.request_timeout,
|
|
213
|
+
)
|
|
214
|
+
response.raise_for_status()
|
|
215
|
+
payload = response_json_object(response)
|
|
216
|
+
return DeviceCode(
|
|
217
|
+
device_code=str(payload["deviceCode"]),
|
|
218
|
+
user_code=str(payload["userCode"]),
|
|
219
|
+
verification_uri=str(payload["verificationUri"]),
|
|
220
|
+
verification_uri_complete=optional_str(payload.get("verificationUriComplete")),
|
|
221
|
+
expires_in=int(payload["expiresIn"]),
|
|
222
|
+
interval=int(payload.get("interval", 2)),
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
def poll_device_authorization(
|
|
226
|
+
self,
|
|
227
|
+
device: DeviceCode,
|
|
228
|
+
*,
|
|
229
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
230
|
+
) -> TokenSet:
|
|
231
|
+
deadline = time.time() + device.expires_in
|
|
232
|
+
interval = device.interval
|
|
233
|
+
client_id, client_secret = self.require_client_credentials()
|
|
234
|
+
|
|
235
|
+
while time.time() < deadline:
|
|
236
|
+
response = self.session.post(
|
|
237
|
+
f"{self.auth_base}/token",
|
|
238
|
+
data={
|
|
239
|
+
"client_id": client_id,
|
|
240
|
+
"device_code": device.device_code,
|
|
241
|
+
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
|
242
|
+
"scope": DEFAULT_SCOPE,
|
|
243
|
+
},
|
|
244
|
+
auth=(client_id, client_secret),
|
|
245
|
+
timeout=self.request_timeout,
|
|
246
|
+
)
|
|
247
|
+
payload = _json_or_empty(response)
|
|
248
|
+
if response.status_code == 200 and payload.get("access_token"):
|
|
249
|
+
token = TokenSet.from_oauth_payload(payload)
|
|
250
|
+
self.save_token(token)
|
|
251
|
+
return token
|
|
252
|
+
|
|
253
|
+
error = payload.get("error")
|
|
254
|
+
if error == "authorization_pending" or payload.get("sub_status") in (1002, "1002"):
|
|
255
|
+
sleep(interval)
|
|
256
|
+
continue
|
|
257
|
+
if error == "slow_down":
|
|
258
|
+
interval += 5
|
|
259
|
+
sleep(interval)
|
|
260
|
+
continue
|
|
261
|
+
if error in {"access_denied", "authorization_declined"}:
|
|
262
|
+
raise DeviceAuthDenied(payload.get("error_description", error))
|
|
263
|
+
if error in {"expired_token", "expired_device_code"}:
|
|
264
|
+
raise DeviceAuthExpired(payload.get("error_description", error))
|
|
265
|
+
|
|
266
|
+
if response.status_code != 200:
|
|
267
|
+
response.raise_for_status()
|
|
268
|
+
raise TidalAuthError(
|
|
269
|
+
payload.get("error_description") or f"TIDAL auth failed: {response.status_code}"
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
raise DeviceAuthExpired("TIDAL device authorization expired")
|
|
273
|
+
|
|
274
|
+
def get_token(self, *, require_user: bool = False) -> TokenSet:
|
|
275
|
+
token = self._best_existing_token(require_user=require_user)
|
|
276
|
+
if token:
|
|
277
|
+
return token
|
|
278
|
+
|
|
279
|
+
refresh_token = self._best_refresh_token()
|
|
280
|
+
if refresh_token:
|
|
281
|
+
try:
|
|
282
|
+
refreshed = self.refresh_token(refresh_token)
|
|
283
|
+
except requests.RequestException:
|
|
284
|
+
if require_user:
|
|
285
|
+
raise
|
|
286
|
+
else:
|
|
287
|
+
if not require_user or refreshed.has_scope("r_usr"):
|
|
288
|
+
return refreshed
|
|
289
|
+
|
|
290
|
+
if require_user:
|
|
291
|
+
raise AuthRequired(
|
|
292
|
+
"TIDAL lyrics require a user-scoped OAuth token; run `beet tidalv1 --auth`."
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
return self.client_credentials_token()
|
|
296
|
+
|
|
297
|
+
def refresh_token(self, refresh_token: str) -> TokenSet:
|
|
298
|
+
client_id, client_secret = self.require_client_credentials()
|
|
299
|
+
response = self.session.post(
|
|
300
|
+
f"{self.auth_base}/token",
|
|
301
|
+
data={
|
|
302
|
+
"client_id": client_id,
|
|
303
|
+
"refresh_token": refresh_token,
|
|
304
|
+
"grant_type": "refresh_token",
|
|
305
|
+
"scope": DEFAULT_SCOPE,
|
|
306
|
+
},
|
|
307
|
+
auth=(client_id, client_secret),
|
|
308
|
+
timeout=self.request_timeout,
|
|
309
|
+
)
|
|
310
|
+
response.raise_for_status()
|
|
311
|
+
token = TokenSet.from_oauth_payload(response_json_object(response))
|
|
312
|
+
if not token.refresh_token:
|
|
313
|
+
token.refresh_token = refresh_token
|
|
314
|
+
self.save_token(token)
|
|
315
|
+
return token
|
|
316
|
+
|
|
317
|
+
def client_credentials_token(self) -> TokenSet:
|
|
318
|
+
client_id, client_secret = self.require_client_credentials()
|
|
319
|
+
response = self.session.post(
|
|
320
|
+
f"{self.auth_base}/token",
|
|
321
|
+
data={"grant_type": "client_credentials"},
|
|
322
|
+
auth=(client_id, client_secret),
|
|
323
|
+
timeout=self.request_timeout,
|
|
324
|
+
)
|
|
325
|
+
response.raise_for_status()
|
|
326
|
+
token = TokenSet.from_oauth_payload(response_json_object(response))
|
|
327
|
+
# A client-credentials grant is never user-scoped, even when TIDAL
|
|
328
|
+
# omits the optional scope field from its response.
|
|
329
|
+
token.scope = ""
|
|
330
|
+
self._memory_token = token
|
|
331
|
+
return token
|
|
332
|
+
|
|
333
|
+
def load_cached_token(self) -> TokenSet | None:
|
|
334
|
+
try:
|
|
335
|
+
payload = json.loads(self.cache_path.read_text())
|
|
336
|
+
if not isinstance(payload, dict):
|
|
337
|
+
return None
|
|
338
|
+
return TokenSet.from_mapping(cast(dict[str, Any], payload))
|
|
339
|
+
except (OSError, json.JSONDecodeError, TypeError, ValueError):
|
|
340
|
+
return None
|
|
341
|
+
|
|
342
|
+
def save_token(self, token: TokenSet) -> None:
|
|
343
|
+
self._memory_token = token
|
|
344
|
+
self.cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
345
|
+
temp_path: Path | None = None
|
|
346
|
+
try:
|
|
347
|
+
with tempfile.NamedTemporaryFile(
|
|
348
|
+
mode="w",
|
|
349
|
+
encoding="utf-8",
|
|
350
|
+
dir=self.cache_path.parent,
|
|
351
|
+
prefix=f".{self.cache_path.name}.",
|
|
352
|
+
suffix=".tmp",
|
|
353
|
+
delete=False,
|
|
354
|
+
) as temp_file:
|
|
355
|
+
temp_path = Path(temp_file.name)
|
|
356
|
+
temp_file.write(json.dumps(token.to_json(), indent=2) + "\n")
|
|
357
|
+
temp_file.flush()
|
|
358
|
+
os.fsync(temp_file.fileno())
|
|
359
|
+
os.replace(temp_path, self.cache_path)
|
|
360
|
+
except Exception:
|
|
361
|
+
if temp_path is not None:
|
|
362
|
+
temp_path.unlink(missing_ok=True)
|
|
363
|
+
raise
|
|
364
|
+
|
|
365
|
+
def _best_existing_token(self, *, require_user: bool) -> TokenSet | None:
|
|
366
|
+
for token in (self._memory_token, self._configured_token, self.load_cached_token()):
|
|
367
|
+
if not token or not token.is_valid():
|
|
368
|
+
continue
|
|
369
|
+
if require_user and not token.has_scope("r_usr"):
|
|
370
|
+
continue
|
|
371
|
+
return token
|
|
372
|
+
return None
|
|
373
|
+
|
|
374
|
+
def _best_refresh_token(self) -> str | None:
|
|
375
|
+
cached = self.load_cached_token()
|
|
376
|
+
return (
|
|
377
|
+
(cached.refresh_token if cached else None)
|
|
378
|
+
or self._configured_refresh_token
|
|
379
|
+
or (self._configured_token.refresh_token if self._configured_token else None)
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
def require_client_id(self) -> str:
|
|
383
|
+
if not self.v1_client_id:
|
|
384
|
+
raise AppCredentialsRequired(
|
|
385
|
+
"TIDAL v1 app client ID is required. Configure `tidalv1.v1_client_id`"
|
|
386
|
+
"or `tidalv1.v1_client_id_secret_b64`."
|
|
387
|
+
)
|
|
388
|
+
return self.v1_client_id
|
|
389
|
+
|
|
390
|
+
def require_client_credentials(self) -> tuple[str, str]:
|
|
391
|
+
client_id = self.require_client_id()
|
|
392
|
+
if not self.v1_client_secret:
|
|
393
|
+
raise AppCredentialsRequired(
|
|
394
|
+
"TIDAL v1 app client secret is required. Configure `tidalv1.v1_client_secret`"
|
|
395
|
+
"or set `tidalv1.v1_client_id_secret_b64`."
|
|
396
|
+
)
|
|
397
|
+
return client_id, self.v1_client_secret
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _config_value(config: Any, key: str, default: Any = None, value_type: Any = None) -> Any:
|
|
401
|
+
try:
|
|
402
|
+
view = config[key]
|
|
403
|
+
except Exception:
|
|
404
|
+
return default
|
|
405
|
+
|
|
406
|
+
try:
|
|
407
|
+
value = view.get(value_type) if value_type else view.get()
|
|
408
|
+
except Exception:
|
|
409
|
+
return default
|
|
410
|
+
return default if value is None else value
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _config_filename(config: Any, key: str) -> Path:
|
|
414
|
+
try:
|
|
415
|
+
view = config[key]
|
|
416
|
+
value = view.get(cast(Any, confuse).Filename(in_app_dir=True))
|
|
417
|
+
except Exception:
|
|
418
|
+
return default_auth_cache_path()
|
|
419
|
+
return Path(cast(str, value)).expanduser()
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _json_or_empty(response: ResponseLike) -> dict[str, Any]:
|
|
423
|
+
try:
|
|
424
|
+
payload = response.json()
|
|
425
|
+
except ValueError:
|
|
426
|
+
return {}
|
|
427
|
+
return cast(dict[str, Any], payload) if isinstance(payload, dict) else {}
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def decode_v1_client_id_secret_b64(value: str) -> tuple[str, str]:
|
|
431
|
+
try:
|
|
432
|
+
decoded = base64.b64decode(value, validate=True).decode()
|
|
433
|
+
client_id, client_secret = decoded.split(";", 1)
|
|
434
|
+
except (binascii.Error, UnicodeDecodeError, ValueError) as exc:
|
|
435
|
+
raise AppCredentialsRequired(
|
|
436
|
+
"`tidalv1.v1_client_id_secret_b64` must be base64 for "
|
|
437
|
+
"`<v1_client_id>;<v1_client_secret>`."
|
|
438
|
+
) from exc
|
|
439
|
+
|
|
440
|
+
if not client_id or not client_secret:
|
|
441
|
+
raise AppCredentialsRequired(
|
|
442
|
+
"`tidalv1.v1_client_id_secret_b64` decoded to an incomplete "
|
|
443
|
+
"`<v1_client_id>;<v1_client_secret>` pair."
|
|
444
|
+
)
|
|
445
|
+
return client_id, client_secret
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _discover_app_credentials(
|
|
449
|
+
session: HTTPSession, request_timeout: float
|
|
450
|
+
) -> tuple[str, str] | None:
|
|
451
|
+
global _discovered_app_credentials
|
|
452
|
+
|
|
453
|
+
if _discovered_app_credentials is not None:
|
|
454
|
+
return _discovered_app_credentials
|
|
455
|
+
|
|
456
|
+
with _discovered_app_credentials_lock:
|
|
457
|
+
if _discovered_app_credentials is not None:
|
|
458
|
+
return _discovered_app_credentials
|
|
459
|
+
|
|
460
|
+
parts = [
|
|
461
|
+
"aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29t",
|
|
462
|
+
"b3NrdnIzNw==",
|
|
463
|
+
"dGlkZGw=",
|
|
464
|
+
"MDVkNjNkMTUzZTAwMGIxNTkwOGYwYmVhYmE3ZDRhNzEwNTQwNjYyMg==",
|
|
465
|
+
"dGlkZGwvY29yZS9hdXRoL2NsaWVudC5weQ==",
|
|
466
|
+
]
|
|
467
|
+
try:
|
|
468
|
+
response = session.get(
|
|
469
|
+
"/".join(base64.b64decode(value).decode() for value in parts),
|
|
470
|
+
timeout=request_timeout,
|
|
471
|
+
)
|
|
472
|
+
except requests.RequestException:
|
|
473
|
+
return None
|
|
474
|
+
|
|
475
|
+
if response.status_code != requests.codes.ok or not response.text:
|
|
476
|
+
return None
|
|
477
|
+
|
|
478
|
+
match = re.search(r"b64decode\((.*?)\)", response.text, re.DOTALL)
|
|
479
|
+
if not match:
|
|
480
|
+
return None
|
|
481
|
+
|
|
482
|
+
_discovered_app_credentials = decode_v1_client_id_secret_b64(match.group(1).strip()[1:-1])
|
|
483
|
+
return _discovered_app_credentials
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def response_json_object(response: ResponseLike) -> dict[str, Any]:
|
|
487
|
+
payload = response.json()
|
|
488
|
+
if not isinstance(payload, dict):
|
|
489
|
+
raise TidalAuthError("TIDAL auth returned an unexpected non-object JSON payload")
|
|
490
|
+
return cast(dict[str, Any], payload)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def optional_str(value: object) -> str | None:
|
|
494
|
+
return str(value) if value is not None else None
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def optional_int(value: object) -> int | None:
|
|
498
|
+
return int(str(value)) if value is not None else None
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import unicodedata
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from difflib import SequenceMatcher
|
|
7
|
+
from typing import Any, cast
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
from .auth import AuthManager
|
|
12
|
+
from .http_types import HTTPSession, ResponseLike
|
|
13
|
+
|
|
14
|
+
DEFAULT_API_BASE = "https://api.tidal.com/v1"
|
|
15
|
+
LISTEN_BASE = "https://listen.tidal.com"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TidalAPIError(RuntimeError):
|
|
19
|
+
"""Raised for unexpected TIDAL API responses."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class TrackMatch:
|
|
24
|
+
id: int
|
|
25
|
+
title: str
|
|
26
|
+
artist: str
|
|
27
|
+
album: str | None
|
|
28
|
+
duration: float | None
|
|
29
|
+
score: float
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def url(self) -> str:
|
|
33
|
+
return f"{LISTEN_BASE}/track/{self.id}"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class AlbumMatch:
|
|
38
|
+
id: int
|
|
39
|
+
title: str
|
|
40
|
+
artist: str
|
|
41
|
+
cover: str
|
|
42
|
+
score: float
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def url(self) -> str:
|
|
46
|
+
return f"{LISTEN_BASE}/album/{self.id}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class LyricsResult:
|
|
51
|
+
text: str
|
|
52
|
+
provider: str | None
|
|
53
|
+
track: TrackMatch
|
|
54
|
+
synced: bool
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def url(self) -> str:
|
|
58
|
+
return self.track.url
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class TidalClient:
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
auth: AuthManager,
|
|
65
|
+
*,
|
|
66
|
+
api_base: str = DEFAULT_API_BASE,
|
|
67
|
+
country_code: str = "US",
|
|
68
|
+
search_limit: int = 10,
|
|
69
|
+
request_timeout: float = 15.0,
|
|
70
|
+
session: HTTPSession | None = None,
|
|
71
|
+
) -> None:
|
|
72
|
+
self.auth = auth
|
|
73
|
+
self.api_base = api_base.rstrip("/")
|
|
74
|
+
self.country_code = country_code
|
|
75
|
+
self.search_limit = search_limit
|
|
76
|
+
self.request_timeout = request_timeout
|
|
77
|
+
self.session: HTTPSession = session or cast(HTTPSession, requests.Session())
|
|
78
|
+
|
|
79
|
+
def search_tracks(self, query: str) -> list[dict[str, Any]]:
|
|
80
|
+
payload = self._request(
|
|
81
|
+
"search",
|
|
82
|
+
params={"query": query, "limit": self.search_limit},
|
|
83
|
+
require_user=False,
|
|
84
|
+
)
|
|
85
|
+
return _items(payload, "tracks")
|
|
86
|
+
|
|
87
|
+
def search_albums(self, query: str) -> list[dict[str, Any]]:
|
|
88
|
+
payload = self._request(
|
|
89
|
+
"search",
|
|
90
|
+
params={"query": query, "limit": self.search_limit},
|
|
91
|
+
require_user=False,
|
|
92
|
+
)
|
|
93
|
+
return _items(payload, "albums")
|
|
94
|
+
|
|
95
|
+
def get_track_lyrics(self, track_id: int) -> dict[str, Any]:
|
|
96
|
+
return self._request(f"tracks/{track_id}/lyrics", require_user=True)
|
|
97
|
+
|
|
98
|
+
def lyrics_for(
|
|
99
|
+
self,
|
|
100
|
+
artist: str,
|
|
101
|
+
title: str,
|
|
102
|
+
*,
|
|
103
|
+
album: str | None = None,
|
|
104
|
+
length: float | None = None,
|
|
105
|
+
prefer_synced: bool = True,
|
|
106
|
+
threshold: float = 0.78,
|
|
107
|
+
) -> LyricsResult | None:
|
|
108
|
+
track = self.find_track(artist, title, album=album, length=length, threshold=threshold)
|
|
109
|
+
if not track:
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
payload = self.get_track_lyrics(track.id)
|
|
113
|
+
subtitles = (payload.get("subtitles") or "").strip()
|
|
114
|
+
plain = (payload.get("lyrics") or "").strip()
|
|
115
|
+
text = subtitles if prefer_synced and subtitles else plain or subtitles
|
|
116
|
+
if not text:
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
return LyricsResult(
|
|
120
|
+
text=text,
|
|
121
|
+
provider=payload.get("lyricsProvider"),
|
|
122
|
+
track=track,
|
|
123
|
+
synced=bool(subtitles and text == subtitles),
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
def find_track(
|
|
127
|
+
self,
|
|
128
|
+
artist: str,
|
|
129
|
+
title: str,
|
|
130
|
+
*,
|
|
131
|
+
album: str | None = None,
|
|
132
|
+
length: float | None = None,
|
|
133
|
+
threshold: float = 0.78,
|
|
134
|
+
) -> TrackMatch | None:
|
|
135
|
+
query = " ".join(part for part in (artist, title) if part)
|
|
136
|
+
matches: list[TrackMatch] = []
|
|
137
|
+
for item in self.search_tracks(query):
|
|
138
|
+
match = _track_match(item, artist=artist, title=title, album=album, length=length)
|
|
139
|
+
if match is not None:
|
|
140
|
+
matches.append(match)
|
|
141
|
+
best = max(matches, key=lambda match: match.score, default=None)
|
|
142
|
+
return best if best and best.score >= threshold else None
|
|
143
|
+
|
|
144
|
+
def find_album(
|
|
145
|
+
self,
|
|
146
|
+
artist: str,
|
|
147
|
+
album: str,
|
|
148
|
+
*,
|
|
149
|
+
threshold: float = 0.78,
|
|
150
|
+
) -> AlbumMatch | None:
|
|
151
|
+
query = " ".join(part for part in (artist, album) if part)
|
|
152
|
+
matches: list[AlbumMatch] = []
|
|
153
|
+
for item in self.search_albums(query):
|
|
154
|
+
match = _album_match(item, artist=artist, album=album)
|
|
155
|
+
if match is not None and match.cover:
|
|
156
|
+
matches.append(match)
|
|
157
|
+
best = max(matches, key=lambda match: match.score, default=None)
|
|
158
|
+
return best if best and best.score >= threshold else None
|
|
159
|
+
|
|
160
|
+
def legacy_username_login(
|
|
161
|
+
self,
|
|
162
|
+
*,
|
|
163
|
+
username: str,
|
|
164
|
+
password: str,
|
|
165
|
+
client_token: str,
|
|
166
|
+
client_version: str = "2.38.0",
|
|
167
|
+
) -> dict[str, Any]:
|
|
168
|
+
response = self.session.post(
|
|
169
|
+
f"{self.api_base}/login/username",
|
|
170
|
+
data={
|
|
171
|
+
"username": username,
|
|
172
|
+
"password": password,
|
|
173
|
+
"token": client_token,
|
|
174
|
+
"clientVersion": client_version,
|
|
175
|
+
},
|
|
176
|
+
timeout=self.request_timeout,
|
|
177
|
+
)
|
|
178
|
+
response.raise_for_status()
|
|
179
|
+
return response_json_object(response)
|
|
180
|
+
|
|
181
|
+
def _request(
|
|
182
|
+
self,
|
|
183
|
+
endpoint: str,
|
|
184
|
+
*,
|
|
185
|
+
params: dict[str, Any] | None = None,
|
|
186
|
+
require_user: bool,
|
|
187
|
+
) -> dict[str, Any]:
|
|
188
|
+
token = self.auth.get_token(require_user=require_user)
|
|
189
|
+
request_params = {"countryCode": token.country_code or self.country_code}
|
|
190
|
+
request_params.update(params or {})
|
|
191
|
+
response = self.session.get(
|
|
192
|
+
f"{self.api_base}/{endpoint.lstrip('/')}",
|
|
193
|
+
params=request_params,
|
|
194
|
+
headers={
|
|
195
|
+
"Authorization": f"{token.token_type} {token.access_token}",
|
|
196
|
+
"Accept": "application/json",
|
|
197
|
+
},
|
|
198
|
+
timeout=self.request_timeout,
|
|
199
|
+
)
|
|
200
|
+
if response.status_code == 404:
|
|
201
|
+
return {}
|
|
202
|
+
if not response.ok:
|
|
203
|
+
raise TidalAPIError(_format_error(response))
|
|
204
|
+
payload = response.json()
|
|
205
|
+
if not isinstance(payload, dict):
|
|
206
|
+
raise TidalAPIError("TIDAL returned an unexpected non-object JSON payload")
|
|
207
|
+
return cast(dict[str, Any], payload)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def cover_url(cover_id: str, size: int = 1280) -> str:
|
|
211
|
+
safe_size = clamp_art_size(size)
|
|
212
|
+
cover_path = cover_id.replace("-", "/")
|
|
213
|
+
return f"https://resources.tidal.com/images/{cover_path}/{safe_size}x{safe_size}.jpg"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def clamp_art_size(size: int) -> int:
|
|
217
|
+
return min(max(int(size), 80), 1280)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _items(payload: dict[str, Any], key: str) -> list[dict[str, Any]]:
|
|
221
|
+
section_obj = payload.get(key)
|
|
222
|
+
if not isinstance(section_obj, dict):
|
|
223
|
+
return []
|
|
224
|
+
section = cast(dict[str, Any], section_obj)
|
|
225
|
+
items_obj = section.get("items")
|
|
226
|
+
if not isinstance(items_obj, list):
|
|
227
|
+
return []
|
|
228
|
+
items = cast(list[object], items_obj)
|
|
229
|
+
matches: list[dict[str, Any]] = []
|
|
230
|
+
for item in items:
|
|
231
|
+
if isinstance(item, dict):
|
|
232
|
+
matches.append(cast(dict[str, Any], item))
|
|
233
|
+
return matches
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _track_match(
|
|
237
|
+
item: dict[str, Any],
|
|
238
|
+
*,
|
|
239
|
+
artist: str,
|
|
240
|
+
title: str,
|
|
241
|
+
album: str | None,
|
|
242
|
+
length: float | None,
|
|
243
|
+
) -> TrackMatch | None:
|
|
244
|
+
track_id = item.get("id")
|
|
245
|
+
item_title = item.get("title") or ""
|
|
246
|
+
if not track_id or not item_title:
|
|
247
|
+
return None
|
|
248
|
+
|
|
249
|
+
item_artist = _artist_name(item)
|
|
250
|
+
item_album = _album_title(item)
|
|
251
|
+
item_duration = _duration(item)
|
|
252
|
+
score = (
|
|
253
|
+
0.55 * similarity(title, item_title)
|
|
254
|
+
+ 0.25 * similarity(artist, item_artist)
|
|
255
|
+
+ 0.10 * (similarity(album, item_album) if album and item_album else 0.5)
|
|
256
|
+
+ 0.10 * duration_similarity(length, item_duration)
|
|
257
|
+
)
|
|
258
|
+
return TrackMatch(
|
|
259
|
+
id=int(track_id),
|
|
260
|
+
title=item_title,
|
|
261
|
+
artist=item_artist,
|
|
262
|
+
album=item_album,
|
|
263
|
+
duration=item_duration,
|
|
264
|
+
score=score,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _album_match(item: dict[str, Any], *, artist: str, album: str) -> AlbumMatch | None:
|
|
269
|
+
album_id = item.get("id")
|
|
270
|
+
title = item.get("title") or ""
|
|
271
|
+
cover = item.get("cover") or ""
|
|
272
|
+
if not album_id or not title or not cover:
|
|
273
|
+
return None
|
|
274
|
+
|
|
275
|
+
item_artist = _artist_name(item)
|
|
276
|
+
score = 0.65 * similarity(album, title) + 0.35 * similarity(artist, item_artist)
|
|
277
|
+
return AlbumMatch(id=int(album_id), title=title, artist=item_artist, cover=cover, score=score)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _artist_name(item: dict[str, Any]) -> str:
|
|
281
|
+
artist_obj = item.get("artist")
|
|
282
|
+
if isinstance(artist_obj, dict):
|
|
283
|
+
artist = cast(dict[str, Any], artist_obj)
|
|
284
|
+
if artist.get("name"):
|
|
285
|
+
return str(artist["name"])
|
|
286
|
+
artists_obj = item.get("artists")
|
|
287
|
+
if isinstance(artists_obj, list):
|
|
288
|
+
names: list[str] = []
|
|
289
|
+
for entry_obj in cast(list[object], artists_obj):
|
|
290
|
+
if isinstance(entry_obj, dict):
|
|
291
|
+
entry = cast(dict[str, Any], entry_obj)
|
|
292
|
+
if entry.get("name"):
|
|
293
|
+
names.append(str(entry["name"]))
|
|
294
|
+
if names:
|
|
295
|
+
return ", ".join(names)
|
|
296
|
+
return ""
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _album_title(item: dict[str, Any]) -> str | None:
|
|
300
|
+
album_obj = item.get("album")
|
|
301
|
+
if isinstance(album_obj, dict):
|
|
302
|
+
album = cast(dict[str, Any], album_obj)
|
|
303
|
+
if album.get("title"):
|
|
304
|
+
return str(album["title"])
|
|
305
|
+
return None
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _duration(item: dict[str, Any]) -> float | None:
|
|
309
|
+
duration = item.get("duration")
|
|
310
|
+
try:
|
|
311
|
+
return float(duration) if duration is not None else None
|
|
312
|
+
except (TypeError, ValueError):
|
|
313
|
+
return None
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def similarity(left: str | None, right: str | None) -> float:
|
|
317
|
+
left_norm = normalize(left)
|
|
318
|
+
right_norm = normalize(right)
|
|
319
|
+
if not left_norm or not right_norm:
|
|
320
|
+
return 0.0
|
|
321
|
+
if left_norm == right_norm:
|
|
322
|
+
return 1.0
|
|
323
|
+
return SequenceMatcher(a=left_norm, b=right_norm).ratio()
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def duration_similarity(left: float | None, right: float | None) -> float:
|
|
327
|
+
if not left or not right:
|
|
328
|
+
return 0.5
|
|
329
|
+
diff = abs(float(left) - float(right))
|
|
330
|
+
if diff <= 2:
|
|
331
|
+
return 1.0
|
|
332
|
+
return max(0.0, 1.0 - diff / max(float(left), float(right), 1.0))
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def normalize(value: str | None) -> str:
|
|
336
|
+
value = unicodedata.normalize("NFKC", value or "").casefold()
|
|
337
|
+
value = re.sub(r"\([^)]*\)", " ", value)
|
|
338
|
+
value = re.sub(r"\b(feat|featuring|ft)\b.*", " ", value)
|
|
339
|
+
value = "".join(
|
|
340
|
+
character if character.isalnum() or unicodedata.category(character).startswith("M") else " "
|
|
341
|
+
for character in value
|
|
342
|
+
)
|
|
343
|
+
return " ".join(value.split())
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _format_error(response: ResponseLike) -> str:
|
|
347
|
+
try:
|
|
348
|
+
payload = response.json()
|
|
349
|
+
except ValueError:
|
|
350
|
+
return f"TIDAL API request failed with HTTP {response.status_code}"
|
|
351
|
+
if isinstance(payload, dict):
|
|
352
|
+
payload_dict = cast(dict[str, Any], payload)
|
|
353
|
+
detail = optional_str(
|
|
354
|
+
payload_dict.get("userMessage")
|
|
355
|
+
or payload_dict.get("description")
|
|
356
|
+
or payload_dict.get("error")
|
|
357
|
+
)
|
|
358
|
+
if detail:
|
|
359
|
+
return f"TIDAL API request failed with HTTP {response.status_code}: {detail}"
|
|
360
|
+
return f"TIDAL API request failed with HTTP {response.status_code}"
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def response_json_object(response: ResponseLike) -> dict[str, Any]:
|
|
364
|
+
payload = response.json()
|
|
365
|
+
if not isinstance(payload, dict):
|
|
366
|
+
raise TidalAPIError("TIDAL returned an unexpected non-object JSON payload")
|
|
367
|
+
return cast(dict[str, Any], payload)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def optional_str(value: object) -> str | None:
|
|
371
|
+
return str(value) if value is not None else None
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Protocol
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ResponseLike(Protocol):
|
|
7
|
+
@property
|
|
8
|
+
def status_code(self) -> int: ...
|
|
9
|
+
|
|
10
|
+
@property
|
|
11
|
+
def ok(self) -> bool: ...
|
|
12
|
+
|
|
13
|
+
@property
|
|
14
|
+
def text(self) -> str: ...
|
|
15
|
+
|
|
16
|
+
def json(self) -> Any: ...
|
|
17
|
+
|
|
18
|
+
def raise_for_status(self) -> None: ...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class HTTPSession(Protocol):
|
|
22
|
+
def get(self, url: str, **kwargs: Any) -> ResponseLike: ...
|
|
23
|
+
|
|
24
|
+
def post(self, url: str, **kwargs: Any) -> ResponseLike: ...
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, cast
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
from beets import config as beets_config
|
|
7
|
+
from beets.util.lyrics import Lyrics
|
|
8
|
+
from beetsplug.fetchart import MetadataMatch, RemoteArtSource
|
|
9
|
+
from beetsplug.lyrics import Backend
|
|
10
|
+
|
|
11
|
+
from beetsplug import fetchart as fetchart_mod
|
|
12
|
+
from beetsplug import lyrics as lyrics_mod
|
|
13
|
+
|
|
14
|
+
from .auth import AuthManager, TidalAuthError
|
|
15
|
+
from .client import DEFAULT_API_BASE, TidalAPIError, TidalClient, clamp_art_size, cover_url
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TidalV1(Backend):
|
|
19
|
+
def fetch(self, artist: str, title: str, album: str, length: int) -> Lyrics | None:
|
|
20
|
+
try:
|
|
21
|
+
client = client_from_config(beets_config["tidalv1"])
|
|
22
|
+
result = client.lyrics_for(
|
|
23
|
+
artist,
|
|
24
|
+
title,
|
|
25
|
+
album=album,
|
|
26
|
+
length=length,
|
|
27
|
+
prefer_synced=_config_value("prefer_synced", True, bool),
|
|
28
|
+
threshold=_config_value("match_threshold", 0.78, float),
|
|
29
|
+
)
|
|
30
|
+
except (TidalAuthError, TidalAPIError, requests.RequestException) as exc:
|
|
31
|
+
cast(Any, self).warn("{}", exc)
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
if not result:
|
|
35
|
+
return None
|
|
36
|
+
return Lyrics(result.text, self.__class__.name, result.url)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TidalArtSource(RemoteArtSource):
|
|
40
|
+
NAME = "TIDAL"
|
|
41
|
+
ID = "tidalv1"
|
|
42
|
+
VALID_MATCHING_CRITERIA = ["default"]
|
|
43
|
+
|
|
44
|
+
def get(self, album: Any, plugin: Any, paths: Any) -> Any:
|
|
45
|
+
try:
|
|
46
|
+
client = client_from_config(beets_config["tidalv1"])
|
|
47
|
+
match = client.find_album(
|
|
48
|
+
album.albumartist,
|
|
49
|
+
album.album,
|
|
50
|
+
threshold=_config_value("match_threshold", 0.78, float),
|
|
51
|
+
)
|
|
52
|
+
except (TidalAuthError, TidalAPIError, requests.RequestException) as exc:
|
|
53
|
+
self._log.warning("TIDAL art source failed: {}", exc)
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
if not match:
|
|
57
|
+
return
|
|
58
|
+
|
|
59
|
+
size = clamp_art_size(_config_value("art_size", 1280, int))
|
|
60
|
+
yield cast(Any, self)._candidate(
|
|
61
|
+
url=cover_url(match.cover, size),
|
|
62
|
+
match=MetadataMatch.EXACT,
|
|
63
|
+
size=(size, size),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def client_from_config(config: Any) -> TidalClient:
|
|
68
|
+
auth = AuthManager.from_config(config)
|
|
69
|
+
country_code = _config_value("country_code", "US")
|
|
70
|
+
return TidalClient(
|
|
71
|
+
auth,
|
|
72
|
+
api_base=_config_value("api_base", DEFAULT_API_BASE),
|
|
73
|
+
country_code=country_code,
|
|
74
|
+
search_limit=_config_value("search_limit", 10, int),
|
|
75
|
+
request_timeout=_config_value("request_timeout", 15.0, float),
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def register_sources() -> None:
|
|
80
|
+
cast(Any, lyrics_mod.BACKEND_BY_NAME).setdefault("tidalv1", TidalV1)
|
|
81
|
+
fetchart_mod.ART_SOURCES.add(TidalArtSource)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _config_value(key: str, default: Any, value_type: Any = None) -> Any:
|
|
85
|
+
view = cast(Any, beets_config)["tidalv1"][key]
|
|
86
|
+
try:
|
|
87
|
+
value: Any = view.get(value_type) if value_type else view.get()
|
|
88
|
+
except Exception:
|
|
89
|
+
return default
|
|
90
|
+
return default if value is None else value
|