File size: 1,997 Bytes
db25fa4
 
 
 
 
 
911912a
 
 
 
db25fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from flask import Flask, request, jsonify, send_file
from yt_dlp import YoutubeDL
import os

app = Flask(__name__)

@app.route('/', methods=['GET'])
def home():
    return jsonify({ 'message': 'Hallo, Welcome' })

@app.route('/formats', methods=['POST'])
def get_formats():
    data = request.json
    url = data.get('url')

    if not url:
        return jsonify({'error': 'URL is required'}), 400

    try:
        with YoutubeDL({'listformats': True}) as ydl:
            info = ydl.extract_info(url, download=False)
            formats = [{
                'format_id': f['format_id'],
                'format_note': f.get('format_note', 'N/A'),
                'ext': f['ext'],
                'filesize': f.get('filesize'),
                'resolution': f.get('resolution', 'audio only'),
            } for f in info['formats']]

        return jsonify({'title': info['title'], 'formats': formats})

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# Endpoint untuk mendownload video atau audio
@app.route('/download', methods=['POST'])
def download_file():
    data = request.json
    url = data.get('url')
    format_id = data.get('format_id')

    if not url or not format_id:
        return jsonify({'error': 'URL and format_id are required'}), 400

    try:
        # Konfigurasi yt-dlp
        ydl_opts = {
            'format': format_id,
            'outtmpl': '%(title)s.%(ext)s',
            'cookiefile': 'www.youtube.com_cookies.txt'  # Jika dibutuhkan
        }

        with YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(url, download=True)
            file_name = ydl.prepare_filename(info)

        # Kirim file ke client
        return send_file(file_name, as_attachment=True)

    except Exception as e:
        return jsonify({'error': str(e)}), 500

    finally:
        # Bersihkan file setelah dikirim
        if os.path.exists(file_name):
            os.remove(file_name)

if __name__ == '__main__':
    app.run(debug=True)