from flask import Flask, request, send_file, jsonify import os import subprocess app = Flask(__name__) # 権限変更コマンドを実行する関数 def change_permissions(directory): try: # chmod 775コマンドを使って権限を変更 subprocess.run(['chmod', '775', directory], check=True) print(f"Permissions for {directory} changed to 775.") except subprocess.CalledProcessError as e: print(f"Error changing permissions for {directory}: {e}") return False return True @app.route('/', methods=['GET']) def download_video(): try: # URLの取得 video_url = request.args.get('url') if not video_url: return jsonify({"error": "URL is required"}), 400 # ダウンロード先ディレクトリ output_path = "downloads" os.makedirs(output_path, exist_ok=True) # ダウンロード先ディレクトリが存在しない場合、作成する # `downloads`ディレクトリの権限を775に変更 if not change_permissions(output_path): return jsonify({"error": "Failed to change directory permissions"}), 500 # 出力ファイル名テンプレート output_file = os.path.join(output_path, '%(title)s.%(ext)s') # yt-dlpコマンドの設定 cookies_file = 'cookies.txt' # エクスポートしたクッキーを指定 cmd = [ 'yt-dlp', '--cookies', cookies_file, '--output', output_file, # 出力ファイルのパスを指定 '-f', 'bestvideo+bestaudio/best', # 最適なビデオ+オーディオフォーマットを選択 video_url ] # yt-dlpコマンドを実行 result = subprocess.run(cmd, check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 出力とエラーメッセージをログに表示 print(result.stdout.decode()) # コマンド実行結果を表示 print(result.stderr.decode()) # エラーメッセージを表示 # エラーメッセージがあれば、それを返す if result.returncode != 0: return jsonify({"error": result.stderr.decode()}), 500 # ダウンロードされたファイル名を取得するために、ダウンロードディレクトリ内のファイルを確認 downloaded_files = os.listdir(output_path) video_file = None # ダウンロードしたファイルがMP4またはWebMの場合、そのファイルを選択 for file in downloaded_files: if file.endswith('.mp4') or file.endswith('.webm'): video_file = os.path.join(output_path, file) break if not video_file: return jsonify({"error": "No video file found"}), 404 # ファイルをクライアントに送信 return send_file(video_file, as_attachment=True) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == '__main__': app.run(host="0.0.0.0", port=7860, debug=True)