Compare commits
87 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9bddeab0d1 | |||
| 03a30ee09a | |||
| 2d908e2f75 | |||
| e8f7bf7313 | |||
| 1f0922f358 | |||
| 3f267a3fa1 | |||
| 22da74a027 | |||
| 783350fe88 | |||
| 0057d43f46 | |||
| 9928968ffb | |||
| af4f1dd401 | |||
| 3414fadbd3 | |||
| 457f30da99 | |||
| d4e621b36c | |||
| 58a733b790 | |||
| c85ab4bc28 | |||
| dac2e99b5a | |||
| d0f494f582 | |||
| 0542d6e86b | |||
| de798e4807 | |||
| 0e7ba6d029 | |||
| 2306b1f8d2 | |||
| 1b0d67702d | |||
| 00e369677f | |||
| c3e1607ca6 | |||
| 59428e7679 | |||
| 33c4698286 | |||
| 3ac4c34d73 | |||
| 88e303cbe4 | |||
| c13855fadd | |||
| 2b12684960 | |||
| 4bc164cc56 | |||
| 46cb65665e | |||
| 276b3b4951 | |||
| e15aadbd61 | |||
| d7639bae8f | |||
| 1af7ab65c9 | |||
| c5240596cb | |||
| c4a9042adc | |||
| 45ac08ecbd | |||
| 0add305d9c | |||
| 9b6b43c0a4 | |||
| 60d20cbebe | |||
| 626d58667e | |||
| 4dd1a7ea12 | |||
| 67964e4acb | |||
| 1486fb13df | |||
| 966536f127 | |||
| 21946321f5 | |||
| 3e3cb0610d | |||
| 160eba0987 | |||
| 71a60ded47 | |||
| e0a0514df9 | |||
| 1e7a48d263 | |||
| 0a83a0dd6e | |||
| da429d9410 | |||
| 63211c726b | |||
| 055cb6991a | |||
| 222d681551 | |||
| 479c6ede2b | |||
| ceb727adb9 | |||
| bbea8ca493 | |||
| f567dd19bf | |||
| 3651833e2a | |||
| 8403b96306 | |||
| d977829e36 | |||
| 2aaf123c98 | |||
| 13567802a0 | |||
| d704782519 | |||
| 884c02278f | |||
| d6abe2bae3 | |||
| 7b858dd0ce | |||
| cfeb9a2ef2 | |||
| 81a78832ff | |||
| 071f20deff | |||
| 03de68ac7b | |||
| 77363f9e61 | |||
| 2df77120cf | |||
| e6e953b2ed | |||
| 72f17479e8 | |||
| 9286fba63c | |||
| 6bf7084959 | |||
| 03cc3d82a7 | |||
| 2acd6fcba1 | |||
| 85a5bb2321 | |||
| 70a955f531 | |||
| 71c8070ec0 |
@@ -1,99 +0,0 @@
|
||||
import asyncio
|
||||
import zendriver as zd
|
||||
|
||||
async def get_metadata(page):
|
||||
max_attempts = 40
|
||||
attempts = 0
|
||||
|
||||
await asyncio.sleep(2)
|
||||
|
||||
await page.evaluate("""
|
||||
window.downloadInfo = null;
|
||||
const originalFetch = window.fetch;
|
||||
window.fetch = async function(...args) {
|
||||
const [url, config] = args;
|
||||
if (url.includes('/api/load?url=%2Fapi%2Ffetch%2Fstream%2Fv2')) {
|
||||
const payload = JSON.parse(config.body);
|
||||
const title = document.querySelector('h1.svelte-6pt9ji').textContent;
|
||||
const artists = Array.from(document.querySelectorAll('h2.svelte-6pt9ji a.normal'))
|
||||
.map(a => a.textContent)
|
||||
.join(', ');
|
||||
const cover = document.querySelector('.svelte-6pt9ji .meta.svelte-6pt9ji a').href;
|
||||
|
||||
window.downloadInfo = {
|
||||
url: payload.url,
|
||||
cover: cover,
|
||||
title: title,
|
||||
artists: artists,
|
||||
token: payload.token.primary,
|
||||
expiry: payload.token.expiry
|
||||
};
|
||||
}
|
||||
return originalFetch.apply(this, args);
|
||||
};
|
||||
""")
|
||||
|
||||
await page.evaluate("""
|
||||
function waitForElement(selector) {
|
||||
return new Promise(resolve => {
|
||||
if (document.querySelector(selector)) {
|
||||
return resolve(document.querySelector(selector));
|
||||
}
|
||||
|
||||
const observer = new MutationObserver(mutations => {
|
||||
if (document.querySelector(selector)) {
|
||||
observer.disconnect();
|
||||
resolve(document.querySelector(selector));
|
||||
}
|
||||
});
|
||||
|
||||
observer.observe(document.documentElement, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (!window.location.hostname.includes('lucida.')) return;
|
||||
|
||||
await Promise.race([
|
||||
waitForElement('.d1-track button'),
|
||||
waitForElement('button[class*="download-button"]')
|
||||
]);
|
||||
|
||||
const clickDownloadButton = () => {
|
||||
const button = document.querySelector('.d1-track button') ||
|
||||
document.querySelector('button[class*="download-button"]');
|
||||
if (button) button.click();
|
||||
};
|
||||
|
||||
clickDownloadButton();
|
||||
})();
|
||||
""")
|
||||
|
||||
while attempts < max_attempts:
|
||||
download_info = await page.evaluate("window.downloadInfo")
|
||||
if download_info:
|
||||
return download_info
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
attempts += 1
|
||||
|
||||
raise TimeoutError("Timeout")
|
||||
|
||||
async def main():
|
||||
browser = await zd.start(headless=False)
|
||||
try:
|
||||
track_id = "2plbrEY59IikOBgBGLjaoe"
|
||||
url = f"https://lucida.to/?url=https%3A%2F%2Fopen.spotify.com%2Ftrack%2F{track_id}&country=auto&to=tidal"
|
||||
|
||||
page = await browser.get(url)
|
||||
download_info = await get_metadata(page)
|
||||
print(download_info)
|
||||
return download_info
|
||||
finally:
|
||||
await browser.stop()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,120 +0,0 @@
|
||||
import requests
|
||||
from tqdm import tqdm
|
||||
import time
|
||||
import os
|
||||
import asyncio
|
||||
from GetMetadata import main as get_metadata
|
||||
|
||||
class TrackDownloader:
|
||||
def __init__(self):
|
||||
self.client = requests.Session()
|
||||
self.headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
||||
}
|
||||
|
||||
async def get_track_info(self):
|
||||
metadata = await get_metadata()
|
||||
return metadata
|
||||
|
||||
def sanitize_filename(self, filename):
|
||||
invalid_chars = '<>:"/\\|?*'
|
||||
for char in invalid_chars:
|
||||
filename = filename.replace(char, '')
|
||||
|
||||
filename = ' '.join(filename.split())
|
||||
filename = filename.replace(' ,', ',')
|
||||
filename = filename.replace(',', ', ')
|
||||
while ' ' in filename:
|
||||
filename = filename.replace(' ', ' ')
|
||||
filename = filename.rsplit('.', 1)
|
||||
filename[0] = filename[0].strip()
|
||||
return '.'.join(filename)
|
||||
|
||||
def download(self, metadata, output_dir):
|
||||
track_url = metadata['url']
|
||||
primary_token = metadata['token']
|
||||
expiry = metadata['expiry']
|
||||
|
||||
print(f"Starting download for: {track_url}")
|
||||
|
||||
initial_request = {
|
||||
"account": {"id": "auto", "type": "country"},
|
||||
"compat": "false",
|
||||
"downscale": "original",
|
||||
"handoff": True,
|
||||
"metadata": True,
|
||||
"private": True,
|
||||
"token": {
|
||||
"expiry": expiry,
|
||||
"primary": primary_token
|
||||
},
|
||||
"upload": {"enabled": False, "service": "pixeldrain"},
|
||||
"url": track_url
|
||||
}
|
||||
|
||||
response = self.client.post("https://lucida.to/api/load?url=/api/fetch/stream/v2",
|
||||
json=initial_request,
|
||||
headers=self.headers)
|
||||
|
||||
csrf_token = response.cookies.get('csrf_token')
|
||||
if csrf_token:
|
||||
self.headers['X-CSRF-Token'] = csrf_token
|
||||
|
||||
initial_response = response.json()
|
||||
|
||||
if not initial_response.get("success", False):
|
||||
raise Exception(f"Initial request failed: {initial_response.get('error', 'Unknown error')}")
|
||||
|
||||
handoff = initial_response["handoff"]
|
||||
server = initial_response["server"]
|
||||
|
||||
file_name = f"{metadata['title']} - {metadata['artists']}.flac"
|
||||
file_name = self.sanitize_filename(file_name)
|
||||
|
||||
completion_url = f"https://{server}.lucida.to/api/fetch/request/{handoff}"
|
||||
|
||||
print("Waiting for track processing to complete")
|
||||
while True:
|
||||
completion_response = self.client.get(completion_url, headers=self.headers).json()
|
||||
if completion_response["status"] == "completed":
|
||||
break
|
||||
elif completion_response["status"] == "error":
|
||||
raise Exception(f"API request failed: {completion_response.get('message', 'Unknown error')}")
|
||||
time.sleep(1)
|
||||
|
||||
download_url = f"https://{server}.lucida.to/api/fetch/request/{handoff}/download"
|
||||
print(f"Starting download of: {file_name}")
|
||||
|
||||
response = self.client.get(download_url, stream=True, headers=self.headers)
|
||||
total_size = int(response.headers.get('content-length', 0))
|
||||
|
||||
file_path = os.path.join(output_dir, file_name)
|
||||
|
||||
with open(file_path, 'wb') as file, tqdm(
|
||||
desc=file_name,
|
||||
total=total_size,
|
||||
unit='iB',
|
||||
unit_scale=True,
|
||||
unit_divisor=1024,
|
||||
) as progress_bar:
|
||||
for data in response.iter_content(chunk_size=1024):
|
||||
size = file.write(data)
|
||||
progress_bar.update(size)
|
||||
|
||||
print(f"Download completed: {file_path}")
|
||||
return file_path
|
||||
|
||||
async def main():
|
||||
downloader = TrackDownloader()
|
||||
output_dir = "."
|
||||
|
||||
try:
|
||||
metadata = await downloader.get_track_info()
|
||||
|
||||
downloaded_file = downloader.download(metadata, output_dir)
|
||||
print(f"File downloaded successfully: {downloaded_file}")
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {str(e)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,33 +1,28 @@
|
||||
[](https://github.com/afkarxyz/SpotifyFLAC/releases)
|
||||
[](https://github.com/afkarxyz/SpotiFLAC/releases)
|
||||
|
||||

|
||||

|
||||
|
||||
<div align="center">
|
||||
<b>Spotify FLAC</b> allows you to download Spotify tracks in true FLAC format through services like Tidal, Amazon Music and Qobuz with the help of Lucida.
|
||||
<b>SpotiFLAC</b> allows you to download Spotify tracks in true FLAC format through services like Qobuz, Tidal & Deezer.
|
||||
</div>
|
||||
|
||||
### [Download](https://github.com/afkarxyz/SpotifyFLAC/releases/download/v1.5/SpotifyFLAC.exe)
|
||||
### [Download](https://github.com/afkarxyz/SpotiFLAC/releases/download/v4.0/SpotiFLAC.exe)
|
||||
|
||||
#
|
||||
|
||||
> [!NOTE]
|
||||
> Requires **Google Chrome**
|
||||
|
||||
> [!WARNING]
|
||||
Sometimes, the **download speed** from Lucida can be fast or slow; it varies unpredictably.
|
||||
> [!Important]
|
||||
> - Requires **Google Chrome, Chromium, Microsoft Edge,** or **Brave** to use `Deezer`
|
||||
> - If after **Cloudflare** verification nothing happens, use a `VPN`, your country is likely blocked by `corsproxy.io`
|
||||
|
||||
## Screenshots
|
||||
|
||||

|
||||

|
||||
|
||||
> - When **Headless** is enabled, the browser runs in the background without a graphical interface, improving performance and allowing seamless automation.
|
||||
> - When **Fallback** is enabled, it will use the backup server Lucida.su
|
||||
> - **Filename: Title** means the filename format is `Title - Artist`, and vice versa.
|
||||
> - I highly recommend **Tidal** or **Amazon Music** because `Qobuz` occasionally experience issues.
|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
## Lossless Audio Check
|
||||
|
||||
@@ -35,4 +30,4 @@ Sometimes, the **download speed** from Lucida can be fast or slow; it varies unp
|
||||
|
||||

|
||||
|
||||
### [Download](https://github.com/afkarxyz/SpotifyFLAC/releases/download/v0/FLAC-Checker.zip) FLAC Checker
|
||||
#### [Download](https://github.com/afkarxyz/SpotiFLAC/releases/download/v0/FLAC-Checker.zip) FLAC Checker
|
||||
|
||||
+1573
File diff suppressed because it is too large
Load Diff
-608
@@ -1,608 +0,0 @@
|
||||
import sys
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
|
||||
QHBoxLayout, QLabel, QLineEdit, QPushButton,
|
||||
QProgressBar, QFileDialog, QCheckBox, QRadioButton,
|
||||
QGroupBox, QComboBox)
|
||||
from PyQt6.QtCore import QThread, pyqtSignal, Qt, QSettings, QSize
|
||||
from PyQt6.QtGui import QIcon, QPixmap, QCursor
|
||||
from getMetadata import get_metadata
|
||||
from getTracks import TrackDownloader
|
||||
|
||||
class ImageDownloader(QThread):
|
||||
finished = pyqtSignal(bytes)
|
||||
|
||||
def __init__(self, url):
|
||||
super().__init__()
|
||||
self.url = url
|
||||
|
||||
def run(self):
|
||||
import requests
|
||||
response = requests.get(self.url)
|
||||
if response.status_code == 200:
|
||||
self.finished.emit(response.content)
|
||||
|
||||
class MetadataFetcher(QThread):
|
||||
finished = pyqtSignal(dict)
|
||||
error = pyqtSignal(str)
|
||||
|
||||
def __init__(self, url, headless=True, service="tidal", use_fallback=False):
|
||||
super().__init__()
|
||||
self.url = url
|
||||
self.headless_mode = headless
|
||||
self.service = service
|
||||
self.use_fallback = use_fallback
|
||||
self.max_retries = 3
|
||||
|
||||
def extract_track_id(self, url):
|
||||
if "track/" in url:
|
||||
return url.split("track/")[1].split("?")[0]
|
||||
return None
|
||||
|
||||
async def fetch_metadata(self, track_id):
|
||||
import zendriver as zd
|
||||
from asyncio import sleep
|
||||
|
||||
domain = "lucida.su" if self.use_fallback else "lucida.to"
|
||||
|
||||
for attempt in range(self.max_retries):
|
||||
try:
|
||||
lucida_url = f"https://{domain}/?url=https%3A%2F%2Fopen.spotify.com%2Ftrack%2F{track_id}&country=auto&to={self.service}"
|
||||
browser = await zd.start(headless=self.headless_mode)
|
||||
try:
|
||||
page = await browser.get(lucida_url)
|
||||
return await get_metadata(page)
|
||||
finally:
|
||||
await browser.stop()
|
||||
except Exception as e:
|
||||
if "refused" in str(e).lower() and attempt < self.max_retries - 1:
|
||||
await sleep(2 * (attempt + 1))
|
||||
continue
|
||||
raise e
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
track_id = self.extract_track_id(self.url)
|
||||
if not track_id:
|
||||
self.error.emit("Invalid Spotify URL")
|
||||
return
|
||||
|
||||
metadata = asyncio.run(self.fetch_metadata(track_id))
|
||||
if metadata:
|
||||
self.finished.emit(metadata)
|
||||
else:
|
||||
self.error.emit("Failed to fetch track metadata")
|
||||
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
if "refused" in error_msg.lower():
|
||||
self.error.emit("Connection refused. Please check your internet connection and try again.")
|
||||
elif "timeout" in error_msg.lower():
|
||||
self.error.emit("Connection timed out. Please check your internet connection and try again.")
|
||||
else:
|
||||
self.error.emit(f"Error: {error_msg}")
|
||||
|
||||
class DownloaderWorker(QThread):
|
||||
progress = pyqtSignal(int)
|
||||
status = pyqtSignal(str)
|
||||
finished = pyqtSignal(str)
|
||||
error = pyqtSignal(str)
|
||||
|
||||
def __init__(self, metadata, output_dir, filename_format='title_artist', use_fallback=False):
|
||||
super().__init__()
|
||||
self.metadata = metadata
|
||||
self.output_dir = output_dir
|
||||
self.filename_format = filename_format
|
||||
self.use_fallback = use_fallback
|
||||
self.downloader = TrackDownloader(use_fallback=use_fallback)
|
||||
self.last_update_time = 0
|
||||
self.last_downloaded_size = 0
|
||||
|
||||
def format_size(self, size_bytes):
|
||||
units = ['B', 'KB', 'MB', 'GB']
|
||||
index = 0
|
||||
while size_bytes >= 1024 and index < len(units) - 1:
|
||||
size_bytes /= 1024
|
||||
index += 1
|
||||
return f"{size_bytes:.2f}{units[index]}"
|
||||
|
||||
def format_speed(self, speed_bytes):
|
||||
speed_bits = speed_bytes * 8
|
||||
|
||||
if speed_bits >= 1024 * 1024:
|
||||
speed_mbps = speed_bits / (1024 * 1024)
|
||||
return f"{speed_mbps:.2f}Mbps"
|
||||
else:
|
||||
speed_kbps = speed_bits / 1024
|
||||
return f"{speed_kbps:.2f}Kbps"
|
||||
|
||||
def progress_callback(self, downloaded_size, total_size):
|
||||
current_time = time.time()
|
||||
if current_time - self.last_update_time >= 0.5:
|
||||
progress = int((downloaded_size / total_size) * 100) if total_size > 0 else 0
|
||||
self.progress.emit(progress)
|
||||
|
||||
time_diff = current_time - self.last_update_time
|
||||
if time_diff > 0:
|
||||
speed = (downloaded_size - self.last_downloaded_size) / time_diff
|
||||
status = f"Downloading... {self.format_size(downloaded_size)}/{self.format_size(total_size)} | {self.format_speed(speed)}"
|
||||
self.status.emit(status)
|
||||
|
||||
self.last_update_time = current_time
|
||||
self.last_downloaded_size = downloaded_size
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
self.status.emit("Preparing...")
|
||||
self.downloader.set_progress_callback(self.progress_callback)
|
||||
self.downloader.set_filename_format(self.filename_format)
|
||||
self.progress.emit(0)
|
||||
downloaded_file = self.downloader.download(self.metadata, self.output_dir)
|
||||
self.progress.emit(100)
|
||||
self.finished.emit("Download complete!")
|
||||
except Exception as e:
|
||||
self.error.emit(f"Error: {str(e)}")
|
||||
|
||||
class ServiceComboBox(QComboBox):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setIconSize(QSize(16, 16))
|
||||
self.setup_items()
|
||||
|
||||
def setup_items(self):
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
icons_dir = os.path.join(current_dir, 'icons')
|
||||
|
||||
if not os.path.exists(icons_dir):
|
||||
os.makedirs(icons_dir)
|
||||
|
||||
services = [
|
||||
{'id': 'tidal', 'name': 'Tidal', 'icon': 'tidal.png'},
|
||||
{'id': 'amazon', 'name': 'Amazon Music', 'icon': 'amazon.png'},
|
||||
{'id': 'qobuz', 'name': 'Qobuz', 'icon': 'qobuz.png'}
|
||||
]
|
||||
|
||||
for service in services:
|
||||
icon_path = os.path.join(icons_dir, service['icon'])
|
||||
if not os.path.exists(icon_path):
|
||||
self.create_placeholder_icon(icon_path)
|
||||
|
||||
icon = QIcon(icon_path)
|
||||
self.addItem(icon, service['name'], service['id'])
|
||||
|
||||
def create_placeholder_icon(self, path):
|
||||
pixmap = QPixmap(16, 16)
|
||||
pixmap.fill(Qt.GlobalColor.transparent)
|
||||
pixmap.save(path)
|
||||
|
||||
class SpotifyFlacGUI(QMainWindow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.settings = QSettings('SpotifyFlac', 'Settings')
|
||||
self.setWindowTitle("Spotify FLAC")
|
||||
|
||||
icon_path = os.path.join(os.path.dirname(__file__), "icon.svg")
|
||||
if os.path.exists(icon_path):
|
||||
self.setWindowIcon(QIcon(icon_path))
|
||||
|
||||
self.setFixedWidth(600)
|
||||
self.setFixedHeight(180)
|
||||
|
||||
self.default_music_dir = str(Path.home() / "Music")
|
||||
if not os.path.exists(self.default_music_dir):
|
||||
os.makedirs(self.default_music_dir)
|
||||
|
||||
self.metadata = None
|
||||
self.init_ui()
|
||||
self.url_input.textChanged.connect(self.validate_url)
|
||||
self.load_settings()
|
||||
self.setup_settings_persistence()
|
||||
|
||||
def load_settings(self):
|
||||
headless = self.settings.value('headless', True, type=bool)
|
||||
fallback = self.settings.value('fallback', False, type=bool)
|
||||
service = self.settings.value('service', 'tidal')
|
||||
format_type = self.settings.value('format', 'title_artist')
|
||||
output_dir = self.settings.value('output_dir', self.default_music_dir)
|
||||
|
||||
self.headless_checkbox.setChecked(headless)
|
||||
self.fallback_checkbox.setChecked(fallback)
|
||||
|
||||
for i in range(self.service_combo.count()):
|
||||
if self.service_combo.itemData(i) == service:
|
||||
self.service_combo.setCurrentIndex(i)
|
||||
break
|
||||
|
||||
self.format_title_artist.setChecked(format_type == 'title_artist')
|
||||
self.format_artist_title.setChecked(format_type == 'artist_title')
|
||||
self.dir_input.setText(output_dir)
|
||||
|
||||
def setup_settings_persistence(self):
|
||||
self.headless_checkbox.stateChanged.connect(
|
||||
lambda x: self.settings.setValue('headless', bool(x)))
|
||||
self.fallback_checkbox.stateChanged.connect(
|
||||
lambda x: self.settings.setValue('fallback', bool(x)))
|
||||
self.service_combo.currentIndexChanged.connect(
|
||||
lambda i: self.settings.setValue('service', self.service_combo.itemData(i)))
|
||||
self.format_title_artist.toggled.connect(
|
||||
lambda x: self.settings.setValue('format', 'title_artist' if x else 'artist_title'))
|
||||
self.dir_input.textChanged.connect(
|
||||
lambda x: self.settings.setValue('output_dir', x))
|
||||
|
||||
def init_ui(self):
|
||||
central_widget = QWidget()
|
||||
self.setCentralWidget(central_widget)
|
||||
self.main_layout = QVBoxLayout(central_widget)
|
||||
self.main_layout.setContentsMargins(10, 10, 10, 10)
|
||||
|
||||
self.input_widget = QWidget()
|
||||
input_layout = QVBoxLayout(self.input_widget)
|
||||
input_layout.setSpacing(10)
|
||||
|
||||
url_layout = QHBoxLayout()
|
||||
url_label = QLabel("Track URL:")
|
||||
url_label.setFixedWidth(100)
|
||||
self.url_input = QLineEdit()
|
||||
self.url_input.setPlaceholderText("Please enter track URL")
|
||||
self.url_input.setClearButtonEnabled(True)
|
||||
self.fetch_button = QPushButton("Fetch")
|
||||
self.fetch_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.fetch_button.setFixedWidth(100)
|
||||
self.fetch_button.setEnabled(False)
|
||||
self.fetch_button.clicked.connect(self.fetch_track_info)
|
||||
url_layout.addWidget(url_label)
|
||||
url_layout.addWidget(self.url_input)
|
||||
url_layout.addWidget(self.fetch_button)
|
||||
input_layout.addLayout(url_layout)
|
||||
|
||||
dir_layout = QHBoxLayout()
|
||||
dir_label = QLabel("Output Directory:")
|
||||
dir_label.setFixedWidth(100)
|
||||
self.dir_input = QLineEdit(self.default_music_dir)
|
||||
self.dir_button = QPushButton("Browse")
|
||||
self.dir_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.dir_button.setFixedWidth(100)
|
||||
dir_layout.addWidget(dir_label)
|
||||
dir_layout.addWidget(self.dir_input)
|
||||
dir_layout.addWidget(self.dir_button)
|
||||
self.dir_button.clicked.connect(self.select_directory)
|
||||
input_layout.addLayout(dir_layout)
|
||||
|
||||
settings_group = QGroupBox("Settings")
|
||||
settings_layout = QHBoxLayout(settings_group)
|
||||
settings_layout.setContentsMargins(10, 0, 10, 10)
|
||||
settings_layout.setSpacing(10)
|
||||
|
||||
settings_container = QWidget()
|
||||
settings_container_layout = QHBoxLayout(settings_container)
|
||||
settings_container_layout.setContentsMargins(0, 0, 0, 0)
|
||||
settings_container_layout.setSpacing(10)
|
||||
|
||||
self.headless_checkbox = QCheckBox("Headless")
|
||||
self.headless_checkbox.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.headless_checkbox.setChecked(True)
|
||||
settings_container_layout.addWidget(self.headless_checkbox)
|
||||
|
||||
self.fallback_checkbox = QCheckBox("Fallback")
|
||||
self.fallback_checkbox.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.fallback_checkbox.setChecked(False)
|
||||
settings_container_layout.addWidget(self.fallback_checkbox)
|
||||
|
||||
service_widget = QWidget()
|
||||
service_layout = QHBoxLayout(service_widget)
|
||||
service_layout.setContentsMargins(0, 0, 0, 0)
|
||||
service_layout.setSpacing(10)
|
||||
|
||||
service_label = QLabel("Service:")
|
||||
self.service_combo = ServiceComboBox()
|
||||
self.service_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
|
||||
service_layout.addWidget(service_label)
|
||||
service_layout.addWidget(self.service_combo)
|
||||
|
||||
settings_container_layout.addWidget(service_widget)
|
||||
|
||||
format_widget = QWidget()
|
||||
format_layout = QHBoxLayout(format_widget)
|
||||
format_layout.setContentsMargins(0, 0, 0, 0)
|
||||
format_layout.setSpacing(10)
|
||||
|
||||
format_label = QLabel("Filename:")
|
||||
self.format_title_artist = QRadioButton("Title")
|
||||
self.format_artist_title = QRadioButton("Artist")
|
||||
self.format_title_artist.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.format_artist_title.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.format_title_artist.setChecked(True)
|
||||
|
||||
format_layout.addWidget(format_label)
|
||||
format_layout.addWidget(self.format_title_artist)
|
||||
format_layout.addWidget(self.format_artist_title)
|
||||
|
||||
settings_container_layout.addWidget(format_widget)
|
||||
|
||||
settings_layout.addStretch()
|
||||
settings_layout.addWidget(settings_container)
|
||||
settings_layout.addStretch()
|
||||
|
||||
input_layout.addWidget(settings_group)
|
||||
self.main_layout.addWidget(self.input_widget)
|
||||
|
||||
self.track_widget = QWidget()
|
||||
self.track_widget.hide()
|
||||
track_layout = QHBoxLayout(self.track_widget)
|
||||
track_layout.setContentsMargins(0, 0, 0, 0)
|
||||
track_layout.setSpacing(10)
|
||||
|
||||
cover_container = QWidget()
|
||||
cover_layout = QVBoxLayout(cover_container)
|
||||
cover_layout.setContentsMargins(0, 0, 0, 0)
|
||||
cover_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
|
||||
|
||||
self.cover_label = QLabel()
|
||||
self.cover_label.setFixedSize(100, 100)
|
||||
self.cover_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
cover_layout.addWidget(self.cover_label)
|
||||
track_layout.addWidget(cover_container)
|
||||
|
||||
track_details_container = QWidget()
|
||||
track_details_layout = QVBoxLayout(track_details_container)
|
||||
track_details_layout.setContentsMargins(0, 0, 0, 0)
|
||||
track_details_layout.setSpacing(2)
|
||||
track_details_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
|
||||
|
||||
self.title_label = QLabel()
|
||||
self.title_label.setStyleSheet("font-size: 14px; font-weight: bold;")
|
||||
self.title_label.setWordWrap(True)
|
||||
self.title_label.setMinimumWidth(400)
|
||||
|
||||
self.artist_label = QLabel()
|
||||
self.artist_label.setStyleSheet("font-size: 12px;")
|
||||
self.artist_label.setWordWrap(True)
|
||||
self.artist_label.setMinimumWidth(400)
|
||||
|
||||
track_details_layout.addWidget(self.title_label)
|
||||
track_details_layout.addWidget(self.artist_label)
|
||||
track_layout.addWidget(track_details_container, stretch=1)
|
||||
track_layout.addStretch()
|
||||
self.main_layout.addWidget(self.track_widget)
|
||||
|
||||
self.download_button = QPushButton("Download")
|
||||
self.download_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.download_button.setFixedWidth(100)
|
||||
self.download_button.clicked.connect(self.button_clicked)
|
||||
self.download_button.hide()
|
||||
|
||||
self.cancel_button = QPushButton("Cancel")
|
||||
self.cancel_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.cancel_button.setFixedWidth(100)
|
||||
self.cancel_button.clicked.connect(self.cancel_clicked)
|
||||
self.cancel_button.hide()
|
||||
|
||||
self.open_button = QPushButton("Open")
|
||||
self.open_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.open_button.setFixedWidth(100)
|
||||
self.open_button.clicked.connect(self.open_output_directory)
|
||||
self.open_button.hide()
|
||||
|
||||
download_layout = QHBoxLayout()
|
||||
download_layout.addStretch()
|
||||
download_layout.addWidget(self.open_button)
|
||||
download_layout.addWidget(self.download_button)
|
||||
download_layout.addWidget(self.cancel_button)
|
||||
download_layout.addStretch()
|
||||
self.main_layout.addLayout(download_layout)
|
||||
|
||||
self.progress_bar = QProgressBar()
|
||||
self.progress_bar.hide()
|
||||
self.main_layout.addWidget(self.progress_bar)
|
||||
|
||||
bottom_layout = QHBoxLayout()
|
||||
|
||||
self.status_label = QLabel("")
|
||||
bottom_layout.addWidget(self.status_label, stretch=1)
|
||||
|
||||
self.update_button = QPushButton()
|
||||
icon_path = os.path.join(os.path.dirname(__file__), "update.svg")
|
||||
if os.path.exists(icon_path):
|
||||
self.update_button.setIcon(QIcon(icon_path))
|
||||
self.update_button.setFixedSize(16, 16)
|
||||
self.update_button.setStyleSheet("""
|
||||
QPushButton {
|
||||
border: none;
|
||||
background: transparent;
|
||||
}
|
||||
QPushButton:hover {
|
||||
background: transparent;
|
||||
}
|
||||
""")
|
||||
self.update_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.update_button.setToolTip("Check for Updates")
|
||||
self.update_button.clicked.connect(self.open_update_page)
|
||||
|
||||
bottom_layout.addWidget(self.update_button)
|
||||
|
||||
self.main_layout.addLayout(bottom_layout)
|
||||
|
||||
def open_update_page(self):
|
||||
import webbrowser
|
||||
webbrowser.open('https://github.com/afkarxyz/SpotifyFLAC/releases')
|
||||
|
||||
def validate_url(self, url):
|
||||
url = url.strip()
|
||||
self.fetch_button.setEnabled(False)
|
||||
if not url:
|
||||
self.status_label.clear()
|
||||
return
|
||||
if "open.spotify.com/" not in url:
|
||||
self.status_label.setText("Please enter a valid Spotify URL")
|
||||
return
|
||||
if "/album/" in url:
|
||||
self.status_label.setText("Album URLs are not supported. Please enter a track URL.")
|
||||
return
|
||||
if "/playlist/" in url:
|
||||
self.status_label.setText("Playlist URLs are not supported. Please enter a track URL.")
|
||||
return
|
||||
if "/track/" not in url:
|
||||
self.status_label.setText("Please enter a valid Spotify track URL")
|
||||
return
|
||||
self.fetch_button.setEnabled(True)
|
||||
self.status_label.clear()
|
||||
|
||||
def fetch_track_info(self):
|
||||
url = self.url_input.text().strip()
|
||||
if not url:
|
||||
self.status_label.setText("Please enter a Track URL")
|
||||
return
|
||||
self.fetch_button.setEnabled(False)
|
||||
self.status_label.setText("Fetching track information...")
|
||||
headless = self.headless_checkbox.isChecked()
|
||||
fallback = self.fallback_checkbox.isChecked()
|
||||
service = self.service_combo.currentData()
|
||||
self.fetcher = MetadataFetcher(url, headless=headless, service=service, use_fallback=fallback)
|
||||
self.fetcher.finished.connect(self.handle_track_info)
|
||||
self.fetcher.error.connect(self.handle_fetch_error)
|
||||
self.fetcher.start()
|
||||
|
||||
def handle_track_info(self, metadata):
|
||||
self.metadata = metadata
|
||||
self.fetch_button.setEnabled(True)
|
||||
self.title_label.setText(metadata['title'].strip())
|
||||
self.artist_label.setText(metadata['artists'].strip())
|
||||
self.image_downloader = ImageDownloader(metadata['cover'])
|
||||
self.image_downloader.finished.connect(self.update_cover_art)
|
||||
self.image_downloader.start()
|
||||
self.input_widget.hide()
|
||||
self.track_widget.show()
|
||||
self.download_button.show()
|
||||
self.cancel_button.show()
|
||||
self.update_button.hide()
|
||||
self.status_label.clear()
|
||||
self.adjustWindowHeight()
|
||||
|
||||
def adjustWindowHeight(self):
|
||||
title_height = self.title_label.sizeHint().height()
|
||||
artist_height = self.artist_label.sizeHint().height()
|
||||
base_height = 180
|
||||
additional_height = max(0, (title_height + artist_height) - 40)
|
||||
new_height = min(300, base_height + additional_height)
|
||||
self.setFixedHeight(int(new_height))
|
||||
|
||||
def update_cover_art(self, image_data):
|
||||
pixmap = QPixmap()
|
||||
pixmap.loadFromData(image_data)
|
||||
scaled_pixmap = pixmap.scaled(100, 100, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
|
||||
self.cover_label.setPixmap(scaled_pixmap)
|
||||
|
||||
def handle_fetch_error(self, error):
|
||||
self.fetch_button.setEnabled(True)
|
||||
self.status_label.setText(f"Error fetching track info: {error}")
|
||||
|
||||
def select_directory(self):
|
||||
directory = QFileDialog.getExistingDirectory(self, "Select Output Directory")
|
||||
if directory:
|
||||
self.dir_input.setText(directory)
|
||||
|
||||
def open_output_directory(self):
|
||||
output_dir = self.dir_input.text().strip() or self.default_music_dir
|
||||
os.startfile(output_dir)
|
||||
|
||||
def cancel_clicked(self):
|
||||
self.track_widget.hide()
|
||||
self.input_widget.show()
|
||||
self.download_button.hide()
|
||||
self.cancel_button.hide()
|
||||
self.progress_bar.hide()
|
||||
self.progress_bar.setValue(0)
|
||||
self.status_label.clear()
|
||||
self.metadata = None
|
||||
self.fetch_button.setEnabled(True)
|
||||
self.update_button.show()
|
||||
self.setFixedHeight(180)
|
||||
|
||||
def button_clicked(self):
|
||||
if self.download_button.text() == "Clear":
|
||||
self.clear_form()
|
||||
else:
|
||||
self.start_download()
|
||||
|
||||
def clear_form(self):
|
||||
self.url_input.clear()
|
||||
self.progress_bar.hide()
|
||||
self.progress_bar.setValue(0)
|
||||
self.status_label.clear()
|
||||
self.download_button.setText("Download")
|
||||
self.download_button.hide()
|
||||
self.cancel_button.hide()
|
||||
self.open_button.hide()
|
||||
self.track_widget.hide()
|
||||
self.input_widget.show()
|
||||
self.metadata = None
|
||||
self.update_button.show()
|
||||
self.setFixedHeight(180)
|
||||
|
||||
def start_download(self):
|
||||
output_dir = self.dir_input.text().strip()
|
||||
if not self.metadata:
|
||||
self.status_label.setText("Please fetch track information first")
|
||||
return
|
||||
if not output_dir:
|
||||
output_dir = self.default_music_dir
|
||||
self.dir_input.setText(output_dir)
|
||||
|
||||
self.download_button.hide()
|
||||
self.cancel_button.hide()
|
||||
self.progress_bar.show()
|
||||
self.progress_bar.setValue(0)
|
||||
self.status_label.setText("Preparing...")
|
||||
|
||||
format_type = 'artist_title' if self.format_artist_title.isChecked() else 'title_artist'
|
||||
fallback = self.fallback_checkbox.isChecked()
|
||||
|
||||
self.worker = DownloaderWorker(
|
||||
metadata=self.metadata,
|
||||
output_dir=output_dir,
|
||||
filename_format=format_type,
|
||||
use_fallback=fallback
|
||||
)
|
||||
|
||||
self.worker.progress.connect(self.update_progress)
|
||||
self.worker.status.connect(self.update_status)
|
||||
self.worker.finished.connect(self.download_finished)
|
||||
self.worker.error.connect(self.download_error)
|
||||
self.worker.start()
|
||||
|
||||
def update_status(self, status):
|
||||
self.status_label.setText(status)
|
||||
|
||||
def update_progress(self, value):
|
||||
self.progress_bar.setValue(value)
|
||||
|
||||
def download_finished(self, message):
|
||||
self.progress_bar.hide()
|
||||
self.status_label.setText(message)
|
||||
self.open_button.show()
|
||||
self.download_button.setText("Clear")
|
||||
self.download_button.show()
|
||||
self.cancel_button.hide()
|
||||
self.download_button.setEnabled(True)
|
||||
|
||||
def download_error(self, error_message):
|
||||
self.progress_bar.hide()
|
||||
self.status_label.setText(error_message)
|
||||
self.download_button.setText("Retry")
|
||||
self.download_button.show()
|
||||
self.cancel_button.show()
|
||||
self.download_button.setEnabled(True)
|
||||
self.cancel_button.setEnabled(True)
|
||||
|
||||
def main():
|
||||
app = QApplication(sys.argv)
|
||||
window = SpotifyFlacGUI()
|
||||
window.show()
|
||||
sys.exit(app.exec())
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
import requests
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
from mutagen.flac import FLAC
|
||||
|
||||
class DeezerDownloader:
|
||||
def __init__(self):
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update({
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
||||
})
|
||||
self.progress_callback = None
|
||||
|
||||
def set_progress_callback(self, callback):
|
||||
self.progress_callback = callback
|
||||
|
||||
def get_track_by_isrc(self, isrc):
|
||||
try:
|
||||
url = f"https://api.deezer.com/2.0/track/isrc:{isrc}"
|
||||
response = self.session.get(url)
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
|
||||
if 'error' in data:
|
||||
print(f"Error from Deezer API: {data['error']['message']}")
|
||||
return None
|
||||
|
||||
return data
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error fetching track data: {e}")
|
||||
return None
|
||||
|
||||
def extract_metadata(self, track_data):
|
||||
metadata = {}
|
||||
|
||||
metadata['title'] = track_data.get('title', '')
|
||||
metadata['title_short'] = track_data.get('title_short', '')
|
||||
metadata['duration'] = track_data.get('duration', 0)
|
||||
metadata['track_position'] = track_data.get('track_position', 1)
|
||||
metadata['disk_number'] = track_data.get('disk_number', 1)
|
||||
metadata['isrc'] = track_data.get('isrc', '')
|
||||
metadata['release_date'] = track_data.get('release_date', '')
|
||||
metadata['explicit_lyrics'] = track_data.get('explicit_lyrics', False)
|
||||
|
||||
if 'artist' in track_data:
|
||||
metadata['artist'] = track_data['artist'].get('name', '')
|
||||
metadata['artist_id'] = track_data['artist'].get('id', '')
|
||||
|
||||
if 'contributors' in track_data:
|
||||
artists = []
|
||||
for contributor in track_data['contributors']:
|
||||
if contributor.get('role') == 'Main':
|
||||
artists.append(contributor.get('name', ''))
|
||||
metadata['artists'] = ', '.join(artists) if artists else metadata.get('artist', '')
|
||||
|
||||
if 'album' in track_data:
|
||||
album = track_data['album']
|
||||
metadata['album'] = album.get('title', '')
|
||||
metadata['album_id'] = album.get('id', '')
|
||||
metadata['cover_url'] = album.get('cover_xl', album.get('cover_big', ''))
|
||||
metadata['cover_md5'] = album.get('md5_image', '')
|
||||
|
||||
metadata['deezer_link'] = track_data.get('link', '')
|
||||
metadata['preview_url'] = track_data.get('preview', '')
|
||||
|
||||
return metadata
|
||||
|
||||
def download_cover_art(self, cover_url, filename):
|
||||
if not cover_url:
|
||||
return None
|
||||
|
||||
try:
|
||||
response = self.session.get(cover_url)
|
||||
response.raise_for_status()
|
||||
|
||||
cover_path = f"{filename}_cover.jpg"
|
||||
with open(cover_path, 'wb') as f:
|
||||
f.write(response.content)
|
||||
|
||||
return cover_path
|
||||
except Exception as e:
|
||||
print(f"Error downloading cover art: {e}")
|
||||
return None
|
||||
|
||||
def embed_metadata(self, file_path, metadata, cover_path=None):
|
||||
try:
|
||||
audio = FLAC(file_path)
|
||||
|
||||
audio.clear()
|
||||
|
||||
if metadata.get('title'):
|
||||
audio['TITLE'] = metadata['title']
|
||||
if metadata.get('artists'):
|
||||
audio['ARTIST'] = metadata['artists']
|
||||
elif metadata.get('artist'):
|
||||
audio['ARTIST'] = metadata['artist']
|
||||
if metadata.get('album'):
|
||||
audio['ALBUM'] = metadata['album']
|
||||
if metadata.get('release_date'):
|
||||
audio['DATE'] = metadata['release_date']
|
||||
if metadata.get('track_position'):
|
||||
audio['TRACKNUMBER'] = str(metadata['track_position'])
|
||||
if metadata.get('disk_number'):
|
||||
audio['DISCNUMBER'] = str(metadata['disk_number'])
|
||||
if metadata.get('isrc'):
|
||||
audio['ISRC'] = metadata['isrc']
|
||||
|
||||
if cover_path and os.path.exists(cover_path):
|
||||
with open(cover_path, 'rb') as f:
|
||||
cover_data = f.read()
|
||||
|
||||
from mutagen.flac import Picture
|
||||
picture = Picture()
|
||||
picture.type = 3
|
||||
picture.mime = 'image/jpeg'
|
||||
picture.desc = 'Cover'
|
||||
picture.data = cover_data
|
||||
audio.add_picture(picture)
|
||||
|
||||
audio.save()
|
||||
print(f"Metadata embedded successfully in {file_path}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error embedding metadata: {e}")
|
||||
|
||||
async def download_by_isrc(self, isrc, output_dir="."):
|
||||
print(f"Fetching track info for ISRC: {isrc}")
|
||||
|
||||
track_data = self.get_track_by_isrc(isrc)
|
||||
if not track_data:
|
||||
print("Failed to get track data from Deezer API")
|
||||
return False
|
||||
|
||||
metadata = self.extract_metadata(track_data)
|
||||
print(f"Found track: {metadata.get('artists', 'Unknown')} - {metadata.get('title', 'Unknown')}")
|
||||
|
||||
track_id = track_data.get('id')
|
||||
if not track_id:
|
||||
print("No track ID found in Deezer API response")
|
||||
return False
|
||||
|
||||
print(f"Using track ID: {track_id}")
|
||||
|
||||
api_url = f"https://api.deezmate.com/dl/{track_id}"
|
||||
print(f"Requesting download links from: {api_url}")
|
||||
|
||||
try:
|
||||
response = self.session.get(api_url)
|
||||
response.raise_for_status()
|
||||
api_data = response.json()
|
||||
|
||||
if not api_data.get('success'):
|
||||
print("API request failed")
|
||||
return False
|
||||
|
||||
links = api_data.get('links', {})
|
||||
flac_url = links.get('flac')
|
||||
|
||||
if not flac_url:
|
||||
print("No FLAC download link found in API response")
|
||||
return False
|
||||
|
||||
print(f"Successfully obtained FLAC download URL")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error getting download URL from API: {e}")
|
||||
return False
|
||||
|
||||
print("Downloading FLAC file...")
|
||||
try:
|
||||
response = self.session.get(flac_url, stream=True)
|
||||
response.raise_for_status()
|
||||
|
||||
total_size = int(response.headers.get('content-length', 0))
|
||||
print(f"File size: {total_size} bytes ({total_size / (1024*1024):.2f} MB)")
|
||||
|
||||
safe_title = "".join(c for c in metadata.get('title', 'Unknown') if c.isalnum() or c in (' ', '-', '_')).rstrip()
|
||||
safe_artist = "".join(c for c in metadata.get('artists', 'Unknown') if c.isalnum() or c in (' ', '-', '_')).rstrip()
|
||||
filename = f"{safe_artist} - {safe_title}.flac"
|
||||
file_path = os.path.join(output_dir, filename)
|
||||
|
||||
downloaded = 0
|
||||
with open(file_path, 'wb') as f:
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
downloaded += len(chunk)
|
||||
if self.progress_callback and total_size > 0:
|
||||
current_mb = downloaded / (1024 * 1024)
|
||||
total_mb = total_size / (1024 * 1024)
|
||||
percent = (downloaded / total_size) * 100
|
||||
self.progress_callback(downloaded, total_size)
|
||||
|
||||
print(f"Downloaded: {file_path}")
|
||||
|
||||
cover_path = None
|
||||
if metadata.get('cover_url'):
|
||||
print("Downloading cover art...")
|
||||
cover_path = self.download_cover_art(metadata['cover_url'],
|
||||
os.path.join(output_dir, f"{safe_artist} - {safe_title}"))
|
||||
|
||||
print("Embedding metadata...")
|
||||
self.embed_metadata(file_path, metadata, cover_path)
|
||||
|
||||
if cover_path and os.path.exists(cover_path):
|
||||
os.remove(cover_path)
|
||||
|
||||
print(f"Successfully downloaded and tagged: {filename}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error downloading file: {e}")
|
||||
return False
|
||||
|
||||
async def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: python deezerDL.py <ISRC>")
|
||||
print("Example: python deezerDL.py USUM72409273")
|
||||
return
|
||||
|
||||
isrc = sys.argv[1]
|
||||
downloader = DeezerDownloader()
|
||||
|
||||
success = await downloader.download_by_isrc(isrc)
|
||||
if success:
|
||||
print("Download completed successfully!")
|
||||
else:
|
||||
print("Download failed!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import nodriver as uc
|
||||
import asyncio
|
||||
|
||||
async def download_deezer_track(deezer_link=None, initial_delay=7.5):
|
||||
if deezer_link is None:
|
||||
deezer_link = "https://www.deezer.com/us/track/2947516331"
|
||||
|
||||
browser = None
|
||||
try:
|
||||
browser = await uc.start(headless=False)
|
||||
page = await browser.get("https://deezmate.com/en")
|
||||
|
||||
print("Loading...")
|
||||
await asyncio.sleep(initial_delay)
|
||||
|
||||
input_selector = 'input[placeholder="Paste your Deezer link here..."]'
|
||||
await page.wait_for(input_selector, timeout=15)
|
||||
input_element = await page.select(input_selector)
|
||||
await input_element.clear_input()
|
||||
await input_element.send_keys(deezer_link)
|
||||
print("Link entered")
|
||||
|
||||
await page.evaluate("""
|
||||
window.apiResponse = null;
|
||||
window.originalFetch = window.fetch;
|
||||
window.fetch = function(...args) {
|
||||
return window.originalFetch(...args).then(async response => {
|
||||
if (response.url.includes('api.deezmate.com/dl/')) {
|
||||
try {
|
||||
const data = await response.clone().json();
|
||||
window.apiResponse = data;
|
||||
console.log('Captured API response:', data);
|
||||
} catch (e) {
|
||||
console.log('Error parsing API response:', e);
|
||||
}
|
||||
}
|
||||
return response;
|
||||
});
|
||||
};
|
||||
""")
|
||||
|
||||
max_retries = 3
|
||||
download_button_clicked = False
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
download_button_selector = 'button.bg-purple.hover\\:bg-purple-dark.cursor-pointer.transition.text-white.rounded-xl.p-2.mt-2.w-full.mb-5'
|
||||
await page.wait_for(download_button_selector, timeout=15)
|
||||
download_button = await page.select(download_button_selector)
|
||||
await download_button.click()
|
||||
print("Processing...")
|
||||
download_button_clicked = True
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
if attempt < max_retries - 1:
|
||||
print(f"Turnstile verification failed, retrying... ({attempt + 1}/{max_retries})")
|
||||
await asyncio.sleep(0.5)
|
||||
await page.evaluate("window.apiResponse = null;")
|
||||
else:
|
||||
print("Failed to pass Turnstile verification after all retries")
|
||||
raise e
|
||||
|
||||
if not download_button_clicked:
|
||||
return None
|
||||
|
||||
try:
|
||||
track_download_selector = 'button.bg-purple.text-white.flex.items-center.gap-2.px-3.py-1.rounded-full.hover\\:bg-purple-dark.transition'
|
||||
await page.wait_for(track_download_selector, timeout=15)
|
||||
track_download_button = await page.select(track_download_selector)
|
||||
await track_download_button.click()
|
||||
except Exception as e:
|
||||
print(f"Failed to click track download button: {e}")
|
||||
return None
|
||||
|
||||
print("Getting FLAC URL from API response...")
|
||||
|
||||
api_response = None
|
||||
for i in range(30):
|
||||
api_response = await page.evaluate("window.apiResponse")
|
||||
if api_response:
|
||||
break
|
||||
await asyncio.sleep(0.2)
|
||||
|
||||
if not api_response:
|
||||
return None
|
||||
|
||||
def parse_nodriver_response(data):
|
||||
if isinstance(data, list):
|
||||
result = {}
|
||||
for item in data:
|
||||
if isinstance(item, list) and len(item) == 2:
|
||||
key = item[0]
|
||||
value_obj = item[1]
|
||||
if isinstance(value_obj, dict) and 'value' in value_obj:
|
||||
if value_obj.get('type') == 'object':
|
||||
result[key] = parse_nodriver_response(value_obj['value'])
|
||||
else:
|
||||
result[key] = value_obj['value']
|
||||
return result
|
||||
return data
|
||||
|
||||
parsed_response = parse_nodriver_response(api_response)
|
||||
|
||||
if parsed_response.get('success') and parsed_response.get('links'):
|
||||
flac_url = parsed_response['links'].get('flac')
|
||||
if flac_url:
|
||||
print(f"Successfully obtained FLAC download URL: {flac_url}")
|
||||
return flac_url
|
||||
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
return None
|
||||
finally:
|
||||
if browser:
|
||||
try:
|
||||
await browser.stop()
|
||||
except:
|
||||
pass
|
||||
|
||||
async def main(deezer_link=None, initial_delay=7.5):
|
||||
flac_url = await download_deezer_track(deezer_link, initial_delay)
|
||||
if not flac_url:
|
||||
print("Failed to download track")
|
||||
return flac_url
|
||||
|
||||
if __name__ == "__main__":
|
||||
uc.loop().run_until_complete(main())
|
||||
+505
-99
@@ -1,99 +1,505 @@
|
||||
import asyncio
|
||||
import zendriver as zd
|
||||
|
||||
async def get_metadata(page, headless=True):
|
||||
max_attempts = 40
|
||||
attempts = 0
|
||||
|
||||
await asyncio.sleep(2)
|
||||
|
||||
await page.evaluate("""
|
||||
window.downloadInfo = null;
|
||||
const originalFetch = window.fetch;
|
||||
window.fetch = async function(...args) {
|
||||
const [url, config] = args;
|
||||
if (url.includes('/api/load?url=%2Fapi%2Ffetch%2Fstream%2Fv2')) {
|
||||
const payload = JSON.parse(config.body);
|
||||
const title = document.querySelector('h1.svelte-6pt9ji').textContent.trim();
|
||||
const artists = Array.from(document.querySelectorAll('h2.svelte-6pt9ji a.normal'))
|
||||
.map(a => a.textContent.trim())
|
||||
.join(', ');
|
||||
const cover = document.querySelector('.svelte-6pt9ji .meta.svelte-6pt9ji a').href;
|
||||
|
||||
window.downloadInfo = {
|
||||
url: payload.url,
|
||||
cover: cover,
|
||||
title: title,
|
||||
artists: artists,
|
||||
token: payload.token.primary,
|
||||
expiry: payload.token.expiry
|
||||
};
|
||||
}
|
||||
return originalFetch.apply(this, args);
|
||||
};
|
||||
""")
|
||||
|
||||
await page.evaluate("""
|
||||
function waitForElement(selector) {
|
||||
return new Promise(resolve => {
|
||||
if (document.querySelector(selector)) {
|
||||
return resolve(document.querySelector(selector));
|
||||
}
|
||||
|
||||
const observer = new MutationObserver(mutations => {
|
||||
if (document.querySelector(selector)) {
|
||||
observer.disconnect();
|
||||
resolve(document.querySelector(selector));
|
||||
}
|
||||
});
|
||||
|
||||
observer.observe(document.documentElement, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (!window.location.hostname.includes('lucida.')) return;
|
||||
|
||||
await Promise.race([
|
||||
waitForElement('.d1-track button'),
|
||||
waitForElement('button[class*="download-button"]')
|
||||
]);
|
||||
|
||||
const clickDownloadButton = () => {
|
||||
const button = document.querySelector('.d1-track button') ||
|
||||
document.querySelector('button[class*="download-button"]');
|
||||
if (button) button.click();
|
||||
};
|
||||
|
||||
clickDownloadButton();
|
||||
})();
|
||||
""")
|
||||
|
||||
while attempts < max_attempts:
|
||||
download_info = await page.evaluate("window.downloadInfo")
|
||||
if download_info:
|
||||
return download_info
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
attempts += 1
|
||||
|
||||
raise TimeoutError("Timeout")
|
||||
|
||||
async def main(headless=True):
|
||||
browser = await zd.start(headless=headless)
|
||||
try:
|
||||
track_id = "2plbrEY59IikOBgBGLjaoe"
|
||||
url = f"https://lucida.to/?url=https%3A%2F%2Fopen.spotify.com%2Ftrack%2F{track_id}&country=auto&to=tidal"
|
||||
|
||||
page = await browser.get(url)
|
||||
download_info = await get_metadata(page)
|
||||
print(download_info)
|
||||
return download_info
|
||||
finally:
|
||||
await browser.stop()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
from time import sleep
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
import pyotp
|
||||
import base64
|
||||
from random import randrange
|
||||
from typing import Dict, Any, List, Tuple
|
||||
|
||||
# https://github.com/visagenull/Spotify-Free
|
||||
def get_random_user_agent():
|
||||
return f"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_{randrange(11, 15)}_{randrange(4, 9)}) AppleWebKit/{randrange(530, 537)}.{randrange(30, 37)} (KHTML, like Gecko) Chrome/{randrange(80, 105)}.0.{randrange(3000, 4500)}.{randrange(60, 125)} Safari/{randrange(530, 537)}.{randrange(30, 36)}"
|
||||
|
||||
def generate_totp():
|
||||
url = "https://raw.githubusercontent.com/Thereallo1026/spotify-secrets/refs/heads/main/secrets/secretBytes.json"
|
||||
|
||||
try:
|
||||
resp = requests.get(url, timeout=10)
|
||||
if resp.status_code != 200:
|
||||
raise Exception(f"Failed to fetch TOTP secrets from GitHub. Status: {resp.status_code}")
|
||||
secrets_list = resp.json()
|
||||
|
||||
latest_entry = max(secrets_list, key=lambda x: x["version"])
|
||||
version = latest_entry["version"]
|
||||
secret_cipher = latest_entry["secret"]
|
||||
except Exception as e:
|
||||
raise Exception(f"Failed to fetch secrets from GitHub: {str(e)}")
|
||||
|
||||
processed = [byte ^ ((i % 33) + 9) for i, byte in enumerate(secret_cipher)]
|
||||
processed_str = "".join(map(str, processed))
|
||||
utf8_bytes = processed_str.encode('utf-8')
|
||||
hex_str = utf8_bytes.hex()
|
||||
secret_bytes = bytes.fromhex(hex_str)
|
||||
b32_secret = base64.b32encode(secret_bytes).decode('utf-8')
|
||||
totp = pyotp.TOTP(b32_secret)
|
||||
|
||||
headers = {
|
||||
"Host": "open.spotify.com",
|
||||
"User-Agent": get_random_user_agent(),
|
||||
"Accept": "*/*",
|
||||
}
|
||||
|
||||
try:
|
||||
resp = requests.get("https://open.spotify.com/api/server-time", headers=headers, timeout=10)
|
||||
if resp.status_code != 200:
|
||||
raise Exception(f"Failed to get server time. Status code: {resp.status_code}")
|
||||
data = resp.json()
|
||||
server_time = data.get("serverTime")
|
||||
if server_time is None:
|
||||
raise Exception("Failed to fetch server time from Spotify")
|
||||
return totp, server_time, version
|
||||
except Exception as e:
|
||||
raise Exception(f"Error getting server time: {str(e)}")
|
||||
|
||||
token_url = 'https://open.spotify.com/api/token'
|
||||
playlist_base_url = 'https://api.spotify.com/v1/playlists/{}'
|
||||
album_base_url = 'https://api.spotify.com/v1/albums/{}'
|
||||
track_base_url = 'https://api.spotify.com/v1/tracks/{}'
|
||||
headers = {
|
||||
'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',
|
||||
'Accept': 'application/json',
|
||||
'Accept-Language': 'en-US,en;q=0.9',
|
||||
'Accept-Encoding': 'gzip, deflate, br',
|
||||
'sec-ch-ua-platform': '"Windows"',
|
||||
'sec-fetch-dest': 'empty',
|
||||
'sec-fetch-mode': 'cors',
|
||||
'sec-fetch-site': 'same-origin',
|
||||
'Referer': 'https://open.spotify.com/',
|
||||
'Origin': 'https://open.spotify.com'
|
||||
}
|
||||
|
||||
class SpotifyInvalidUrlException(Exception):
|
||||
pass
|
||||
|
||||
class SpotifyWebsiteParserException(Exception):
|
||||
pass
|
||||
|
||||
def parse_uri(uri):
|
||||
u = urlparse(uri)
|
||||
if u.netloc == "embed.spotify.com":
|
||||
if not u.query:
|
||||
raise SpotifyInvalidUrlException("ERROR: url {} is not supported".format(uri))
|
||||
qs = parse_qs(u.query)
|
||||
return parse_uri(qs['uri'][0])
|
||||
|
||||
if not u.scheme and not u.netloc:
|
||||
return {"type": "playlist", "id": u.path}
|
||||
|
||||
if u.scheme == "spotify":
|
||||
parts = uri.split(":")
|
||||
else:
|
||||
if u.netloc != "open.spotify.com" and u.netloc != "play.spotify.com":
|
||||
raise SpotifyInvalidUrlException("ERROR: url {} is not supported".format(uri))
|
||||
parts = u.path.split("/")
|
||||
|
||||
if parts[1] == "embed":
|
||||
parts = parts[1:]
|
||||
|
||||
l = len(parts)
|
||||
if l == 3 and parts[1] in ["album", "track", "playlist"]:
|
||||
return {"type": parts[1], "id": parts[2]}
|
||||
if l == 5 and parts[3] == "playlist":
|
||||
return {"type": parts[3], "id": parts[4]}
|
||||
|
||||
raise SpotifyInvalidUrlException("ERROR: unable to determine Spotify URL type or type is unsupported.")
|
||||
|
||||
def get_json_from_api(api_url, access_token):
|
||||
headers.update({'Authorization': 'Bearer {}'.format(access_token)})
|
||||
|
||||
req = requests.get(api_url, headers=headers, timeout=10)
|
||||
|
||||
if req.status_code == 429:
|
||||
seconds = int(req.headers.get("Retry-After", "5")) + 1
|
||||
print(f"INFO: rate limited! Sleeping for {seconds} seconds")
|
||||
sleep(seconds)
|
||||
return None
|
||||
|
||||
if req.status_code != 200:
|
||||
raise SpotifyWebsiteParserException(f"ERROR: {api_url} gave us not a 200. Instead: {req.status_code}")
|
||||
|
||||
return req.json()
|
||||
|
||||
def get_access_token():
|
||||
try:
|
||||
totp, server_time, totp_version = generate_totp()
|
||||
otp_code = totp.at(int(server_time))
|
||||
timestamp_ms = int(time.time() * 1000)
|
||||
|
||||
params = {
|
||||
'reason': 'init',
|
||||
'productType': 'web-player',
|
||||
'totp': otp_code,
|
||||
'totpServerTime': server_time,
|
||||
'totpVer': str(totp_version),
|
||||
'sTime': server_time,
|
||||
'cTime': timestamp_ms,
|
||||
'buildVer': 'web-player_2025-07-02_1720000000000_12345678',
|
||||
'buildDate': '2025-07-02'
|
||||
}
|
||||
|
||||
req = requests.get(token_url, headers=headers, params=params, timeout=10)
|
||||
if req.status_code != 200:
|
||||
return {"error": f"Failed to get access token. Status code: {req.status_code}"}
|
||||
return req.json()
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to get access token: {str(e)}"}
|
||||
|
||||
def fetch_tracks_in_batches(url: str, access_token: str, batch_size: int = 100, delay: float = 1.0) -> Tuple[List[Dict[str, Any]], int]:
|
||||
all_tracks = []
|
||||
current_batch = 0
|
||||
|
||||
while url:
|
||||
print(f"Batch : {current_batch}")
|
||||
|
||||
url_parts = url.split("offset=")
|
||||
if len(url_parts) > 1:
|
||||
offset_part = url_parts[1].split("&")[0]
|
||||
print(f"Offset : {offset_part}")
|
||||
print("-------------")
|
||||
|
||||
track_data = get_json_from_api(url, access_token)
|
||||
if not track_data:
|
||||
break
|
||||
|
||||
items = track_data.get('items', [])
|
||||
all_tracks.extend(items)
|
||||
|
||||
url = track_data.get('next')
|
||||
if url and "&locale=" in url:
|
||||
url = url.split("&locale=")[0]
|
||||
|
||||
if url and delay > 0:
|
||||
sleep(delay)
|
||||
|
||||
current_batch += 1
|
||||
|
||||
return all_tracks, current_batch
|
||||
|
||||
def get_raw_spotify_data(spotify_url, batch: bool = False, delay: float = 1.0):
|
||||
url_info = parse_uri(spotify_url)
|
||||
token = get_access_token()
|
||||
|
||||
if "error" in token:
|
||||
return token
|
||||
|
||||
access_token = token["accessToken"]
|
||||
raw_data = {}
|
||||
|
||||
if url_info['type'] == "playlist":
|
||||
try:
|
||||
playlist_data = get_json_from_api(
|
||||
playlist_base_url.format(url_info["id"]),
|
||||
access_token
|
||||
)
|
||||
if not playlist_data:
|
||||
return {"error": "Failed to get playlist data"}
|
||||
|
||||
raw_data = playlist_data
|
||||
total_tracks = playlist_data.get('tracks', {}).get('total', 0)
|
||||
|
||||
if batch:
|
||||
tracks_url = f'https://api.spotify.com/v1/playlists/{url_info["id"]}/tracks?limit=100'
|
||||
tracks, num_batches = fetch_tracks_in_batches(tracks_url, access_token, 100, delay)
|
||||
raw_data['tracks']['items'] = tracks
|
||||
raw_data['_batch_count'] = num_batches
|
||||
raw_data['_batch_enabled'] = True
|
||||
|
||||
if len(tracks) < total_tracks:
|
||||
last_offset = len(tracks)
|
||||
remaining_tracks = []
|
||||
|
||||
while last_offset < total_tracks:
|
||||
print(f"Batch : {num_batches}")
|
||||
print(f"Offset : {last_offset}")
|
||||
print("-------------")
|
||||
|
||||
remainder_url = f'https://api.spotify.com/v1/playlists/{url_info["id"]}/tracks?offset={last_offset}&limit=100'
|
||||
track_data = get_json_from_api(remainder_url, access_token)
|
||||
|
||||
if not track_data or not track_data.get('items'):
|
||||
break
|
||||
|
||||
items = track_data.get('items', [])
|
||||
remaining_tracks.extend(items)
|
||||
|
||||
if len(items) < 100:
|
||||
break
|
||||
|
||||
last_offset += len(items)
|
||||
num_batches += 1
|
||||
|
||||
if delay > 0:
|
||||
sleep(delay)
|
||||
|
||||
tracks.extend(remaining_tracks)
|
||||
raw_data['tracks']['items'] = tracks
|
||||
raw_data['_batch_count'] = num_batches
|
||||
else:
|
||||
tracks = []
|
||||
tracks_url = f'https://api.spotify.com/v1/playlists/{url_info["id"]}/tracks?limit=100'
|
||||
while tracks_url:
|
||||
track_data = get_json_from_api(tracks_url, access_token)
|
||||
if not track_data:
|
||||
break
|
||||
|
||||
tracks.extend(track_data['items'])
|
||||
tracks_url = track_data.get('next')
|
||||
if tracks_url and "&locale=" in tracks_url:
|
||||
tracks_url = tracks_url.split("&locale=")[0]
|
||||
|
||||
raw_data['tracks']['items'] = tracks
|
||||
raw_data['_batch_enabled'] = False
|
||||
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to get playlist data: {str(e)}"}
|
||||
|
||||
elif url_info["type"] == "album":
|
||||
try:
|
||||
album_data = get_json_from_api(
|
||||
album_base_url.format(url_info["id"]),
|
||||
access_token
|
||||
)
|
||||
if not album_data:
|
||||
return {"error": "Failed to get album data"}
|
||||
|
||||
album_data['_token'] = access_token
|
||||
raw_data = album_data
|
||||
total_tracks = album_data.get('total_tracks', 0)
|
||||
|
||||
if batch:
|
||||
tracks_url = f'{album_base_url.format(url_info["id"])}/tracks?limit=50'
|
||||
tracks, num_batches = fetch_tracks_in_batches(tracks_url, access_token, 50, delay)
|
||||
raw_data['tracks']['items'] = tracks
|
||||
raw_data['_batch_count'] = num_batches
|
||||
raw_data['_batch_enabled'] = True
|
||||
|
||||
if len(tracks) < total_tracks:
|
||||
last_offset = len(tracks)
|
||||
remaining_tracks = []
|
||||
|
||||
while last_offset < total_tracks:
|
||||
print(f"Batch : {num_batches}")
|
||||
print(f"Offset : {last_offset}")
|
||||
print("-------------")
|
||||
|
||||
remainder_url = f'{album_base_url.format(url_info["id"])}/tracks?offset={last_offset}&limit=50'
|
||||
track_data = get_json_from_api(remainder_url, access_token)
|
||||
|
||||
if not track_data or not track_data.get('items'):
|
||||
break
|
||||
|
||||
items = track_data.get('items', [])
|
||||
remaining_tracks.extend(items)
|
||||
|
||||
if len(items) < 50:
|
||||
break
|
||||
|
||||
last_offset += len(items)
|
||||
num_batches += 1
|
||||
|
||||
if delay > 0:
|
||||
sleep(delay)
|
||||
|
||||
tracks.extend(remaining_tracks)
|
||||
raw_data['tracks']['items'] = tracks
|
||||
raw_data['_batch_count'] = num_batches
|
||||
else:
|
||||
tracks = []
|
||||
tracks_url = f'{album_base_url.format(url_info["id"])}/tracks?limit=50'
|
||||
while tracks_url:
|
||||
track_data = get_json_from_api(tracks_url, access_token)
|
||||
if not track_data:
|
||||
break
|
||||
|
||||
tracks.extend(track_data['items'])
|
||||
tracks_url = track_data.get('next')
|
||||
if tracks_url and "&locale=" in tracks_url:
|
||||
tracks_url = tracks_url.split("&locale=")[0]
|
||||
|
||||
raw_data['tracks']['items'] = tracks
|
||||
raw_data['_batch_enabled'] = False
|
||||
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to get album data: {str(e)}"}
|
||||
|
||||
elif url_info["type"] == "track":
|
||||
try:
|
||||
track_data = get_json_from_api(
|
||||
track_base_url.format(url_info["id"]),
|
||||
access_token
|
||||
)
|
||||
if not track_data:
|
||||
return {"error": "Failed to get track data"}
|
||||
|
||||
raw_data = track_data
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to get track data: {str(e)}"}
|
||||
|
||||
return raw_data
|
||||
|
||||
def format_track_data(track_data):
|
||||
artists = []
|
||||
for artist in track_data.get('artists', []):
|
||||
artists.append(artist['name'])
|
||||
|
||||
image_url = track_data.get('album', {}).get('images', [{}])[0].get('url', '') if track_data.get('album', {}).get('images') else ''
|
||||
|
||||
isrc = track_data.get('external_ids', {}).get('isrc', '')
|
||||
|
||||
return {
|
||||
"track": {
|
||||
"artists": ", ".join(artists),
|
||||
"name": track_data.get('name', ''),
|
||||
"album_name": track_data.get('album', {}).get('name', ''),
|
||||
"duration_ms": track_data.get('duration_ms', 0),
|
||||
"images": image_url,
|
||||
"release_date": track_data.get('album', {}).get('release_date', ''),
|
||||
"track_number": track_data.get('track_number', 0),
|
||||
"external_urls": track_data.get('external_urls', {}).get('spotify', ''),
|
||||
"isrc": isrc
|
||||
}
|
||||
}
|
||||
|
||||
def format_album_data(album_data):
|
||||
artists = []
|
||||
for artist in album_data.get('artists', []):
|
||||
artists.append(artist['name'])
|
||||
|
||||
image_url = album_data.get('images', [{}])[0].get('url', '') if album_data.get('images') else ''
|
||||
|
||||
track_list = []
|
||||
for track in album_data.get('tracks', {}).get('items', []):
|
||||
track_artists = []
|
||||
for artist in track.get('artists', []):
|
||||
track_artists.append(artist['name'])
|
||||
|
||||
track_id = track.get('id', '')
|
||||
track_isrc = ''
|
||||
|
||||
if track_id and album_data.get('_token'):
|
||||
try:
|
||||
full_track_data = get_json_from_api(
|
||||
track_base_url.format(track_id),
|
||||
album_data.get('_token')
|
||||
)
|
||||
if full_track_data:
|
||||
track_isrc = full_track_data.get('external_ids', {}).get('isrc', '')
|
||||
except:
|
||||
pass
|
||||
|
||||
track_list.append({
|
||||
"artists": ", ".join(track_artists),
|
||||
"name": track.get('name', ''),
|
||||
"album_name": album_data.get('name', ''),
|
||||
"duration_ms": track.get('duration_ms', 0),
|
||||
"images": image_url,
|
||||
"release_date": album_data.get('release_date', ''),
|
||||
"track_number": track.get('track_number', 0),
|
||||
"external_urls": track.get('external_urls', {}).get('spotify', ''),
|
||||
"isrc": track_isrc
|
||||
})
|
||||
|
||||
album_info = {
|
||||
"total_tracks": album_data.get('total_tracks', 0),
|
||||
"name": album_data.get('name', ''),
|
||||
"release_date": album_data.get('release_date', ''),
|
||||
"artists": ", ".join(artists),
|
||||
"images": image_url
|
||||
}
|
||||
|
||||
if album_data.get('_batch_enabled', False):
|
||||
album_info["batch"] = f"{album_data.get('_batch_count', 1)}"
|
||||
|
||||
return {
|
||||
"album_info": album_info,
|
||||
"track_list": track_list
|
||||
}
|
||||
|
||||
def format_playlist_data(playlist_data):
|
||||
image_url = playlist_data.get('images', [{}])[0].get('url', '') if playlist_data.get('images') else ''
|
||||
|
||||
track_list = []
|
||||
for item in playlist_data.get('tracks', {}).get('items', []):
|
||||
track = item.get('track', {})
|
||||
if not track:
|
||||
continue
|
||||
|
||||
artists = []
|
||||
for artist in track.get('artists', []):
|
||||
artists.append(artist['name'])
|
||||
|
||||
track_image = ''
|
||||
if track.get('album', {}).get('images'):
|
||||
track_image = track.get('album', {}).get('images', [{}])[0].get('url', '')
|
||||
|
||||
track_isrc = track.get('external_ids', {}).get('isrc', '')
|
||||
|
||||
track_list.append({
|
||||
"artists": ", ".join(artists),
|
||||
"name": track.get('name', ''),
|
||||
"album_name": track.get('album', {}).get('name', ''),
|
||||
"duration_ms": track.get('duration_ms', 0),
|
||||
"images": track_image,
|
||||
"release_date": track.get('album', {}).get('release_date', ''),
|
||||
"track_number": track.get('track_number', 0),
|
||||
"external_urls": track.get('external_urls', {}).get('spotify', ''),
|
||||
"isrc": track_isrc
|
||||
})
|
||||
|
||||
playlist_info = {
|
||||
"tracks": {"total": playlist_data.get('tracks', {}).get('total', 0)},
|
||||
"followers": {"total": playlist_data.get('followers', {}).get('total', 0)},
|
||||
"owner": {
|
||||
"display_name": playlist_data.get('owner', {}).get('display_name', ''),
|
||||
"name": playlist_data.get('name', ''),
|
||||
"images": image_url
|
||||
}
|
||||
}
|
||||
|
||||
if playlist_data.get('_batch_enabled', False):
|
||||
playlist_info["batch"] = f"{playlist_data.get('_batch_count', 1)}"
|
||||
|
||||
return {
|
||||
"playlist_info": playlist_info,
|
||||
"track_list": track_list
|
||||
}
|
||||
|
||||
def process_spotify_data(raw_data, data_type):
|
||||
if not raw_data or "error" in raw_data:
|
||||
return {"error": "Invalid data provided"}
|
||||
|
||||
try:
|
||||
if data_type == "track":
|
||||
return format_track_data(raw_data)
|
||||
elif data_type == "album":
|
||||
return format_album_data(raw_data)
|
||||
elif data_type == "playlist":
|
||||
return format_playlist_data(raw_data)
|
||||
else:
|
||||
return {"error": "Invalid data type"}
|
||||
except Exception as e:
|
||||
return {"error": f"Error processing data: {str(e)}"}
|
||||
|
||||
def get_filtered_data(spotify_url, batch=False, delay=1.0):
|
||||
raw_data = get_raw_spotify_data(spotify_url, batch=batch, delay=delay)
|
||||
if raw_data and "error" not in raw_data:
|
||||
url_info = parse_uri(spotify_url)
|
||||
filtered_data = process_spotify_data(raw_data, url_info['type'])
|
||||
return filtered_data
|
||||
return {"error": "Failed to get raw data"}
|
||||
|
||||
if __name__ == '__main__':
|
||||
playlist = "https://open.spotify.com/playlist/37i9dQZEVXbNG2KDcFcKOF"
|
||||
album = "https://open.spotify.com/album/6J84szYCnMfzEcvIcfWMFL"
|
||||
song = "https://open.spotify.com/track/7so0lgd0zP2Sbgs2d7a1SZ"
|
||||
|
||||
filtered_playlist = get_filtered_data(playlist, batch=True, delay=0.1)
|
||||
print(json.dumps(filtered_playlist, indent=2))
|
||||
|
||||
filtered_album = get_filtered_data(album)
|
||||
print(json.dumps(filtered_album, indent=2))
|
||||
|
||||
filtered_track = get_filtered_data(song)
|
||||
print(json.dumps(filtered_track, indent=2))
|
||||
-143
@@ -1,143 +0,0 @@
|
||||
import requests
|
||||
import time
|
||||
import os
|
||||
import asyncio
|
||||
from GetMetadata import main as get_metadata
|
||||
|
||||
class TrackDownloader:
|
||||
def __init__(self, use_fallback=False):
|
||||
self.client = requests.Session()
|
||||
self.headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
||||
}
|
||||
self.progress_callback = None
|
||||
self.filename_format = 'title_artist'
|
||||
self.use_fallback = use_fallback
|
||||
self.base_domain = "lucida.su" if use_fallback else "lucida.to"
|
||||
|
||||
def set_progress_callback(self, callback):
|
||||
self.progress_callback = callback
|
||||
|
||||
def set_filename_format(self, format_type):
|
||||
self.filename_format = format_type
|
||||
|
||||
def generate_filename(self, metadata):
|
||||
if self.filename_format == 'artist_title':
|
||||
filename = f"{metadata['artists']} - {metadata['title']}.flac"
|
||||
else:
|
||||
filename = f"{metadata['title']} - {metadata['artists']}.flac"
|
||||
return self.sanitize_filename(filename)
|
||||
|
||||
async def get_track_info(self):
|
||||
metadata = await get_metadata()
|
||||
return metadata
|
||||
|
||||
def sanitize_filename(self, filename):
|
||||
invalid_chars = '<>:"/\\|?*'
|
||||
for char in invalid_chars:
|
||||
filename = filename.replace(char, '')
|
||||
|
||||
filename = ' '.join(filename.split())
|
||||
filename = filename.replace(' ,', ',')
|
||||
filename = filename.replace(',', ', ')
|
||||
while ' ' in filename:
|
||||
filename = filename.replace(' ', ' ')
|
||||
filename = filename.rsplit('.', 1)
|
||||
filename[0] = filename[0].strip()
|
||||
return '.'.join(filename)
|
||||
|
||||
def download(self, metadata, output_dir):
|
||||
track_url = metadata['url']
|
||||
primary_token = metadata['token']
|
||||
expiry = metadata['expiry']
|
||||
|
||||
print(f"Starting download for: {track_url}")
|
||||
|
||||
initial_request = {
|
||||
"account": {"id": "auto", "type": "country"},
|
||||
"compat": "false",
|
||||
"downscale": "original",
|
||||
"handoff": True,
|
||||
"metadata": True,
|
||||
"private": True,
|
||||
"token": {
|
||||
"expiry": expiry,
|
||||
"primary": primary_token
|
||||
},
|
||||
"upload": {"enabled": False, "service": "pixeldrain"},
|
||||
"url": track_url
|
||||
}
|
||||
|
||||
response = self.client.post(f"https://{self.base_domain}/api/load?url=/api/fetch/stream/v2",
|
||||
json=initial_request,
|
||||
headers=self.headers)
|
||||
|
||||
csrf_token = response.cookies.get('csrf_token')
|
||||
if csrf_token:
|
||||
self.headers['X-CSRF-Token'] = csrf_token
|
||||
|
||||
initial_response = response.json()
|
||||
|
||||
if not initial_response.get("success", False):
|
||||
raise Exception(f"Initial request failed: {initial_response.get('error', 'Unknown error')}")
|
||||
|
||||
handoff = initial_response["handoff"]
|
||||
server = initial_response["server"]
|
||||
|
||||
file_name = self.generate_filename(metadata)
|
||||
|
||||
completion_url = f"https://{server}.{self.base_domain}/api/fetch/request/{handoff}"
|
||||
|
||||
print("Waiting for track processing to complete")
|
||||
while True:
|
||||
completion_response = self.client.get(completion_url, headers=self.headers).json()
|
||||
if completion_response["status"] == "completed":
|
||||
break
|
||||
elif completion_response["status"] == "error":
|
||||
raise Exception(f"API request failed: {completion_response.get('message', 'Unknown error')}")
|
||||
time.sleep(1)
|
||||
|
||||
download_url = f"https://{server}.{self.base_domain}/api/fetch/request/{handoff}/download"
|
||||
print(f"Starting download of: {file_name}")
|
||||
|
||||
response = self.client.get(download_url, stream=True, headers=self.headers)
|
||||
total_size = int(response.headers.get('content-length', 0))
|
||||
downloaded_size = 0
|
||||
|
||||
file_path = os.path.join(output_dir, file_name)
|
||||
|
||||
try:
|
||||
with open(file_path, 'wb') as file:
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
if chunk:
|
||||
file.write(chunk)
|
||||
downloaded_size += len(chunk)
|
||||
if self.progress_callback:
|
||||
self.progress_callback(downloaded_size, total_size)
|
||||
|
||||
if downloaded_size == 0:
|
||||
raise Exception("No data received from server")
|
||||
|
||||
return file_path
|
||||
|
||||
except Exception as e:
|
||||
if os.path.exists(file_path) and os.path.getsize(file_path) == 0:
|
||||
try:
|
||||
os.remove(file_path)
|
||||
except:
|
||||
pass
|
||||
raise e
|
||||
|
||||
async def main():
|
||||
downloader = TrackDownloader()
|
||||
output_dir = "."
|
||||
|
||||
try:
|
||||
metadata = await downloader.get_track_info()
|
||||
downloaded_file = downloader.download(metadata, output_dir)
|
||||
print(f"File downloaded successfully: {downloaded_file}")
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {str(e)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+271
@@ -0,0 +1,271 @@
|
||||
import requests
|
||||
import time
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
from mutagen.flac import FLAC, Picture
|
||||
from mutagen.id3 import PictureType
|
||||
|
||||
class ProgressCallback:
|
||||
def __call__(self, current, total):
|
||||
if total > 0:
|
||||
percent = (current / total) * 100
|
||||
print(f"\r{percent:.2f}% ({current}/{total})", end="")
|
||||
else:
|
||||
print(f"\r{current / (1024 * 1024):.2f} MB", end="")
|
||||
|
||||
class QobuzDownloader:
|
||||
def __init__(self, region="us", timeout=30):
|
||||
if region not in ["eu", "us"]:
|
||||
raise ValueError("Region must be either 'us' or 'eu'")
|
||||
|
||||
self.region = region
|
||||
self.timeout = timeout
|
||||
self.session = requests.Session()
|
||||
self.headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
||||
}
|
||||
self.base_api_url = f"https://{region}.qobuz.squid.wtf/api"
|
||||
self.download_chunk_size = 256 * 1024
|
||||
self.progress_callback = ProgressCallback()
|
||||
|
||||
def set_progress_callback(self, callback):
|
||||
self.progress_callback = callback
|
||||
|
||||
def sanitize_filename(self, filename):
|
||||
if not filename:
|
||||
return "Unknown Track"
|
||||
sanitized = re.sub(r'[\\/*?:"<>|]', "", str(filename))
|
||||
return re.sub(r'\s+', ' ', sanitized).strip() or "Unnamed Track"
|
||||
|
||||
def get_track_info(self, isrc):
|
||||
print(f"Fetching: {isrc}")
|
||||
search_url = f"{self.base_api_url}/get-music"
|
||||
params = {'q': isrc, 'offset': 0, 'limit': 10}
|
||||
|
||||
try:
|
||||
response = self.session.get(search_url, params=params, timeout=self.timeout)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
selected_track = None
|
||||
if data and data.get("success"):
|
||||
items = data.get("data", {}).get("tracks", {}).get("items", [])
|
||||
priority = {24: 1, 16: 2}
|
||||
for track in items:
|
||||
if track.get("isrc") == isrc:
|
||||
current_prio = priority.get(track.get("maximum_bit_depth"), 3)
|
||||
if selected_track is None or current_prio < priority.get(selected_track.get("maximum_bit_depth"), 3):
|
||||
selected_track = track
|
||||
if current_prio == 1:
|
||||
break
|
||||
|
||||
if not selected_track:
|
||||
raise Exception(f"Track not found: {isrc}")
|
||||
|
||||
title = selected_track.get('title', 'Unknown')
|
||||
bit_depth = selected_track.get('maximum_bit_depth', 'Unknown')
|
||||
print(f"Found: {title} ({bit_depth}b)")
|
||||
return selected_track
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
raise Exception(f"Request error: {e}")
|
||||
except Exception as e:
|
||||
raise Exception(f"Error: {e}")
|
||||
|
||||
def get_download_url(self, track_id):
|
||||
print("Fetching URL...")
|
||||
download_api_url = f"{self.base_api_url}/download-music"
|
||||
params = {'track_id': track_id, 'quality': 27}
|
||||
|
||||
try:
|
||||
response = self.session.get(download_api_url, params=params, timeout=self.timeout)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
if data and data.get("success") and data.get("data", {}).get("url"):
|
||||
download_url = data["data"]["url"]
|
||||
print("URL found")
|
||||
return download_url
|
||||
else:
|
||||
error_msg = data.get('error', {}).get('message', 'Unknown API error')
|
||||
raise Exception(f"API error: {error_msg}")
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
raise Exception(f"Request error: {e}")
|
||||
except Exception as e:
|
||||
raise Exception(f"Error: {e}")
|
||||
|
||||
def download(self, isrc, output_dir=".", is_paused_callback=None, is_stopped_callback=None):
|
||||
if output_dir != ".":
|
||||
try:
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
except OSError as e:
|
||||
raise Exception(f"Directory error: {e}")
|
||||
|
||||
track_info = self.get_track_info(isrc)
|
||||
track_id = track_info.get("id")
|
||||
|
||||
if not track_id:
|
||||
raise Exception("No track ID found")
|
||||
|
||||
artist_name = self.sanitize_filename(track_info.get('performer', {}).get('name'))
|
||||
track_title = self.sanitize_filename(track_info.get('title'))
|
||||
output_filename = os.path.join(output_dir, f"{artist_name} - {track_title}.flac")
|
||||
|
||||
if os.path.exists(output_filename):
|
||||
file_size = os.path.getsize(output_filename)
|
||||
if file_size > 0:
|
||||
print(f"File already exists: {output_filename} ({file_size / (1024 * 1024):.2f} MB)")
|
||||
return output_filename
|
||||
|
||||
download_url = self.get_download_url(track_id)
|
||||
temp_filename = output_filename + ".part"
|
||||
|
||||
print(f"Downloading...")
|
||||
try:
|
||||
with self.session.get(download_url, stream=True, timeout=900) as response, \
|
||||
open(temp_filename, 'wb') as f:
|
||||
response.raise_for_status()
|
||||
total_size = int(response.headers.get('content-length', 0))
|
||||
downloaded_size = 0
|
||||
start_time = time.time()
|
||||
last_update_time = start_time
|
||||
|
||||
for chunk in response.iter_content(chunk_size=self.download_chunk_size):
|
||||
if is_stopped_callback and is_stopped_callback():
|
||||
f.close()
|
||||
if os.path.exists(temp_filename):
|
||||
os.remove(temp_filename)
|
||||
raise Exception("Download stopped")
|
||||
|
||||
while is_paused_callback and is_paused_callback():
|
||||
time.sleep(0.1)
|
||||
if is_stopped_callback and is_stopped_callback():
|
||||
f.close()
|
||||
if os.path.exists(temp_filename):
|
||||
os.remove(temp_filename)
|
||||
raise Exception("Download stopped")
|
||||
f.write(chunk)
|
||||
downloaded_size += len(chunk)
|
||||
|
||||
current_time = time.time()
|
||||
if current_time - last_update_time >= 1:
|
||||
if total_size > 0:
|
||||
progress_percent = (downloaded_size / total_size) * 100
|
||||
elapsed_time = current_time - start_time
|
||||
speed = downloaded_size / (1024 * 1024 * elapsed_time) if elapsed_time > 0 else 0
|
||||
print(f"{progress_percent:.2f}% - {speed:.2f} MB/s")
|
||||
else:
|
||||
print(f"{downloaded_size / (1024 * 1024):.2f} MB")
|
||||
|
||||
last_update_time = current_time
|
||||
|
||||
if self.progress_callback:
|
||||
self.progress_callback(downloaded_size, total_size)
|
||||
|
||||
os.rename(temp_filename, output_filename)
|
||||
print("Download complete")
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
if os.path.exists(temp_filename):
|
||||
os.remove(temp_filename)
|
||||
raise Exception(f"Download failed: {e}")
|
||||
except Exception as e:
|
||||
if os.path.exists(temp_filename):
|
||||
os.remove(temp_filename)
|
||||
raise Exception(f"File error: {e}")
|
||||
|
||||
print("Adding metadata...")
|
||||
try:
|
||||
self._embed_metadata(output_filename, track_info)
|
||||
print("Metadata saved")
|
||||
except Exception as e:
|
||||
print(f"Tagging failed: {e}")
|
||||
|
||||
print(f"Done")
|
||||
return output_filename
|
||||
|
||||
def _embed_metadata(self, filename, track_info):
|
||||
try:
|
||||
audio = FLAC(filename)
|
||||
audio.delete()
|
||||
audio.clear_pictures()
|
||||
|
||||
album_info = track_info.get('album', {})
|
||||
artist = track_info.get('performer', {}).get('name')
|
||||
|
||||
if track_info.get('title'):
|
||||
audio['TITLE'] = track_info['title']
|
||||
if artist:
|
||||
audio['ARTIST'] = artist
|
||||
if album_info.get('title'):
|
||||
audio['ALBUM'] = album_info['title']
|
||||
if album_info.get('artist', {}).get('name', artist):
|
||||
audio['ALBUMARTIST'] = album_info.get('artist', {}).get('name', artist)
|
||||
if track_info.get('track_number'):
|
||||
audio['TRACKNUMBER'] = str(track_info['track_number'])
|
||||
if track_info.get('release_date_original'):
|
||||
audio['DATE'] = track_info['release_date_original']
|
||||
try:
|
||||
audio['YEAR'] = str(datetime.strptime(track_info['release_date_original'], '%Y-%m-%d').year)
|
||||
except ValueError:
|
||||
pass
|
||||
if album_info.get('genre', {}).get('name'):
|
||||
audio['GENRE'] = album_info['genre']['name']
|
||||
if track_info.get('copyright'):
|
||||
audio['COPYRIGHT'] = track_info['copyright']
|
||||
if track_info.get('isrc'):
|
||||
audio['ISRC'] = track_info['isrc']
|
||||
if album_info.get('label', {}).get('name'):
|
||||
audio['ORGANIZATION'] = album_info['label']['name']
|
||||
|
||||
img_info = album_info.get('image', {})
|
||||
cover_url = img_info.get('large') or img_info.get('small') or img_info.get('thumbnail')
|
||||
if cover_url:
|
||||
try:
|
||||
img_response = self.session.get(cover_url, timeout=30)
|
||||
img_response.raise_for_status()
|
||||
mime_type = img_response.headers.get('Content-Type', 'image/jpeg').lower()
|
||||
if mime_type in ['image/jpeg', 'image/png']:
|
||||
picture = Picture()
|
||||
picture.data = img_response.content
|
||||
picture.type = PictureType.COVER_FRONT
|
||||
picture.mime = mime_type
|
||||
audio.add_picture(picture)
|
||||
print("Cover added")
|
||||
except Exception as e:
|
||||
print(f"Cover error: {str(e)}")
|
||||
|
||||
audio.save()
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"Metadata error: {e}")
|
||||
|
||||
def main():
|
||||
print("=== QobuzDL - Qobuz Downloader ===")
|
||||
downloader = QobuzDownloader(region="us")
|
||||
|
||||
isrc = "USAT22409172"
|
||||
output_dir = "."
|
||||
|
||||
try:
|
||||
downloaded_file = downloader.download(isrc, output_dir)
|
||||
print(f"Success: File saved as {downloaded_file}")
|
||||
except Exception as e:
|
||||
print(f"Error: {str(e)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
import sys
|
||||
if sys.platform == "win32":
|
||||
import os
|
||||
os.system("chcp 65001 > nul")
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
except:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
main()
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import httpx
|
||||
from mutagen.flac import FLAC, Picture
|
||||
from mutagen.id3 import PictureType
|
||||
|
||||
class ProgressCallback:
|
||||
def __call__(self, current, total):
|
||||
if total > 0:
|
||||
percent = (current / total) * 100
|
||||
print(f"\r{percent:.2f}% ({current}/{total})", end="")
|
||||
else:
|
||||
print(f"\r{current / (1024 * 1024):.2f} MB", end="")
|
||||
|
||||
class TidalDownloader:
|
||||
def __init__(self, timeout=30, max_retries=3):
|
||||
self.timeout = timeout
|
||||
self.max_retries = max_retries
|
||||
self.download_chunk_size = 256 * 1024
|
||||
self.progress_callback = ProgressCallback()
|
||||
self.client_id = "zU4XHVVkc2tDPo4t"
|
||||
self.client_secret = "VJKhDFqJPqvsPVNBV6ukXTJmwlvbttP7wlMlrc72se4="
|
||||
|
||||
def set_progress_callback(self, callback):
|
||||
self.progress_callback = callback
|
||||
|
||||
|
||||
|
||||
def sanitize_filename(self, filename):
|
||||
if not filename:
|
||||
return "Unknown Track"
|
||||
sanitized = re.sub(r'[\\/*?:"<>|]', "", str(filename))
|
||||
return re.sub(r'\s+', ' ', sanitized).strip() or "Unnamed Track"
|
||||
|
||||
async def get_access_token(self):
|
||||
refresh_url = "https://auth.tidal.com/v1/oauth2/token"
|
||||
|
||||
payload = {
|
||||
"client_id": self.client_id,
|
||||
"grant_type": "client_credentials",
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(http2=True) as client:
|
||||
try:
|
||||
response = await client.post(
|
||||
url=refresh_url,
|
||||
data=payload,
|
||||
auth=(self.client_id, self.client_secret),
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
token_data = response.json()
|
||||
return token_data.get("access_token")
|
||||
else:
|
||||
return None
|
||||
|
||||
except:
|
||||
return None
|
||||
|
||||
async def search_tracks(self, query):
|
||||
try:
|
||||
tidal_token = await self.get_access_token()
|
||||
if not tidal_token:
|
||||
raise Exception("Failed to get access token")
|
||||
|
||||
search_url = f"https://api.tidal.com/v1/search/tracks?query={query}&limit=25&offset=0&countryCode=US"
|
||||
header = {"authorization": f"Bearer {tidal_token}"}
|
||||
|
||||
async with httpx.AsyncClient(http2=True) as client:
|
||||
search_data = await client.get(url=search_url, headers=header)
|
||||
response_data = search_data.json()
|
||||
|
||||
filtered_items = [{
|
||||
"id": item.get("id"),
|
||||
"title": item.get("title"),
|
||||
"url": item.get("url"),
|
||||
"isrc": item.get("isrc"),
|
||||
"audioQuality": item.get("audioQuality"),
|
||||
"mediaMetadata": item.get("mediaMetadata"),
|
||||
"album": item.get("album", {}),
|
||||
"artists": item.get("artists", []),
|
||||
"artist": item.get("artist", {}),
|
||||
"trackNumber": item.get("trackNumber"),
|
||||
"volumeNumber": item.get("volumeNumber"),
|
||||
"duration": item.get("duration"),
|
||||
"copyright": item.get("copyright"),
|
||||
"explicit": item.get("explicit")
|
||||
} for item in response_data.get("items", [])]
|
||||
|
||||
return {
|
||||
"limit": response_data.get("limit"),
|
||||
"offset": response_data.get("offset"),
|
||||
"totalNumberOfItems": response_data.get("totalNumberOfItems"),
|
||||
"items": filtered_items
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"Search error: {str(e)}")
|
||||
|
||||
async def get_track_info(self, query, isrc=None):
|
||||
print(f"Fetching: {query}" + (f" (ISRC: {isrc})" if isrc else ""))
|
||||
|
||||
try:
|
||||
result = await self.search_tracks(query)
|
||||
|
||||
if not result or not result.get("items"):
|
||||
raise Exception(f"No tracks found for query: {query}")
|
||||
|
||||
selected_track = None
|
||||
if isrc:
|
||||
isrc_items = [item for item in result["items"] if item.get("isrc") == isrc]
|
||||
|
||||
if len(isrc_items) > 1:
|
||||
hires_items = []
|
||||
for item in isrc_items:
|
||||
media_metadata = item.get("mediaMetadata", {})
|
||||
tags = media_metadata.get("tags", []) if media_metadata else []
|
||||
if "HIRES_LOSSLESS" in tags:
|
||||
hires_items.append(item)
|
||||
|
||||
if hires_items:
|
||||
selected_track = hires_items[0]
|
||||
else:
|
||||
selected_track = isrc_items[0]
|
||||
elif len(isrc_items) == 1:
|
||||
selected_track = isrc_items[0]
|
||||
else:
|
||||
selected_track = result["items"][0]
|
||||
else:
|
||||
selected_track = result["items"][0]
|
||||
|
||||
if not selected_track:
|
||||
raise Exception(f"Track not found: {query}" + (f" (ISRC: {isrc})" if isrc else ""))
|
||||
|
||||
title = selected_track.get('title', 'Unknown')
|
||||
quality = selected_track.get('audioQuality', 'Unknown')
|
||||
print(f"Found: {title} ({quality})")
|
||||
return selected_track
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"Error getting track info: {str(e)}")
|
||||
|
||||
async def get_download_url(self, track_id, quality="LOSSLESS"):
|
||||
print("Fetching URL...")
|
||||
download_api_url = f"https://hifi.401658.xyz/track/?id={track_id}&quality={quality}"
|
||||
|
||||
async with httpx.AsyncClient(http2=True, timeout=self.timeout) as client:
|
||||
try:
|
||||
response = await client.get(download_api_url)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
|
||||
for item in data:
|
||||
if "OriginalTrackUrl" in item:
|
||||
print("URL found")
|
||||
return {
|
||||
"download_url": item["OriginalTrackUrl"],
|
||||
"track_info": data[0] if data else {}
|
||||
}
|
||||
|
||||
raise Exception("Download URL not found in response")
|
||||
else:
|
||||
raise Exception(f"API returned status code: {response.status_code}")
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"Error getting download URL: {str(e)}")
|
||||
|
||||
async def download_album_art(self, album_id, size="1280x1280"):
|
||||
try:
|
||||
art_url = f"https://resources.tidal.com/images/{album_id.replace('-', '/')}/{size}.jpg"
|
||||
|
||||
async with httpx.AsyncClient(http2=True, timeout=self.timeout) as client:
|
||||
response = await client.get(art_url)
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.content
|
||||
else:
|
||||
print(f"Failed to download album art: HTTP {response.status_code}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error downloading album art: {str(e)}")
|
||||
return None
|
||||
|
||||
async def download_file(self, url, filepath, is_paused_callback=None, is_stopped_callback=None):
|
||||
temp_filepath = filepath + ".part"
|
||||
retry_count = 0
|
||||
|
||||
while retry_count <= self.max_retries:
|
||||
try:
|
||||
async with httpx.AsyncClient(http2=True, timeout=60.0) as client:
|
||||
async with client.stream('GET', url) as response:
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"HTTP {response.status_code}")
|
||||
|
||||
total_size = int(response.headers.get('content-length', 0))
|
||||
downloaded_size = 0
|
||||
start_time = time.time()
|
||||
last_update_time = start_time
|
||||
|
||||
with open(temp_filepath, 'wb') as f:
|
||||
async for chunk in response.aiter_bytes(chunk_size=self.download_chunk_size):
|
||||
if is_stopped_callback and is_stopped_callback():
|
||||
f.close()
|
||||
if os.path.exists(temp_filepath):
|
||||
os.remove(temp_filepath)
|
||||
raise Exception("Download stopped")
|
||||
|
||||
while is_paused_callback and is_paused_callback():
|
||||
await asyncio.sleep(0.1)
|
||||
if is_stopped_callback and is_stopped_callback():
|
||||
f.close()
|
||||
if os.path.exists(temp_filepath):
|
||||
os.remove(temp_filepath)
|
||||
raise Exception("Download stopped")
|
||||
|
||||
f.write(chunk)
|
||||
downloaded_size += len(chunk)
|
||||
|
||||
current_time = time.time()
|
||||
if current_time - last_update_time >= 1:
|
||||
if total_size > 0:
|
||||
progress_percent = (downloaded_size / total_size) * 100
|
||||
elapsed_time = current_time - start_time
|
||||
speed = downloaded_size / (1024 * 1024 * elapsed_time) if elapsed_time > 0 else 0
|
||||
print(f"{progress_percent:.2f}% - {speed:.2f} MB/s")
|
||||
else:
|
||||
print(f"{downloaded_size / (1024 * 1024):.2f} MB")
|
||||
|
||||
last_update_time = current_time
|
||||
|
||||
if self.progress_callback:
|
||||
self.progress_callback(downloaded_size, total_size)
|
||||
|
||||
os.rename(temp_filepath, filepath)
|
||||
print("Download complete")
|
||||
return {"success": True, "size": downloaded_size}
|
||||
|
||||
except Exception as e:
|
||||
retry_count += 1
|
||||
if retry_count > self.max_retries:
|
||||
if os.path.exists(temp_filepath):
|
||||
try:
|
||||
os.remove(temp_filepath)
|
||||
except:
|
||||
pass
|
||||
raise Exception(f"Download error after {self.max_retries} retries: {str(e)}")
|
||||
|
||||
print(f"Download error (attempt {retry_count}/{self.max_retries}): {str(e)}")
|
||||
print(f"Retrying in {retry_count * 2} seconds...")
|
||||
await asyncio.sleep(retry_count * 2)
|
||||
|
||||
async def embed_metadata(self, filepath, track_info, search_info=None):
|
||||
try:
|
||||
print("Embedding metadata...")
|
||||
audio = FLAC(filepath)
|
||||
audio.clear()
|
||||
audio.clear_pictures()
|
||||
|
||||
if track_info.get("title"):
|
||||
audio["TITLE"] = track_info["title"]
|
||||
|
||||
artists_list = []
|
||||
if search_info and search_info.get("artists"):
|
||||
for artist in search_info["artists"]:
|
||||
if artist.get("name"):
|
||||
artists_list.append(artist["name"])
|
||||
elif search_info and search_info.get("artist") and search_info["artist"].get("name"):
|
||||
artists_list.append(search_info["artist"]["name"])
|
||||
elif track_info.get("artists"):
|
||||
for artist in track_info["artists"]:
|
||||
if artist.get("name"):
|
||||
artists_list.append(artist["name"])
|
||||
elif track_info.get("artist") and track_info["artist"].get("name"):
|
||||
artists_list.append(track_info["artist"]["name"])
|
||||
|
||||
if artists_list:
|
||||
audio["ARTIST"] = artists_list[0]
|
||||
if len(artists_list) > 1:
|
||||
audio["ALBUMARTIST"] = "; ".join(artists_list)
|
||||
else:
|
||||
audio["ALBUMARTIST"] = artists_list[0]
|
||||
|
||||
album_info = search_info.get("album", {}) if search_info else track_info.get("album", {})
|
||||
if album_info.get("title"):
|
||||
audio["ALBUM"] = album_info["title"]
|
||||
|
||||
if search_info and search_info.get("trackNumber"):
|
||||
audio["TRACKNUMBER"] = str(search_info["trackNumber"])
|
||||
elif track_info.get("trackNumber"):
|
||||
audio["TRACKNUMBER"] = str(track_info["trackNumber"])
|
||||
|
||||
if search_info and search_info.get("volumeNumber"):
|
||||
audio["DISCNUMBER"] = str(search_info["volumeNumber"])
|
||||
elif track_info.get("volumeNumber"):
|
||||
audio["DISCNUMBER"] = str(track_info["volumeNumber"])
|
||||
|
||||
duration = search_info.get("duration") if search_info else track_info.get("duration")
|
||||
if duration:
|
||||
audio["LENGTH"] = str(duration)
|
||||
|
||||
isrc = search_info.get("isrc") if search_info else track_info.get("isrc")
|
||||
if isrc:
|
||||
audio["ISRC"] = isrc
|
||||
|
||||
copyright_info = search_info.get("copyright") if search_info else track_info.get("copyright")
|
||||
if copyright_info:
|
||||
audio["COPYRIGHT"] = copyright_info
|
||||
|
||||
if album_info.get("releaseDate"):
|
||||
audio["DATE"] = album_info["releaseDate"][:4]
|
||||
try:
|
||||
audio["YEAR"] = album_info["releaseDate"][:4]
|
||||
except:
|
||||
pass
|
||||
|
||||
if track_info.get("genre"):
|
||||
audio["GENRE"] = track_info["genre"]
|
||||
|
||||
if track_info.get("audioQuality"):
|
||||
audio["COMMENT"] = f"Tidal {track_info['audioQuality']}"
|
||||
|
||||
if album_info.get("cover"):
|
||||
album_art = await self.download_album_art(album_info["cover"])
|
||||
if album_art:
|
||||
picture = Picture()
|
||||
picture.data = album_art
|
||||
picture.type = PictureType.COVER_FRONT
|
||||
picture.mime = "image/jpeg"
|
||||
picture.desc = "Cover"
|
||||
audio.add_picture(picture)
|
||||
print("Album art embedded")
|
||||
|
||||
audio.save()
|
||||
print(f"Metadata embedded successfully for: {track_info.get('title', 'Unknown')}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error embedding metadata: {str(e)}")
|
||||
return False
|
||||
|
||||
async def download(self, query, isrc=None, output_dir=".", quality="LOSSLESS", is_paused_callback=None, is_stopped_callback=None):
|
||||
if output_dir != ".":
|
||||
try:
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
except OSError as e:
|
||||
raise Exception(f"Directory error: {e}")
|
||||
|
||||
track_info = await self.get_track_info(query, isrc)
|
||||
track_id = track_info.get("id")
|
||||
|
||||
if not track_id:
|
||||
raise Exception("No track ID found")
|
||||
|
||||
artists_list = []
|
||||
if track_info.get("artists"):
|
||||
for artist in track_info["artists"]:
|
||||
if artist.get("name"):
|
||||
artists_list.append(artist["name"])
|
||||
elif track_info.get("artist") and track_info["artist"].get("name"):
|
||||
artists_list.append(track_info["artist"]["name"])
|
||||
|
||||
artist_name = ", ".join(artists_list) if artists_list else "Unknown Artist"
|
||||
artist_name = self.sanitize_filename(artist_name)
|
||||
track_title = self.sanitize_filename(track_info.get("title", f"track_{track_id}"))
|
||||
|
||||
output_filename = os.path.join(output_dir, f"{artist_name} - {track_title}.flac")
|
||||
|
||||
if os.path.exists(output_filename):
|
||||
file_size = os.path.getsize(output_filename)
|
||||
if file_size > 0:
|
||||
print(f"File already exists: {output_filename} ({file_size / (1024 * 1024):.2f} MB)")
|
||||
return output_filename
|
||||
|
||||
download_info = await self.get_download_url(track_id, quality)
|
||||
download_url = download_info["download_url"]
|
||||
download_track_info = download_info["track_info"]
|
||||
|
||||
print(f"Downloading to: {output_filename}")
|
||||
await self.download_file(
|
||||
download_url,
|
||||
output_filename,
|
||||
is_paused_callback=is_paused_callback,
|
||||
is_stopped_callback=is_stopped_callback
|
||||
)
|
||||
|
||||
print("Adding metadata...")
|
||||
try:
|
||||
await self.embed_metadata(output_filename, download_track_info, track_info)
|
||||
print("Metadata saved")
|
||||
except Exception as e:
|
||||
print(f"Tagging failed: {e}")
|
||||
|
||||
print("Done")
|
||||
return output_filename
|
||||
|
||||
async def main():
|
||||
print("=== TidalDL - Tidal Downloader ===")
|
||||
downloader = TidalDownloader(timeout=30, max_retries=3)
|
||||
|
||||
query = "APT."
|
||||
isrc = "USAT22409172"
|
||||
output_dir = "."
|
||||
|
||||
try:
|
||||
downloaded_file = await downloader.download(query, isrc, output_dir)
|
||||
print(f"Success: File saved as {downloaded_file}")
|
||||
except Exception as e:
|
||||
print(f"Error: {str(e)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
import sys
|
||||
if sys.platform == "win32":
|
||||
import os
|
||||
os.system("chcp 65001 > nul")
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
except:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"version": "4.0"
|
||||
}
|
||||
Reference in New Issue
Block a user