from flask import Flask, request, send_file, jsonify
import subprocess
import os

app = Flask(__name__)

@app.route('/download', methods=['POST'])
def download_podcast():
    url = request.args.get('url')
    if not url:
        return jsonify({"error": "URL parameter is missing"}), 400

    try:
        # Define the output file name for the downloaded podcast
        output_file = "downloaded_podcast.mp3"

        # Use subprocess to run the spotify-dlx command
        command = f"python -m spotify_dlx --url {url} -o {output_file}"
        subprocess.run(command, shell=True, check=True)

        # Check if the file was downloaded
        if os.path.exists(output_file):
            # Send the file as a binary response
            return send_file(output_file, as_attachment=True)
        else:
            return jsonify({"error": "File download failed"}), 500
    except subprocess.CalledProcessError as e:
        return jsonify({"error": str(e)}), 500
    finally:
        # Clean up: remove the file after sending it
        if os.path.exists(output_file):
            os.remove(output_file)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5729)

