Spaces:
Sleeping
Sleeping
Upload 9 files
Browse files- Dockerfile +11 -0
- LICENSE +22 -0
- api_test.py +111 -0
- docker-compose.yml +14 -0
- main.py +793 -0
- requirements.txt +8 -0
- tidal_auth/requirements.txt +4 -0
- tidal_auth/tidal_auth.py +200 -0
- token.json +9 -0
Dockerfile
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.13.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --upgrade pip && \
|
| 7 |
+
pip install --no-cache-dir -r requirements.txt
|
| 8 |
+
|
| 9 |
+
COPY . .
|
| 10 |
+
|
| 11 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
Copyright (c) 2023 sachin senal
|
| 5 |
+
|
| 6 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 7 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 8 |
+
in the Software without restriction, including without limitation the rights
|
| 9 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 10 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 11 |
+
furnished to do so, subject to the following conditions:
|
| 12 |
+
|
| 13 |
+
The above copyright notice and this permission notice shall be included in all
|
| 14 |
+
copies or substantial portions of the Software.
|
| 15 |
+
|
| 16 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 17 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 18 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 19 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 20 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 21 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 22 |
+
SOFTWARE.
|
api_test.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import curses
|
| 3 |
+
import time
|
| 4 |
+
import httpx
|
| 5 |
+
from collections import deque
|
| 6 |
+
|
| 7 |
+
# Configuration
|
| 8 |
+
URL = "http://localhost:8001/track/?id=194567102&quality=HI_RES_LOSSLESS" # Default URL
|
| 9 |
+
|
| 10 |
+
async def make_request(client, url, stats):
|
| 11 |
+
try:
|
| 12 |
+
start = time.time()
|
| 13 |
+
resp = await client.get(url)
|
| 14 |
+
latency = time.time() - start
|
| 15 |
+
stats['total'] += 1
|
| 16 |
+
stats['latency'].append(latency)
|
| 17 |
+
if len(stats['latency']) > 100:
|
| 18 |
+
stats['latency'].popleft()
|
| 19 |
+
|
| 20 |
+
if resp.status_code == 200:
|
| 21 |
+
stats['success'] += 1
|
| 22 |
+
else:
|
| 23 |
+
stats['fail'] += 1
|
| 24 |
+
stats['last_error'] = f"Status {resp.status_code}"
|
| 25 |
+
except Exception as e:
|
| 26 |
+
stats['total'] += 1
|
| 27 |
+
stats['fail'] += 1
|
| 28 |
+
stats['last_error'] = str(e)
|
| 29 |
+
|
| 30 |
+
async def worker(stdscr):
|
| 31 |
+
# Setup curses
|
| 32 |
+
curses.curs_set(0)
|
| 33 |
+
stdscr.nodelay(True)
|
| 34 |
+
|
| 35 |
+
# State
|
| 36 |
+
rate = 100 # Requests per second
|
| 37 |
+
stats = {
|
| 38 |
+
'total': 0,
|
| 39 |
+
'success': 0,
|
| 40 |
+
'fail': 0,
|
| 41 |
+
'latency': deque(),
|
| 42 |
+
'last_error': "None"
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
# Async client
|
| 46 |
+
async with httpx.AsyncClient() as client:
|
| 47 |
+
last_check = time.time()
|
| 48 |
+
tokens = 0.0
|
| 49 |
+
|
| 50 |
+
while True:
|
| 51 |
+
# Handle Input
|
| 52 |
+
try:
|
| 53 |
+
key = stdscr.getch()
|
| 54 |
+
if key == curses.KEY_UP:
|
| 55 |
+
rate += 1
|
| 56 |
+
elif key == curses.KEY_DOWN:
|
| 57 |
+
rate = max(1, rate - 1)
|
| 58 |
+
elif key == curses.KEY_RIGHT:
|
| 59 |
+
rate += 10
|
| 60 |
+
elif key == curses.KEY_LEFT:
|
| 61 |
+
rate = max(1, rate - 10)
|
| 62 |
+
elif key == ord('q'):
|
| 63 |
+
break
|
| 64 |
+
except:
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
# Update tokens based on time passed
|
| 68 |
+
now = time.time()
|
| 69 |
+
dt = now - last_check
|
| 70 |
+
last_check = now
|
| 71 |
+
|
| 72 |
+
tokens += dt * rate
|
| 73 |
+
|
| 74 |
+
# Cap tokens to avoid massive bursts if we stall
|
| 75 |
+
if tokens > rate:
|
| 76 |
+
tokens = rate
|
| 77 |
+
|
| 78 |
+
# Spend tokens
|
| 79 |
+
while tokens >= 1.0:
|
| 80 |
+
asyncio.create_task(make_request(client, URL, stats))
|
| 81 |
+
tokens -= 1.0
|
| 82 |
+
|
| 83 |
+
# Draw UI
|
| 84 |
+
try:
|
| 85 |
+
stdscr.erase()
|
| 86 |
+
stdscr.addstr(0, 0, f"API Spammer - Target: {URL}")
|
| 87 |
+
stdscr.addstr(2, 0, f"Target Rate: {rate} req/s (Arrows to adjust)")
|
| 88 |
+
stdscr.addstr(4, 0, f"Total Requests: {stats['total']}")
|
| 89 |
+
stdscr.addstr(5, 0, f"Success: {stats['success']}")
|
| 90 |
+
stdscr.addstr(6, 0, f"Failed: {stats['fail']}")
|
| 91 |
+
|
| 92 |
+
avg_lat = 0
|
| 93 |
+
if stats['latency']:
|
| 94 |
+
avg_lat = sum(stats['latency']) / len(stats['latency']) * 1000
|
| 95 |
+
stdscr.addstr(7, 0, f"Avg Latency (last 100): {avg_lat:.2f} ms")
|
| 96 |
+
stdscr.addstr(8, 0, f"Last Error: {stats['last_error']}")
|
| 97 |
+
stdscr.addstr(10, 0, "Press 'q' to quit")
|
| 98 |
+
stdscr.refresh()
|
| 99 |
+
except curses.error:
|
| 100 |
+
pass # Ignore resize errors etc
|
| 101 |
+
|
| 102 |
+
await asyncio.sleep(0.01)
|
| 103 |
+
|
| 104 |
+
def main(stdscr):
|
| 105 |
+
try:
|
| 106 |
+
asyncio.run(worker(stdscr))
|
| 107 |
+
except KeyboardInterrupt:
|
| 108 |
+
pass
|
| 109 |
+
|
| 110 |
+
if __name__ == "__main__":
|
| 111 |
+
curses.wrapper(main)
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
web:
|
| 3 |
+
build: .
|
| 4 |
+
env_file:
|
| 5 |
+
- .env
|
| 6 |
+
ports:
|
| 7 |
+
- "0.0.0.0:8000:8000"
|
| 8 |
+
volumes:
|
| 9 |
+
- ./token.json:/app/token.json:ro
|
| 10 |
+
restart: unless-stopped
|
| 11 |
+
|
| 12 |
+
networks:
|
| 13 |
+
default:
|
| 14 |
+
driver: bridge
|
main.py
ADDED
|
@@ -0,0 +1,793 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import asyncio
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
import time
|
| 7 |
+
from contextlib import asynccontextmanager
|
| 8 |
+
from typing import Dict, List, Optional, Union
|
| 9 |
+
|
| 10 |
+
import httpx
|
| 11 |
+
import uvicorn
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
from fastapi import FastAPI, HTTPException, Query, Request
|
| 14 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 15 |
+
|
| 16 |
+
import logging
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
load_dotenv()
|
| 21 |
+
|
| 22 |
+
# Shared HTTP client is created in app lifespan for connection reuse
|
| 23 |
+
_http_client: Optional[httpx.AsyncClient] = None
|
| 24 |
+
|
| 25 |
+
# One lock per credential to avoid global contention during token refreshes
|
| 26 |
+
_refresh_locks: Dict[str, asyncio.Lock] = {}
|
| 27 |
+
|
| 28 |
+
# Loaded credential set from token.json; each entry will be enriched with access cache
|
| 29 |
+
_creds: List[dict] = []
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@asynccontextmanager
|
| 33 |
+
async def lifespan(app: FastAPI):
|
| 34 |
+
global _http_client
|
| 35 |
+
_http_client = httpx.AsyncClient(
|
| 36 |
+
http2=True,
|
| 37 |
+
timeout=httpx.Timeout(connect=3.0, read=12.0, write=8.0, pool=12.0),
|
| 38 |
+
limits=httpx.Limits(
|
| 39 |
+
max_keepalive_connections=200,
|
| 40 |
+
max_connections=300,
|
| 41 |
+
keepalive_expiry=30.0,
|
| 42 |
+
),
|
| 43 |
+
)
|
| 44 |
+
try:
|
| 45 |
+
yield
|
| 46 |
+
finally:
|
| 47 |
+
if _http_client:
|
| 48 |
+
await _http_client.aclose()
|
| 49 |
+
|
| 50 |
+
API_VERSION = "2.4"
|
| 51 |
+
|
| 52 |
+
app = FastAPI(
|
| 53 |
+
title="HiFi-RestAPI",
|
| 54 |
+
version=API_VERSION,
|
| 55 |
+
description="Tidal Music Proxy",
|
| 56 |
+
lifespan=lifespan,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
app.add_middleware(
|
| 60 |
+
CORSMiddleware,
|
| 61 |
+
allow_origins=["*"],
|
| 62 |
+
allow_credentials=True,
|
| 63 |
+
allow_methods=["*"],
|
| 64 |
+
allow_headers=["*"],
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Config (defaults act as fallback if token file missing)
|
| 69 |
+
CLIENT_ID = os.getenv("CLIENT_ID", "zU4XHVVkc2tDPo4t")
|
| 70 |
+
CLIENT_SECRET = os.getenv("CLIENT_SECRET", "VJKhDFqJPqvsPVNBV6ukXTJmwlvbttP7wlMlrc72se4=")
|
| 71 |
+
REFRESH_TOKEN: Optional[str] = os.getenv("REFRESH_TOKEN")
|
| 72 |
+
USER_ID = os.getenv("USER_ID")
|
| 73 |
+
TOKEN_FILE = os.getenv("TOKEN_FILE", "token.json")
|
| 74 |
+
COUNTRY_CODE = os.getenv("COUNTRY_CODE", "US")
|
| 75 |
+
|
| 76 |
+
if os.path.exists(TOKEN_FILE):
|
| 77 |
+
with open(TOKEN_FILE, "r") as tok:
|
| 78 |
+
token_data = json.load(tok)
|
| 79 |
+
if isinstance(token_data, dict):
|
| 80 |
+
token_data = [token_data]
|
| 81 |
+
|
| 82 |
+
for entry in token_data:
|
| 83 |
+
cred = {
|
| 84 |
+
"client_id": entry.get("client_ID") or CLIENT_ID,
|
| 85 |
+
"client_secret": entry.get("client_secret") or CLIENT_SECRET,
|
| 86 |
+
"refresh_token": entry.get("refresh_token") or REFRESH_TOKEN,
|
| 87 |
+
"user_id": entry.get("userID") or USER_ID,
|
| 88 |
+
# Access tokens in file have unknown expiry; force refresh on first use
|
| 89 |
+
"access_token": None,
|
| 90 |
+
"expires_at": 0,
|
| 91 |
+
}
|
| 92 |
+
if cred["refresh_token"]:
|
| 93 |
+
_creds.append(cred)
|
| 94 |
+
|
| 95 |
+
# Add env var credential if available and unique (simple check)
|
| 96 |
+
if REFRESH_TOKEN:
|
| 97 |
+
env_cred = {
|
| 98 |
+
"client_id": CLIENT_ID,
|
| 99 |
+
"client_secret": CLIENT_SECRET,
|
| 100 |
+
"refresh_token": REFRESH_TOKEN,
|
| 101 |
+
"user_id": USER_ID,
|
| 102 |
+
"access_token": None,
|
| 103 |
+
"expires_at": 0,
|
| 104 |
+
}
|
| 105 |
+
# Avoid adding duplicate if it was already loaded from file with same refresh token
|
| 106 |
+
if not any(c["refresh_token"] == REFRESH_TOKEN for c in _creds):
|
| 107 |
+
_creds.append(env_cred)
|
| 108 |
+
|
| 109 |
+
if _creds:
|
| 110 |
+
CLIENT_ID = _creds[0]["client_id"]
|
| 111 |
+
CLIENT_SECRET = _creds[0]["client_secret"]
|
| 112 |
+
REFRESH_TOKEN = _creds[0]["refresh_token"]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _pick_credential() -> dict:
|
| 116 |
+
if not _creds:
|
| 117 |
+
raise HTTPException(status_code=500, detail="No Tidal credentials available; populate token.json")
|
| 118 |
+
return random.choice(_creds)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _lock_for_cred(cred: dict) -> asyncio.Lock:
|
| 122 |
+
key = f"{cred['client_id']}:{cred['refresh_token']}"
|
| 123 |
+
lock = _refresh_locks.get(key)
|
| 124 |
+
if lock is None:
|
| 125 |
+
lock = asyncio.Lock()
|
| 126 |
+
_refresh_locks[key] = lock
|
| 127 |
+
return lock
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
async def get_http_client() -> httpx.AsyncClient:
|
| 131 |
+
if _http_client is None:
|
| 132 |
+
# Fallback for contexts where lifespan is not run (e.g., direct calls)
|
| 133 |
+
return httpx.AsyncClient(http2=True)
|
| 134 |
+
return _http_client
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
async def refresh_tidal_token(cred: Optional[dict] = None):
|
| 138 |
+
"""Refresh a token for the provided credential set."""
|
| 139 |
+
cred = cred or _pick_credential()
|
| 140 |
+
|
| 141 |
+
async with _lock_for_cred(cred):
|
| 142 |
+
if cred["access_token"] and time.time() < cred["expires_at"]:
|
| 143 |
+
return cred["access_token"]
|
| 144 |
+
|
| 145 |
+
try:
|
| 146 |
+
client = await get_http_client()
|
| 147 |
+
res = await client.post(
|
| 148 |
+
"https://auth.tidal.com/v1/oauth2/token",
|
| 149 |
+
data={
|
| 150 |
+
"client_id": cred["client_id"],
|
| 151 |
+
"refresh_token": cred["refresh_token"],
|
| 152 |
+
"grant_type": "refresh_token",
|
| 153 |
+
"scope": "r_usr+w_usr+w_sub",
|
| 154 |
+
},
|
| 155 |
+
auth=(cred["client_id"], cred["client_secret"]),
|
| 156 |
+
)
|
| 157 |
+
res.raise_for_status()
|
| 158 |
+
data = res.json()
|
| 159 |
+
new_token = data["access_token"]
|
| 160 |
+
expires_in = data.get("expires_in", 3600)
|
| 161 |
+
|
| 162 |
+
cred["access_token"] = new_token
|
| 163 |
+
cred["expires_at"] = time.time() + expires_in - 60
|
| 164 |
+
|
| 165 |
+
return new_token
|
| 166 |
+
except httpx.HTTPError as e:
|
| 167 |
+
raise HTTPException(status_code=401, detail=f"Token refresh failed: {str(e)}")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
async def get_tidal_token(force_refresh: bool = False):
|
| 171 |
+
return await get_tidal_token_for_cred(force_refresh=force_refresh)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
async def get_tidal_token_for_cred(force_refresh: bool = False, cred: Optional[dict] = None):
|
| 175 |
+
"""Retrieve an access token for a specific credential; pick random if not provided."""
|
| 176 |
+
cred = cred or _pick_credential()
|
| 177 |
+
|
| 178 |
+
if not force_refresh and cred["access_token"] and time.time() < cred["expires_at"]:
|
| 179 |
+
return cred["access_token"], cred
|
| 180 |
+
|
| 181 |
+
token = await refresh_tidal_token(cred)
|
| 182 |
+
return token, cred
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
async def make_request(url: str, token: Optional[str] = None, params: Optional[dict] = None, cred: Optional[dict] = None):
|
| 186 |
+
if token is None:
|
| 187 |
+
token, cred = await get_tidal_token_for_cred(cred=cred)
|
| 188 |
+
client = await get_http_client()
|
| 189 |
+
headers = {"authorization": f"Bearer {token}"}
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
resp = await client.get(url, headers=headers, params=params)
|
| 193 |
+
|
| 194 |
+
if resp.status_code == 401:
|
| 195 |
+
# Token expired, refresh and retry
|
| 196 |
+
token, cred = await get_tidal_token_for_cred(force_refresh=True, cred=cred)
|
| 197 |
+
headers = {"authorization": f"Bearer {token}"}
|
| 198 |
+
resp = await client.get(url, headers=headers, params=params)
|
| 199 |
+
|
| 200 |
+
resp.raise_for_status()
|
| 201 |
+
return {"version": API_VERSION, "data": resp.json()}
|
| 202 |
+
except httpx.HTTPStatusError as e:
|
| 203 |
+
if e.response.status_code == 404:
|
| 204 |
+
raise HTTPException(status_code=404, detail="Resource not found")
|
| 205 |
+
else:
|
| 206 |
+
logger.error(
|
| 207 |
+
"Upstream API error %s %s %s",
|
| 208 |
+
e.response.status_code,
|
| 209 |
+
url,
|
| 210 |
+
e.response.text,
|
| 211 |
+
exc_info=e,
|
| 212 |
+
)
|
| 213 |
+
raise HTTPException(status_code=e.response.status_code, detail="Upstream API error")
|
| 214 |
+
except httpx.RequestError as e:
|
| 215 |
+
if isinstance(e, httpx.TimeoutException):
|
| 216 |
+
raise HTTPException(status_code=429, detail="Upstream timeout")
|
| 217 |
+
raise HTTPException(status_code=503, detail="Connection error to Tidal")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
async def authed_get_json(
|
| 221 |
+
url: str,
|
| 222 |
+
*,
|
| 223 |
+
params: Optional[dict] = None,
|
| 224 |
+
token: Optional[str] = None,
|
| 225 |
+
cred: Optional[dict] = None,
|
| 226 |
+
):
|
| 227 |
+
"""Perform an authenticated GET, retrying once on 401. Returns payload with updated token/cred."""
|
| 228 |
+
|
| 229 |
+
if token is None:
|
| 230 |
+
token, cred = await get_tidal_token_for_cred(cred=cred)
|
| 231 |
+
|
| 232 |
+
client = await get_http_client()
|
| 233 |
+
headers = {"authorization": f"Bearer {token}"}
|
| 234 |
+
|
| 235 |
+
try:
|
| 236 |
+
resp = await client.get(url, headers=headers, params=params)
|
| 237 |
+
|
| 238 |
+
if resp.status_code == 401:
|
| 239 |
+
token, cred = await get_tidal_token_for_cred(force_refresh=True, cred=cred)
|
| 240 |
+
headers["authorization"] = f"Bearer {token}"
|
| 241 |
+
resp = await client.get(url, headers=headers, params=params)
|
| 242 |
+
|
| 243 |
+
resp.raise_for_status()
|
| 244 |
+
return resp.json(), token, cred
|
| 245 |
+
except httpx.HTTPStatusError as e:
|
| 246 |
+
if e.response.status_code == 404:
|
| 247 |
+
raise HTTPException(status_code=404, detail="Resource not found")
|
| 248 |
+
if e.response.status_code == 429:
|
| 249 |
+
raise HTTPException(status_code=429, detail="Upstream rate limited")
|
| 250 |
+
raise HTTPException(status_code=e.response.status_code, detail="Upstream API error")
|
| 251 |
+
except httpx.RequestError as e:
|
| 252 |
+
if isinstance(e, httpx.TimeoutException):
|
| 253 |
+
raise HTTPException(status_code=429, detail="Upstream timeout")
|
| 254 |
+
raise HTTPException(status_code=503, detail="Connection error to Tidal")
|
| 255 |
+
|
| 256 |
+
@app.get("/")
|
| 257 |
+
async def index():
|
| 258 |
+
return {"version": API_VERSION, "Repo": "https://github.com/uimaxbai/hifi-api"}
|
| 259 |
+
|
| 260 |
+
@app.get("/info/")
|
| 261 |
+
async def get_info(id: int):
|
| 262 |
+
url = f"https://api.tidal.com/v1/tracks/{id}/"
|
| 263 |
+
return await make_request(url, params={"countryCode": COUNTRY_CODE})
|
| 264 |
+
|
| 265 |
+
@app.get("/track/")
|
| 266 |
+
async def get_track(id: int, quality: str = "HI_RES_LOSSLESS"):
|
| 267 |
+
track_url = f"https://tidal.com/v1/tracks/{id}/playbackinfo"
|
| 268 |
+
params = {
|
| 269 |
+
"audioquality": quality,
|
| 270 |
+
"playbackmode": "STREAM",
|
| 271 |
+
"assetpresentation": "FULL",
|
| 272 |
+
}
|
| 273 |
+
return await make_request(track_url, params=params)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@app.get("/recommendations/")
|
| 277 |
+
async def get_recommendations(id: int):
|
| 278 |
+
recommendations_url = f"https://tidal.com/v1/tracks/{id}/recommendations"
|
| 279 |
+
params = {"limit": "20", "countryCode": "US"}
|
| 280 |
+
return await make_request(recommendations_url, params=params)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
@app.api_route("/search/", methods=["GET"])
|
| 284 |
+
async def search(
|
| 285 |
+
s: Union[str, None] = Query(default=None),
|
| 286 |
+
a: Union[str, None] = Query(default=None),
|
| 287 |
+
al: Union[str, None] = Query(default=None),
|
| 288 |
+
v: Union[str, None] = Query(default=None),
|
| 289 |
+
p: Union[str, None] = Query(default=None),
|
| 290 |
+
):
|
| 291 |
+
"""Search endpoint supporting track/artist/album/video/playlist queries via distinct params."""
|
| 292 |
+
queries = (
|
| 293 |
+
(s, "https://api.tidal.com/v1/search/tracks", {
|
| 294 |
+
"query": s,
|
| 295 |
+
"limit": 25,
|
| 296 |
+
"offset": 0,
|
| 297 |
+
"countryCode": COUNTRY_CODE,
|
| 298 |
+
}),
|
| 299 |
+
(a, "https://api.tidal.com/v1/search/top-hits", {
|
| 300 |
+
"query": a,
|
| 301 |
+
"limit": 25,
|
| 302 |
+
"offset": 0,
|
| 303 |
+
"types": "ARTISTS,TRACKS",
|
| 304 |
+
"countryCode": COUNTRY_CODE,
|
| 305 |
+
}),
|
| 306 |
+
(al, "https://api.tidal.com/v1/search/top-hits", {
|
| 307 |
+
"query": al,
|
| 308 |
+
"limit": 25,
|
| 309 |
+
"offset": 0,
|
| 310 |
+
"types": "ALBUMS",
|
| 311 |
+
"countryCode": COUNTRY_CODE,
|
| 312 |
+
}),
|
| 313 |
+
(v, "https://api.tidal.com/v1/search/top-hits", {
|
| 314 |
+
"query": v,
|
| 315 |
+
"limit": 25,
|
| 316 |
+
"offset": 0,
|
| 317 |
+
"types": "VIDEOS",
|
| 318 |
+
"countryCode": COUNTRY_CODE,
|
| 319 |
+
}),
|
| 320 |
+
(p, "https://api.tidal.com/v1/search/top-hits", {
|
| 321 |
+
"query": p,
|
| 322 |
+
"limit": 25,
|
| 323 |
+
"offset": 0,
|
| 324 |
+
"types": "PLAYLISTS",
|
| 325 |
+
"countryCode": COUNTRY_CODE,
|
| 326 |
+
}),
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
for value, url, params in queries:
|
| 330 |
+
if value:
|
| 331 |
+
return await make_request(url, params=params)
|
| 332 |
+
|
| 333 |
+
raise HTTPException(status_code=400, detail="Provide one of s, a, al, v, or p")
|
| 334 |
+
|
| 335 |
+
@app.get("/album/")
|
| 336 |
+
async def get_album(
|
| 337 |
+
id: int = Query(..., description="Album ID"),
|
| 338 |
+
limit: int = Query(100, ge=1, le=500),
|
| 339 |
+
offset: int = Query(0, ge=0),
|
| 340 |
+
):
|
| 341 |
+
token, cred = await get_tidal_token_for_cred()
|
| 342 |
+
|
| 343 |
+
album_url = f"https://api.tidal.com/v1/albums/{id}"
|
| 344 |
+
items_url = f"https://api.tidal.com/v1/albums/{id}/items"
|
| 345 |
+
|
| 346 |
+
async def fetch(url: str, params: Optional[dict] = None):
|
| 347 |
+
nonlocal token, cred
|
| 348 |
+
payload, token, cred = await authed_get_json(
|
| 349 |
+
url,
|
| 350 |
+
params=params,
|
| 351 |
+
token=token,
|
| 352 |
+
cred=cred,
|
| 353 |
+
)
|
| 354 |
+
return payload
|
| 355 |
+
|
| 356 |
+
tasks = [fetch(album_url, {"countryCode": COUNTRY_CODE})]
|
| 357 |
+
|
| 358 |
+
max_chunk = 100
|
| 359 |
+
current_offset = offset
|
| 360 |
+
remaining_limit = limit
|
| 361 |
+
|
| 362 |
+
while remaining_limit > 0:
|
| 363 |
+
chunk_size = min(remaining_limit, max_chunk)
|
| 364 |
+
tasks.append(
|
| 365 |
+
fetch(items_url, {"countryCode": COUNTRY_CODE, "limit": chunk_size, "offset": current_offset})
|
| 366 |
+
)
|
| 367 |
+
current_offset += chunk_size
|
| 368 |
+
remaining_limit -= chunk_size
|
| 369 |
+
|
| 370 |
+
results = await asyncio.gather(*tasks)
|
| 371 |
+
|
| 372 |
+
album_data = results[0]
|
| 373 |
+
items_pages = results[1:]
|
| 374 |
+
|
| 375 |
+
all_items = []
|
| 376 |
+
for page in items_pages:
|
| 377 |
+
page_items = page.get("items", page)
|
| 378 |
+
all_items.extend(page_items)
|
| 379 |
+
|
| 380 |
+
album_data["items"] = all_items
|
| 381 |
+
|
| 382 |
+
return {
|
| 383 |
+
"version": API_VERSION,
|
| 384 |
+
"data": album_data,
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
@app.get("/mix/")
|
| 389 |
+
async def get_mix(
|
| 390 |
+
id: str = Query(..., description="Mix ID")
|
| 391 |
+
):
|
| 392 |
+
"""Fetch items from a Tidal mix by its ID."""
|
| 393 |
+
token, cred = await get_tidal_token_for_cred()
|
| 394 |
+
url = "https://api.tidal.com/v1/pages/mix"
|
| 395 |
+
params = {
|
| 396 |
+
"mixId": id,
|
| 397 |
+
"countryCode": COUNTRY_CODE,
|
| 398 |
+
"deviceType": "BROWSER",
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
data, _, _ = await authed_get_json(
|
| 402 |
+
url,
|
| 403 |
+
params=params,
|
| 404 |
+
token=token,
|
| 405 |
+
cred=cred,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
header = {}
|
| 409 |
+
items = []
|
| 410 |
+
|
| 411 |
+
rows = data.get("rows", [])
|
| 412 |
+
for row in rows:
|
| 413 |
+
modules = row.get("modules", [])
|
| 414 |
+
for module in modules:
|
| 415 |
+
if module.get("type") == "MIX_HEADER":
|
| 416 |
+
header = module.get("mix", {})
|
| 417 |
+
elif module.get("type") == "TRACK_LIST":
|
| 418 |
+
paged_list = module.get("pagedList", {})
|
| 419 |
+
items = paged_list.get("items", [])
|
| 420 |
+
|
| 421 |
+
return {
|
| 422 |
+
"version": API_VERSION,
|
| 423 |
+
"mix": header,
|
| 424 |
+
"items": [item.get("item", item) for item in items],
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
@app.get("/playlist/")
|
| 429 |
+
async def get_playlist(
|
| 430 |
+
id: str = Query(..., min_length=1),
|
| 431 |
+
limit: int = Query(100, ge=1, le=500),
|
| 432 |
+
offset: int = Query(0, ge=0),
|
| 433 |
+
):
|
| 434 |
+
"""Fetch playlist metadata plus items concurrently, using shared client and single token."""
|
| 435 |
+
|
| 436 |
+
token, cred = await get_tidal_token_for_cred()
|
| 437 |
+
|
| 438 |
+
playlist_url = f"https://api.tidal.com/v1/playlists/{id}"
|
| 439 |
+
items_url = f"https://api.tidal.com/v1/playlists/{id}/items"
|
| 440 |
+
|
| 441 |
+
async def fetch(url: str, params: Optional[dict] = None):
|
| 442 |
+
nonlocal token, cred
|
| 443 |
+
payload, token, cred = await authed_get_json(
|
| 444 |
+
url,
|
| 445 |
+
params=params,
|
| 446 |
+
token=token,
|
| 447 |
+
cred=cred,
|
| 448 |
+
)
|
| 449 |
+
return payload
|
| 450 |
+
|
| 451 |
+
playlist_data, items_data = await asyncio.gather(
|
| 452 |
+
fetch(playlist_url, {"countryCode": COUNTRY_CODE}),
|
| 453 |
+
fetch(items_url, {"countryCode": COUNTRY_CODE, "limit": limit, "offset": offset}),
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
return {
|
| 457 |
+
"version": API_VERSION,
|
| 458 |
+
"playlist": playlist_data,
|
| 459 |
+
"items": items_data.get("items", items_data),
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def _extract_uuid_from_tidal_url(href: str) -> Optional[str]:
|
| 464 |
+
"""Extract and reconstruct a hyphenated UUID from a Tidal resource URL."""
|
| 465 |
+
parts = href.split("/") if href else []
|
| 466 |
+
return "-".join(parts[4:9]) if len(parts) >= 9 else None
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
@app.get("/artist/similar/")
|
| 470 |
+
async def get_similar_artists(
|
| 471 |
+
id: int = Query(..., description="Artist ID"),
|
| 472 |
+
cursor: Union[int, str, None] = None
|
| 473 |
+
):
|
| 474 |
+
"""Fetch artists similar to another by its ID using V2 API."""
|
| 475 |
+
url = f"https://openapi.tidal.com/v2/artists/{id}/relationships/similarArtists"
|
| 476 |
+
params = {
|
| 477 |
+
"page[cursor]": cursor,
|
| 478 |
+
"countryCode": COUNTRY_CODE,
|
| 479 |
+
"include": "similarArtists,similarArtists.profileArt"
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
payload, _, _ = await authed_get_json(url, params=params)
|
| 483 |
+
included = payload.get("included", [])
|
| 484 |
+
artists_map = {i["id"]: i for i in included if i["type"] == "artists"}
|
| 485 |
+
artworks_map = {i["id"]: i for i in included if i["type"] == "artworks"}
|
| 486 |
+
|
| 487 |
+
def resolve_artist(entry):
|
| 488 |
+
aid = entry["id"]
|
| 489 |
+
inc = artists_map.get(aid, {})
|
| 490 |
+
attr = inc.get("attributes", {})
|
| 491 |
+
|
| 492 |
+
pic_id = None
|
| 493 |
+
if art_data := inc.get("relationships", {}).get("profileArt", {}).get("data"):
|
| 494 |
+
if artwork := artworks_map.get(art_data[0].get("id")):
|
| 495 |
+
if files := artwork.get("attributes", {}).get("files"):
|
| 496 |
+
pic_id = _extract_uuid_from_tidal_url(files[0].get("href"))
|
| 497 |
+
|
| 498 |
+
return {
|
| 499 |
+
**attr,
|
| 500 |
+
"id": int(aid) if aid.isdigit() else aid,
|
| 501 |
+
"picture": pic_id or attr.get("selectedAlbumCoverFallback"),
|
| 502 |
+
"url": f"http://www.tidal.com/artist/{aid}",
|
| 503 |
+
"relationType": "SIMILAR_ARTIST"
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
return {
|
| 507 |
+
"version": API_VERSION,
|
| 508 |
+
"artists": [resolve_artist(e) for e in payload.get("data", [])]
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
@app.get("/album/similar/")
|
| 513 |
+
async def get_similar_albums(
|
| 514 |
+
id: int = Query(..., description="Album ID"),
|
| 515 |
+
cursor: Union[int, str, None] = None
|
| 516 |
+
):
|
| 517 |
+
"""Fetch albums similar to another by its ID using V2 API."""
|
| 518 |
+
url = f"https://openapi.tidal.com/v2/albums/{id}/relationships/similarAlbums"
|
| 519 |
+
params = {
|
| 520 |
+
"page[cursor]": cursor,
|
| 521 |
+
"countryCode": COUNTRY_CODE,
|
| 522 |
+
"include": "similarAlbums,similarAlbums.coverArt,similarAlbums.artists"
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
payload, _, _ = await authed_get_json(url, params=params)
|
| 526 |
+
included = payload.get("included", [])
|
| 527 |
+
albums_map = {i["id"]: i for i in included if i["type"] == "albums"}
|
| 528 |
+
artworks_map = {i["id"]: i for i in included if i["type"] == "artworks"}
|
| 529 |
+
artists_map = {i["id"]: i for i in included if i["type"] == "artists"}
|
| 530 |
+
|
| 531 |
+
def resolve_album(entry):
|
| 532 |
+
aid = entry["id"]
|
| 533 |
+
inc = albums_map.get(aid, {})
|
| 534 |
+
attr = inc.get("attributes", {})
|
| 535 |
+
|
| 536 |
+
cover_id = None
|
| 537 |
+
if art_data := inc.get("relationships", {}).get("coverArt", {}).get("data"):
|
| 538 |
+
if artwork := artworks_map.get(art_data[0].get("id")):
|
| 539 |
+
if files := artwork.get("attributes", {}).get("files"):
|
| 540 |
+
cover_id = _extract_uuid_from_tidal_url(files[0].get("href"))
|
| 541 |
+
|
| 542 |
+
artist_list = []
|
| 543 |
+
if art_data := inc.get("relationships", {}).get("artists", {}).get("data"):
|
| 544 |
+
for a_entry in art_data:
|
| 545 |
+
if a_obj := artists_map.get(a_entry["id"]):
|
| 546 |
+
a_id = a_obj["id"]
|
| 547 |
+
artist_list.append({
|
| 548 |
+
"id": int(a_id) if a_id.isdigit() else a_id,
|
| 549 |
+
"name": a_obj["attributes"]["name"]
|
| 550 |
+
})
|
| 551 |
+
|
| 552 |
+
return {
|
| 553 |
+
**attr,
|
| 554 |
+
"id": int(aid) if aid.isdigit() else aid,
|
| 555 |
+
"cover": cover_id,
|
| 556 |
+
"artists": artist_list,
|
| 557 |
+
"url": f"http://www.tidal.com/album/{aid}"
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
return {
|
| 561 |
+
"version": API_VERSION,
|
| 562 |
+
"albums": [resolve_album(e) for e in payload.get("data", [])]
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
@app.get("/artist/")
|
| 567 |
+
async def get_artist(
|
| 568 |
+
id: Optional[int] = Query(default=None),
|
| 569 |
+
f: Optional[int] = Query(default=None),
|
| 570 |
+
skip_tracks: bool = Query(default=False),
|
| 571 |
+
):
|
| 572 |
+
"""Artist detail or album+track aggregation.
|
| 573 |
+
|
| 574 |
+
- id: basic artist metadata + cover URLs
|
| 575 |
+
- f: fetch artist albums page and aggregate tracks across albums (capped concurrency)
|
| 576 |
+
- skip_tracks: if true, returns only albums without aggregating tracks (when using 'f')
|
| 577 |
+
"""
|
| 578 |
+
|
| 579 |
+
if id is None and f is None:
|
| 580 |
+
raise HTTPException(status_code=400, detail="Provide id or f query param")
|
| 581 |
+
|
| 582 |
+
token, cred = await get_tidal_token_for_cred()
|
| 583 |
+
|
| 584 |
+
if id is not None:
|
| 585 |
+
artist_url = f"https://api.tidal.com/v1/artists/{id}"
|
| 586 |
+
artist_data, token, cred = await authed_get_json(
|
| 587 |
+
artist_url,
|
| 588 |
+
params={"countryCode": COUNTRY_CODE},
|
| 589 |
+
token=token,
|
| 590 |
+
cred=cred,
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
picture = artist_data.get("picture")
|
| 594 |
+
fallback = artist_data.get("selectedAlbumCoverFallback")
|
| 595 |
+
|
| 596 |
+
if not picture and fallback:
|
| 597 |
+
artist_data["picture"] = fallback
|
| 598 |
+
picture = fallback
|
| 599 |
+
|
| 600 |
+
cover = None
|
| 601 |
+
if picture:
|
| 602 |
+
slug = picture.replace("-", "/")
|
| 603 |
+
cover = {
|
| 604 |
+
"id": artist_data.get("id"),
|
| 605 |
+
"name": artist_data.get("name"),
|
| 606 |
+
"750": f"https://resources.tidal.com/images/{slug}/750x750.jpg",
|
| 607 |
+
}
|
| 608 |
+
|
| 609 |
+
return {"version": API_VERSION, "artist": artist_data, "cover": cover}
|
| 610 |
+
|
| 611 |
+
# Fetch albums and singles/EPs directly in parallel
|
| 612 |
+
albums_url = f"https://api.tidal.com/v1/artists/{f}/albums"
|
| 613 |
+
common_params = {"countryCode": COUNTRY_CODE, "limit": 100}
|
| 614 |
+
|
| 615 |
+
tasks = [
|
| 616 |
+
authed_get_json(albums_url, params=common_params, token=token, cred=cred),
|
| 617 |
+
authed_get_json(albums_url, params={**common_params, "filter": "EPSANDSINGLES"}, token=token, cred=cred),
|
| 618 |
+
]
|
| 619 |
+
|
| 620 |
+
if skip_tracks:
|
| 621 |
+
tasks.append(
|
| 622 |
+
authed_get_json(
|
| 623 |
+
f"https://api.tidal.com/v1/artists/{f}/toptracks",
|
| 624 |
+
params={"countryCode": COUNTRY_CODE, "limit": 15},
|
| 625 |
+
token=token,
|
| 626 |
+
cred=cred
|
| 627 |
+
)
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 631 |
+
|
| 632 |
+
unique_releases = []
|
| 633 |
+
seen_ids = set()
|
| 634 |
+
|
| 635 |
+
# Process albums (first 2 results)
|
| 636 |
+
for res in results[:2]:
|
| 637 |
+
if isinstance(res, tuple) and len(res) > 0:
|
| 638 |
+
data, token, cred = res # Update tokens from latest responses
|
| 639 |
+
for item in data.get("items", []):
|
| 640 |
+
if item.get("id") and item["id"] not in seen_ids:
|
| 641 |
+
unique_releases.append(item)
|
| 642 |
+
seen_ids.add(item["id"])
|
| 643 |
+
elif isinstance(res, Exception):
|
| 644 |
+
print(f"Error fetching artist releases: {res}")
|
| 645 |
+
|
| 646 |
+
album_ids: List[int] = [item["id"] for item in unique_releases]
|
| 647 |
+
page_data = {"items": unique_releases}
|
| 648 |
+
|
| 649 |
+
if skip_tracks:
|
| 650 |
+
top_tracks = []
|
| 651 |
+
if len(results) > 2:
|
| 652 |
+
res = results[2]
|
| 653 |
+
if isinstance(res, tuple) and len(res) > 0:
|
| 654 |
+
data, token, cred = res
|
| 655 |
+
top_tracks = data.get("items", [])
|
| 656 |
+
elif isinstance(res, Exception):
|
| 657 |
+
print(f"Error fetching top tracks: {res}")
|
| 658 |
+
|
| 659 |
+
return {"version": API_VERSION, "albums": page_data, "tracks": top_tracks}
|
| 660 |
+
|
| 661 |
+
if not album_ids:
|
| 662 |
+
return {"version": API_VERSION, "albums": page_data, "tracks": []}
|
| 663 |
+
|
| 664 |
+
sem = asyncio.Semaphore(6)
|
| 665 |
+
|
| 666 |
+
async def fetch_album_tracks(album_id: int):
|
| 667 |
+
nonlocal token, cred
|
| 668 |
+
async with sem:
|
| 669 |
+
album_data, token, cred = await authed_get_json(
|
| 670 |
+
"https://api.tidal.com/v1/pages/album",
|
| 671 |
+
params={
|
| 672 |
+
"albumId": album_id,
|
| 673 |
+
"countryCode": COUNTRY_CODE,
|
| 674 |
+
"deviceType": "BROWSER",
|
| 675 |
+
},
|
| 676 |
+
token=token,
|
| 677 |
+
cred=cred,
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
rows = album_data.get("rows", [])
|
| 681 |
+
if len(rows) < 2:
|
| 682 |
+
return []
|
| 683 |
+
modules = rows[1].get("modules", [])
|
| 684 |
+
if not modules:
|
| 685 |
+
return []
|
| 686 |
+
paged_list = modules[0].get("pagedList", {})
|
| 687 |
+
items = paged_list.get("items", [])
|
| 688 |
+
tracks = [track.get("item", track) for track in items]
|
| 689 |
+
return tracks
|
| 690 |
+
|
| 691 |
+
results = await asyncio.gather(
|
| 692 |
+
*(fetch_album_tracks(album_id) for album_id in album_ids),
|
| 693 |
+
return_exceptions=True,
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
tracks: List[dict] = []
|
| 697 |
+
for res in results:
|
| 698 |
+
if isinstance(res, Exception):
|
| 699 |
+
continue
|
| 700 |
+
tracks.extend(res)
|
| 701 |
+
|
| 702 |
+
return {"version": API_VERSION, "albums": page_data, "tracks": tracks}
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
@app.get("/cover/")
|
| 706 |
+
async def get_cover(
|
| 707 |
+
id: Optional[int] = Query(default=None),
|
| 708 |
+
q: Optional[str] = Query(default=None),
|
| 709 |
+
):
|
| 710 |
+
"""Fetch album cover data for a track id or search query."""
|
| 711 |
+
|
| 712 |
+
if id is None and q is None:
|
| 713 |
+
raise HTTPException(status_code=400, detail="Provide id or q query param")
|
| 714 |
+
|
| 715 |
+
token, cred = await get_tidal_token_for_cred()
|
| 716 |
+
|
| 717 |
+
def build_cover_entry(cover_slug: str, name: Optional[str], track_id: Optional[int]):
|
| 718 |
+
slug = cover_slug.replace("-", "/")
|
| 719 |
+
return {
|
| 720 |
+
"id": track_id,
|
| 721 |
+
"name": name,
|
| 722 |
+
"1280": f"https://resources.tidal.com/images/{slug}/1280x1280.jpg",
|
| 723 |
+
"640": f"https://resources.tidal.com/images/{slug}/640x640.jpg",
|
| 724 |
+
"80": f"https://resources.tidal.com/images/{slug}/80x80.jpg",
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
if id is not None:
|
| 728 |
+
track_data, token, cred = await authed_get_json(
|
| 729 |
+
f"https://api.tidal.com/v1/tracks/{id}/",
|
| 730 |
+
params={"countryCode": COUNTRY_CODE},
|
| 731 |
+
token=token,
|
| 732 |
+
cred=cred,
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
album = track_data.get("album") or {}
|
| 736 |
+
cover_slug = album.get("cover")
|
| 737 |
+
if not cover_slug:
|
| 738 |
+
raise HTTPException(status_code=404, detail="Cover not found")
|
| 739 |
+
|
| 740 |
+
entry = build_cover_entry(
|
| 741 |
+
cover_slug,
|
| 742 |
+
album.get("title") or track_data.get("title"),
|
| 743 |
+
album.get("id") or id,
|
| 744 |
+
)
|
| 745 |
+
return {"version": API_VERSION, "covers": [entry]}
|
| 746 |
+
|
| 747 |
+
search_data, token, cred = await authed_get_json(
|
| 748 |
+
"https://api.tidal.com/v1/search/tracks",
|
| 749 |
+
params={"countryCode": COUNTRY_CODE, "query": q, "limit": 10},
|
| 750 |
+
token=token,
|
| 751 |
+
cred=cred,
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
items = search_data.get("items", [])[:10]
|
| 755 |
+
if not items:
|
| 756 |
+
raise HTTPException(status_code=404, detail="Cover not found")
|
| 757 |
+
|
| 758 |
+
covers = []
|
| 759 |
+
for track in items:
|
| 760 |
+
album = track.get("album") or {}
|
| 761 |
+
cover_slug = album.get("cover")
|
| 762 |
+
if not cover_slug:
|
| 763 |
+
continue
|
| 764 |
+
covers.append(
|
| 765 |
+
build_cover_entry(
|
| 766 |
+
cover_slug,
|
| 767 |
+
track.get("title"),
|
| 768 |
+
track.get("id"),
|
| 769 |
+
)
|
| 770 |
+
)
|
| 771 |
+
|
| 772 |
+
if not covers:
|
| 773 |
+
raise HTTPException(status_code=404, detail="Cover not found")
|
| 774 |
+
|
| 775 |
+
return {"version": API_VERSION, "covers": covers}
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
@app.get("/lyrics/")
|
| 779 |
+
async def get_lyrics(id: int):
|
| 780 |
+
url = f"https://api.tidal.com/v1/tracks/{id}/lyrics"
|
| 781 |
+
data, token, cred = await authed_get_json(
|
| 782 |
+
url,
|
| 783 |
+
params={"countryCode": COUNTRY_CODE, "locale": "en_US", "deviceType": "BROWSER"},
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
if not data:
|
| 787 |
+
raise HTTPException(status_code=404, detail="Lyrics not found")
|
| 788 |
+
|
| 789 |
+
return {"version": API_VERSION, "lyrics": data}
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
if __name__ == "__main__":
|
| 793 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Automatically generated by https://github.com/damnever/pigar.
|
| 2 |
+
|
| 3 |
+
hypercorn[h3]==0.16.0
|
| 4 |
+
fastapi[all]==0.109.1
|
| 5 |
+
httpx[http2]==0.25.2
|
| 6 |
+
python-dotenv==1.0.0
|
| 7 |
+
rich==13.3.3
|
| 8 |
+
uvicorn[standard]==0.25.0
|
tidal_auth/requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Automatically generated by https://github.com/damnever/pigar.
|
| 2 |
+
|
| 3 |
+
httpx==0.25.2
|
| 4 |
+
rich==13.3.3
|
tidal_auth/tidal_auth.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 5 |
+
import webbrowser
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import httpx
|
| 9 |
+
import rich
|
| 10 |
+
|
| 11 |
+
TOKEN_FILE = Path(os.getenv("TOKEN_FILE", Path(__file__).resolve().parent.parent / "token.json"))
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Hifi:
|
| 15 |
+
def __init__(self, client_id, scope, url, client_secret):
|
| 16 |
+
self.client_id = client_id
|
| 17 |
+
self.scope = scope
|
| 18 |
+
self.url = url
|
| 19 |
+
self.client_secret = client_secret
|
| 20 |
+
|
| 21 |
+
@staticmethod
|
| 22 |
+
def Quality(quality):
|
| 23 |
+
rate = {quality: "HI_RES"}
|
| 24 |
+
return rate[quality]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Auth(Hifi):
|
| 28 |
+
def __init__(self, client_id, scope, url, client_secret):
|
| 29 |
+
super().__init__(client_id, scope, url, client_secret)
|
| 30 |
+
self.response = None
|
| 31 |
+
|
| 32 |
+
async def get_auth_response(self):
|
| 33 |
+
data = {"client_id": self.client_id, "scope": self.scope}
|
| 34 |
+
headers = {
|
| 35 |
+
"User-Agent": "Mozilla/5.0 (Linux; Android 8.0.0; SM-G965F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.109 Mobile Safari/537.36"
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
async with httpx.AsyncClient() as client:
|
| 39 |
+
response = await client.post(self.url, data=data, headers=headers)
|
| 40 |
+
# We handle status codes in the main loop now
|
| 41 |
+
|
| 42 |
+
self.response = response
|
| 43 |
+
|
| 44 |
+
def __str__(self):
|
| 45 |
+
return str(self.response)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_tokens():
|
| 49 |
+
if TOKEN_FILE.exists():
|
| 50 |
+
with open(TOKEN_FILE, "r") as f:
|
| 51 |
+
data = json.load(f)
|
| 52 |
+
if isinstance(data, list):
|
| 53 |
+
return data
|
| 54 |
+
return [data]
|
| 55 |
+
return []
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def save_token_entry(entry):
|
| 59 |
+
tokens = load_tokens()
|
| 60 |
+
tokens = [t for t in tokens if not (
|
| 61 |
+
t.get("client_ID") == entry["client_ID"] and t.get("refresh_token") == entry["refresh_token"]
|
| 62 |
+
)]
|
| 63 |
+
tokens.append(entry)
|
| 64 |
+
with open(TOKEN_FILE, "w") as f:
|
| 65 |
+
json.dump(tokens, f, indent=4)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
async def poll_for_authorization(url, data, auth):
|
| 69 |
+
async with httpx.AsyncClient() as client:
|
| 70 |
+
while True:
|
| 71 |
+
response = await client.post(url, data=data, auth=auth)
|
| 72 |
+
if response.status_code == 200:
|
| 73 |
+
return response.json()
|
| 74 |
+
await asyncio.sleep(5)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
async def fetch_credentials():
|
| 78 |
+
url = "https://api.github.com/gists/48d01f5a24b4b7b37f19443977c22cd6"
|
| 79 |
+
async with httpx.AsyncClient() as client:
|
| 80 |
+
resp = await client.get(url)
|
| 81 |
+
resp.raise_for_status()
|
| 82 |
+
gist_data = resp.json()
|
| 83 |
+
|
| 84 |
+
content_str = gist_data["files"]["tidal-api-key.json"]["content"]
|
| 85 |
+
keys_data = json.loads(content_str)
|
| 86 |
+
|
| 87 |
+
hifi_creds = [
|
| 88 |
+
("fX2JxdmntZWK0ixT", "1Nn9AfDAjxrgJFJbKNWLeAyKGVGmINuXPPLHVXAvxAg=")
|
| 89 |
+
]
|
| 90 |
+
other_creds = []
|
| 91 |
+
|
| 92 |
+
for key_entry in keys_data["keys"]:
|
| 93 |
+
if key_entry.get("valid") == "True":
|
| 94 |
+
cred = (key_entry["clientId"], key_entry["clientSecret"])
|
| 95 |
+
if "hifi" in key_entry.get("formats", "").lower():
|
| 96 |
+
hifi_creds.append(cred)
|
| 97 |
+
else:
|
| 98 |
+
other_creds.append(cred)
|
| 99 |
+
|
| 100 |
+
if not hifi_creds and not other_creds:
|
| 101 |
+
raise Exception("No valid Tidal credentials found in Gist")
|
| 102 |
+
return hifi_creds, other_creds
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
async def main():
|
| 106 |
+
hifi_creds, other_creds = await fetch_credentials()
|
| 107 |
+
random.shuffle(hifi_creds)
|
| 108 |
+
random.shuffle(other_creds)
|
| 109 |
+
all_creds = hifi_creds + other_creds
|
| 110 |
+
|
| 111 |
+
async def run_link_flow():
|
| 112 |
+
authrize = None
|
| 113 |
+
for client_id, client_secret in all_creds:
|
| 114 |
+
rich.print(f"Trying Client ID: {client_id}")
|
| 115 |
+
authrize = Auth(
|
| 116 |
+
client_id=client_id,
|
| 117 |
+
scope="r_usr+w_usr+w_sub",
|
| 118 |
+
url="https://auth.tidal.com/v1/oauth2/device_authorization",
|
| 119 |
+
client_secret=client_secret,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
await authrize.get_auth_response()
|
| 124 |
+
if authrize.response.status_code == 200:
|
| 125 |
+
break
|
| 126 |
+
elif authrize.response.status_code == 401:
|
| 127 |
+
rich.print(f"[yellow]Client ID {client_id} failed with 401. Trying next...[/yellow]")
|
| 128 |
+
continue
|
| 129 |
+
else:
|
| 130 |
+
rich.print(f"[red]Error {authrize.response.status_code}. Trying next...[/red]")
|
| 131 |
+
continue
|
| 132 |
+
except Exception as e:
|
| 133 |
+
rich.print(f"[red]Exception: {e}. Trying next...[/red]")
|
| 134 |
+
continue
|
| 135 |
+
else:
|
| 136 |
+
rich.print("[red]All tokens failed.[/red]")
|
| 137 |
+
return False
|
| 138 |
+
|
| 139 |
+
res = authrize.response.json()
|
| 140 |
+
|
| 141 |
+
verifyurl = res["verificationUriComplete"]
|
| 142 |
+
dcode = res["deviceCode"]
|
| 143 |
+
|
| 144 |
+
rich.print(verifyurl)
|
| 145 |
+
rich.print(dcode)
|
| 146 |
+
|
| 147 |
+
HI_RES = authrize.Quality(quality="True")
|
| 148 |
+
rich.print(HI_RES)
|
| 149 |
+
|
| 150 |
+
webbrowser.open(verifyurl)
|
| 151 |
+
|
| 152 |
+
url2 = "https://auth.tidal.com/v1/oauth2/token"
|
| 153 |
+
|
| 154 |
+
data2 = {
|
| 155 |
+
"client_id": authrize.client_id,
|
| 156 |
+
"scope": authrize.scope,
|
| 157 |
+
"device_code": dcode,
|
| 158 |
+
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
basic = (authrize.client_id, authrize.client_secret)
|
| 162 |
+
|
| 163 |
+
auth_response = await poll_for_authorization(url2, data2, basic)
|
| 164 |
+
|
| 165 |
+
access_token = auth_response["access_token"]
|
| 166 |
+
refresh_token = auth_response["refresh_token"]
|
| 167 |
+
user_id = auth_response["user"]["userId"]
|
| 168 |
+
accs = {
|
| 169 |
+
"access_token": access_token,
|
| 170 |
+
"refresh_token": refresh_token,
|
| 171 |
+
"userID": user_id,
|
| 172 |
+
"client_ID": client_id,
|
| 173 |
+
"client_secret": client_secret,
|
| 174 |
+
}
|
| 175 |
+
save_token_entry(accs)
|
| 176 |
+
rich.print(accs)
|
| 177 |
+
acs_tok = access_token
|
| 178 |
+
|
| 179 |
+
url3 = f"https://api.tidal.com/v1/tracks/286266926/playbackinfopostpaywall?countryCode=en_US&audioquality={HI_RES}&playbackmode=STREAM&assetpresentation=FULL"
|
| 180 |
+
|
| 181 |
+
headers = {"authorization": f"Bearer {acs_tok}"}
|
| 182 |
+
|
| 183 |
+
async with httpx.AsyncClient() as client:
|
| 184 |
+
res3 = await client.get(url3, headers=headers)
|
| 185 |
+
|
| 186 |
+
rich.print(res3.json())
|
| 187 |
+
print("TOKEN IS VALID")
|
| 188 |
+
return True
|
| 189 |
+
|
| 190 |
+
while True:
|
| 191 |
+
success = await run_link_flow()
|
| 192 |
+
if not success:
|
| 193 |
+
break
|
| 194 |
+
again = input("Add another token? (y/N): ").strip().lower()
|
| 195 |
+
if again not in ("y", "yes"):
|
| 196 |
+
break
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == "__main__":
|
| 200 |
+
asyncio.run(main())
|
token.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"access_token": "eyJraWQiOiJ2OU1GbFhqWSIsImFsZyI6IkVTMjU2In0.eyJ0eXBlIjoibzJfYWNjZXNzIiwidWlkIjoyMDc1Nzk4MzksInNjb3BlIjoid191c3Igcl91c3Igd19zdWIiLCJnVmVyIjowLCJzVmVyIjowLCJjaWQiOjEzMzE5LCJjYyI6IlVTIiwiYXQiOiJJTlRFUk5BTCIsImV4cCI6MTc3MTU3MjgxNiwic2lkIjoiYTM4ZjEyY2QtMjlmYS00ZDlmLTg4ZDctZjIzMmUwYTI4NDM4IiwiaXNzIjoiaHR0cHM6Ly9hdXRoLnRpZGFsLmNvbS92MSJ9.kTF-hb8QvUaZoI0bNBmJQr-fj0rY-mGsjGnEoy8-0oFQpbyRwdjMQ9UYBRpxWcCI9JNP7A_7ch2vIctlFNOGvQ",
|
| 4 |
+
"refresh_token": "eyJraWQiOiJoUzFKYTdVMCIsImFsZyI6IkVTNTEyIn0.eyJ0eXBlIjoibzJfcmVmcmVzaCIsInVpZCI6MjA3NTc5ODM5LCJzY29wZSI6IndfdXNyIHJfdXNyIHdfc3ViIiwiY2lkIjoxMzMxOSwic1ZlciI6MCwiZ1ZlciI6MCwiaXNzIjoiaHR0cHM6Ly9hdXRoLnRpZGFsLmNvbS92MSJ9.AS34PAWm7xT9uZF-PgrbZy7UscEVewmGnb7pNO-HkvH7UVzaAAgqpCI33QqY7Fjss5ahw5NryKDnVFsEwh207RTtAG-B6Sqex2GNYDnyrrGaIIkPyEPeDuxb8iaAdPwWeH6r_bdurTiNsnIN0YbUyd42ZsIKOInEBAhbWo442RBg3_ia",
|
| 5 |
+
"userID": 207579839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