import re import time from urllib.parse import urlparse import cloudscraper from lxml import etree from plugins.common import DownloadCancelled from plugins.stream import download_stream_url def _get_mediafire_direct_link(url: str) -> str: """Resuelve la URL directa de descarga de MediaFire usando Cloudscraper y XPath/Regex.""" scraper = cloudscraper.create_scraper( browser={"browser": "chrome", "platform": "windows", "mobile": False} ) scraper.headers.update({ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", "Accept-Language": "es-ES,es;q=0.9,en;q=0.8", }) # Limpiar parĂ¡metros residuales como ?action=check que provocan 403 Forbidden directo en MediaFire parsed = urlparse(url) curr_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path}" for attempt in range(4): resp = scraper.get(curr_url, timeout=30, allow_redirects=True) if resp.status_code != 403 or "action=check" not in resp.url or attempt == 3: resp.raise_for_status() break curr_url = urlparse(resp.url)._replace(query="").geturl() time.sleep(0.5 * (2 ** attempt)) # Si la URL final ya es de descarga directa dl_match = re.search(r"https?://download\d+\.mediafire\.com/[^\s\"'<>]+", resp.url) if dl_match: return dl_match.group(0) # Buscar en el HTML tree = etree.HTML(resp.text) if tree is not None: buttons = ( tree.xpath('//a[@aria-label="Download file"]/@href') or tree.xpath('//a[@id="downloadButton"]/@href') or tree.xpath('//a[contains(@class, "download_link")]/@href') or tree.xpath('//a[@id="download_link"]/@href') or tree.xpath('//a[contains(@class, "popsok")]/@href') or tree.xpath('//a[contains(@href, "download") and contains(@href, "mediafire.com")]/@href') or tree.xpath('//a[@id="downloadButton"]/@data-href') ) for b in buttons: if b and "download_repair.php" not in str(b) and not str(b).startswith("javascript:"): return str(b) # Regex en el cuerpo direct_match = re.search(r'https?://download\d+\.mediafire\.com/[^\s"\'<>]+', resp.text) if direct_match: return direct_match.group(0) js_match = re.search(r'(?:kNO|location\.href)\s*=\s*["\'](https?://[^"\']+)["\']', resp.text) if js_match and "mediafire.com" in js_match.group(1) and "download_repair.php" not in js_match.group(1): return js_match.group(1) raise RuntimeError("No se pudo obtener el enlace de descarga directa de MediaFire.") def download_mediafire( url: str, output_dir: str, progress_fn=None, cancel_event=None ) -> str: """Resuelve el enlace de MediaFire y lo descarga por streaming.""" if cancel_event and cancel_event.is_set(): raise DownloadCancelled() direct_url = _get_mediafire_direct_link(url) mf_headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Referer": "https://www.mediafire.com/", } out_path, _ = download_stream_url(direct_url, output_dir, progress_fn=progress_fn, cancel_event=cancel_event, headers=mf_headers) return out_path