This commit is contained in:
garfi 2024-09-08 01:21:06 +02:00
commit 384a10c1be
5 changed files with 279 additions and 0 deletions

7
README.md Normal file
View File

@ -0,0 +1,7 @@
Petit applicatif pour télécharger depuis des url Spotify à l'aide de Youtube-music
backend: spotdl, falsk , flask-login
Pour le lancer: python3 app.py
Ou avec le run.sh pour modifier le port
Demo

129
app.py Normal file
View File

@ -0,0 +1,129 @@
from flask import Flask, render_template, request, Response, redirect, url_for, send_file
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
import subprocess
import os
import shutil
import zipfile
from io import BytesIO
app = Flask(__name__)
app.secret_key = 'your_secret_key'
# Configuration Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
# Utilisateur fictif
class User(UserMixin):
def __init__(self, id):
self.id = id
# Stockage simple d'utilisateurs (en production, utiliser une base de données)
users = {'garfi': {'admin': 'password123'}}
@login_manager.user_loader
def load_user(user_id):
return User(user_id)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users and users[username]['password'] == password:
user = User(username)
login_user(user)
return redirect(url_for('index'))
else:
return "Nom d'utilisateur ou mot de passe incorrect", 401
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
@app.route('/')
@login_required
def index():
return render_template('stream.html')
@app.route('/download', methods=['POST'])
@login_required
def download():
url = request.form['url']
format_choice = request.form['format']
delete_choice = request.form['delete_choice']
copy_choice = request.form['copy_choice'] # Nouvelle option pour copier ou non
def generate_output():
# Répertoires pour le téléchargement en fonction du format choisi
output_dir = "/home/garfi/Musique/flac" if format_choice == "flac" else "/home/garfi/Musique/mp3"
# Si l'utilisateur a choisi de supprimer les anciens répertoires
if delete_choice == "1":
yield "Suppression des anciens répertoires...\n"
try:
if os.path.exists("/home/garfi/Musique/flac"):
shutil.rmtree("/home/garfi/Musique/flac")
yield "Le répertoire /home/garfi/Musique/flac a été supprimé.\n"
if os.path.exists("/home/garfi/Musique/mp3"):
shutil.rmtree("/home/garfi/Musique/mp3")
yield "Le répertoire /home/garfi/Musique/mp3 a été supprimé.\n"
except FileNotFoundError as e:
yield f"Erreur : {str(e)} - Le répertoire n'existe pas.\n"
except Exception as e:
yield f"Erreur inattendue lors de la suppression : {str(e)}\n"
# Créer le répertoire pour stocker les nouveaux fichiers
os.makedirs(output_dir, exist_ok=True)
# Lancer le téléchargement avec spotdl
command = f'spotdl --output "{{artist}}/{{album}}/{{track-number}} - {{title}}.{{output-ext}}" "{url}" --format={format_choice}'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=output_dir)
for line in process.stdout:
yield line # Envoyer les lignes de la commande en temps réel
process.wait()
if process.returncode == 0:
yield "\nTéléchargement terminé avec succès.\n"
# Si l'utilisateur a choisi de copier vers /mnt/data/Musique/
if copy_choice == "1":
share_dir = "/mnt/data/Musique/"
try:
shutil.copytree(output_dir, share_dir, dirs_exist_ok=True)
yield f"\nLes fichiers ont été copiés vers {share_dir}.\n"
except Exception as e:
yield f"\nErreur lors de la copie des fichiers vers {share_dir} : {str(e)}\n"
else:
yield f"\nUne erreur est survenue avec le code {process.returncode}.\n"
return Response(generate_output(), mimetype='text/plain')
@app.route('/download_zip')
@login_required
def download_zip():
format_choice = request.args.get('format')
output_dir = "/home/garfi/Musique/flac" if format_choice == "flac" else "/home/garfi/Musique/mp3"
# Créer un fichier ZIP dans la mémoire
memory_file = BytesIO()
with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf:
for root, dirs, files in os.walk(output_dir):
for file in files:
file_path = os.path.join(root, file)
zf.write(file_path, arcname=os.path.relpath(file_path, output_dir))
memory_file.seek(0)
# Télécharger le fichier ZIP
return send_file(memory_file, mimetype='application/zip', as_attachment=True, download_name=f'musique_{format_choice}.zip')
if __name__ == '__main__':
app.run(debug=True)

2
run.sh Executable file
View File

@ -0,0 +1,2 @@
cd /home/garfi/sys/spotdl-py
flask run --host=192.168.1.10 --port=5024

36
templates/login.html Normal file
View File

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Connexion</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card mt-5">
<div class="card-body">
<h3 class="card-title text-center">Connexion</h3>
<form method="POST">
<div class="mb-3">
<label for="username" class="form-label">Nom d'utilisateur</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Mot de passe</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary w-100">Se connecter</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

105
templates/stream.html Normal file
View File

@ -0,0 +1,105 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Téléchargement en temps réel</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background-color: #f8f9fa; }
.container { margin-top: 50px; }
.card { border-radius: 10px; }
.output-container {
background-color: #f1f1f1;
padding: 20px;
border-radius: 10px;
white-space: pre-wrap;
font-family: monospace;
height: 400px;
overflow-y: scroll;
}
</style>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<div class="card-body">
<h2 class="text-center mb-4">Télécharger Musique Spotify</h2>
<form id="download-form">
<div class="mb-3">
<label for="url" class="form-label">Saisir l'URL Spotify :</label>
<input type="text" class="form-control" id="url" name="url" required>
</div>
<div class="mb-3">
<label for="format" class="form-label">Choisissez le format :</label>
<select class="form-select" id="format" name="format" required>
<option value="flac">FLAC</option>
<option value="mp3">MP3</option>
</select>
</div>
<div class="mb-3">
<label for="delete_choice" class="form-label">Supprimer les anciens répertoires :</label>
<select class="form-select" id="delete_choice" name="delete_choice" required>
<option value="1">Oui</option>
<option value="2">Non</option>
</select>
</div>
<div class="mb-3">
<label for="copy_choice" class="form-label">Copier vers /mnt/data/Musique/ :</label>
<select class="form-select" id="copy_choice" name="copy_choice" required>
<option value="1">Oui</option>
<option value="2">Non</option>
</select>
</div>
<button type="submit" class="btn btn-primary w-100">Lancer le téléchargement</button>
</form>
</div>
</div>
<div class="card mt-4">
<div class="card-body">
<h4>Output :</h4>
<div id="output" class="output-container"></div>
</div>
</div>
<!-- Button to download the ZIP -->
<button class="btn btn-secondary w-100 mt-3" onclick="window.location.href='/download_zip?format=' + document.getElementById('format').value">Télécharger ZIP</button>
</div>
</div>
</div>
<script>
document.getElementById('download-form').addEventListener('submit', function (event) {
event.preventDefault();
const url = document.getElementById('url').value;
const format = document.getElementById('format').value;
const delete_choice = document.getElementById('delete_choice').value;
const copy_choice = document.getElementById('copy_choice').value;
const formData = new URLSearchParams();
formData.append('url', url);
formData.append('format', format);
formData.append('delete_choice', delete_choice);
formData.append('copy_choice', copy_choice);
fetch('/download', {
method: 'POST',
body: formData
})
.then(response => {
const outputContainer = document.getElementById('output');
const reader = response.body.getReader();
const decoder = new TextDecoder();
function read() {
reader.read().then(({ done, value }) => {
if (done) return;
outputContainer.textContent += decoder.decode(value, { stream: true });
outputContainer.scrollTop = outputContainer.scrollHeight;
read();
});
}
read();
})
.catch(error => console.error('Erreur:', error));
});
</script>
</body>
</html>