File size: 2,193 Bytes
4bcc346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08b9d9a
 
4bcc346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08b9d9a
4bcc346
 
 
 
08b9d9a
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
from flask import Flask, request, send_file, jsonify
from pytube import YouTube
import os

app = Flask(__name__)

@app.route('/watch', methods=['GET'])
def download_video():
    # URLパラパータを取得
    video_id = request.args.get('id')
    file_type = request.args.get('file', 'mp4')  # γƒ‡γƒ•γ‚©γƒ«γƒˆγ― mp4
    quality = request.args.get('quality', '720p')  # γƒ‡γƒ•γ‚©γƒ«γƒˆγ― 720p

    if not video_id:
        return jsonify({'error': 'Missing video ID'}), 400

    file_path = None  # file_path γ‚’δΊ‹ε‰γ«εˆζœŸεŒ–

    try:
        # YouTube URLγ‚’δ½œζˆ
        youtube_url = f'https://www.youtube.com/watch?v={video_id}'
        yt = YouTube(youtube_url)

        # γƒ•γ‚‘γ‚€γƒ«δΏε­˜η”¨γƒ‡γ‚£γƒ¬γ‚―γƒˆγƒͺ
        download_dir = "downloads"
        if not os.path.exists(download_dir):
            os.makedirs(download_dir)

        # 動画をダウンロード (MP4)
        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)
        
        # γ‚ͺーディγ‚ͺをダウンロード (MP3)
        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'

            # 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(debug=True, host='0.0.0.0')