forked from sachinsenal0x64/hifi
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathmain.py
More file actions
1252 lines (1043 loc) · 43.7 KB
/
main.py
File metadata and controls
1252 lines (1043 loc) · 43.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import asyncio
import json
import os
import random
import time
from contextlib import asynccontextmanager
from typing import Dict, List, Optional, Union
import httpx
import uvicorn
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
import logging
logger = logging.getLogger(__name__)
load_dotenv()
API_VERSION = "2.10"
# Shared HTTP client is created in app lifespan for connection reuse
_http_client: Optional[httpx.AsyncClient] = None
_http_client_lock = asyncio.Lock()
# One lock per credential to avoid global contention during token refreshes
_refresh_locks: Dict[str, asyncio.Lock] = {}
# Loaded credential set from token.json; each entry will be enriched with access cache
_creds: List[dict] = []
# Global semaphore to limit concurrent album track fetches across all requests
_album_tracks_sem = asyncio.Semaphore(20)
# List of proxies loaded from file at startup
_proxies: List[str] = []
# Cache of the last proxy confirmed to be working
_last_known_good_proxy: Optional[str] = None
def _build_http_client(proxy_url: Optional[str] = None) -> httpx.AsyncClient:
# Pack common settings into a dictionary to keep things DRY
client_kwargs = {
"http2": True,
"headers": _tidal_headers(),
"timeout": httpx.Timeout(connect=3.0, read=12.0, write=8.0, pool=12.0),
"limits": httpx.Limits(
max_keepalive_connections=500,
max_connections=1000,
keepalive_expiry=30.0,
),
}
try:
# Modern httpx
return httpx.AsyncClient(proxy=proxy_url, **client_kwargs)
except TypeError:
# Legacy httpx
# If proxy_url is None, proxies=None is perfectly valid.
# If it's a string, older httpx versions require it to be a dictionary mapping.
legacy_proxies = {"all://": proxy_url} if proxy_url else None
return httpx.AsyncClient(proxies=legacy_proxies, **client_kwargs)
@asynccontextmanager
async def lifespan(app: FastAPI):
global _http_client
if DEV_MODE:
logger.warning("DEV_MODE is enabled — upstream responses will be logged at DEBUG level")
if _http_client is None:
proxy_url = None
if USE_PROXIES:
proxy_url = await get_working_proxy()
if not proxy_url and not FALLBACK_TO_DIRECT_CONNECTION:
logger.error("Could not find a working proxy and FALLBACK_TO_DIRECT_CONNECTION is False. Shutting down.")
raise RuntimeError("No working proxies available")
elif not proxy_url and FALLBACK_TO_DIRECT_CONNECTION:
logger.warning("Could not find a working proxy, falling back to direct connection. HOST IP MAY BE EXPOSED!")
_http_client = _build_http_client(proxy_url)
try:
yield
finally:
if _http_client:
await _http_client.aclose()
_http_client = None
app = FastAPI(
title="HiFi-RestAPI",
version=API_VERSION,
description="Tidal Music Proxy",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
# Config (defaults act as fallback if token file missing)
CLIENT_ID = os.getenv("CLIENT_ID", "")
CLIENT_SECRET = os.getenv("CLIENT_SECRET", "")
REFRESH_TOKEN: Optional[str] = os.getenv("REFRESH_TOKEN")
USER_ID = os.getenv("USER_ID")
TOKEN_FILE = os.getenv("TOKEN_FILE", "token.json")
COUNTRY_CODE = os.getenv("COUNTRY_CODE", "US")
USE_PROXIES = os.getenv("USE_PROXIES", "False").lower() in ("true", "1", "yes")
ROTATE_PROXIES_ON_REFRESH = os.getenv("ROTATE_PROXIES_ON_REFRESH", "False").lower() in ("true", "1", "yes")
PROXIES_FILE = os.getenv("PROXIES_FILE", "proxies.txt")
FALLBACK_TO_DIRECT_CONNECTION = os.getenv("FALLBACK_TO_DIRECT_CONNECTION", "False").lower() in ("true", "1", "yes")
# Maximum number of proxy candidates to test per get_working_proxy() call
MAX_PROXY_CANDIDATES = 10
# Maximum number of concurrent proxy tests inside get_working_proxy()
_PROXY_TEST_CONCURRENCY = 5
_max_retries_raw = os.getenv("MAX_RETRIES", "2")
_USER_AGENTS = [
"Dalvik/2.1.0 (Linux; U; Android 14; SM-S928B Build/AP2A.240905.003)",
"Dalvik/2.1.0 (Linux; U; Android 14; Pixel 8 Pro Build/AP2A.240905.003)",
"Dalvik/2.1.0 (Linux; U; Android 14; SM-G998B Build/UP1A.231005.007)",
"Dalvik/2.1.0 (Linux; U; Android 13; SM-A546B Build/TP1A.220624.014)",
"Dalvik/2.1.0 (Linux; U; Android 13; Pixel 7 Build/TQ3A.230901.001)",
"Dalvik/2.1.0 (Linux; U; Android 13; SM-S911B Build/TP1A.220624.014)",
"Dalvik/2.1.0 (Linux; U; Android 12; SM-G991B Build/SP1A.210812.016)",
"Dalvik/2.1.0 (Linux; U; Android 12; Pixel 6 Build/SP2A.220405.004)",
"Dalvik/2.1.0 (Linux; U; Android 14; OnePlus CPH2423 Build/AP2A.240905.003)",
"Dalvik/2.1.0 (Linux; U; Android 13; moto g84 5G Build/U1TDS33.73-27)",
]
_custom_ua = os.getenv("USER_AGENT")
def random_user_agent() -> str:
if _custom_ua:
return _custom_ua
return random.choice(_USER_AGENTS)
USER_AGENT = random_user_agent()
def _tidal_headers(extra: dict | None = None) -> dict:
h = {
"User-Agent": random_user_agent(),
"Accept": "*/*",
"Accept-Encoding": "gzip",
"Accept-Language": "en-US,en;q=0.9",
"X-Platform": "android",
"X-Tidal-Platform": "android",
}
if extra:
h.update(extra)
return h
_TIDAL_DEFAULT_HEADERS = _tidal_headers()
DEV_MODE = os.getenv("DEV_MODE", "False").lower() in ("true", "1", "yes")
_RATE_LIMIT_MAX_RETRIES = 3
_RATE_LIMIT_BASE_DELAY = 1.0
_RATE_LIMIT_MAX_DELAY = 10.0
def _log_response(method: str, url: str, resp: httpx.Response):
if not DEV_MODE:
return
logger.info(
"[DEV] %s %s → %s\n headers: %s\n body: %s",
method,
url,
resp.status_code,
dict(resp.headers),
resp.text[:2000],
)
try:
MAX_RETRIES = int(_max_retries_raw)
except ValueError:
MAX_RETRIES = 2
if MAX_RETRIES < 1:
MAX_RETRIES = 1
def load_proxies():
"""Load proxies from file into the global _proxies list."""
global _proxies
if not os.path.exists(PROXIES_FILE):
logger.warning(f"Proxies file {PROXIES_FILE} not found.")
_proxies = []
return
with open(PROXIES_FILE, "r") as f:
_proxies = [line.strip() for line in f if line.strip()]
logger.info(f"Loaded {len(_proxies)} proxies.")
async def test_proxy(proxy_url: str) -> bool:
try:
async with httpx.AsyncClient(proxy=proxy_url, timeout=5.0) as client:
resp = await client.get("http://example.com")
return resp.status_code == 200
except Exception:
return False
async def get_working_proxy(avoid_proxy: Optional[str] = None) -> Optional[str]:
global _last_known_good_proxy
if not _proxies:
return None
# Try the cached proxy first (unless it is the one we want to avoid)
if _last_known_good_proxy and _last_known_good_proxy != avoid_proxy:
if await test_proxy(_last_known_good_proxy):
return _last_known_good_proxy
shuffled_proxies = _proxies[:]
random.shuffle(shuffled_proxies)
if avoid_proxy:
candidate_proxies = [p for p in shuffled_proxies if p != avoid_proxy]
if not candidate_proxies:
candidate_proxies = shuffled_proxies
else:
candidate_proxies = shuffled_proxies
# Exclude the already-tested cached proxy and cap the candidate list
if _last_known_good_proxy:
candidate_proxies = [p for p in candidate_proxies if p != _last_known_good_proxy]
candidate_proxies = candidate_proxies[:MAX_PROXY_CANDIDATES]
# Test candidates concurrently, returning the first one that succeeds
sem = asyncio.Semaphore(_PROXY_TEST_CONCURRENCY)
found_event = asyncio.Event()
selected_proxy: List[Optional[str]] = [None]
async def probe(proxy: str) -> None:
if found_event.is_set():
return
async with sem:
if found_event.is_set():
return
if await test_proxy(proxy):
if not found_event.is_set():
selected_proxy[0] = proxy
found_event.set()
await asyncio.gather(*[probe(p) for p in candidate_proxies], return_exceptions=True)
if selected_proxy[0]:
_last_known_good_proxy = selected_proxy[0]
return selected_proxy[0]
async def _delayed_close(client: httpx.AsyncClient):
await asyncio.sleep(15)
await client.aclose()
async def update_global_client(force_new_proxy: bool = False):
global _http_client
async with _http_client_lock:
proxy_to_avoid = None
if force_new_proxy and _http_client and _http_client.proxy:
proxy_to_avoid = str(_http_client.proxy.url)
proxy_url = None
if USE_PROXIES:
proxy_url = await get_working_proxy(avoid_proxy=proxy_to_avoid)
if not proxy_url:
if FALLBACK_TO_DIRECT_CONNECTION:
logger.warning("Could not find a working proxy, falling back to direct connection. HOST IP MAY BE EXPOSED!")
else:
logger.error("Could not find a working proxy and FALLBACK_TO_DIRECT_CONNECTION is False.")
raise HTTPException(status_code=503, detail="Service Unavailable")
# Only create a new client if the proxy is actually different
current_proxy_url: Optional[str] = None
if _http_client and _http_client.proxy:
current_proxy_url = str(_http_client.proxy.url)
if _http_client and current_proxy_url == proxy_url:
return
new_client = _build_http_client(proxy_url)
old_client = _http_client
_http_client = new_client
if old_client is not None:
asyncio.create_task(_delayed_close(old_client))
if USE_PROXIES:
load_proxies()
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE, "r") as tok:
token_data = json.load(tok)
if isinstance(token_data, dict):
token_data = [token_data]
for entry in token_data:
cred = {
"client_id": entry.get("client_ID") or CLIENT_ID,
"client_secret": entry.get("client_secret") or CLIENT_SECRET,
"refresh_token": entry.get("refresh_token") or REFRESH_TOKEN,
"user_id": entry.get("userID") or USER_ID,
# Access tokens in file have unknown expiry; force refresh on first use
"access_token": None,
"expires_at": 0,
}
if cred["refresh_token"]:
_creds.append(cred)
# Add env var credential if available and unique (simple check)
if REFRESH_TOKEN:
env_cred = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"refresh_token": REFRESH_TOKEN,
"user_id": USER_ID,
"access_token": None,
"expires_at": 0,
}
# Avoid adding duplicate if it was already loaded from file with same refresh token
if not any(c["refresh_token"] == REFRESH_TOKEN for c in _creds):
_creds.append(env_cred)
if _creds:
CLIENT_ID = _creds[0]["client_id"]
CLIENT_SECRET = _creds[0]["client_secret"]
REFRESH_TOKEN = _creds[0]["refresh_token"]
def _pick_credential() -> dict:
if not _creds:
raise HTTPException(status_code=500, detail="No Tidal credentials available; populate token.json")
return random.choice(_creds)
def _lock_for_cred(cred: dict) -> asyncio.Lock:
key = f"{cred['client_id']}:{cred['refresh_token']}"
lock = _refresh_locks.get(key)
if lock is None:
lock = asyncio.Lock()
_refresh_locks[key] = lock
return lock
async def get_http_client() -> httpx.AsyncClient:
global _http_client
if _http_client is None:
async with _http_client_lock:
if _http_client is None:
proxy_url = None
if USE_PROXIES:
proxy_url = await get_working_proxy()
if not proxy_url and not FALLBACK_TO_DIRECT_CONNECTION:
raise HTTPException(status_code=503, detail="Service Unavailable")
elif not proxy_url and FALLBACK_TO_DIRECT_CONNECTION:
logger.warning("Could not find a working proxy, falling back to direct connection. HOST IP MAY BE EXPOSED!")
_http_client = _build_http_client(proxy_url)
return _http_client
async def refresh_tidal_token(cred: Optional[dict] = None):
"""Refresh a token for the provided credential set."""
cred = cred or _pick_credential()
async with _lock_for_cred(cred):
if cred["access_token"] and time.time() < cred["expires_at"]:
return cred["access_token"]
if USE_PROXIES and ROTATE_PROXIES_ON_REFRESH:
await update_global_client(force_new_proxy=True)
max_retries = MAX_RETRIES if USE_PROXIES else 1
for attempt in range(max_retries):
try:
client = await get_http_client()
res = await client.post(
"https://auth.tidal.com/v1/oauth2/token",
data={
"client_id": cred["client_id"],
"refresh_token": cred["refresh_token"],
"grant_type": "refresh_token",
"scope": "r_usr+w_usr+w_sub",
},
auth=(cred["client_id"], cred["client_secret"]),
)
_log_response("POST", "https://auth.tidal.com/v1/oauth2/token", res)
if res.status_code in [400, 401]:
try:
error_data = res.json()
if error_data.get("error") in ["invalid_client", "invalid_grant"]:
logger.error(f"Tidal Auth Error: {error_data}")
raise HTTPException(status_code=401, detail=f"Tidal Auth Error: {error_data.get('error_description')}")
except ValueError:
pass
res.raise_for_status()
data = res.json()
new_token = data["access_token"]
expires_in = data.get("expires_in", 3600)
cred["access_token"] = new_token
cred["expires_at"] = time.time() + expires_in - 60
return new_token
except httpx.RequestError as e:
if USE_PROXIES and attempt < max_retries - 1:
logger.warning(f"Proxy failed during token refresh: {e}. Healing proxy...")
await update_global_client(force_new_proxy=True)
continue
raise HTTPException(status_code=401, detail=f"Token refresh failed: {str(e)}")
except httpx.HTTPStatusError as e:
if USE_PROXIES and e.response.status_code in [403, 429] and attempt < max_retries - 1:
logger.warning(f"Proxy blocked during token refresh ({e.response.status_code}). Healing proxy...")
await update_global_client(force_new_proxy=True)
continue
raise HTTPException(status_code=401, detail=f"Token refresh failed: {str(e)}")
async def get_tidal_token(force_refresh: bool = False):
return await get_tidal_token_for_cred(force_refresh=force_refresh)
async def get_tidal_token_for_cred(force_refresh: bool = False, cred: Optional[dict] = None):
"""Retrieve an access token for a specific credential; pick random if not provided."""
cred = cred or _pick_credential()
if not force_refresh and cred["access_token"] and time.time() < cred["expires_at"]:
return cred["access_token"], cred
token = await refresh_tidal_token(cred)
return token, cred
async def make_request(url: str, token: Optional[str] = None, params: Optional[dict] = None, cred: Optional[dict] = None):
if token is None:
token, cred = await get_tidal_token_for_cred(cred=cred)
client = await get_http_client()
headers = {"authorization": f"Bearer {token}"}
try:
for attempt in range(_RATE_LIMIT_MAX_RETRIES + 1):
resp = await client.get(url, headers=headers, params=params)
_log_response("GET", url, resp)
if resp.status_code == 401:
token, cred = await get_tidal_token_for_cred(force_refresh=True, cred=cred)
headers = {"authorization": f"Bearer {token}"}
resp = await client.get(url, headers=headers, params=params)
_log_response("GET (retry after 401)", url, resp)
if resp.status_code == 429 and attempt < _RATE_LIMIT_MAX_RETRIES:
delay = min(_RATE_LIMIT_BASE_DELAY * (2 ** attempt), _RATE_LIMIT_MAX_DELAY)
retry_after = resp.headers.get("Retry-After")
if retry_after:
try:
delay = min(delay, max(float(retry_after), 0))
except ValueError:
pass
delay = min(delay, _RATE_LIMIT_MAX_DELAY)
logger.warning("Upstream 429 for %s, retrying in %.1fs (attempt %d/%d)", url, delay, attempt + 1, _RATE_LIMIT_MAX_RETRIES)
await asyncio.sleep(delay)
continue
if resp.status_code == 404:
fresh_token, fresh_cred = await get_tidal_token_for_cred(force_refresh=True, cred=cred)
if fresh_token != token:
headers = {"authorization": f"Bearer {fresh_token}"}
resp = await client.get(url, headers=headers, params=params)
_log_response("GET (retry after 404 token refresh)", url, resp)
token, cred = fresh_token, fresh_cred
break
resp.raise_for_status()
return {"version": API_VERSION, "data": resp.json()}
except httpx.HTTPStatusError as e:
logger.error(
"Upstream API error %s %s %s",
e.response.status_code,
url,
e.response.text[:1000],
exc_info=e,
)
raise HTTPException(status_code=e.response.status_code, detail="Upstream API error")
except httpx.RequestError as e:
if isinstance(e, httpx.TimeoutException):
raise HTTPException(status_code=429, detail="Upstream timeout")
raise HTTPException(status_code=503, detail="Connection error to Tidal")
async def authed_get_json(
url: str,
*,
params: Optional[dict] = None,
token: Optional[str] = None,
cred: Optional[dict] = None,
):
"""Perform an authenticated GET, retrying once on 401. Returns payload with updated token/cred."""
if token is None:
token, cred = await get_tidal_token_for_cred(cred=cred)
client = await get_http_client()
headers = {"authorization": f"Bearer {token}"}
try:
for attempt in range(_RATE_LIMIT_MAX_RETRIES + 1):
resp = await client.get(url, headers=headers, params=params)
_log_response("GET", url, resp)
if resp.status_code == 401:
token, cred = await get_tidal_token_for_cred(force_refresh=True, cred=cred)
headers["authorization"] = f"Bearer {token}"
resp = await client.get(url, headers=headers, params=params)
_log_response("GET (retry after 401)", url, resp)
if resp.status_code == 429 and attempt < _RATE_LIMIT_MAX_RETRIES:
delay = min(_RATE_LIMIT_BASE_DELAY * (2 ** attempt), _RATE_LIMIT_MAX_DELAY)
retry_after = resp.headers.get("Retry-After")
if retry_after:
try:
delay = min(delay, max(float(retry_after), 0))
except ValueError:
pass
delay = min(delay, _RATE_LIMIT_MAX_DELAY)
logger.warning("Upstream 429 for %s, retrying in %.1fs (attempt %d/%d)", url, delay, attempt + 1, _RATE_LIMIT_MAX_RETRIES)
await asyncio.sleep(delay)
continue
if resp.status_code == 404:
fresh_token, fresh_cred = await get_tidal_token_for_cred(force_refresh=True, cred=cred)
if fresh_token != token:
headers["authorization"] = f"Bearer {fresh_token}"
resp = await client.get(url, headers=headers, params=params)
_log_response("GET (retry after 404 token refresh)", url, resp)
token, cred = fresh_token, fresh_cred
break
resp.raise_for_status()
return resp.json(), token, cred
except httpx.HTTPStatusError as e:
logger.error(
"Upstream API error %s %s %s",
e.response.status_code,
url,
e.response.text[:1000],
exc_info=e,
)
raise HTTPException(status_code=e.response.status_code, detail="Upstream API error")
except httpx.RequestError as e:
if isinstance(e, httpx.TimeoutException):
raise HTTPException(status_code=429, detail="Upstream timeout")
raise HTTPException(status_code=503, detail="Connection error to Tidal")
@app.get("/")
async def index():
return {"version": API_VERSION, "Repo": "https://github.com/binimum/hifi-api"}
@app.get("/info/")
async def get_info(id: int):
url = f"https://api.tidal.com/v1/tracks/{id}/"
return await make_request(url, params={"countryCode": COUNTRY_CODE})
@app.get("/track/")
async def get_track(id: int, quality: str = "HI_RES_LOSSLESS", immersiveaudio: bool = False):
track_url = f"https://api.tidal.com/v1/tracks/{id}/playbackinfo"
params = {
"audioquality": quality,
"playbackmode": "STREAM",
"assetpresentation": "FULL",
"immersiveaudio": immersiveaudio
}
return await make_request(track_url, params=params)
@app.get("/trackManifests/")
async def get_track_manifests(
id: str,
request: Request,
formats: List[str] = Query(default=["HEAACV1", "AACLC", "FLAC", "FLAC_HIRES", "EAC3_JOC"]),
adaptive: str = Query(default="true"),
manifestType: str = Query(default="MPEG_DASH"),
uriScheme: str = Query(default="HTTPS"),
usage: str = Query(default="PLAYBACK")
):
url = f"https://openapi.tidal.com/v2/trackManifests/{id}"
params = [
("adaptive", adaptive),
("manifestType", manifestType),
("uriScheme", uriScheme),
("usage", usage),
]
for f in formats:
params.append(("formats", f))
res = await make_request(url, params=params)
try:
drm_data = res["data"]["data"]["attributes"]["drmData"]
if drm_data:
proxy_url = str(request.base_url).rstrip("/") + "/widevine"
drm_data["licenseUrl"] = proxy_url
drm_data["certificateUrl"] = proxy_url
except (KeyError, TypeError):
pass
return res
# Not really necessary but I'm including it anyway
@app.api_route("/widevine", methods=["GET", "POST"])
async def widevine_proxy(request: Request):
client = await get_http_client()
body = await request.body()
url = "https://api.tidal.com/v2/widevine"
token, cred = await get_tidal_token_for_cred()
headers = {
"authorization": f"Bearer {token}",
"Content-Type": request.headers.get("Content-Type", "application/octet-stream")
}
try:
resp = await client.request(request.method, url, headers=headers, content=body)
_log_response(request.method, url, resp)
if resp.status_code == 401:
token, cred = await get_tidal_token_for_cred(force_refresh=True, cred=cred)
headers["authorization"] = f"Bearer {token}"
resp = await client.request(request.method, url, headers=headers, content=body)
_log_response(f"{request.method} (retry)", url, resp)
return fastapi.Response(
content=resp.content,
status_code=resp.status_code,
headers={"Content-Type": resp.headers.get("Content-Type", "application/json")}
)
except Exception as e:
raise fastapi.HTTPException(status_code=502, detail="Error communicating with widevine server")
@app.get("/recommendations/")
async def get_recommendations(id: int):
recommendations_url = f"https://api.tidal.com/v1/tracks/{id}/recommendations"
params = {"limit": "20", "countryCode": COUNTRY_CODE}
return await make_request(recommendations_url, params=params)
@app.api_route("/search/", methods=["GET"])
async def search(
s: Union[str, None] = Query(default=None),
a: Union[str, None] = Query(default=None),
al: Union[str, None] = Query(default=None),
v: Union[str, None] = Query(default=None),
p: Union[str, None] = Query(default=None),
i: Union[str, None] = Query(default=None, description="ISRC query"),
offset: int = Query(default=0, ge=0),
limit: int = Query(default=25, ge=1, le=500),
):
"""Search endpoint supporting track/artist/album/video/playlist queries via distinct params."""
isrc_query = i.strip() if isinstance(i, str) else None
if isrc_query:
return await make_request(
"https://api.tidal.com/v1/tracks",
params={
"isrc": isrc_query,
"limit": limit,
"offset": offset,
"countryCode": COUNTRY_CODE,
},
)
queries = (
(s, "https://api.tidal.com/v1/search/tracks", {
"query": s,
"limit": limit,
"offset": offset,
"countryCode": COUNTRY_CODE,
}),
(a, "https://api.tidal.com/v1/search/top-hits", {
"query": a,
"limit": limit,
"offset": offset,
"types": "ARTISTS,TRACKS",
"countryCode": COUNTRY_CODE,
}),
(al, "https://api.tidal.com/v1/search/top-hits", {
"query": al,
"limit": limit,
"offset": offset,
"types": "ALBUMS",
"countryCode": COUNTRY_CODE,
}),
(v, "https://api.tidal.com/v1/search/top-hits", {
"query": v,
"limit": limit,
"offset": offset,
"types": "VIDEOS",
"countryCode": COUNTRY_CODE,
}),
(p, "https://api.tidal.com/v1/search/top-hits", {
"query": p,
"limit": limit,
"offset": offset,
"types": "PLAYLISTS",
"countryCode": COUNTRY_CODE,
}),
)
for value, url, params in queries:
if value:
return await make_request(url, params=params)
raise HTTPException(status_code=400, detail="Provide one of s, a, al, v, p, or i")
@app.get("/album/")
async def get_album(
id: int = Query(..., description="Album ID"),
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
):
token, cred = await get_tidal_token_for_cred()
album_url = f"https://api.tidal.com/v1/albums/{id}"
items_url = f"https://api.tidal.com/v1/albums/{id}/items"
async def fetch(url: str, params: Optional[dict] = None):
payload, _, _ = await authed_get_json(
url,
params=params,
token=token,
cred=cred,
)
return payload
tasks = [fetch(album_url, {"countryCode": COUNTRY_CODE})]
max_chunk = 100
current_offset = offset
remaining_limit = limit
while remaining_limit > 0:
chunk_size = min(remaining_limit, max_chunk)
tasks.append(
fetch(items_url, {"countryCode": COUNTRY_CODE, "limit": chunk_size, "offset": current_offset})
)
current_offset += chunk_size
remaining_limit -= chunk_size
results = await asyncio.gather(*tasks)
album_data = results[0]
items_pages = results[1:]
all_items = []
for page in items_pages:
page_items = page.get("items", page) if isinstance(page, dict) else page
if isinstance(page_items, list):
all_items.extend(page_items)
album_data["items"] = all_items
return {
"version": API_VERSION,
"data": album_data,
}
@app.get("/mix/")
async def get_mix(
id: str = Query(..., description="Mix ID")
):
"""Fetch items from a Tidal mix by its ID."""
token, cred = await get_tidal_token_for_cred()
url = "https://api.tidal.com/v1/pages/mix"
params = {
"mixId": id,
"countryCode": COUNTRY_CODE,
"deviceType": "BROWSER",
}
data, _, _ = await authed_get_json(
url,
params=params,
token=token,
cred=cred,
)
header = {}
items = []
rows = data.get("rows", [])
for row in rows:
modules = row.get("modules", [])
for module in modules:
if module.get("type") == "MIX_HEADER":
header = module.get("mix", {})
elif module.get("type") == "TRACK_LIST":
paged_list = module.get("pagedList", {})
items = paged_list.get("items", [])
return {
"version": API_VERSION,
"mix": header,
"items": [item.get("item", item) if isinstance(item, dict) else item for item in items],
}
@app.get("/playlist/")
async def get_playlist(
id: str = Query(..., min_length=1),
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
):
"""Fetch playlist metadata plus items concurrently, using shared client and single token."""
token, cred = await get_tidal_token_for_cred()
playlist_url = f"https://api.tidal.com/v1/playlists/{id}"
items_url = f"https://api.tidal.com/v1/playlists/{id}/items"
async def fetch(url: str, params: Optional[dict] = None):
payload, _, _ = await authed_get_json(
url,
params=params,
token=token,
cred=cred,
)
return payload
playlist_data, items_data = await asyncio.gather(
fetch(playlist_url, {"countryCode": COUNTRY_CODE}),
fetch(items_url, {"countryCode": COUNTRY_CODE, "limit": limit, "offset": offset}),
)
return {
"version": API_VERSION,
"playlist": playlist_data,
"items": items_data.get("items", items_data) if isinstance(items_data, dict) else items_data,
}
def _extract_uuid_from_tidal_url(href: str) -> Optional[str]:
"""Extract and reconstruct a hyphenated UUID from a Tidal resource URL."""
parts = href.split("/") if href else []
return "-".join(parts[4:9]) if len(parts) >= 9 else None
@app.get("/artist/similar/")
async def get_similar_artists(
id: int = Query(..., description="Artist ID"),
cursor: Union[int, str, None] = None
):
"""Fetch artists similar to another by its ID using V2 API."""
url = f"https://openapi.tidal.com/v2/artists/{id}/relationships/similarArtists"
params = {
"page[cursor]": cursor,
"countryCode": COUNTRY_CODE,
"include": "similarArtists,similarArtists.profileArt"
}
payload, _, _ = await authed_get_json(url, params=params)
included = payload.get("included", [])
artists_map = {i["id"]: i for i in included if i["type"] == "artists"}
artworks_map = {i["id"]: i for i in included if i["type"] == "artworks"}
def resolve_artist(entry):
aid = entry["id"]
inc = artists_map.get(aid, {})
attr = inc.get("attributes", {})
pic_id = None
if art_data := inc.get("relationships", {}).get("profileArt", {}).get("data"):
if artwork := artworks_map.get(art_data[0].get("id")):
if files := artwork.get("attributes", {}).get("files"):
pic_id = _extract_uuid_from_tidal_url(files[0].get("href"))
return {
**attr,
"id": int(aid) if str(aid).isdigit() else aid,
"picture": pic_id or attr.get("selectedAlbumCoverFallback"),
"url": f"http://www.tidal.com/artist/{aid}",
"relationType": "SIMILAR_ARTIST"
}
return {
"version": API_VERSION,
"artists": [resolve_artist(e) for e in payload.get("data", [])]
}
@app.get("/album/similar/")
async def get_similar_albums(
id: int = Query(..., description="Album ID"),
cursor: Union[int, str, None] = None
):
"""Fetch albums similar to another by its ID using V2 API."""
url = f"https://openapi.tidal.com/v2/albums/{id}/relationships/similarAlbums"
params = {
"page[cursor]": cursor,
"countryCode": COUNTRY_CODE,
"include": "similarAlbums,similarAlbums.coverArt,similarAlbums.artists"
}
payload, _, _ = await authed_get_json(url, params=params)
included = payload.get("included", [])
albums_map = {i["id"]: i for i in included if i["type"] == "albums"}
artworks_map = {i["id"]: i for i in included if i["type"] == "artworks"}
artists_map = {i["id"]: i for i in included if i["type"] == "artists"}
def resolve_album(entry):
aid = entry["id"]
inc = albums_map.get(aid, {})
attr = inc.get("attributes", {})
cover_id = None
if art_data := inc.get("relationships", {}).get("coverArt", {}).get("data"):
if artwork := artworks_map.get(art_data[0].get("id")):
if files := artwork.get("attributes", {}).get("files"):
cover_id = _extract_uuid_from_tidal_url(files[0].get("href"))
artist_list = []
if art_data := inc.get("relationships", {}).get("artists", {}).get("data"):
for a_entry in art_data:
if a_obj := artists_map.get(a_entry["id"]):
a_id = a_obj["id"]
artist_list.append({
"id": int(a_id) if str(a_id).isdigit() else a_id,
"name": a_obj["attributes"]["name"]
})
return {
**attr,
"id": int(aid) if str(aid).isdigit() else aid,
"cover": cover_id,
"artists": artist_list,
"url": f"http://www.tidal.com/album/{aid}"
}
return {
"version": API_VERSION,
"albums": [resolve_album(e) for e in payload.get("data", [])]
}
@app.get("/artist/")
async def get_artist(
id: Optional[int] = Query(default=None),
f: Optional[int] = Query(default=None),
skip_tracks: bool = Query(default=False),
):
"""Artist detail or album+track aggregation.
- id: basic artist metadata + cover URLs
- f: fetch artist albums page and aggregate tracks across albums (capped concurrency)
- skip_tracks: if true, returns only albums without aggregating tracks (when using 'f')
"""
if id is None and f is None:
raise HTTPException(status_code=400, detail="Provide id or f query param")
token, cred = await get_tidal_token_for_cred()
if id is not None:
artist_url = f"https://api.tidal.com/v1/artists/{id}"
artist_data, token, cred = await authed_get_json(
artist_url,
params={"countryCode": COUNTRY_CODE},
token=token,
cred=cred,
)
picture = artist_data.get("picture")
fallback = artist_data.get("selectedAlbumCoverFallback")
if not picture and fallback:
artist_data["picture"] = fallback
picture = fallback
cover = None
if picture:
slug = picture.replace("-", "/")
cover = {
"id": artist_data.get("id"),
"name": artist_data.get("name"),
"750": f"https://resources.tidal.com/images/{slug}/750x750.jpg",
}
return {"version": API_VERSION, "artist": artist_data, "cover": cover}
# Fetch albums and singles/EPs directly in parallel
albums_url = f"https://api.tidal.com/v1/artists/{f}/albums"
common_params = {"countryCode": COUNTRY_CODE, "limit": 100}
tasks = [
authed_get_json(albums_url, params=common_params, token=token, cred=cred),
authed_get_json(albums_url, params={**common_params, "filter": "EPSANDSINGLES"}, token=token, cred=cred),