File size: 8,162 Bytes
4d0d26b
b6fc0a2
262a6f1
7a5a781
 
 
 
262a6f1
b6fc0a2
7a5a781
b6fc0a2
 
 
 
 
 
 
 
 
 
7a5a781
b6fc0a2
 
 
 
7a5a781
 
 
262a6f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6fc0a2
 
 
 
7a5a781
262a6f1
 
 
 
 
b6fc0a2
262a6f1
 
 
 
 
 
b6fc0a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262a6f1
 
 
 
 
b6fc0a2
 
 
 
 
 
 
7a5a781
b6fc0a2
 
 
 
 
 
 
 
 
 
 
 
 
 
7a5a781
b6fc0a2
 
 
176be93
b6fc0a2
 
 
 
 
 
 
 
4d0d26b
b6fc0a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d0d26b
b6fc0a2
4d0d26b
b6fc0a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262a6f1
 
 
 
 
 
 
 
 
 
 
 
b6fc0a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262a6f1
 
 
 
 
b6fc0a2
 
 
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
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

# 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_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")

async def get_track_download_url(track_id: str) -> str:
    """Get download URL with fallback."""
    apis = [
        f"https://downspotifyapis.vercel.app/api/v2/track/{track_id}",
        f"https://downspotifyapis.vercel.app/api/v1/track/{track_id}"
    ]
    
    for api_url in apis:
        try:
            logger.info(f"Attempting to get download URL from: {api_url}")
            response = requests.get(api_url, timeout=30)
            if response.status_code == 200:
                download_url = response.json().get("url")
                if download_url:
                    logger.info(f"Successfully obtained download URL from {api_url}")
                    return download_url
        except requests.exceptions.RequestException as e:
            logger.warning(f"Failed to get download URL from {api_url}: {str(e)}")
            continue
    
    logger.error(f"No download URL found for track {track_id}")
    raise HTTPException(status_code=404, detail="Download URL not found")

@app.get("/get-track")
async def get_track(
    request: Request,
    track_id: Optional[str] = None,
    track_url: Optional[str] = None
):
    """
    Get track information and download URL.
    Requires either track_id or track_url parameter.
    """
    request_id = datetime.now().strftime('%Y%m%d%H%M%S%f')
    logger.info(f"Request {request_id} started - Track ID: {track_id}, URL: {track_url}")
    
    start_time = time.time()
    
    try:
        # Input validation
        if not track_id and not track_url:
            raise HTTPException(status_code=400, detail="Track ID or Track URL must be provided")
        
        # Extract track ID from URL if provided
        if track_url:
            track_id = extract_track_id(track_url)
        
        # Get Spotify API token
        access_token = get_spotify_token()
        
        # Get track metadata from Spotify
        logger.info(f"Request {request_id} - Fetching track metadata for {track_id}")
        response = requests.get(
            f"{SPOTIFY_API_URL}/tracks/{track_id}",
            headers={"Authorization": f"Bearer {access_token}"},
            timeout=10
        )
        
        # Handle token expiration
        if response.status_code == 401:
            logger.info("Token expired, requesting new token")
            token_cache.token = None  # Clear expired token
            access_token = get_spotify_token()
            # Retry the request with new token
            response = requests.get(
                f"{SPOTIFY_API_URL}/tracks/{track_id}",
                headers={"Authorization": f"Bearer {access_token}"},
                timeout=10
            )
        
        if response.status_code != 200:
            logger.error(f"Request {request_id} - Spotify API error: {response.text}")
            raise HTTPException(
                status_code=response.status_code,
                detail="Failed to fetch track information from Spotify"
            )
        
        track_data = response.json()
        
        # Get download URL
        download_url = await get_track_download_url(track_id)
        
        # Prepare response
        result = {
            "track_id": track_id,
            "name": track_data["name"],
            "album": track_data["album"]["name"],
            "artist": track_data["artists"][0]["name"],
            "release_date": track_data["album"]["release_date"],
            "duration_ms": track_data["duration_ms"],
            "url": download_url
        }
        
        logger.info(f"Request {request_id} completed successfully in {time.time() - start_time:.2f}s")
        return result
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Request {request_id} failed with error: {str(e)}")
        raise HTTPException(status_code=500, detail="Internal server error")

@app.get("/health")
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)}