File size: 2,673 Bytes
4bcc346
 
 
 
 
 
0db7be7
4bcc346
 
 
 
 
 
 
 
 
08b9d9a
 
4bcc346
 
 
9f1ef4c
 
 
11511b8
9f1ef4c
 
 
 
4bcc346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0db7be7
4bcc346
 
 
 
08b9d9a
4bcc346
 
 
f62ef1f
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
70
71
72
73
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():
    # 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}'
        
        # OAuthを有効化してYouTubeオブジェクトを作成
        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)

        # 動画をダウンロード (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(host='0.0.0.0', port=7860, debug=True)