from flask import Flask, render_template, request, redirect, url_for, send_from_directory
import subprocess, yt_dlp, shutil, os

    
app=Flask(__name__)
app.secret_key="clave"
@app.route("/")
def indice():
    msg=request.args.get("msg","")
    command="ls -A /var/www/DS/videos/"
    scan_command=subprocess.run(command,shell=True,text=True,capture_output=True)
    dir_scan=(scan_command.stdout).splitlines()
    return render_template("index.html",msg=msg, dir_scan=dir_scan)

@app.route("/descargas",methods=["POST"])

def descarga():
    
    try:
    
        url=request.form.get("url")
        if not url:
            return redirect(url_for("indice"))
        
        if "youtube" in url:
            if "list=" in url:
                command="ls -A /var/www/DS/videos/"
                scan_command=subprocess.run(command,shell=True,text=True,capture_output=True)
                dir_scan=(scan_command.stdout).splitlines()
                info_list=(yt_dlp.YoutubeDL()).extract_info(url, download=False)
                if info_list["title"] in dir_scan:
                    return url_for("indice",msg="La playlist introducida ya existe")
                subprocess.run(["mkdir",f"/var/www/DS/videos/{info_list['title']}"])
                parametros={
                    'format': 'bestvideo+bestaudio/best',
                    'merge_output_format': 'mp4',
                    'outtmpl': f'./videos/{info_list['title']}/%(title)s.%(ext)s',
                    'noplaylist': False,
                }
            else:
                parametros={
                    'format': 'bestvideo+bestaudio/best',
                    'merge_output_format': 'mp4',
                    'outtmpl': f'{"./videos"}/%(title)s.%(ext)s',
                    'noplaylist': True,
                }
            try:
                with yt_dlp.YoutubeDL(parametros) as info:
                    info.download([url])
                return redirect(url_for("indice",msg="Descargado correctamente"))

            except:
                return redirect(url_for("indice", msg=f"Ha ocurrido un error de descarga"))
        elif "spotify" in url:
            if "playlist" in url:
                subprocess.run(f"spotdl {url} --output '/var/www/DS/videos/%playlist_name%/%artist% - %title%.mp3'")
                return redirect(url_for("indice", msg=f"Ha ocurrido un error de descarga"))
            elif "track" in url:
                subprocess.run(f"spotdl {url} --output '/var/www/DS/videos/%artist% - %title%.mp3'")
                return redirect(url_for("indice", msg=f"Ha ocurrido un error de descarga"))
        else:
            return redirect(url_for("indice", msg=f"Ha ocurrido un error de descarga"))
    except:
        return redirect(url_for("indice", msg=f"Ha ocurrido un error de descarga"))
    
@app.route("/video")
def repro():
    video=request.args.get("video","")
    if video.endswith(".mp4") :
        return render_template("video.html",video=video)
    else:
        command=f"ls -A /var/www/DS/videos/{video}/"
        scan_command=subprocess.run(command,shell=True,text=True,capture_output=True)
        dir_scan=str(scan_command.stdout)
        return redirect(url_for("vid_dir",dir_scan=dir_scan,playlist=video))
    
@app.route("/dir")
def vid_dir():
    dir_scan_str=request.args.get("dir_scan","")
    playlist=request.args.get("playlist","")
    dir_scan=str(dir_scan_str).splitlines()
    return render_template("index.html",dir_scan=dir_scan,playlist=playlist)

@app.route("/videos/<path:filename>")
def videos(filename):
    return send_from_directory("/var/www/DS/videos", filename, as_attachment=True)


@app.route("/download_playlist/<path:filename>")
def download_playlist(filename):
    directorio=f"/var/www/DS/videos/{filename}"
    compress_zip=f"/tmp/{filename}.zip"
    compress=f"/tmp/{filename}"
    if os.path.exists(compress_zip):
        os.remove(compress_zip)
    shutil.make_archive(compress.replace(".zip",""),"zip",directorio)
    return send_from_directory("/tmp/", f"{filename}.zip", as_attachment=True)

@app.route("/delete/<path:filename>")
def eliminar(filename):
    fichero=f"/var/www/DS/videos/{filename}"
    os.remove(fichero)
    return redirect(url_for("indice"))

@app.route("/deletedir/<path:filename>")
def eliminardir(filename):
    fichero=f"/var/www/DS/videos/{filename}"
    shutil.rmtree(fichero)
    return redirect(url_for("indice"))

#revovinacion, en desarrollo
@app.route("/pre")
def pre():
    vid=request.args.get("filename","")
    command=f"find /var/www/DS/videos/{vid}"
    command_exec=subprocess.run(command,shell=True,capture_output=True,text=True)
    command2=f"dirname '{command_exec.stdout}'"
    command_exec2=subprocess.run(command2,shell=True,capture_output=True,text=True)
    command3=f"ls {command_exec2.stdout}"
    command_exec3=subprocess.run(command3,shell=True,capture_output=True,text=True)
    scan_dir=str(command_exec3.stdout).splitlines()


app.run(debug=True,host="0.0.0.0")