Upload 2 files
Browse filesFiles changed (2)
- app.py+14-110
- requirements.txt+2-3
5 unmodified lines67891011126 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921935 unmodified linesfrom yt_dlp.utils import DownloadError# --- DNS BYPASS PATCH START ---# The local DNS might block these domains. We will ask Google/Cloudflare DNS instead.BYPASS_DOMAINS = ["youtube.com", "googlevideo.com", "youtu.be","vimeo.com", "vimeocdn.com",6 unmodified linestry:import dns.resolver# Store the original socket function_original_getaddrinfo = socket.getaddrinfodef patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):# Check if the host matches any of the bypass domainsif host and any(domain in host for domain in BYPASS_DOMAINS):try:# Create a custom resolver pointing to Google and Cloudflare DNSres = dns.resolver.Resolver()res.nameservers = ['8.8.8.8', '1.1.1.1']# Get the IPv4 addressanswers = res.resolve(host, 'A')ip_address = answers[0].to_text()print(f"[DNS BYPASS] Resolved {host} -> {ip_address}", file=sys.stderr)# Return the resolved IP to Python in the expected formatreturn [(socket.AF_INET, type, proto, '', (ip_address, port))]except Exception as e:print(f"[DNS BYPASS] Failed to resolve {host}: {e}", file=sys.stderr)# Fallback to system DNS if bypass failsreturn _original_getaddrinfo(host, port, family, type, proto, flags)# For all other domains (like localhost), use system DNSreturn _original_getaddrinfo(host, port, family, type, proto, flags)# Apply the patchsocket.getaddrinfo = patched_getaddrinfoprint(f"[INIT] DNS Bypass installed for {len(BYPASS_DOMAINS)} domains.", file=sys.stderr)except ImportError:print("❌ CRITICAL: dnspython not installed. DNS Bypass failed.", file=sys.stderr)# --- DNS BYPASS PATCH END ---flask_app = Flask(__name__)# --- ASGI WRAPPER START ---# Wrap Flask (WSGI) as an ASGI app for Uvicorn compatibilitytry:from a2wsgi import ASGIMiddlewareapp = ASGIMiddleware(flask_app)except ImportError:# Fallback to the original app if a2wsgi is not installedapp = flask_app# --- ASGI WRAPPER END ---def log(msg):print(f"[DEBUG] {msg}", file=sys.stderr)@flask_app.route('/')def index():return "YT-DLP API (DNS Bypassed) is running."@flask_app.route('/info', methods=['POST'])def get_info():"""Returns the full metadata of a video without downloading it."""data = request.get_json()if not data or 'url' not in data:return jsonify({"error": "URL is missing"}), 400url = data['url']log(f"Fetching metadata for: {url}")try:ydl_opts = {'quiet': True,'noplaylist': True,'skip_download': True,'force_ipv4': True,'cache_dir': '/tmp/.yt-dlp-cache',}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=False)# sanitize_info ensures the dictionary is JSON serializablesanitized_info = ydl.sanitize_info(info)return jsonify({"status": "ok","info": sanitized_info})except Exception as e:log(f"❌ ERROR: {str(e)}")return jsonify({"error": str(e)}), 500@flask_app.route('/get_link', methods=['POST'])def get_link():"""Returns the best MP4 download URL for a video."""data = request.get_json()if not data or 'url' not in data:return jsonify({"error": "URL is missing"}), 400url = data['url']log(f"Processing link for: {url}")try:ydl_opts = {'quiet': True,'noplaylist': True,'skip_download': True,'simulate': True,'force_formats': True,'cache_dir': '/tmp/.yt-dlp-cache','force_ipv4': True,}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=False)formats = info.get('formats', [])best = None# Logic: Find mp4 with audiofor f in formats:if f.get('ext') == 'mp4' and f.get('acodec') != 'none':best = fif not best and formats:best = formats[-1]return jsonify({"status": "ok","download_url": best.get('url') if best else None,"title": info.get('title'),"thumbnail": info.get('thumbnail')})except Exception as e:log(f"❌ ERROR: {str(e)}")return jsonify({"error": str(e)}), 500@flask_app.route('/hls', methods=['POST'])def get_hls_link():"""Handles raw HLS (.m3u8) URLs and returns the best direct stream link."""data = request.get_json()if not data or 'url' not in data:return jsonify({"error": "M3U8 URL is missing"}), 400m3u8_url = data['url']log(f"Processing HLS: {m3u8_url}")try:# We use a very light configuration for direct HLS linksydl_opts = {'quiet': True,'skip_download': True,'force_ipv4': True,'format': 'best', # Get the highest quality stream in the manifest}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(m3u8_url, download=False)return jsonify({"status": "ok","download_url": info.get('url'),"title": info.get('title', 'HLS Stream'),"protocol": info.get('protocol'),"ext": info.get('ext')})except Exception as e:log(f"❌ HLS ERROR: {str(e)}")return jsonify({"error": str(e)}), 500if __name__ == "__main__":port = int(os.environ.get("PORT", 7860))flask_app.run(host='0.0.0.0', port=port)5 unmodified lines678910116 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596975 unmodified linesfrom yt_dlp.utils import DownloadError# --- DNS BYPASS PATCH START ---BYPASS_DOMAINS = ["youtube.com", "googlevideo.com", "youtu.be","vimeo.com", "vimeocdn.com",6 unmodified linestry:import dns.resolver_original_getaddrinfo = socket.getaddrinfodef patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):if host and any(domain in host for domain in BYPASS_DOMAINS):try:res = dns.resolver.Resolver()res.nameservers = ['8.8.8.8', '1.1.1.1']answers = res.resolve(host, 'A')ip_address = answers[0].to_text()return [(socket.AF_INET, type, proto, '', (ip_address, port))]except Exception:return _original_getaddrinfo(host, port, family, type, proto, flags)return _original_getaddrinfo(host, port, family, type, proto, flags)socket.getaddrinfo = patched_getaddrinfoprint(f"[INIT] DNS Bypass installed for {len(BYPASS_DOMAINS)} domains.", file=sys.stderr)except ImportError:print("❌ CRITICAL: dnspython not installed. DNS Bypass failed.", file=sys.stderr)# --- DNS BYPASS PATCH END ---app = Flask(__name__)def log(msg):print(f"[DEBUG] {msg}", file=sys.stderr)@app.route('/')def index():return "YT-DLP API (DNS Bypassed) is running."@app.route('/info', methods=['POST'])def get_info():data = request.get_json()if not data or 'url' not in data:return jsonify({"error": "URL is missing"}), 400url = data['url']try:ydl_opts = {'quiet': True, 'noplaylist': True, 'skip_download': True, 'force_ipv4': True, 'cache_dir': '/tmp/.yt-dlp-cache'}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=False)sanitized_info = ydl.sanitize_info(info)return jsonify({"status": "ok", "info": sanitized_info})except Exception as e:return jsonify({"error": str(e)}), 500@app.route('/get_link', methods=['POST'])def get_link():data = request.get_json()if not data or 'url' not in data:return jsonify({"error": "URL is missing"}), 400url = data['url']try:ydl_opts = {'quiet': True, 'noplaylist': True, 'skip_download': True, 'simulate': True, 'force_formats': True, 'cache_dir': '/tmp/.yt-dlp-cache', 'force_ipv4': True}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=False)formats = info.get('formats', [])best = next((f for f in formats if f.get('ext') == 'mp4' and f.get('acodec') != 'none'), formats[-1] if formats else None)return jsonify({"status": "ok", "download_url": best.get('url') if best else None, "title": info.get('title'), "thumbnail": info.get('thumbnail')})except Exception as e:return jsonify({"error": str(e)}), 500@app.route('/hls', methods=['POST'])def get_hls_link():data = request.get_json()if not data or 'url' not in data:return jsonify({"error": "M3U8 URL is missing"}), 400m3u8_url = data['url']try:ydl_opts = {'quiet': True, 'skip_download': True, 'force_ipv4': True, 'format': 'best'}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(m3u8_url, download=False)return jsonify({"status": "ok", "download_url": info.get('url'), "title": info.get('title', 'HLS Stream'), "protocol": info.get('protocol'), "ext": info.get('ext')})except Exception as e:return jsonify({"error": str(e)}), 500if __name__ == "__main__":port = int(os.environ.get("PORT", 7860))app.run(host='0.0.0.0', port=port)
123456flaskyt-dlpdnspythona2wsgiuvicorncachetools12345flaskyt-dlpdnspythongunicorncachetools
app.py+14-110
requirements.txt+2-3