File size: 10,636 Bytes
4d0d26b
b6fc0a2
262a6f1
7a5a781
 
 
 
262a6f1
b6fc0a2
18310da
 
 
 
33eac3d
 
cf5846e
7a5a781
b6fc0a2
 
 
 
 
 
 
 
 
 
7a5a781
b6fc0a2
33eac3d
b6fc0a2
 
7a5a781
 
 
262a6f1
 
 
 
 
 
 
33eac3d
262a6f1
 
 
33eac3d
262a6f1
 
 
 
33eac3d
262a6f1
 
 
33eac3d
262a6f1
b6fc0a2
 
 
 
7a5a781
33eac3d
262a6f1
 
 
 
 
b6fc0a2
262a6f1
 
 
 
 
 
b6fc0a2
 
33eac3d
b6fc0a2
 
33eac3d
b6fc0a2
 
33eac3d
b6fc0a2
 
 
 
 
 
33eac3d
b6fc0a2
 
33eac3d
262a6f1
 
33eac3d
262a6f1
 
33eac3d
b6fc0a2
 
 
 
 
 
7a5a781
33eac3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6fc0a2
 
 
 
 
 
 
 
33eac3d
 
 
 
 
459c7b6
 
 
33eac3d
 
 
 
 
 
 
 
 
 
 
 
459c7b6
33eac3d
 
459c7b6
0b7f6c9
 
 
 
 
 
 
 
459c7b6
0b7f6c9
 
 
 
459c7b6
0b7f6c9
 
 
33eac3d
 
 
 
 
 
 
 
 
 
459c7b6
33eac3d
 
 
 
0b7f6c9
 
 
33eac3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459c7b6
33eac3d
 
b6fc0a2
459c7b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33eac3d
 
 
 
b6fc0a2
18310da
b6fc0a2
 
 
 
 
262a6f1
 
 
 
 
b6fc0a2
 
33eac3d
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
import base64
import logging
from typing import Optional, Dict
from fastapi import FastAPI, HTTPException, Request
import requests
from bs4 import BeautifulSoup
import os
from datetime import datetime, timedelta
import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import asyncio
from typing import Optional, Dict, Tuple
import urllib.parse
from fastapi.responses import JSONResponse
import re

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('spotify_api.log')
    ]
)
logger = logging.getLogger(__name__)

app = FastAPI(title="Spotify Track API",
              description="API for retrieving Spotify track information and download URLs")

# Constants
SPOTIFY_API_URL = "https://api.spotify.com/v1"
SPOTIFY_CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
SPOTIFY_CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET")
TOKEN_EXPIRY = 3500  # Slightly less than 1 hour to ensure token refresh before expiration

# Token cache
class TokenCache:
    def __init__(self):
        self.token: Optional[str] = None
        self.expiry_time: Optional[datetime] = None

    def set_token(self, token: str):
        self.token = token
        self.expiry_time = datetime.now() + timedelta(seconds=TOKEN_EXPIRY)

    def get_token(self) -> Optional[str]:
        if not self.token or not self.expiry_time or datetime.now() >= self.expiry_time:
            return None
        return self.token

    def is_expired(self) -> bool:
        return not self.token or not self.expiry_time or datetime.now() >= self.expiry_time


token_cache = TokenCache()

# Custom exception for Spotify API errors
class SpotifyAPIError(Exception):
    pass


def get_spotify_token() -> str:
    """
    Get Spotify access token with expiration handling.
    Returns a valid token, either from cache or by requesting a new one.
    """
    try:
        # Check if we have a valid cached token
        cached_token = token_cache.get_token()
        if cached_token:
            logger.info("Using cached Spotify token")
            return cached_token

        logger.info("Requesting new Spotify access token")
        start_time = time.time()

        if not SPOTIFY_CLIENT_ID or not SPOTIFY_CLIENT_SECRET:
            raise SpotifyAPIError("Spotify credentials not configured")

        auth_string = f"{SPOTIFY_CLIENT_ID}:{SPOTIFY_CLIENT_SECRET}"
        auth_bytes = base64.b64encode(auth_string.encode()).decode()

        auth_response = requests.post(
            'https://accounts.spotify.com/api/token',
            data={'grant_type': 'client_credentials'},
            headers={'Authorization': f'Basic {auth_bytes}'},
            timeout=10
        )

        if auth_response.status_code != 200:
            raise SpotifyAPIError(f"Failed to get token: {auth_response.text}")

        new_token = auth_response.json()['access_token']
        token_cache.set_token(new_token)

        logger.info(f"New token obtained successfully in {time.time() - start_time:.2f}s")
        return new_token

    except requests.exceptions.RequestException as e:
        logger.error(f"Network error during token request: {str(e)}")
        raise HTTPException(status_code=503, detail="Spotify authentication service unavailable")
    except Exception as e:
        logger.error(f"Unexpected error during token request: {str(e)}")
        raise HTTPException(status_code=500, detail="Internal server error")

def extract_album_id(album_url: str) -> str:
    """Extract album ID from Spotify URL."""
    try:
        return album_url.split("/")[-1].split("?")[0]
    except Exception as e:
        logger.error(f"Failed to extract album ID from URL {album_url}: {str(e)}")
        raise HTTPException(status_code=400, detail="Invalid Spotify album URL format")


@app.post("/album")
async def get_album_data(request: Request):
    try:
        # Get the JSON data from the request
        data = await request.json()
        album_url = data.get('album_url')
        if not album_url:
            raise HTTPException(status_code=400, detail="Missing 'album_url' in JSON data")

        # Extract the album ID from the URL
        album_id = extract_album_id(album_url)

        # Get the Spotify access token
        access_token = get_spotify_token()

        # Make a request to the Spotify API to get album data
        headers = {
            'Authorization': f'Bearer {access_token}'
        }
        album_api_url = f"{SPOTIFY_API_URL}/albums/{album_id}"
        response = requests.get(album_api_url, headers=headers, timeout=10)

        if response.status_code != 200:
            raise SpotifyAPIError(f"Failed to get album data: {response.text}")

        album_data = response.json()
        return album_data

    except SpotifyAPIError as e:
        logger.error(f"Spotify API error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        logger.error(f"Unexpected error: {str(e)}")
        raise HTTPException(status_code=500, detail="Internal server error")


def extract_playlist_id(playlist_url: str) -> str:
    """Extract playlist ID from Spotify URL."""
    try:
        return playlist_url.split("/")[-1].split("?")[0]
        
    except Exception as e:
        logger.error(f"Failed to extract playlist ID from URL {playlist_url}: {str(e)}")
        raise HTTPException(status_code=400, detail="Invalid Spotify playlist URL format")


@app.post("/playlist")
async def get_playlist_data(request: Request):
    try:
        # Get the JSON data from the request
        data = await request.json()
        playlist_url = data.get('playlist_url')
        if not playlist_url:
            raise HTTPException(status_code=400, detail="Missing 'playlist_url' in JSON data")

        # Extract the playlist ID from the URL
        playlist_id = extract_playlist_id(playlist_url)
        logger.info(f"Extracted playlist ID: {playlist_id}")

        # Get the Spotify access token
        access_token = get_spotify_token()

        # Make a request to the Spotify API to get playlist data
        headers = {
            'Authorization': f'Bearer {access_token}'
        }
        playlist_api_url = f"{SPOTIFY_API_URL}/playlists/{playlist_id}/tracks"
        response = requests.get(playlist_api_url, headers=headers, timeout=10)

        if response.status_code != 200:
            raise SpotifyAPIError(f"Failed to get playlist data: {response.text}")

        playlist_data = response.json()
        return playlist_data

    except SpotifyAPIError as e:
        logger.error(f"Spotify API error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        logger.error(f"Unexpected error: {str(e)}")
        raise HTTPException(status_code=500, detail="Internal server error")


def extract_track_id(track_url: str) -> str:
    """Extract track ID from Spotify URL."""
    try:
        return track_url.split("/")[-1].split("?")[0]
    except Exception as e:
        logger.error(f"Failed to extract track ID from URL {track_url}: {str(e)}")
        raise HTTPException(status_code=400, detail="Invalid Spotify URL format")









def get_cookie():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36'
    }

    try:
        session = requests.Session()
        response = session.get('https://spotisongdownloader.to/', headers=headers)
        response.raise_for_status()
        cookies = session.cookies.get_dict()
        return f"PHPSESSID={cookies['PHPSESSID']}; quality=m4a"

    except requests.exceptions.RequestException:
        return None


def get_api():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36'
    }

    try:
        response = requests.get('https://spotisongdownloader.to/track.php', headers=headers)
        response.raise_for_status()

        match = re.search(r'url:\s*"(/api/composer/spotify/[^"]+)"', response.text)
        if match:
            api_endpoint = match.group(1)
            return f"https://spotisongdownloader.to{api_endpoint}"

    except requests.exceptions.RequestException:
        return None


def get_data(track_id):
    link = f"https://open.spotify.com/track/{track_id}"
    try:
        response = requests.get(
            'https://spotisongdownloader.to/api/composer/spotify/xsingle_track.php',
            params={'url': link}
        )
        return response.json()

    except:
        return None


def get_url(track_data, cookie):
    url = get_api()
    if not url:
        return None

    payload = {
        'song_name': track_data['song_name'],
        'artist_name': track_data['artist'],
        'url': track_data['url']
    }

    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Cookie': cookie,
        'Origin': 'https://spotisongdownloader.to',
        'Referer': 'https://spotisongdownloader.to/track.php',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
    }

    try:
        response = requests.post(url, data=payload, headers=headers)
        response.raise_for_status()
        download_data = response.json()

        encoded_link = urllib.parse.quote(download_data['dlink'], safe=':/?=')
        return encoded_link

    except:
        return None


@app.get("/{track_id}")
async def download_track(track_id: str):
    cookie = get_cookie()
    if not cookie:
        return {"error": "Failed to get session cookie"}, 500

    track_data = get_data(track_id)
    if not track_data:
        return {"error": "Failed to get track data"}, 404

    download_link = get_url(track_data, cookie)
    if not download_link:
        return {"error": "Failed to get download URL"}, 500

    return {"url": download_link}






@app.get("/")
async def health_check():
    """Health check endpoint."""
    try:
        # Test Spotify API token generation
        token = get_spotify_token()
        return {
            "status": "healthy",
            "spotify_auth": "ok",
            "token_expires_in": token_cache.expiry_time.timestamp() - datetime.now().timestamp() if token_cache.expiry_time else None
        }
    except Exception as e:
        logger.error(f"Health check failed: {str(e)}")
        return {"status": "unhealthy", "error": str(e)}