File size: 14,911 Bytes
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
 
 
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
b1d075d
965b972
 
b1d075d
965b972
 
 
 
 
 
 
 
 
b1d075d
965b972
 
 
 
 
 
 
b1d075d
965b972
b1d075d
 
 
 
 
 
 
 
 
 
 
 
965b972
 
 
 
 
b1d075d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
965b972
b1d075d
 
965b972
 
b1d075d
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
 
 
 
 
 
 
b1d075d
965b972
 
 
 
 
b1d075d
965b972
 
 
 
 
 
 
b1d075d
965b972
 
 
 
 
 
b1d075d
 
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
 
 
 
 
 
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
 
b1d075d
965b972
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
 
b1d075d
965b972
b1d075d
965b972
 
 
 
b1d075d
 
 
 
 
 
 
 
 
 
 
 
965b972
 
 
b1d075d
965b972
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
 
b1d075d
965b972
 
 
 
b1d075d
 
965b972
b1d075d
 
965b972
b1d075d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d075d
965b972
 
 
 
 
 
 
 
b1d075d
965b972
 
 
 
b1d075d
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Spotify Web API Client

Provides access to Spotify's database for audio features and preview URLs.
Used as secondary data source for BeatDebate.
"""

import base64
import time
from typing import Dict, List, Optional, Any
from dataclasses import dataclass

import structlog

from .base_client import BaseAPIClient
from .rate_limiter import UnifiedRateLimiter

logger = structlog.get_logger(__name__)


@dataclass
class SpotifyTrack:
    """Spotify track data."""
    id: str
    name: str
    artist: str
    album: str
    preview_url: Optional[str] = None
    external_urls: Optional[Dict[str, str]] = None
    duration_ms: Optional[int] = None
    popularity: Optional[int] = None
    
    
@dataclass
class AudioFeatures:
    """Spotify audio features."""
    track_id: str
    danceability: float
    energy: float
    valence: float
    acousticness: float
    instrumentalness: float
    speechiness: float
    liveness: float
    loudness: float
    tempo: float
    time_signature: int
    key: int
    mode: int


class SpotifyClient(BaseAPIClient):
    """
    Spotify Web API client with unified authentication and rate limiting.
    
    Focuses on audio features and preview URLs for BeatDebate.
    Inherits from BaseAPIClient for consistent HTTP handling across all API clients.
    """
    
    BASE_URL = "https://api.spotify.com/v1"
    AUTH_URL = "https://accounts.spotify.com/api/token"
    
    def __init__(
        self, 
        client_id: str, 
        client_secret: str,
        rate_limiter: Optional[UnifiedRateLimiter] = None
    ):
        """
        Initialize Spotify client.
        
        Args:
            client_id: Spotify client ID
            client_secret: Spotify client secret
            rate_limiter: Rate limiter instance (optional, will create default if not provided)
        """
        # Create default rate limiter if not provided
        if rate_limiter is None:
            rate_limiter = UnifiedRateLimiter.for_spotify()
        
        # Initialize base client
        super().__init__(
            base_url=self.BASE_URL,
            rate_limiter=rate_limiter,
            timeout=10,
            service_name="Spotify"
        )
        
        self.client_id = client_id
        self.client_secret = client_secret
        self.access_token: Optional[str] = None
        self.token_expires_at: float = 0.0
        
        self.logger.info("Spotify client initialized")
    
    def _extract_api_error(self, data: Dict[str, Any]) -> Optional[str]:
        """
        Extract Spotify API error information from response data.
        
        Args:
            data: Parsed response data
            
        Returns:
            Error message if found, None otherwise
        """
        if "error" in data:
            error_info = data["error"]
            if isinstance(error_info, dict):
                return error_info.get("message", f"Error {error_info.get('status', 'unknown')}")
            return str(error_info)
        return None
    
    async def __aenter__(self):
        """Async context manager entry with authentication."""
        await super().__aenter__()
        await self._authenticate()
        return self
    
    async def _authenticate(self) -> None:
        """Authenticate with Spotify API using client credentials flow."""
        if not self.session:
            raise RuntimeError("Client not initialized. Use async context manager.")
            
        # Prepare authentication
        auth_str = f"{self.client_id}:{self.client_secret}"
        auth_b64 = base64.b64encode(auth_str.encode()).decode()
        
        headers = {
            "Authorization": f"Basic {auth_b64}",
            "Content-Type": "application/x-www-form-urlencoded"
        }
        
        data = {"grant_type": "client_credentials"}
        
        try:
            async with self.session.post(
                self.AUTH_URL,
                headers=headers,
                data=data
            ) as response:
                if response.status == 200:
                    token_data = await response.json()
                    self.access_token = token_data["access_token"]
                    expires_in = token_data.get("expires_in", 3600)
                    self.token_expires_at = time.time() + expires_in - 60  # 1min buffer
                    
                    self.logger.info(
                        "Spotify authentication successful",
                        expires_in=expires_in
                    )
                else:
                    error_data = await response.json()
                    self.logger.error(
                        "Spotify authentication failed",
                        status=response.status,
                        error=error_data
                    )
                    raise Exception(f"Spotify auth failed: {error_data}")
                    
        except Exception as e:
            self.logger.error("Spotify authentication error", error=str(e))
            raise
            
    async def _ensure_valid_token(self) -> None:
        """Ensure we have a valid access token."""
        if not self.access_token or time.time() >= self.token_expires_at:
            await self._authenticate()
    
    async def _make_spotify_request(
        self,
        endpoint: str,
        params: Optional[Dict[str, Any]] = None,
        retries: int = 3
    ) -> Dict[str, Any]:
        """
        Make authenticated request to Spotify API.
        
        Args:
            endpoint: API endpoint (without base URL)
            params: Query parameters
            retries: Number of retry attempts
            
        Returns:
            API response data
        """
        await self._ensure_valid_token()
        
        headers = {
            "Authorization": f"Bearer {self.access_token}",
            "Content-Type": "application/json"
        }
        
        return await self._make_request(
            endpoint=endpoint,
            params=params,
            headers=headers,
            retries=retries
        )
    
    async def search_track(
        self,
        artist: str,
        track: str,
        limit: int = 1
    ) -> Optional[SpotifyTrack]:
        """
        Search for a track on Spotify.
        
        Args:
            artist: Artist name
            track: Track name
            limit: Number of results (default: 1)
            
        Returns:
            First matching Spotify track or None
        """
        try:
            query = f"artist:{artist} track:{track}"
            data = await self._make_spotify_request(
                "search",
                {
                    "q": query,
                    "type": "track",
                    "limit": limit
                }
            )
            
            if "tracks" in data and data["tracks"]["items"]:
                track_data = data["tracks"]["items"][0]
                
                return SpotifyTrack(
                    id=track_data["id"],
                    name=track_data["name"],
                    artist=track_data["artists"][0]["name"],
                    album=track_data["album"]["name"],
                    preview_url=track_data.get("preview_url"),
                    external_urls=track_data.get("external_urls"),
                    duration_ms=track_data.get("duration_ms"),
                    popularity=track_data.get("popularity")
                )
                
            return None
            
        except Exception as e:
            self.logger.error(
                "Spotify track search failed",
                artist=artist,
                track=track,
                error=str(e)
            )
            return None
    
    async def get_track(self, track_id: str) -> Optional[SpotifyTrack]:
        """
        Get track details by Spotify ID.
        
        Args:
            track_id: Spotify track ID
            
        Returns:
            Spotify track data or None if not found
        """
        try:
            data = await self._make_spotify_request(f"tracks/{track_id}")
            
            return SpotifyTrack(
                id=data["id"],
                name=data["name"],
                artist=data["artists"][0]["name"],
                album=data["album"]["name"],
                preview_url=data.get("preview_url"),
                external_urls=data.get("external_urls"),
                duration_ms=data.get("duration_ms"),
                popularity=data.get("popularity")
            )
            
        except Exception as e:
            self.logger.error(
                "Get Spotify track failed",
                track_id=track_id,
                error=str(e)
            )
            return None
    
    async def get_audio_features(self, track_id: str) -> Optional[AudioFeatures]:
        """
        Get audio features for a track.
        
        Args:
            track_id: Spotify track ID
            
        Returns:
            Audio features or None if not found
        """
        try:
            data = await self._make_spotify_request(f"audio-features/{track_id}")
            
            if not data or data.get("id") is None:
                return None
                
            return AudioFeatures(
                track_id=data["id"],
                danceability=data["danceability"],
                energy=data["energy"],
                valence=data["valence"],
                acousticness=data["acousticness"],
                instrumentalness=data["instrumentalness"],
                speechiness=data["speechiness"],
                liveness=data["liveness"],
                loudness=data["loudness"],
                tempo=data["tempo"],
                time_signature=data["time_signature"],
                key=data["key"],
                mode=data["mode"]
            )
            
        except Exception as e:
            self.logger.error(
                "Get audio features failed",
                track_id=track_id,
                error=str(e)
            )
            return None
    
    async def get_multiple_audio_features(
        self, 
        track_ids: List[str]
    ) -> Dict[str, AudioFeatures]:
        """
        Get audio features for multiple tracks.
        
        Args:
            track_ids: List of Spotify track IDs (max 100)
            
        Returns:
            Dictionary mapping track IDs to audio features
        """
        if not track_ids:
            return {}
            
        # Spotify API allows max 100 IDs per request
        track_ids = track_ids[:100]
        
        try:
            data = await self._make_spotify_request(
                "audio-features",
                {"ids": ",".join(track_ids)}
            )
            
            features_dict = {}
            if "audio_features" in data:
                for features_data in data["audio_features"]:
                    if features_data:  # Can be None for tracks without features
                        features = AudioFeatures(
                            track_id=features_data["id"],
                            danceability=features_data["danceability"],
                            energy=features_data["energy"],
                            valence=features_data["valence"],
                            acousticness=features_data["acousticness"],
                            instrumentalness=features_data["instrumentalness"],
                            speechiness=features_data["speechiness"],
                            liveness=features_data["liveness"],
                            loudness=features_data["loudness"],
                            tempo=features_data["tempo"],
                            time_signature=features_data["time_signature"],
                            key=features_data["key"],
                            mode=features_data["mode"]
                        )
                        features_dict[features.track_id] = features
                        
            self.logger.info(
                "Multiple audio features retrieved",
                requested=len(track_ids),
                retrieved=len(features_dict)
            )
            
            return features_dict
            
        except Exception as e:
            self.logger.error(
                "Get multiple audio features failed",
                track_count=len(track_ids),
                error=str(e)
            )
            return {}
    
    async def search_tracks(
        self,
        query: str,
        limit: int = 20,
        offset: int = 0
    ) -> List[SpotifyTrack]:
        """
        Search for tracks with a general query.
        
        Args:
            query: Search query
            limit: Number of results
            offset: Result offset
            
        Returns:
            List of matching tracks
        """
        try:
            data = await self._make_spotify_request(
                "search",
                {
                    "q": query,
                    "type": "track",
                    "limit": limit,
                    "offset": offset
                }
            )
            
            tracks = []
            if "tracks" in data and "items" in data["tracks"]:
                for track_data in data["tracks"]["items"]:
                    track = SpotifyTrack(
                        id=track_data["id"],
                        name=track_data["name"],
                        artist=track_data["artists"][0]["name"],
                        album=track_data["album"]["name"],
                        preview_url=track_data.get("preview_url"),
                        external_urls=track_data.get("external_urls"),
                        duration_ms=track_data.get("duration_ms"),
                        popularity=track_data.get("popularity")
                    )
                    tracks.append(track)
                    
            self.logger.info(
                "Spotify search completed",
                query=query,
                results_count=len(tracks)
            )
            
            return tracks
            
        except Exception as e:
            self.logger.error(
                "Spotify search failed",
                query=query,
                error=str(e)
            )
            return []


# Legacy compatibility - maintain the old SpotifyRateLimiter class for backward compatibility
class SpotifyRateLimiter:
    """Legacy Spotify rate limiter for backward compatibility."""
    
    def __init__(self, calls_per_hour: int = 50):
        self.calls_per_hour = calls_per_hour
        self._unified_limiter = UnifiedRateLimiter.for_spotify(calls_per_hour)
        
    async def wait_if_needed(self) -> None:
        """Wait if necessary to respect rate limits."""
        await self._unified_limiter.wait_if_needed()