|
from flask import Flask, request, send_file, jsonify |
|
from pytube import YouTube |
|
import os |
|
|
|
app = Flask(__name__) |
|
|
|
@app.route('/download', methods=['GET']) |
|
def download_video(): |
|
|
|
video_id = request.args.get('id') |
|
file_type = request.args.get('file', 'mp4') |
|
quality = request.args.get('quality', '720p') |
|
|
|
if not video_id: |
|
return jsonify({'error': 'Missing video ID'}), 400 |
|
|
|
file_path = None |
|
|
|
try: |
|
|
|
youtube_url = f'https://www.youtube.com/watch?v={video_id}' |
|
|
|
|
|
try: |
|
yt = YouTube(youtube_url, use_oauth=False) |
|
except Exception as e: |
|
if "device" in str(e).lower(): |
|
return jsonify({'error': 'OAuth authentication required. Please follow the instructions in the log to complete authentication.'}), 401 |
|
return jsonify({'error': str(e)}), 500 |
|
|
|
|
|
download_dir = "downloads" |
|
if not os.path.exists(download_dir): |
|
os.makedirs(download_dir) |
|
|
|
|
|
if file_type == 'mp4': |
|
stream = yt.streams.filter(res=quality, file_extension='mp4').first() |
|
if not stream: |
|
return jsonify({'error': f'Video with quality {quality} not found'}), 404 |
|
|
|
file_path = stream.download(output_path=download_dir) |
|
|
|
|
|
elif file_type == 'mp3': |
|
stream = yt.streams.filter(only_audio=True).first() |
|
if not stream: |
|
return jsonify({'error': 'Audio stream not found'}), 404 |
|
|
|
temp_file_path = stream.download(output_path=download_dir) |
|
file_path = os.path.splitext(temp_file_path)[0] + '.mp3' |
|
|
|
|
|
os.rename(temp_file_path, file_path) |
|
|
|
else: |
|
return jsonify({'error': 'Invalid file type. Use "mp4" or "mp3"'}), 400 |
|
|
|
|
|
return send_file(file_path, as_attachment=True) |
|
|
|
except Exception as e: |
|
|
|
return jsonify({'error': str(e)}), 500 |
|
|
|
finally: |
|
|
|
if file_path and os.path.exists(file_path): |
|
os.remove(file_path) |
|
|
|
if __name__ == '__main__': |
|
app.run(host='0.0.0.0', port=7860, debug=True) |
|
|