GR-Jukebox/main1.py
2024-08-11 02:08:13 -04:00

142 lines
4.9 KiB
Python

from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_cors import CORS
import yt_dlp
import vlc
import time
import os
import eyed3
home_directory = os.path.expanduser("~")
#app = Flask(__name__,template_folder=home_directory)
app = Flask(__name__,template_folder=(home_directory+"/Code/GR/GR-Jukebox"))
CORS(app, resources={r"/*": {"origins": "*"}})
player = vlc.MediaPlayer()
music_queue = []
title_queue = []
music_directory = os.path.expanduser('~/Music') # Adjust path as necessary
@app.route('/')
def index():
return render_template('manage1.html')
@app.route('/admin')
def index():
return render_template('manage1.html')
@app.route('/display')
def display():
return render_template('display1.html')
@app.route('/music')
def list_music():
music_files = []
for filename in os.listdir(music_directory):
if filename.endswith('.mp3'):
path = os.path.join(music_directory, filename)
audiofile = eyed3.load(path)
title = audiofile.tag.title if audiofile.tag else 'Unknown Title'
music_files.append({'id': filename.split('.')[0], 'title': title})
return jsonify(music_files)
@app.route('/download', methods=['POST'])
def download():
url = request.form['youtube_url']
if 'youtube.com' in url:
video_id = url.split('=')[1][:11] # Extract the video ID from the YouTube URL
elif 'youtu.be' in url:
video_id = url.split('youtu.be/')[1][:11]
else:
return jsonify({'status': 'error', 'message': 'Invalid YouTube URL'})
output_path = os.path.expanduser(f'{home_directory}/Music/{video_id}.mp3') # Path where the file will be saved
if not os.path.exists(output_path):
print("Downloading...")
# Configure yt-dlp to download best audio quality
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'noplaylist': True,
'quiet': True,
'outtmpl': output_path[:-4] # Use the custom path as the output template
}
# Use yt-dlp to extract information and download the audio file
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
title = info.get('title') # Extract the title from video information
# Load the downloaded file using eyed3 and add ID3 tags
audiofile = eyed3.load(output_path)
if audiofile.tag is None: # Create an ID3 tag if none exist
audiofile.tag = eyed3.id3.Tag()
audiofile.tag.file_info = eyed3.id3.FileInfo(output_path)
print(f"Downloaded: {title}")
audiofile.tag.title = title
audiofile.tag.save() # Save the metadata
#return redirect(url_for('index')) # Redirect back to the main page
return jsonify({'status': 'success', 'message': 'Song added successfully'})
playing_thread = False
@app.route('/play', methods=['POST'])
def play():
global music_queue
global title_queue
global playing_thread
global player
music_queue.append(request.json['songId'])
title_queue.append(request.json['songTitle'])
if not playing_thread:
while len(music_queue) > 0:
playing_thread = True
player = vlc.MediaPlayer(f'{home_directory}/Music/{music_queue[0]}.mp3')
player.play()
# Wait for the audio to start playing and check periodically if it is still playing
time.sleep(1) # Short initial delay to allow playback to start
while player.is_playing():
print('Playing...')
time.sleep(0.5) # Check every second if it is still playing
player.stop()
music_queue.pop(0)
title_queue.pop(0)
playing_thread = False
return jsonify({'status': 'success', 'message': 'Playing song'})
@app.route('/queue')
def get_queue():
global title_queue
return jsonify([{'id': idx, 'title': title} for idx, title in enumerate(title_queue)])
@app.route('/remove_from_queue', methods=['POST'])
def remove_from_queue():
global music_queue
global title_queue
global player
data = request.json
song_id = int(data['songId'])
try:
#del music_queue[song_id]
#del title_queue[song_id]
if song_id == 0:
player.stop()
else:
music_queue.pop(song_id)
title_queue.pop(song_id)
return jsonify({'status': 'success', 'message': 'Song removed successfully'})
except IndexError:
return jsonify({'status': 'error', 'message': 'Invalid song ID'}), 400
@app.route('/current')
def current():
global title_queue
if len(title_queue) > 0:
return {'title': title_queue[0]}
return {'title': 'Nothing is playing'}
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True, port=5000)