Upload 2 files
Browse filesFiles changed (2)
- app.py+14-110
- requirements.txt+2-3
5 unmodified lines6789910116 unmodified lines1819202223212223272425302627333428293738394030424344313246473334503536533738394058596061626364656667684142434445734647484977505179525354835585865688899091929394955758599860100101102103104105616210763641106566112676869116701181197112112212312412512612712812913072737413375135136137138139140141142143144145146147148149150151767778153798015681821588384851628616416587167168169170171172173174888990177178179180181182183184185919218793949596192193975 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 lines
try: import dns.resolver # Store the original socket function _original_getaddrinfo = socket.getaddrinfo
def patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): # Check if the host matches any of the bypass domains if host and any(domain in host for domain in BYPASS_DOMAINS): try: # Create a custom resolver pointing to Google and Cloudflare DNS res = dns.resolver.Resolver() res.nameservers = ['8.8.8.8', '1.1.1.1'] # Get the IPv4 address answers = 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 format return [(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 fails except Exception: return _original_getaddrinfo(host, port, family, type, proto, flags) # For all other domains (like localhost), use system DNS return _original_getaddrinfo(host, port, family, type, proto, flags)
# Apply the patch socket.getaddrinfo = patched_getaddrinfo print(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 ASGIMiddleware app = ASGIMiddleware(flask_app)except ImportError: # Fallback to the original app if a2wsgi is not installed app = flask_app# --- ASGI WRAPPER END ---app = Flask(__name__)
def log(msg): print(f"[DEBUG] {msg}", file=sys.stderr)
@flask_app.route('/')@app.route('/')def index(): return "YT-DLP API (DNS Bypassed) is running."
@flask_app.route('/info', methods=['POST'])@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"}), 400
url = 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', }
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 serializable sanitized_info = ydl.sanitize_info(info) return jsonify({ "status": "ok", "info": sanitized_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'])@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"}), 400
url = 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, }
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 audio for f in formats: if f.get('ext') == 'mp4' and f.get('acodec') != 'none': best = f if 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') })
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: log(f"❌ ERROR: {str(e)}") return jsonify({"error": str(e)}), 500
@flask_app.route('/hls', methods=['POST'])@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"}), 400
m3u8_url = data['url'] log(f"Processing HLS: {m3u8_url}")
try: # We use a very light configuration for direct HLS links ydl_opts = { 'quiet': True, 'skip_download': True, 'force_ipv4': True, 'format': 'best', # Get the highest quality stream in the manifest }
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') })
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)}), 500
if __name__ == "__main__": port = int(os.environ.get("PORT", 7860)) flask_app.run(host='0.0.0.0', port=port)
app.run(host='0.0.0.0', port=port)12345645flaskyt-dlpdnspythona2wsgiuvicorncachetoolsgunicorncachetoolsapp.py+14-110
requirements.txt+2-3