Update main.py
Browse files189 unmodified lines190191192193189 unmodified linesraise HTTPException(status_code=404, detail="No matching video ID found on YouTube Music after search.")else:logger.error(f"Match endpoint: YTMusic search for '{search_query}' yielded no results.")raise HTTPException(status_code=404, detail="No results found on YouTube Music for the track.")189 unmodified lines190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374189 unmodified linesraise HTTPException(status_code=404, detail="No matching video ID found on YouTube Music after search.")else:logger.error(f"Match endpoint: YTMusic search for '{search_query}' yielded no results.")raise HTTPException(status_code=404, detail="No results found on YouTube Music for the track.")import socketimport sysimport osfrom flask import Flask, request, jsonifyimport yt_dlpfrom 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","dailymotion.com", "dmcdn.net","twitch.tv", "ttvnw.net","facebook.com", "fbcdn.net","instagram.com", "tiktok.com","bilibili.com", "biliapi.net"]try: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 ---app = Flask(__name__)def log(msg):print(f"[DEBUG] {msg}", file=sys.stderr)@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@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@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)}), 500
main.py+182-1