File size: 17,592 Bytes
b90715b ff4dac6 e4ae20c ff4dac6 a6cceab ff4dac6 b90715b 7debc2e b90715b ff4dac6 6502ff3 e4ae20c ff4dac6 6502ff3 ff4dac6 6502ff3 ff4dac6 6502ff3 ff4dac6 6502ff3 ff4dac6 6502ff3 ff4dac6 6502ff3 ff4dac6 6502ff3 ff4dac6 6502ff3 ff4dac6 6502ff3 ff4dac6 6502ff3 ff4dac6 b90715b a6cceab 7debc2e a6cceab ff4dac6 7debc2e a6cceab 7debc2e ff4dac6 7debc2e ff4dac6 7debc2e ff4dac6 7debc2e ff4dac6 6502ff3 ff4dac6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 | import logging
import os
import re
import secrets
import time
from typing import Any, List, Optional, Tuple, Union
import requests
from Crypto.Cipher import AES
from Crypto.Util import Counter
from mega import Mega
from mega.crypto import (
a32_to_str,
base64_to_a32,
base64_url_decode,
decrypt_attr,
decrypt_key,
)
from plugins.common import DownloadCancelled
logger = logging.getLogger("plugins.mega")
REQUEST_TIMEOUT = (15, 60)
MAX_FOLDER_FILES = 50
def is_mega_folder_url(url: str) -> bool:
"""Verifica si la URL corresponde a una carpeta de Mega.nz."""
u = str(url or "").strip().lower()
return "/folder/" in u or "/#f!" in u or "#f!" in u
def parse_mega_folder_url(url: str) -> Tuple[str, str]:
"""Extrae (folder_handle, folder_key) de URLs de carpetas de Mega."""
u = str(url or "").strip()
if "/folder/" in u:
parts = u.split("/folder/", 1)[1].split("?", 1)[0].rstrip("/")
if "#" in parts:
handle, key = parts.split("#", 1)
handle = handle.split("/")[0].strip()
key = key.split("/")[0].strip()
if handle and key:
return handle, key
for marker in ("/#F!", "/#f!", "#F!", "#f!"):
if marker in u:
parts = u.split(marker, 1)[1].split("?", 1)[0].rstrip("/")
sub = parts.split("!")
if len(sub) >= 2:
handle = sub[0].strip()
key = sub[1].strip()
if handle and key:
return handle, key
raise ValueError("El enlace no tiene un formato de carpeta de Mega reconocido.")
def parse_mega_file_url(url: str) -> Tuple[str, str]:
"""Extrae (file_handle, file_key) de URLs de archivos individuales de Mega."""
u = str(url or "").strip()
if "/file/" in u:
parts = u.split("/file/", 1)[1].split("?", 1)[0].rstrip("/")
if "#" in parts:
handle, key = parts.split("#", 1)
handle = handle.split("/")[0].strip()
key = key.split("/")[0].strip()
if handle and key:
return handle, key
elif "!" in parts:
sub = parts.lstrip("#!").split("!")
if len(sub) >= 2:
handle = sub[0].strip()
key = sub[1].strip()
if handle and key:
return handle, key
for marker in ("/#!", "#!"):
if marker in u:
parts = u.split(marker, 1)[1].split("?", 1)[0].rstrip("/")
sub = parts.split("!")
if len(sub) >= 2:
handle = sub[0].strip()
key = sub[1].strip()
if handle and key:
return handle, key
raise ValueError("El enlace no tiene un formato de archivo de Mega reconocido.")
def sanitize_filename(filename: str, default: str = "archivo_mega") -> str:
"""Limpia caracteres inválidos del nombre de archivo."""
if not filename:
return default
clean = re.sub(r'[\/\\:\*\?"<>\|\x00-\x1f]', '_', filename).strip(' ._')
return clean if clean else default
def _download_stream_decrypt(
file_url: str,
output_path: str,
declared_size: int,
k_str: bytes = None,
initial_counter_val: int = None,
aes_cipher: Optional[Any] = None,
progress_fn=None,
cancel_event=None,
chunk_size: int = 512 * 1024,
current_offset: int = 0,
total_batch_size: int = 0,
max_retries: int = 8,
) -> str:
"""
Descarga por HTTP stream y descifra en tiempo real con AES-CTR directamente al archivo destino,
con soporte de reanudación automática (Range: bytes=N-) y reintentos ante caídas de conexión.
"""
target_dir = os.path.dirname(output_path)
if target_dir:
os.makedirs(target_dir, exist_ok=True)
part_path = output_path + ".part"
downloaded = 0
if os.path.exists(part_path):
cur_sz = os.path.getsize(part_path)
# Reanudar estrictamente en múltiplos de bloques AES (16 bytes)
downloaded = (cur_sz // 16) * 16
if downloaded < cur_sz:
try:
with open(part_path, "r+b") as f:
f.truncate(downloaded)
except Exception:
downloaded = 0
try:
os.remove(part_path)
except Exception:
pass
attempt = 0
sess = requests.Session()
while True:
if cancel_event and cancel_event.is_set():
raise DownloadCancelled()
if declared_size > 0 and downloaded >= declared_size:
break
if declared_size == 0 and downloaded > 0:
break
attempt += 1
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",
"Accept": "*/*",
}
if downloaded > 0:
headers["Range"] = f"bytes={downloaded}-"
try:
r = sess.get(file_url, headers=headers, stream=True, timeout=REQUEST_TIMEOUT)
if r.status_code == 509:
raise RuntimeError("Límite de transferencia de Mega excedido para la IP del worker.")
if r.status_code not in (200, 206):
r.raise_for_status()
# Si el servidor no soportó Range y devolvió 200 en vez de 206 al reanudar, reiniciar desde 0
if downloaded > 0 and r.status_code == 200:
logger.warning("[Mega] El servidor no respetó Range en reanudación, reiniciando desde 0...")
downloaded = 0
if os.path.exists(part_path):
try:
os.remove(part_path)
except Exception:
pass
# Inicializar cifrador AES-CTR en el offset correspondiente
if k_str is not None and initial_counter_val is not None:
block_offset = downloaded // 16
cur_counter_val = initial_counter_val + block_offset
counter = Counter.new(128, initial_value=cur_counter_val)
active_aes = AES.new(k_str, AES.MODE_CTR, counter=counter)
else:
active_aes = aes_cipher
mode = "ab" if (downloaded > 0 and os.path.exists(part_path)) else "wb"
with open(part_path, mode, buffering=4 * 1024 * 1024) as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if cancel_event and cancel_event.is_set():
raise DownloadCancelled()
if chunk:
decrypted_chunk = active_aes.decrypt(chunk)
f.write(decrypted_chunk)
downloaded += len(chunk)
if progress_fn:
if total_batch_size > 0:
progress_fn(current_offset + downloaded, total_batch_size)
else:
progress_fn(downloaded, declared_size)
if declared_size > 0 and downloaded >= declared_size:
break
if declared_size == 0 and downloaded > 0:
break
# Si el iter_content finalizó sin error pero no descargó todos los bytes
if declared_size > 0 and downloaded < declared_size:
logger.warning(f"[Mega] Stream finalizó prematuramente ({downloaded}/{declared_size} bytes). Reintentando...")
if attempt >= max_retries:
raise RuntimeError(f"Descarga incompleta de Mega: se recibieron {downloaded} de {declared_size} bytes tras {max_retries} intentos.")
time.sleep(min(2 * attempt, 10))
continue
except DownloadCancelled:
raise
except RuntimeError as re_err:
if "Límite de transferencia" in str(re_err):
raise
if attempt >= max_retries:
raise
time.sleep(min(2 * attempt, 10))
except Exception as conn_err:
logger.warning(f"[Mega] Error en stream (intento {attempt}/{max_retries}): {conn_err}")
if attempt >= max_retries:
raise RuntimeError(f"Error descargando desde Mega tras {max_retries} intentos: {conn_err}")
time.sleep(min(2 * attempt, 10))
if declared_size > 0 and downloaded < declared_size:
raise RuntimeError(f"Descarga incompleta de Mega: se recibieron {downloaded} de {declared_size} bytes.")
if downloaded == 0:
raise RuntimeError("No se descargaron datos de Mega (archivo vacío o servidor no respondió).")
if not os.path.exists(part_path) or os.path.getsize(part_path) == 0:
raise RuntimeError("El archivo descargado de Mega quedó vacío en disco.")
if os.path.exists(output_path):
try:
os.remove(output_path)
except Exception:
pass
os.replace(part_path, output_path)
return output_path
def _download_mega_folder(
url: str,
output_dir: str,
progress_fn=None,
cancel_event=None
) -> List[str]:
"""Descarga e inspecciona recursivamente una carpeta pública de Mega."""
if cancel_event and cancel_event.is_set():
raise DownloadCancelled()
folder_handle, folder_key = parse_mega_folder_url(url)
rand_id = secrets.randbelow(2**31)
resp = requests.post(
"https://g.api.mega.co.nz/cs",
params={"id": rand_id, "n": folder_handle},
json=[{"a": "f", "c": 1, "r": 1}],
timeout=REQUEST_TIMEOUT,
)
resp.raise_for_status()
data = resp.json()
if not isinstance(data, list) or not data or not isinstance(data[0], dict):
raise RuntimeError("Mega rechazó la consulta de la carpeta.")
nodes = data[0].get("f", [])
if not nodes:
raise RuntimeError("La carpeta de Mega está vacía o no contiene archivos descargables.")
master_key_a32 = base64_to_a32(folder_key)
file_items = []
total_folder_bytes = 0
for node in nodes:
if node.get("t") != 0: # 0 = archivo, 1 = carpeta
continue
k_val = node.get("k", "")
if ":" not in k_val:
continue
k_enc = k_val.split(":")[1]
try:
k_a32 = base64_to_a32(k_enc)
node_key_a32 = decrypt_key(k_a32, master_key_a32)
k_derived = (
node_key_a32[0] ^ node_key_a32[4],
node_key_a32[1] ^ node_key_a32[5],
node_key_a32[2] ^ node_key_a32[6],
node_key_a32[3] ^ node_key_a32[7],
)
raw_attr = base64_url_decode(node.get("a", ""))
attr = decrypt_attr(raw_attr, k_derived)
if not attr or "n" not in attr:
continue
fn = sanitize_filename(attr["n"])
size = int(node.get("s", 0))
file_items.append({
"handle": node.get("h"),
"name": fn,
"size": size,
"key_a32": node_key_a32,
"k_derived": k_derived,
})
total_folder_bytes += size
except Exception as e:
logger.debug(f"[Mega] No se pudo desencriptar nodo {node.get('h')}: {e}")
if not file_items:
raise RuntimeError("La carpeta de Mega está vacía o no contiene archivos descargables.")
if len(file_items) > MAX_FOLDER_FILES:
logger.warning(f"[Mega] Carpeta con {len(file_items)} archivos; limitando a {MAX_FOLDER_FILES}.")
file_items = file_items[:MAX_FOLDER_FILES]
downloaded_files = []
overall_downloaded = 0
for idx, item in enumerate(file_items, 1):
if cancel_event and cancel_event.is_set():
raise DownloadCancelled()
f_handle = item["handle"]
fn = item["name"]
f_size = item["size"]
node_key_a32 = item["key_a32"]
k_derived = item["k_derived"]
rand_id = secrets.randbelow(2**31)
r_link = requests.post(
"https://g.api.mega.co.nz/cs",
params={"id": rand_id, "n": folder_handle},
json=[{"a": "g", "g": 1, "n": f_handle}],
timeout=REQUEST_TIMEOUT,
)
r_link.raise_for_status()
link_data = r_link.json()
if not isinstance(link_data, list) or not link_data or not isinstance(link_data[0], dict) or "g" not in link_data[0]:
logger.warning(f"No se pudo obtener enlace de descarga para {fn} ({f_handle})")
continue
dl_url = link_data[0]["g"]
out_file = os.path.join(output_dir, fn)
k_str = a32_to_str(k_derived)
iv = node_key_a32[4:6] + (0, 0)
initial_counter_val = ((iv[0] << 32) + iv[1]) << 64
_download_stream_decrypt(
dl_url,
out_file,
f_size,
k_str=k_str,
initial_counter_val=initial_counter_val,
progress_fn=progress_fn,
cancel_event=cancel_event,
current_offset=overall_downloaded,
total_batch_size=total_folder_bytes,
)
overall_downloaded += f_size
downloaded_files.append(out_file)
if not downloaded_files:
raise RuntimeError("No se pudo descargar ningún archivo de la carpeta de Mega.")
return downloaded_files
def _download_mega_file(
url: str,
output_dir: str,
progress_fn=None,
cancel_event=None
) -> str:
"""Descarga un archivo individual de Mega con desencriptado en streaming al vuelo."""
if cancel_event and cancel_event.is_set():
raise DownloadCancelled()
file_id, file_key = parse_mega_file_url(url)
rand_id = secrets.randbelow(2**31)
resp = requests.post(
"https://g.api.mega.co.nz/cs",
params={"id": rand_id},
json=[{"a": "g", "g": 1, "p": file_id}],
timeout=REQUEST_TIMEOUT,
)
resp.raise_for_status()
data = resp.json()
if not isinstance(data, list) or not data:
raise RuntimeError("Mega rechazó la consulta del archivo.")
res = data[0]
if isinstance(res, int):
if res == -9:
raise RuntimeError("El archivo de Mega no existe o fue eliminado.")
elif res == -16:
raise RuntimeError("El archivo de Mega fue bloqueado por copyright o violación de términos.")
elif res == -18:
raise RuntimeError("Límite de transferencia de Mega excedido para la IP del worker.")
elif res == -3:
raise RuntimeError("Mega está ocupado temporalmente. Reintenta más tarde.")
else:
raise RuntimeError(f"Mega retornó código de error {res}.")
if not isinstance(res, dict) or "g" not in res:
raise RuntimeError("Mega no devolvió enlace de descarga directo.")
file_url = res["g"]
declared_size = int(res.get("s", 0))
file_key_decoded = base64_to_a32(file_key)
k = (
file_key_decoded[0] ^ file_key_decoded[4],
file_key_decoded[1] ^ file_key_decoded[5],
file_key_decoded[2] ^ file_key_decoded[6],
file_key_decoded[3] ^ file_key_decoded[7],
)
iv = file_key_decoded[4:6] + (0, 0)
try:
raw_attr = base64_url_decode(res.get("at", ""))
attr = decrypt_attr(raw_attr, k)
filename = attr["n"] if (isinstance(attr, dict) and "n" in attr) else f"mega_{file_id}"
except Exception:
filename = f"mega_{file_id}"
safe_name = sanitize_filename(filename)
output_path = os.path.join(output_dir, safe_name)
k_str = a32_to_str(k)
initial_counter_val = ((iv[0] << 32) + iv[1]) << 64
return _download_stream_decrypt(
file_url,
output_path,
declared_size,
k_str=k_str,
initial_counter_val=initial_counter_val,
progress_fn=progress_fn,
cancel_event=cancel_event,
)
def download_mega(
url: str,
output_dir: str,
progress_fn=None,
cancel_event=None
) -> Union[str, List[str]]:
"""Descarga enlaces de MEGA (archivo individual o carpeta completa) con streaming directo y desencriptado al vuelo."""
if cancel_event and cancel_event.is_set():
raise DownloadCancelled()
os.makedirs(output_dir, exist_ok=True)
if is_mega_folder_url(url):
logger.info(f"[Mega] Detectada carpeta de Mega: {url}")
return _download_mega_folder(url, output_dir, progress_fn=progress_fn, cancel_event=cancel_event)
# Archivo individual: intentar descarga nativa directa
try:
logger.info(f"[Mega] Detectado archivo individual de Mega: {url}")
return _download_mega_file(url, output_dir, progress_fn=progress_fn, cancel_event=cancel_event)
except DownloadCancelled:
raise
except Exception as native_err:
logger.warning(f"[Mega] Falló descarga nativa directa ({native_err}), intentando fallback con mega.py...")
try:
mega = Mega()
m = mega.login_anonymous()
m = mega if m is None else m
res = m.download_url(url, dest_path=output_dir)
if not res or not os.path.exists(str(res)) or os.path.getsize(str(res)) == 0:
if res and os.path.exists(str(res)):
try:
os.remove(str(res))
except Exception:
pass
raise RuntimeError(str(native_err))
return str(res)
except DownloadCancelled:
raise
except Exception:
raise native_err
|