from flask import Flask, render_template, request, send_file, jsonify from pytube import YouTube from yt_dlp import YoutubeDL import instaloader import os import uuid import shutil from waitress import serve app = Flask(__name__) # Create downloads directory os.makedirs('downloads', exist_ok=True) @app.route('/') def home(): return render_template('index.html') @app.route('/download', methods=['POST']) def download(): url = request.form.get('url') if not url: return jsonify({'error': 'No URL provided'}), 400 try: if 'youtube.com' in url or 'youtu.be' in url: return download_youtube(url) elif 'instagram.com' in url: return download_instagram(url) elif 'tiktok.com' in url: return download_tiktok(url) else: return jsonify({'error': 'Please enter a valid YouTube, Instagram, or TikTok URL'}), 400 except Exception as e: return jsonify({'error': str(e)}), 500 def download_youtube(url): try: yt = YouTube(url) stream = yt.streams.get_highest_resolution() filename = f"youtube_{uuid.uuid4().hex}.mp4" filepath = os.path.join('downloads', filename) stream.download(output_path='downloads', filename=filename) return send_file(filepath, as_attachment=True, download_name=f"{yt.title}.mp4") except Exception as e: return jsonify({'error': f'YouTube download failed: {str(e)}'}), 500 def download_instagram(url): try: L = instaloader.Instaloader() temp_dir = f"downloads/insta_{uuid.uuid4().hex}" os.makedirs(temp_dir, exist_ok=True) shortcode = url.split("/p/")[1].split("/")[0] if "/p/" in url else url.split("/reel/")[1].split("/")[0] post = instaloader.Post.from_shortcode(L.context, shortcode) L.download_post(post, target=temp_dir) for file in os.listdir(temp_dir): if file.endswith('.mp4'): filepath = os.path.join(temp_dir, file) return send_file(filepath, as_attachment=True) raise Exception("No video found in this post") except Exception as e: return jsonify({'error': f'Instagram download failed: {str(e)}'}), 500 finally: if os.path.exists(temp_dir): shutil.rmtree(temp_dir) def download_tiktok(url): try: filename = f"tiktok_{uuid.uuid4().hex}.mp4" filepath = os.path.join('downloads', filename) ydl_opts = { 'format': 'best', 'outtmpl': filepath, 'quiet': True } with YoutubeDL(ydl_opts) as ydl: ydl.download([url]) return send_file(filepath, as_attachment=True) except Exception as e: return jsonify({'error': f'TikTok download failed: {str(e)}'}), 500 @app.after_request def cleanup(response): for file in os.listdir('downloads'): filepath = os.path.join('downloads', file) try: if os.path.isfile(filepath): os.remove(filepath) except Exception: pass return response if __name__ == "__main__": port = int(os.environ.get("PORT", 7860)) serve(app, host="0.0.0.0", port=port)