File size: 12,960 Bytes
6e4b6a1
a775fb8
cdd2ff8
b3ceabe
cdd2ff8
a108d08
7d46648
6ceeee9
ff7a5f2
a108d08
40bd669
15fbf8b
b3ceabe
da751e9
a9f35e5
 
2dd163d
 
 
63f8901
da751e9
ff7a5f2
7d46648
 
 
 
ff7a5f2
40bd669
 
cdd2ff8
a108d08
bd7e531
a108d08
 
 
cdd2ff8
 
 
4f0e710
21291a5
4f0e710
390c953
 
73ead9a
697d26d
 
 
ac14607
697d26d
4c4c396
 
 
 
 
 
 
 
 
 
 
ff7a5f2
 
bb24960
ff7a5f2
15fbf8b
bb24960
 
ff7a5f2
cdd2ff8
 
ff7a5f2
cdd2ff8
bb24960
 
 
cdd2ff8
7d46648
cdd2ff8
 
15fbf8b
bb24960
 
 
 
 
15fbf8b
2dd163d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a108d08
15fbf8b
 
cdd2ff8
2dd163d
 
 
 
 
 
 
 
 
 
 
ac14607
 
 
 
76a2c73
15fbf8b
4c4c396
 
15fbf8b
ac14607
15fbf8b
 
 
 
 
 
 
bb24960
 
cdd2ff8
 
 
 
7d46648
 
 
15fbf8b
 
7d46648
6e4b6a1
 
 
 
 
 
 
cdd2ff8
0d8cf7c
 
 
 
 
 
 
 
 
 
 
 
a108d08
15fbf8b
 
363ed4f
 
15fbf8b
 
363ed4f
15fbf8b
363ed4f
0a1f269
15fbf8b
 
495a536
 
 
6e4b6a1
a108d08
6a8c623
4f0e710
6a8c623
7d46648
63f8901
 
ff7a5f2
7d46648
ff7a5f2
 
15fbf8b
332ce83
 
 
 
 
d14d034
 
332ce83
 
d14d034
 
 
3f2a2be
 
 
 
 
 
 
 
 
 
 
 
d14d034
 
3f2a2be
d14d034
 
3f2a2be
332ce83
 
 
 
 
d14d034
 
 
 
332ce83
 
d14d034
 
 
c23aa3d
 
 
 
 
 
 
 
 
 
 
 
d14d034
c23aa3d
 
d14d034
c23aa3d
 
d14d034
 
 
cdd2ff8
ff7a5f2
 
 
cdd2ff8
 
bb24960
 
 
ff7a5f2
7d46648
15fbf8b
af3f642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import shutil
from fastapi import FastAPI, HTTPException, Request
from deezspot.deezloader import DeeLogin
from deezspot.spotloader import SpoLogin
import requests
import os
import logging
import json
from typing import Optional
from fastapi.staticfiles import StaticFiles
from dotenv import load_dotenv
from pydantic import BaseModel
from urllib.parse import quote
from pathlib import Path
import uuid
from fastapi import BackgroundTasks
from collections import defaultdict
import time
from datetime import timedelta
import gc


# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="Deezer API")
# Load environment variables
load_dotenv()

# Mount a static files directory to serve downloaded files

os.makedirs("downloads", exist_ok=True)
app.mount("/downloads", StaticFiles(directory="downloads"), name="downloads")

# Deezer API base URL
DEEZER_API_URL = "https://api.deezer.com"

# Base URL for the server
BASE_URL = "https://chrunos-depot.hf.space"

# Deezer ARL token (required for deezspot downloads)
ARL_TOKEN = os.getenv('ARL')

class DownloadRequest(BaseModel):
    url: str
    quality: str
    arl: str



def convert_deezer_short_link_async(short_link: str) -> str:
    try:
        response = requests.get(short_link, allow_redirects=True)
        return response.url
    except requests.RequestException as e:
        print(f"An error occurred: {e}")
        return ""


@app.get("/")
def read_root():
    return {"message": "running"}


# Helper function to get track info
def get_track_info(track_id: str):
    try:
        response = requests.get(f"{DEEZER_API_URL}/track/{track_id}")
        if response.status_code != 200:
            raise HTTPException(status_code=404, detail="Track not found")
        return response.json()
    except requests.exceptions.RequestException as e:
        logger.error(f"Network error fetching track metadata: {e}")
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        logger.error(f"Error fetching track metadata: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# Fetch track metadata from Deezer API
@app.get("/track/{track_id}")
def get_track(track_id: str):
    return get_track_info(track_id)


# Rate limiting dictionary
class RateLimiter:
    def __init__(self, max_requests: int, time_window: timedelta):
        self.max_requests = max_requests
        self.time_window = time_window
        self.requests: Dict[str, list] = defaultdict(list)
    
    def _cleanup_old_requests(self, user_ip: str) -> None:
        """Remove requests that are outside the time window."""
        current_time = time.time()
        self.requests[user_ip] = [
            timestamp for timestamp in self.requests[user_ip]
            if current_time - timestamp < self.time_window.total_seconds()
        ]
    
    def is_rate_limited(self, user_ip: str) -> bool:
        """Check if the user has exceeded their rate limit."""
        self._cleanup_old_requests(user_ip)
        
        # Get current count after cleanup
        current_count = len(self.requests[user_ip])
        
        # Add current request timestamp (incrementing the count)
        current_time = time.time()
        self.requests[user_ip].append(current_time)
        
        # Check if user has exceeded the maximum requests
        return (current_count + 1) > self.max_requests
    
    def get_current_count(self, user_ip: str) -> int:
        """Get the current request count for an IP."""
        self._cleanup_old_requests(user_ip)
        return len(self.requests[user_ip])


# Initialize rate limiter with 25 requests per day
rate_limiter = RateLimiter(
    max_requests=25,
    time_window=timedelta(days=1)
)

def get_user_ip(request: Request) -> str:
    """Helper function to get user's IP address."""
    forwarded = request.headers.get("X-Forwarded-For")
    if forwarded:
        return forwarded.split(",")[0]
    return request.client.host


# Download a track and return a download URL
@app.post("/download/track")
def download_track(request: DownloadRequest):
    try:
        user_ip = get_user_ip(request)
    
        if rate_limiter.is_rate_limited(user_ip):
            current_count = rate_limiter.get_current_count(user_ip)
            raise HTTPException(
                status_code=429,
                detail={
                    "detail": "You have exceeded the maximum number of requests per day. Please try again tomorrow.",
                    "help": "https://t.me/chrunoss"
                }
            )
        if request.arl is None or request.arl.strip() == "":
            ARL = ARL_TOKEN
        else:
            ARL = request.arl
        logger.info(f'arl: {ARL}')
        url = request.url
        if 'deezer.page' in url:
            url = convert_deezer_short_link_async(url)
        quality = request.quality
        dl = DeeLogin(arl=ARL)

        if quality not in ["MP3_320", "MP3_128", "FLAC"]:
            raise HTTPException(status_code=400, detail="Invalid quality specified")

        # 提取 track_id (假设 url 格式为 https://api.deezer.com/track/{track_id})
        track_id = url.split("/")[-1]

        # Fetch track info
        track_info = get_track_info(track_id)
        track_link = track_info.get("link")
        if not track_link:
            raise HTTPException(status_code=404, detail="Track link not found")

        # Sanitize filename
        track_title = track_info.get("title", "track")
        artist_name = track_info.get("artist", {}).get("name", "unknown")
        file_extension = "flac" if quality == "FLAC" else "mp3"
        expected_filename = f"{artist_name} - {track_title}.{file_extension}".replace("/", "_")  # Sanitize filename

        # Clear the downloads directory
        for root, dirs, files in os.walk("downloads"):
            for file in files:
                os.remove(os.path.join(root, file))
            for dir in dirs:
                shutil.rmtree(os.path.join(root, dir))

        # Download the track using deezspot
        try:
            # 下载文件的代码
            dl.download_trackdee(
                link_track=track_link,
                output_dir="downloads",
                quality_download=quality,
                recursive_quality=False,
                recursive_download=False
            )
        except Exception as e:
            logger.error(f"Error downloading file: {e}")
            raise HTTPException(status_code=500, detail="File download failed")

        # Recursively search for the file in the downloads directory
        filepath = None
        for root, dirs, files in os.walk("downloads"):
            for file in files:
                if file.endswith(f'.{file_extension}'):
                    filepath = os.path.join(root, file)
                    break
            if filepath:
                break

        if not filepath:
            raise HTTPException(status_code=500, detail=f"{file_extension} file not found after download")
        if filepath:
            file_size = os.path.getsize(filepath)
            logger.info(f"Downloaded file size: {file_size} bytes")

        # Return the download URL
        relative_path = quote(str(os.path.relpath(filepath, "downloads")))
        # Remove spaces from the relative path
        download_url = f"{BASE_URL}/downloads/{relative_path}"
        logger.info(f"Download successful: {download_url}")
        gc.collect()
        return {"download_url": download_url, "requests_remaining": rate_limiter.max_requests - rate_limiter.get_current_count(user_ip)}
    except Exception as e:
        logger.error(f"Error downloading track: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# Pydantic model for album request
class AlbumRequest(BaseModel):
    album_id: str


# Fetch album data
@app.post("/album")
def fetch_album(request: AlbumRequest):
    album_id = request.album_id
    try:
        response = requests.get(f"{DEEZER_API_URL}/album/{album_id}")
        response.raise_for_status()
        album_data = response.json()
        tracks = album_data.get("tracks", {}).get("data", [])
        result = []
        for track in tracks:
            title = track.get("title")
            link = track.get("link")
            if title and link:
                result.append({
                    "title": title,
                    "link": link
                })
        return result
    except requests.exceptions.RequestException as e:
        logger.error(f"Network error fetching album: {e}")
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        logger.error(f"Error fetching album: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# Pydantic model for playlist request
class PlaylistRequest(BaseModel):
    playlist_id: str


# Fetch playlist data
@app.post("/playlist")
def fetch_playlist(request: PlaylistRequest):
    playlist_id = request.playlist_id
    try:
        response = requests.get(f"{DEEZER_API_URL}/playlist/{playlist_id}")
        response.raise_for_status()
        playlist_data = response.json()
        tracks = playlist_data.get("tracks", {}).get("data", [])
        result = []
        for track in tracks:
            title = track.get("title")
            link = track.get("link")
            if title and link:
                result.append({
                    "title": title,
                    "link": link
                })
        return result
    except requests.exceptions.RequestException as e:
        logger.error(f"Network error fetching album: {e}")
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        logger.error(f"Error fetching album: {e}")
        raise HTTPException(status_code=500, detail=str(e))



# Search tracks using Deezer API
@app.get("/search")
def search_tracks(query: str, limit: Optional[int] = 10):
    try:
        response = requests.get(f"{DEEZER_API_URL}/search", params={"q": query, "limit": limit})
        return response.json()
    except requests.exceptions.RequestException as e:
        logger.error(f"Network error searching tracks: {e}")
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        logger.error(f"Error searching tracks: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# Spotify credentials from environment variables
'''SPOTIFY_USERNAME = os.getenv("SPOTIFY_USERNAME")
SPOTIFY_CREDENTIALS = os.getenv("SPOTIFY_CREDENTIALS")

if not SPOTIFY_USERNAME or not SPOTIFY_CREDENTIALS:
    raise RuntimeError("Spotify credentials not found in environment variables")

# Create a temporary credentials.json file
CREDENTIALS_PATH = "/tmp/credentials.json"
with open(CREDENTIALS_PATH, "w") as f:
    json.dump({
        "username": SPOTIFY_USERNAME,
        "credentials": SPOTIFY_CREDENTIALS,
        "type": "AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS"
    }, f)

# Initialize Spotify client
spo = SpoLogin(credentials_path=CREDENTIALS_PATH)


# 定义请求体模型
class DownloadRequest(BaseModel):
    url: str
    quality: str


def cleanup_dir(dir_path: Path):
    """Background task to clean up directory"""
    try:
        shutil.rmtree(dir_path)
        logger.info(f"Cleaned up directory: {dir_path}")
    except Exception as e:
        logger.error(f"Error cleaning up {dir_path}: {e}")


# Download a Spotify track and return a download URL       
@app.post("/spot-track/{track_id}")
async def download_spotify_track(
    track_id: str,
    background_tasks: BackgroundTasks
):
    try:
        downloads_dir = Path("downloads")
        # Create unique directory for this download
        download_id = uuid.uuid4().hex
        download_dir = downloads_dir / download_id
        download_dir.mkdir(parents=True, exist_ok=True)

        # Download to unique directory
        logger.info(f"Downloading to {download_dir}")
        spo.download_track(
            link_track=f"https://open.spotify.com/track/{track_id}",
            output_dir=str(download_dir),
            quality_download="VERY_HIGH",
            recursive_quality=False,
            recursive_download=False,
            not_interface=False,
            method_save=1
        )

        # Find downloaded file
        filepath = next(download_dir.glob(f"**/*.ogg"), None)
        if not filepath:
            raise HTTPException(status_code=500, detail="File not found after download")

        # Schedule cleanup after response is sent
        #background_tasks.add_task(cleanup_dir, download_dir)

        # Return path with unique directory
        relative_path = quote(str(filepath.relative_to(downloads_dir)))
        return {"download_url": f"{BASE_URL}/downloads/{relative_path}"}

    except Exception as e:
        logger.error(f"Error downloading track: {e}")
        raise HTTPException(status_code=500, detail=str(e))
'''