"""MEGA.nz client — file search, cache management, Hashcash PoW support.""" import os import re import json import time import base64 import struct import pickle import hashlib import threading import logging from typing import Optional from ..config import settings from .. import db logger = logging.getLogger(__name__) _BROWSER_HEADERS = { "User-Agent": ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/125.0.0.0 Safari/537.36" ), "Accept": "application/json, text/plain, */*", "Accept-Language": "en-US,en;q=0.9", "Origin": "https://mega.co.nz", "Referer": "https://mega.co.nz/", } def _proxy_dict() -> dict | None: proxy = ( os.getenv("HTTPS_PROXY") or os.getenv("https_proxy") or os.getenv("HTTP_PROXY") or os.getenv("http_proxy") ) if proxy: return {"http": proxy, "https": proxy} import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.settimeout(1) s.connect(("127.0.0.1", 22307)) s.close() return {"http": "http://127.0.0.1:22307", "https": "http://127.0.0.1:22307"} except Exception: return None def _solve_hashcash(challenge: str, easiness: int) -> str: """Solve MEGA Hashcash proof-of-work (SHA-256 brute-force).""" from mega.crypto import base64_url_decode, base64_url_encode token = base64_url_decode(challenge) token += b"\0" * (-len(token) % 16) if len(token) != 48: raise ValueError(f"Invalid hashcash token length: {len(token)}") buffer = bytearray(b"\0" * 4 + token * 0x40000) threshold = (((easiness & 63) << 1) + 1) << ((easiness >> 6) * 7 + 3) nonce = 0 last_log = 0 while True: struct.pack_into("I", h[:4])[0] if achieved <= threshold: return base64_url_encode(buffer[:4]) nonce += 1 if nonce - last_log >= 4_000_000: last_log = nonce logger.info("Hashcash solving... %dM iterations", nonce // 1_000_000) class MegaClient: """MEGA.nz client — file search + local SQLite cache fallback.""" CACHE_TTL = 3600 DISK_CACHE_TTL = 3600 CACHE_FILE = os.path.join(os.path.dirname(__file__), "..", ".mega_file_cache.pkl") def __init__(self, email: str = None, password: str = None): self._email = email or settings.MEGA_EMAIL self._password = password or settings.MEGA_PASSWORD self._mega = None self._proxies = _proxy_dict() self._file_cache = None self._file_cache_time = 0.0 self._lock = threading.Lock() self._refresh_lock = threading.RLock() self._last_full_fetch = 0.0 self._last_sync_at = 0.0 self._fetch_fail_until = 0.0 self._fetch_fail_count = 0 self._try_load_disk_cache() def _try_load_disk_cache(self): cache_path = self.CACHE_FILE if not os.path.exists(cache_path): return try: with open(cache_path, "rb") as f: data = pickle.load(f) self._file_cache = data.get("files") cache_time = data.get("time", 0.0) age = time.time() - cache_time if self._file_cache is None or age > self.DISK_CACHE_TTL: logger.info("MEGA disk cache expired (age=%.0fs)", age) self._file_cache = None self._file_cache_time = 0.0 return self._file_cache_time = cache_time self._last_full_fetch = time.monotonic() - age logger.info( "MEGA disk cache loaded (%d items, age=%.0fs)", len(self._file_cache), age, ) except Exception as e: logger.warning("MEGA disk cache load failed: %s", e) self._file_cache = None self._file_cache_time = 0.0 def _save_disk_cache(self): if self._file_cache is None: return try: with open(self.CACHE_FILE, "wb") as f: pickle.dump( {"files": self._file_cache, "time": self._file_cache_time}, f ) logger.info("MEGA disk cache saved (%d items)", len(self._file_cache)) except Exception as e: logger.warning("MEGA disk cache save failed: %s", e) def _patch_mega(self): """Monkey-patch mega.Mega._api_request for proxy + Hashcash + retry.""" # Python 3.12+ removed asyncio.coroutine — mega.py still uses it internally import asyncio if not hasattr(asyncio, "coroutine"): def _coroutine_compat(func): return func asyncio.coroutine = _coroutine_compat import mega.mega as mega_mod import json import requests def patched_api_request(self, data): params = {"id": self.sequence_num} self.sequence_num += 1 if self.sid: params["sid"] = self.sid if not isinstance(data, list): data = [data] url = f"{self.schema}://g.api.{self.domain}/cs" proxies = getattr(self, "_proxies", None) request_headers = dict(_BROWSER_HEADERS) max_attempts = 4 for attempt in range(max_attempts): try: response = requests.post( url, params=params, data=json.dumps(data), timeout=self.timeout, proxies=proxies, headers=request_headers, ) except ( requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.ChunkedEncodingError, ) as e: logger.warning( "MEGA API 连接失败 (attempt %d/%d): %s", attempt + 1, max_attempts, e, ) if attempt < max_attempts - 1: time.sleep(2**attempt) continue raise RuntimeError(f"MEGA API 连接失败: {e}") if response.status_code == 402: challenge_header = response.headers.get("X-Hashcash") if challenge_header and attempt == 0: parts = challenge_header.split(":") if len(parts) == 4: logger.info("MEGA Hashcash challenge received, solving...") easiness = int(parts[1]) proof = _solve_hashcash(parts[3], easiness) request_headers["X-Hashcash"] = f"1:{parts[3]}:{proof}" logger.info("Hashcash solved, retrying request") time.sleep(1.5) continue raise RuntimeError("MEGA API returned HTTP 402 (Hashcash unsolvable)") try: text = response.text except Exception as e: logger.warning( "MEGA 响应读取失败 (attempt %d/%d): %s", attempt + 1, max_attempts, e, ) if attempt < max_attempts - 1: time.sleep(2**attempt) self.sid = None continue raise RuntimeError(f"MEGA 响应读取失败: {e}") json_resp = json.loads(text) try: if isinstance(json_resp, list): int_resp = json_resp[0] if isinstance(json_resp[0], int) else None elif isinstance(json_resp, int): int_resp = json_resp else: int_resp = None except IndexError: int_resp = None if int_resp is not None: if int_resp == 0: return int_resp if int_resp == -3: logger.info("MEGA API -3 (EAGAIN), retrying (attempt %d/%d)", attempt + 1, max_attempts) if attempt < max_attempts - 1: time.sleep(2**attempt) self.sid = None continue raise RuntimeError("MEGA API 返回 -3 重试耗尽") from mega.errors import RequestError raise RequestError(int_resp) return json_resp[0] raise RuntimeError("MEGA API request failed after all retries") mega_mod.Mega._api_request = patched_api_request def _ensure_login(self): if self._mega is not None: return with self._lock: if self._mega is not None: # double-check after acquiring lock return if not self._email or not self._password: raise RuntimeError("MEGA_EMAIL or MEGA_PASSWORD not configured") self._patch_mega() from mega import Mega m = Mega() if self._proxies: m._proxies = self._proxies m.timeout = 30 self._mega = m.login(self._email, self._password) self._mega.timeout = 180 logger.info("MEGA login OK (%s)", self._email) def _fetch_all_nodes(self) -> dict: """Fetch the complete node list, merging MEGA's `f` and `f2` buckets. Large accounts get their node list split across two arrays; mega.py's get_files() reads only `f`, silently hiding every node MEGA places in `f2` (99 files on the current account). """ raw = self._mega._api_request({"a": "f", "c": 1, "r": 1}) nodes = list(raw.get("f") or []) + list(raw.get("f2") or []) shared_keys = {} self._mega._init_shared_keys(raw, shared_keys) files = {} for node in nodes: try: processed = self._mega._process_file(dict(node), shared_keys) except Exception as e: logger.warning("MEGA node decrypt failed (%s): %s", node.get("h"), e) continue if processed.get("a"): files[node["h"]] = processed logger.info( "MEGA nodes fetched: %d total (f=%d, f2=%d)", len(files), len(raw.get("f") or []), len(raw.get("f2") or []), ) return files # ─── External share links ─── # Nodes living outside this account (other accounts, revoked shares, files # that never landed in the tree) can never appear in get_files(). Register # their public links in mega_links.json and they become searchable too. LINKS_FILE_NAME = "mega_links.json" _LINK_RE = re.compile( r"mega\.nz/(?:file|folder)/([A-Za-z0-9_-]{8})#([A-Za-z0-9_-]{22,})" ) @property def links_file(self) -> str: """Resolve mega_links.json. Order: MEGA_LINKS_FILE env -> project root -> data dir. The root file is the one shipped with the code, so the list survives redeploys; the data path is kept for existing local installs. """ override = os.getenv("MEGA_LINKS_FILE", "").strip() if override: return override root_file = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(__file__))), self.LINKS_FILE_NAME, ) if os.path.exists(root_file): return root_file data_file = os.path.join(settings.DB_DIR, self.LINKS_FILE_NAME) if os.path.exists(data_file): return data_file return root_file @staticmethod def _b64url(text: str) -> bytes: return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) @classmethod def _parse_share_link(cls, url: str): match = cls._LINK_RE.search(url or "") if not match: return None return match.group(1), match.group(2) @classmethod def _decrypt_link_attr(cls, at_b64: str, key_str: str) -> Optional[dict]: """Decrypt a share link's `at` blob using the key from the URL fragment. MEGA splits the 32-byte link key in half: AES-128 key is the XOR of the two halves. Current uploads use an all-zero IV, older ones use the second half — try both and keep whichever yields a `MEGA{...}` payload. """ from Crypto.Cipher import AES key = cls._b64url(key_str) if len(key) < 32: return None aes_key = bytes(a ^ b for a, b in zip(key[:16], key[16:32])) try: raw = cls._b64url(at_b64) except Exception: return None for iv in (b"\x00" * 16, key[16:32]): try: plain = AES.new(aes_key, AES.MODE_CBC, iv).decrypt(raw) except ValueError: continue idx = plain.find(b"MEGA{") if idx < 0: continue try: payload = json.loads(plain[idx + 4:].rstrip(b"\x00").decode("utf-8")) except (UnicodeDecodeError, json.JSONDecodeError): continue if isinstance(payload, dict) and payload.get("n"): return payload return None def _resolve_share_link(self, url: str) -> Optional[dict]: parsed = self._parse_share_link(url) if not parsed: logger.warning("MEGA link ignored (unrecognised format): %s", url) return None handle, key = parsed try: info = self._mega._api_request({"a": "g", "g": 1, "p": handle}) except Exception as e: logger.warning("MEGA link resolve failed (%s): %s", handle, e) return None if not isinstance(info, dict): logger.warning("MEGA link resolve returned unexpected data: %s", handle) return None if "at" not in info: logger.warning("MEGA link is a folder (not expanded): %s", handle) return None attrs = self._decrypt_link_attr(info["at"], key) if not attrs: logger.warning("MEGA link attribute decrypt failed: %s", handle) return None return { "file_name": attrs["n"], "file_size": info.get("s", 0), "file_id": handle, "mega_link": url, } def _load_share_links(self) -> list[dict]: path = self.links_file if not os.path.exists(path): return [] try: with open(path, "r", encoding="utf-8") as f: data = json.load(f) except Exception as e: logger.warning("mega_links.json parse failed: %s", e) return [] entries = data.get("links", data) if isinstance(data, dict) else data if not isinstance(entries, list): return [] result = [] for item in entries: if isinstance(item, str): result.append({"url": item}) elif isinstance(item, dict) and item.get("url"): result.append(item) return result def sync_share_links(self) -> int: """Resolve every link in mega_links.json into mega_cache (with mega_link set).""" entries = self._load_share_links() if not entries: return 0 self._ensure_login() rows = [] for item in entries: resolved = self._resolve_share_link(item["url"]) if not resolved: continue override = (item.get("name") or "").strip() if override: resolved["file_name"] = override rows.append(resolved) if rows: db.upsert_mega_cache_links(rows) logger.info("MEGA share links synced: %d/%d", len(rows), len(entries)) return len(rows) def _get_files_cached(self, force: bool = False) -> dict: self._ensure_login() now = time.time() if force or self._file_cache is None or (now - self._file_cache_time) > self.CACHE_TTL: logger.info("Fetching MEGA file list (cache miss)...") self._file_cache = self._fetch_all_nodes() self._file_cache_time = now self._last_full_fetch = time.monotonic() logger.info("MEGA file list loaded (%d items)", len(self._file_cache)) self._save_disk_cache() return self._file_cache def preload_files(self): self._get_files_cached() def sync_file_index(self): """Sync file names/sizes/file_ids from MEGA to local SQLite (no link generation). Serialised on ``_refresh_lock`` (reentrant) so the startup refresh, the scheduler and on-demand searches can never write the index concurrently (SQLite would raise "database is locked"). """ with self._refresh_lock: return self._sync_file_index_unlocked() def _sync_file_index_unlocked(self): all_files = self._get_files_cached() count = 0 batch = [] for file_id, info in all_files.items(): if info.get("t") != 0: # skip folders continue file_name = info.get("a", {}).get("n", "") if not file_name: continue # Fix UTF-8 bytes decoded as Latin-1 by mega.py try: fixed = file_name.encode("latin-1").decode("utf-8") file_name = fixed except (UnicodeEncodeError, UnicodeDecodeError): pass batch.append({ "file_name": file_name, "file_size": info.get("s", 0), "file_id": str(file_id), }) count += 1 if len(batch) >= 200: db.upsert_mega_cache(batch) batch = [] if batch: db.upsert_mega_cache(batch) try: self.sync_share_links() except Exception as e: logger.warning("MEGA share link sync failed: %s", e) logger.info("MEGA file index synced: %d files (links generated on-demand)", count) self._last_sync_at = time.monotonic() return count def refresh_index(self) -> int: """Re-fetch the MEGA node list, then re-sync the SQLite index. Serialised and rate limited so a burst of concurrent searches cannot hammer the MEGA account: - only one thread fetches at a time (``_refresh_lock``); the others wait and then reuse that fetch instead of issuing their own - a full fetch happens at most once per MEGA_MIN_REFRESH_INTERVAL - consecutive failures back off exponentially (MEGA_REFRESH_FAIL_BACKOFF) """ now = time.monotonic() if now < self._fetch_fail_until: logger.info( "MEGA refresh skipped (failure backoff, %.0fs remaining)", self._fetch_fail_until - now, ) return db.get_mega_cache_count() with self._refresh_lock: age = time.monotonic() - self._last_full_fetch if self._last_full_fetch and age < settings.MEGA_MIN_REFRESH_INTERVAL: logger.info( "MEGA refresh skipped (fetched %.0fs ago, min interval %ds)", age, settings.MEGA_MIN_REFRESH_INTERVAL, ) if self._last_sync_at >= self._last_full_fetch: return db.get_mega_cache_count() return self.sync_file_index() try: self._get_files_cached(force=True) except Exception as exc: if "ESID" in str(exc) or "expired" in str(exc).lower(): logger.warning("MEGA session expired, reconnecting...") with self._lock: self._mega = None try: self._ensure_login() self._get_files_cached(force=True) except Exception as retry_exc: exc = retry_exc else: self._fetch_fail_count = 0 self._fetch_fail_until = 0.0 return self.sync_file_index() self._fetch_fail_count += 1 backoff = min( settings.MEGA_REFRESH_FAIL_BACKOFF * (2 ** (self._fetch_fail_count - 1)), 7200, ) self._fetch_fail_until = time.monotonic() + backoff logger.error( "MEGA node list fetch failed (%d consecutive), backing off %ds: %s", self._fetch_fail_count, backoff, exc, ) raise self._fetch_fail_count = 0 self._fetch_fail_until = 0.0 return self.sync_file_index() def ensure_links(self, names: list[str]) -> dict[str, str]: """Generate MEGA download links for specific files by name. Looks up file_id from the in-memory file cache, calls get_link() for each, caches the result in SQLite. Only generates links for files that don't already have one in the DB. Returns: {file_name: link} for newly generated links. """ # Filter names that already have links in DB existing = db.get_exported_names_with_links() needed = [n for n in names if n not in existing] if not needed: return {} all_files = self._get_files_cached() # Build name -> (file_id, info) lookup from in-memory cache name_to_node = {} for file_id, info in all_files.items(): if info.get("t") != 0: continue name = info.get("a", {}).get("n", "") if name: name_to_node[name] = (file_id, info) results = {} first_error = None for name in needed: node = name_to_node.get(name) if not node: continue try: link = self._mega.get_link(node) results[name] = link except Exception as e: if first_error is None: first_error = str(e) logger.warning("Failed to get link for '%s': %s", name, e) time.sleep(0.1) # throttle: at most 10 link requests per second # Session expired — reconnect and retry once if not results and first_error and ("ESID" in str(first_error) or "Invalid or expired" in str(first_error)): logger.warning("MEGA session expired, reconnecting and retrying...") with self._lock: self._mega = None self._ensure_login() all_files = self._get_files_cached() name_to_node = {} for file_id, info in all_files.items(): if info.get("t") != 0: continue name = info.get("a", {}).get("n", "") if name: name_to_node[name] = (file_id, info) results = {} first_error = None for name in needed: node = name_to_node.get(name) if not node: continue try: link = self._mega.get_link(node) results[name] = link except Exception as e: if first_error is None: first_error = str(e) logger.warning("Failed to get link for '%s' (retry): %s", name, e) time.sleep(0.1) # throttle: at most 10 link requests per second if results: db.update_mega_links(results) logger.info("Generated %d new MEGA links on-demand", len(results)) elif first_error: raise RuntimeError(f"MEGA 链接生成失败: {first_error}") return results def search_files_db(self, name_query: str, max_results: int = 10) -> list[dict]: """Search local SQLite cache (zero MEGA dependency).""" return db.search_mega_cache(name_query, max_results) def search_files( self, name_query: str, max_results: int = 10, use_cache: bool = False ) -> list[dict]: """Search MEGA files — prefer local SQLite cache, fallback to API.""" cnt = db.get_mega_cache_count() if cnt > 0: return db.search_mega_cache(name_query, max_results) self._ensure_login() all_files = self._get_files_cached() if use_cache else self._fetch_all_nodes() matches = [] seen_names: set[str] = set() for file_id, info in all_files.items(): if info.get("t") != 0: continue file_name = info.get("a", {}).get("n", "") if name_query.lower() in file_name.lower(): if file_name in seen_names: continue seen_names.add(file_name) try: link = self._mega.get_link((file_id, info)) except Exception: link = None matches.append({ "name": file_name, "link": link, "size": info.get("s", 0), "id": file_id, }) if len(matches) >= max_results: break return matches def search_os_version(self, os_version: str) -> list[dict]: import re key = re.sub(r"_\d{8}_\d{6}_.*", "", os_version) return self.search_files(key) _default_client: Optional["MegaClient"] = None _client_lock = threading.Lock() def get_client() -> MegaClient: global _default_client with _client_lock: client = _default_client if client is None: client = MegaClient() _default_client = client if not client._mega: try: client._ensure_login() logger.info("MEGA client pre-logged-in successfully") except Exception as e: logger.warning( "MEGA client pre-login failed (will retry at query time): %s", e ) return client