Compare commits

...

7 Commits

Author SHA1 Message Date
653e94463e Directory destination /mnt/Musique 2026-03-21 01:46:08 +01:00
ee0b0f3abd Fix Flask app context error in SSE stream route 2026-03-21 01:30:57 +01:00
5860e4634b Fix Flask app context error in run_download thread 2026-03-21 01:26:52 +01:00
5387e3abba Fix JS regex to accept Spotify URLs with locale prefix (intl-fr, en, etc.) 2026-03-21 01:21:42 +01:00
198a005ac7 Fix readme 2026-03-21 01:17:47 +01:00
9893ea0943 Fix readme 2026-03-21 01:16:20 +01:00
2fbdc6e8cb Fix regex 2026-03-21 01:15:41 +01:00
4 changed files with 422 additions and 112 deletions

View File

@@ -1,11 +1,15 @@
Petit applicatif pour télécharger depuis des url Spotify à l'aide de Youtube-music (flac ou mp3)
backend: spotdl, sacad, falsk, flask-login
Run:
## Run:
install requiments python:
```
pip install -r requirements.txt
```
Init db sqlite:
```
python3 app.py & ctrl+c
```
```
python3 app.py
@@ -14,4 +18,4 @@ dispo sur 127.0.0.1:5000
Demo
![picture](https://git.zestes.fr/garfi/spotdl-py/raw/tag/1.1.0.0/demo.png))
![picture](https://git.zestes.fr/jules/spotdl-py/raw/branch/main/demo.png))

225
app.py
View File

@@ -96,6 +96,9 @@ def create_admin():
def validate_spotify_url(url):
patterns = [
r'https?://open\.spotify\.com/[^/]+/track/[\w-]+',
r'https?://open\.spotify\.com/[^/]+/album/[\w-]+',
r'https?://open\.spotify\.com/[^/]+/playlist/[\w-]+',
r'https?://open\.spotify\.com/track/[\w-]+',
r'https?://open\.spotify\.com/album/[\w-]+',
r'https?://open\.spotify\.com/playlist/[\w-]+',
@@ -105,127 +108,128 @@ def validate_spotify_url(url):
def run_download(download_id, urls, format_type, delete_old, copy_choice):
download = Download.query.get(download_id)
if not download:
return
with app.app_context():
download = Download.query.get(download_id)
if not download:
return
download.status = 'running'
db.session.commit()
download.status = 'running'
db.session.commit()
if format_type == 'flac':
download_dir = os.getenv('DOWNLOAD_DIR_FLAC', '/home/jules/Musique/flac')
else:
download_dir = os.getenv('DOWNLOAD_DIR_MP3', '/home/jules/Musique/mp3')
if format_type == 'flac':
download_dir = os.getenv('DOWNLOAD_DIR_FLAC', '/home/jules/Musique/flac')
else:
download_dir = os.getenv('DOWNLOAD_DIR_MP3', '/home/jules/Musique/mp3')
copy_destination = os.getenv('COPY_DESTINATION', '/mnt/data/Musique')
copy_destination = os.getenv('COPY_DESTINATION', '/mnt/Musique')
if delete_old and os.path.exists(download_dir):
shutil.rmtree(download_dir)
if delete_old and os.path.exists(download_dir):
shutil.rmtree(download_dir)
os.makedirs(download_dir, exist_ok=True)
os.makedirs(download_dir, exist_ok=True)
total_urls = len(urls)
try:
for idx, url in enumerate(urls, 1):
download.append_log(f"[{idx}/{total_urls}] Téléchargement: {url}")
total_urls = len(urls)
try:
for idx, url in enumerate(urls, 1):
download.append_log(f"[{idx}/{total_urls}] Téléchargement: {url}")
db.session.commit()
spotdl_command = [
'spotdl',
'--output', '{artist}/{album}/{track-number} - {title}.{output-ext}',
'--format', format_type,
url
]
process = subprocess.Popen(
['stdbuf', '-oL'] + spotdl_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
cwd=download_dir,
bufsize=1
)
download_processes[download_id] = process
download.process_id = process.pid
db.session.commit()
for line in iter(process.stdout.readline, ""):
if download_id not in download_processes:
process.terminate()
break
line = line.strip()
if line:
download.append_log(line)
if 'Downloaded' in line or '100%' in line:
progress = int((idx / total_urls) * 100)
download.progress = progress
db.session.commit()
process.stdout.close()
process.wait()
if process.returncode != 0:
stderr = process.stderr.read()
download.append_log(f"Erreur: {stderr}")
db.session.commit()
download.progress = int((idx / total_urls) * 100)
db.session.commit()
download.append_log("Ajout des couvertures...")
db.session.commit()
spotdl_command = [
'spotdl',
'--output', '{artist}/{album}/{track-number} - {title}.{output-ext}',
'--format', format_type,
url
]
process = subprocess.Popen(
['stdbuf', '-oL'] + spotdl_command,
sacad_command = ['sacad_r', download_dir, '900', 'cover.jpg']
sacad_process = subprocess.Popen(
['stdbuf', '-oL'] + sacad_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
cwd=download_dir,
bufsize=1
)
download_processes[download_id] = process
download.process_id = process.pid
db.session.commit()
for line in iter(process.stdout.readline, ""):
for line in iter(sacad_process.stdout.readline, ""):
if download_id not in download_processes:
process.terminate()
sacad_process.terminate()
break
line = line.strip()
if line:
download.append_log(line)
if 'Downloaded' in line or '100%' in line:
progress = int((idx / total_urls) * 100)
download.progress = progress
db.session.commit()
process.stdout.close()
process.wait()
sacad_process.wait()
if process.returncode != 0:
stderr = process.stderr.read()
download.append_log(f"Erreur: {stderr}")
if copy_choice == 'yes':
download.append_log(f"Copie vers {copy_destination}...")
db.session.commit()
if os.path.exists(download_dir) and os.listdir(download_dir):
for root, dirs, files in os.walk(download_dir):
for file in files:
src = os.path.join(root, file)
dst = os.path.join(copy_destination, os.path.relpath(src, download_dir))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copy2(src, dst)
download.append_log("Copie terminée.")
else:
download.append_log("Aucune copie - répertoire vide.")
download.progress = int((idx / total_urls) * 100)
download.status = 'completed'
download.progress = 100
download.completed_at = datetime.utcnow()
download.append_log("=== Téléchargement terminé ===")
db.session.commit()
download.append_log("Ajout des couvertures...")
db.session.commit()
sacad_command = ['sacad_r', download_dir, '900', 'cover.jpg']
sacad_process = subprocess.Popen(
['stdbuf', '-oL'] + sacad_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
bufsize=1
)
for line in iter(sacad_process.stdout.readline, ""):
if download_id not in download_processes:
sacad_process.terminate()
break
line = line.strip()
if line:
download.append_log(line)
db.session.commit()
sacad_process.wait()
if copy_choice == 'yes':
download.append_log(f"Copie vers {copy_destination}...")
except Exception as e:
download.status = 'error'
download.error = str(e)
download.append_log(f"Erreur critique: {e}")
db.session.commit()
if os.path.exists(download_dir) and os.listdir(download_dir):
for root, dirs, files in os.walk(download_dir):
for file in files:
src = os.path.join(root, file)
dst = os.path.join(copy_destination, os.path.relpath(src, download_dir))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copy2(src, dst)
download.append_log("Copie terminée.")
else:
download.append_log("Aucune copie - répertoire vide.")
download.status = 'completed'
download.progress = 100
download.completed_at = datetime.utcnow()
download.append_log("=== Téléchargement terminé ===")
db.session.commit()
except Exception as e:
download.status = 'error'
download.error = str(e)
download.append_log(f"Erreur critique: {e}")
db.session.commit()
finally:
if download_id in download_processes:
del download_processes[download_id]
finally:
if download_id in download_processes:
del download_processes[download_id]
@app.route('/')
@@ -354,26 +358,29 @@ def api_download():
@login_required
def stream_download(download_id):
download = Download.query.get_or_404(download_id)
download_id_val = download.id
def generate():
last_len = 0
while True:
db.session.refresh(download)
current_len = len(download.log)
if current_len > last_len:
new_log = download.log[last_len:]
data = f"data: {download.id}|{download.status}|{download.progress}|{new_log}\n\n"
yield data
last_len = current_len
with app.app_context():
download = Download.query.get(download_id_val)
last_len = 0
while True:
db.session.refresh(download)
current_len = len(download.log)
if current_len > last_len:
new_log = download.log[last_len:]
data = f"data: {download.id}|{download.status}|{download.progress}|{new_log}\n\n"
yield data
last_len = current_len
if download.status in ('completed', 'error'):
data = f"data: {download.id}|{download.status}|{download.progress}|__END__\n\n"
yield data
break
if download.status in ('completed', 'error', 'cancelled'):
data = f"data: {download.id}|{download.status}|{download.progress}|__END__\n\n"
yield data
break
import time
time.sleep(0.5)
import time
time.sleep(0.5)
return Response(generate(), mimetype='text/event-stream')

299
index.html Normal file
View File

@@ -0,0 +1,299 @@
{% extends "layout.html" %}
{% block title %}Télécharger - Spotify Downloader{% endblock %}
{% block content %}
<div class="row justify-content-center">
<div class="col-lg-8">
<div class="card">
<div class="card-header">
<h4 class="mb-0"><i class="bi bi-download me-2"></i>Nouveau téléchargement</h4>
</div>
<div class="card-body">
<form id="downloadForm">
<div class="mb-3">
<label for="url" class="form-label">
<i class="bi bi-link-45deg me-1"></i>URL Spotify
</label>
<textarea
class="form-control"
id="url"
name="url"
rows="4"
placeholder="Collez une ou plusieurs URLs Spotify (une par ligne)&#10;Exemple:&#10;https://open.spotify.com/track/...&#10;https://open.spotify.com/playlist/..."
required
></textarea>
<div class="form-text">Accepte les tracks, albums et playlists Spotify</div>
<div id="urlError" class="text-danger mt-1" style="display: none;"></div>
</div>
<div class="row g-3 mb-3">
<div class="col-md-4">
<label for="format" class="form-label">
<i class="bi bi-music-note me-1"></i>Format
</label>
<select class="form-select" id="format" name="format">
<option value="mp3">MP3</option>
<option value="flac">FLAC</option>
</select>
</div>
<div class="col-md-4">
<label for="copy_choice" class="form-label">
<i class="bi bi-folder-plus me-1"></i>Copier vers NAS
</label>
<select class="form-select" id="copy_choice" name="copy_choice">
<option value="no">Non</option>
<option value="yes">Oui</option>
</select>
</div>
<div class="col-md-4 d-flex align-items-end">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="delete_old" name="delete_old">
<label class="form-check-label" for="delete_old">Supprimer anciens fichiers</label>
</div>
</div>
</div>
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
<button type="button" id="cancelBtn" class="btn btn-outline-danger me-md-2" disabled>
<i class="bi bi-x-circle me-1"></i>Annuler
</button>
<button type="submit" id="submitBtn" class="btn btn-spotify">
<i class="bi bi-download me-1"></i>Télécharger
</button>
</div>
</form>
<div id="downloadStatus" class="mt-4" style="display: none;">
<div class="d-flex justify-content-between align-items-center mb-2">
<span id="statusText" class="badge bg-info">En attente...</span>
<span id="progressText" class="text-muted small">0%</span>
</div>
<div id="progressContainer" class="progress mb-3 progress-indeterminate" style="height: 25px;">
<div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" style="width: 100%;"></div>
</div>
<div class="output-box rounded p-3" id="logOutput" style="max-height: 400px; overflow-y: auto;">
<div class="text-muted text-center">En attente du téléchargement...</div>
</div>
</div>
</div>
</div>
{% if recent_downloads %}
<div class="card mt-4">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0"><i class="bi bi-clock-history me-2"></i>Téléchargements récents</h5>
<a href="{{ url_for('history') }}" class="btn btn-sm btn-outline-light">Voir tout</a>
</div>
<div class="card-body p-0">
<div class="list-group list-group-flush">
{% for dl in recent_downloads %}
<div class="list-group-item bg-transparent d-flex justify-content-between align-items-center">
<div>
<span class="badge bg-{{ 'success' if dl.status == 'completed' else 'danger' if dl.status == 'error' else 'warning' if dl.status == 'running' else 'secondary' }}">
{{ dl.status }}
</span>
<small class="text-muted ms-2">{{ dl.format_type.upper() }}</small>
</div>
<small class="text-muted">{{ dl.created_at.strftime('%d/%m %H:%M') }}</small>
</div>
{% endfor %}
</div>
</div>
</div>
{% endif %}
</div>
</div>
{% endblock %}
{% block extra_js %}
<script>
(function() {
'use strict';
const form = document.getElementById('downloadForm');
const submitBtn = document.getElementById('submitBtn');
const cancelBtn = document.getElementById('cancelBtn');
const downloadStatus = document.getElementById('downloadStatus');
const statusText = document.getElementById('statusText');
const progressText = document.getElementById('progressText');
const progressBar = document.getElementById('progressBar');
const progressContainer = document.getElementById('progressContainer');
const logOutput = document.getElementById('logOutput');
const urlError = document.getElementById('urlError');
let currentDownloadId = null;
let eventSource = null;
const spotifyPattern = /^https?:\/\/open\.spotify\.com\/(track|album|playlist)\/[\w-]+/;
function validateUrls(text) {
const urls = text.split('\n').filter(u => u.trim());
for (const url of urls) {
if (!spotifyPattern.test(url.trim())) {
return { valid: false, invalid: url };
}
}
return { valid: true, count: urls.length };
}
document.getElementById('url').addEventListener('input', function() {
const result = validateUrls(this.value);
if (this.value.trim() && !result.valid) {
urlError.textContent = `URL invalide: ${result.invalid.substring(0, 50)}...`;
urlError.style.display = 'block';
} else {
urlError.style.display = 'none';
}
});
function appendLog(message, type = 'info') {
const lines = message.split('\n').filter(l => l.trim());
lines.forEach(line => {
const span = document.createElement('div');
span.className = `log-${type}`;
span.textContent = line;
logOutput.appendChild(span);
});
logOutput.scrollTop = logOutput.scrollHeight;
}
function setStatus(status, progress) {
const badges = {
'pending': ['bg-secondary', 'En attente...'],
'running': ['bg-warning', 'En cours...'],
'completed': ['bg-success', 'Terminé !'],
'error': ['bg-danger', 'Erreur'],
'cancelled': ['bg-secondary', 'Annulé']
};
const [color, text] = badges[status] || ['bg-secondary', status];
statusText.className = `badge ${color}`;
statusText.textContent = text;
progressText.textContent = `${progress}%`;
if (status === 'running') {
progressBar.classList.add('progress-bar-animated');
progressBar.style.width = '100%';
progressContainer.classList.add('progress-indeterminate');
} else {
progressBar.classList.remove('progress-bar-animated');
progressBar.style.width = `${progress}%`;
progressContainer.classList.remove('progress-indeterminate');
if (status === 'completed') {
progressBar.classList.remove('progress-bar-striped');
showToast('Téléchargement terminé avec succès !', 'success');
} else if (status === 'error') {
showToast('Erreur lors du téléchargement', 'error');
} else if (status === 'cancelled') {
showToast('Téléchargement annulé', 'warning');
}
}
}
function startStream(downloadId) {
if (eventSource) {
eventSource.close();
}
eventSource = new EventSource(`/api/download/${downloadId}/stream`);
eventSource.onmessage = function(e) {
const [id, status, progress, log] = e.data.split('|');
if (log !== '__END__' && log) {
let type = 'info';
if (log.includes('Erreur') || log.includes('Error')) type = 'error';
else if (log.includes('terminé') || log.includes('Terminé')) type = 'success';
else if (log.includes('Downloaded')) type = 'success';
else if (log.includes('Ajout')) type = 'info';
appendLog(log, type);
}
setStatus(status, parseInt(progress));
if (status === 'completed' || status === 'error' || status === 'cancelled') {
eventSource.close();
eventSource = null;
submitBtn.disabled = false;
cancelBtn.disabled = true;
}
};
eventSource.onerror = function() {
eventSource.close();
eventSource = null;
};
}
form.addEventListener('submit', async function(e) {
e.preventDefault();
const urlValue = document.getElementById('url').value;
const validation = validateUrls(urlValue);
if (!validation.valid) {
urlError.textContent = `URL invalide: ${validation.invalid.substring(0, 50)}...`;
urlError.style.display = 'block';
return;
}
const formData = {
url: urlValue,
format: document.getElementById('format').value,
delete_old: document.getElementById('delete_old').checked,
copy_choice: document.getElementById('copy_choice').value
};
submitBtn.disabled = true;
cancelBtn.disabled = false;
downloadStatus.style.display = 'block';
logOutput.innerHTML = '';
setStatus('pending', 0);
appendLog(`Démarrage de ${validation.count} téléchargement(s)...`, 'info');
try {
const response = await fetch('/api/download', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});
const data = await response.json();
if (data.error) {
appendLog(`Erreur: ${data.error}`, 'error');
setStatus('error', 0);
submitBtn.disabled = false;
cancelBtn.disabled = true;
return;
}
currentDownloadId = data.id;
setStatus('running', 0);
startStream(currentDownloadId);
} catch (err) {
appendLog(`Erreur réseau: ${err.message}`, 'error');
setStatus('error', 0);
submitBtn.disabled = false;
cancelBtn.disabled = true;
}
});
cancelBtn.addEventListener('click', async function() {
if (!currentDownloadId) return;
try {
await fetch(`/api/download/${currentDownloadId}/cancel`, {
method: 'POST'
});
appendLog('Annulation en cours...', 'warning');
} catch (err) {
appendLog(`Erreur: ${err.message}`, 'error');
}
});
})();
</script>
{% endblock %}

View File

@@ -125,7 +125,7 @@
let currentDownloadId = null;
let eventSource = null;
const spotifyPattern = /^https?:\/\/open\.spotify\.com\/(track|album|playlist)\/[\w-]+/;
const spotifyPattern = /^https?:\/\/open\.spotify\.com\/[^/]+\/(track|album|playlist)\/[\w-]+/;
function validateUrls(text) {
const urls = text.split('\n').filter(u => u.trim());