Skip to content

Bulk asynchronous downloader for multiple file hosts

feat: enable mega.nz crawler (#1149)

NTFSvolumed3952ca2d6a3
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index f7ce4f55a..9c2f15e4c 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -259,21 +259,55 @@ class DownloadClient:
) -> None:
"""Appends content to a file."""
- check_free_space = partial(self.manager.storage_manager.check_free_space, media_item)
+ check_free_space = self.make_free_space_checker(media_item)
+ check_download_speed = self.make_speed_checker(media_item)
await check_free_space()
+ await self._pre_download_check(media_item)
- def prepare():
+ async with aiofiles.open(media_item.partial_file, mode="ab") as f: # type: ignore
+ async for chunk in content.iter_chunked(self.chunk_size):
+ await self.manager.states.RUNNING.wait()
+ await check_free_space()
+ chunk_size = len(chunk)
+ await self.client_manager.speed_limiter.acquire(chunk_size)
+ await f.write(chunk)
+ update_progress(chunk_size)
+ check_download_speed()
+
+ self._post_download_check(media_item, content)
+
+ def _pre_download_check(self, media_item: MediaItem) -> Coroutine[Any, Any, None]:
+ def prepare() -> None:
media_item.partial_file.parent.mkdir(parents=True, exist_ok=True)
if not media_item.partial_file.is_file():
media_item.partial_file.touch()
- await asyncio.to_thread(prepare)
+ return asyncio.to_thread(prepare)
+
+ def _post_download_check(self, media_item: MediaItem, content: aiohttp.StreamReader) -> None:
+ if not content.total_bytes and not media_item.partial_file.stat().st_size:
+ media_item.partial_file.unlink()
+ raise DownloadError(status=HTTPStatus.INTERNAL_SERVER_ERROR, message="File is empty")
+
+ def make_free_space_checker(self, media_item: MediaItem) -> Callable[[], Coroutine[Any, Any, None]]:
+ current_chunk = 0
+
+ async def check_free_space() -> None:
+ nonlocal current_chunk
+ current_chunk += 1
+ if current_chunk % 5 == 0:
+ return await self.manager.storage_manager.check_free_space(media_item)
+ return check_free_space
+
+ def make_speed_checker(self, media_item: MediaItem) -> Callable[[], None]:
last_slow_speed_read = None
def check_download_speed() -> None:
nonlocal last_slow_speed_read
- assert media_item.task_id
+ if not self.download_speed_threshold:
+ return
+ assert media_item.task_id is not None
speed = self.manager.progress_manager.file_progress.get_speed(media_item.task_id)
if speed > self.download_speed_threshold:
last_slow_speed_read = None
@@ -282,22 +316,7 @@ class DownloadClient:
elif time.perf_counter() - last_slow_speed_read > self.slow_download_period:
raise SlowDownloadError(origin=media_item)
- async with aiofiles.open(media_item.partial_file, mode="ab") as f: # type: ignore
- async for chunk in content.iter_chunked(self.chunk_size):
- await self.manager.states.RUNNING.wait()
- await check_free_space()
- chunk_size = len(chunk)
- await self.client_manager.speed_limiter.acquire(chunk_size)
- await asyncio.sleep(0)
- await f.write(chunk)
- update_progress(chunk_size)
-
- if self.download_speed_threshold:
- check_download_speed()
-
- if not content.total_bytes and not media_item.partial_file.stat().st_size:
- media_item.partial_file.unlink()
- raise DownloadError(status=HTTPStatus.INTERNAL_SERVER_ERROR, message="File is empty")
+ return check_download_speed
async def download_file(self, manager: Manager, domain: str, media_item: MediaItem) -> bool:
"""Starts a file."""
diff --git a/cyberdrop_dl/crawlers/__init__.py b/cyberdrop_dl/crawlers/__init__.py
index af23edba4..80c5ca7f8 100644
--- a/cyberdrop_dl/crawlers/__init__.py
+++ b/cyberdrop_dl/crawlers/__init__.py
@@ -109,7 +109,7 @@ ALL_CRAWLERS: set[type[Crawler]] = {
crawler for name, crawler in globals().items() if name.endswith("Crawler") and crawler is not Crawler
}
ALL_CRAWLERS.update(WP_CRAWLERS, GENERIC_CRAWLERS, FORUM_CRAWLERS)
-DEBUG_CRAWLERS = {SimpCityCrawler, BunkrAlbumsIOCrawler, MegaNzCrawler}
+DEBUG_CRAWLERS = {SimpCityCrawler, BunkrAlbumsIOCrawler}
if env.ENABLE_DEBUG_CRAWLERS == "d396ab8c85fcb1fecd22c8d9b58acf944a44e6d35014e9dd39e42c9a64091eda":
CRAWLERS = ALL_CRAWLERS
else:
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index 24d558a2a..ea3534b6b 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -189,6 +189,11 @@ class Crawler(ABC):
def allow_no_extension(self) -> bool:
return not self.manager.config_manager.settings_data.ignore_options.exclude_files_with_no_extension
+ def _init_downloader(self) -> Downloader:
+ self.downloader = dl = Downloader(self.manager, self.DOMAIN)
+ dl.startup()
+ return dl
+
@final
async def startup(self) -> None:
"""Starts the crawler."""
@@ -196,8 +201,7 @@ class Crawler(ABC):
if self.ready:
return
self.client = self.manager.client_manager.scraper_session
- self.downloader = Downloader(self.manager, self.DOMAIN)
- self.downloader.startup()
+ self.downloader = self._init_downloader()
await self.async_startup()
self.ready = True
diff --git a/cyberdrop_dl/crawlers/mega_nz.py b/cyberdrop_dl/crawlers/mega_nz.py
index bc43aa427..f5f954b48 100644
--- a/cyberdrop_dl/crawlers/mega_nz.py
+++ b/cyberdrop_dl/crawlers/mega_nz.py
@@ -1,23 +1,24 @@
+"""Crawler to download files and folders from mega.nz
+
+This crawler does several CPU intensive operations
+
+It calls checks_complete_by_referer several times even if no request is going to be made, to skip unnecesary compute time
+"""
+
from __future__ import annotations
+import asyncio
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, cast
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
-from cyberdrop_dl.downloader.mega_nz import (
- DecryptData,
- File,
- MegaApi,
- MegaDownloader,
- NodeType,
- base64_to_a32,
- base64_url_decode,
- decrypt_attr,
-)
-from cyberdrop_dl.exceptions import ScrapeError
+from cyberdrop_dl.downloader import mega_nz as mega
+from cyberdrop_dl.exceptions import LoginError, ScrapeError
from cyberdrop_dl.utils.utilities import error_handling_wrapper
if TYPE_CHECKING:
+ from pathlib import Path
+
from cyberdrop_dl.data_structures.url_objects import ScrapeItem
PRIMARY_URL = AbsoluteHttpURL("https://mega.nz")
@@ -25,14 +26,21 @@ PRIMARY_URL = AbsoluteHttpURL("https://mega.nz")
class FileTuple(NamedTuple):
id: str
- crypto: DecryptData
+ crypto: mega.DecryptData
class MegaNzCrawler(Crawler):
SUPPORTED_PATHS: ClassVar[SupportedPaths] = {
- "File": ("/file/<handle>#<share_key>", "/!#<handle>!<share_key>"),
- "Folder": ("/folder/<handle>#<share_key>", "/!F#<handle>!<share_key>"),
- "**NOTE**": "Downloads can not be resumed. Partial downloads will always be deleted ans a new downloa dwill start from 0",
+ "File": (
+ "/file/<file_id>#<share_key>",
+ "/folder/<folder_id>#<share_key>/file/<file_id>",
+ "/!#<file_id>!<share_key>",
+ ),
+ "Folder": (
+ "/folder/<folder_id>#<share_key>",
+ "/F!#<folder_id>!<share_key>",
+ ),
+ "**NOTE**": "Downloads can not be resumed. Partial downloads will always be deleted and new downloads will start over",
}
PRIMARY_URL: ClassVar[AbsoluteHttpURL] = PRIMARY_URL
SKIP_PRE_CHECK: ClassVar[bool] = True
@@ -40,114 +48,139 @@ class MegaNzCrawler(Crawler):
FOLDER_DOMAIN: ClassVar[str] = "MegaNz"
def __post_init__(self) -> None:
- self.api = MegaApi(self.manager)
- self.user = self.manager.config_manager.authentication_data.meganz.email or None
- self.password = self.manager.config_manager.authentication_data.meganz.password or None
- self.downloader: MegaDownloader
-
- async def startup(self) -> None:
- """Starts the crawler."""
- async with self.startup_lock:
- if self.ready:
- return
- self.client = self.manager.client_manager.scraper_session
- self.downloader = MegaDownloader(self.api, self.DOMAIN)
- self.downloader.startup()
- await self.async_startup()
- self.ready = True
+ self.downloader: mega.MegaDownloader
+
+ @property
+ def user(self) -> str | None:
+ return self.manager.auth_config.meganz.email or None
+
+ @property
+ def password(self) -> str | None:
+ return self.manager.auth_config.meganz.password or None
+
+ def _init_downloader(self) -> mega.MegaDownloader:
+ self.downloader = dl = mega.MegaDownloader(self.manager, self.DOMAIN)
+ dl.startup()
+ return dl
async def async_startup(self) -> None:
await self.login(PRIMARY_URL)
async def fetch(self, scrape_item: ScrapeItem) -> None:
- if scrape_item.url.fragment: # Mega stores access key in fragment. We can't do anything without the key
- if "file" in scrape_item.url.parts or scrape_item.url.fragment.startswith("!"):
- return await self.file(scrape_item)
- if "folder" in scrape_item.url.parts or scrape_item.url.fragment.startswith("F!"):
- return await self.folder(scrape_item)
+ if not self.logged_in:
+ return
+ if frag := scrape_item.url.fragment: # Mega stores access key in fragment. We can't do anything without the key
+ # v1 URLs
+ if frag.count("!") == 2:
+ if frag.startswith("F!"):
+ folder_id, _, shared_key = frag.removeprefix("F!").partition("!")
+ return await self.folder(scrape_item, folder_id, shared_key)
+ if frag.startswith("!"):
+ # https://mega.nz/#!Ue5VRSIQ!kC2E4a4JwfWWCWYNJovGFHlbz8F
+ file_id, _, shared_key = frag.removeprefix("!").partition("!")
+ return await self.file(scrape_item, file_id, shared_key)
+
+ # v2 URLs
+ match scrape_item.url.parts[1:]:
+ # https://mega.nz/folder/oZZxyBrY#oU4jASLPpJVvqGHJIMRcgQ/file/IYZABDGY
+ # https://mega.nz/folder/oZZxyBrY#oU4jASLPpJVvqGHJIMRcgQ
+ case ["folder", folder_id]:
+ shared_key, _, file_id = frag.partition("/file/")
+ return await self.folder(scrape_item, folder_id, shared_key, file_id or None)
+ # https://mega.nz/file/cH51DYDR#qH7QOfRcM-7N9riZWdSjsRq
+ case ["file", file_id]:
+ return await self.file(scrape_item, file_id, frag)
+
raise ValueError
@error_handling_wrapper
- async def file(self, scrape_item: ScrapeItem) -> None:
- if "file" in scrape_item.url.parts:
- # V2 URL structure, ex: https://mega.nz/file/cH51DYDR#qH7QOfRcM-7N9riZWdSjsRq
- file_id = scrape_item.url.name
- shared_key = scrape_item.url.fragment
-
- elif scrape_item.url.fragment.startswith("!"):
- # V1 URL structure, ex: https://mega.nz/#!Ue5VRSIQ!kC2E4a4JwfWWCWYNJovGFHlbz8F
- file_id, shared_key = scrape_item.url.fragment.rsplit("!", 1)
- else:
- raise ScrapeError(422)
-
- canonical_url = PRIMARY_URL / "file" / file_id / shared_key
+ async def file(self, scrape_item: ScrapeItem, file_id: str, shared_key: str) -> None:
+ canonical_url = (PRIMARY_URL / "file" / file_id).with_fragment(shared_key)
if await self.check_complete_from_referer(canonical_url):
return
-
scrape_item.url = canonical_url
- file_key = base64_to_a32(shared_key)
-
- k: tuple[int, ...] = (
- file_key[0] ^ file_key[4],
- file_key[1] ^ file_key[5],
- file_key[2] ^ file_key[6],
- file_key[3] ^ file_key[7],
- )
- iv: tuple[int, ...] = (*file_key[4:6], 0, 0)
- meta_mac: tuple[int, ...] = file_key[6:8]
- file = FileTuple(file_id, DecryptData(iv, k, meta_mac))
- await self.proccess_file(scrape_item, file)
-
- async def proccess_file(self, scrape_item: ScrapeItem, file: FileTuple) -> None:
- file_data: dict[str, Any] = await self.api.request({"a": "g", "g": 1, "p": file.id})
- file_size: int = file_data["s"]
- if "g" not in file_data:
- raise ScrapeError(410, "File not accessible anymore")
+ full_key = mega.base64_to_a32(shared_key)
+ crypto = mega.get_decrypt_data(mega.NodeType.FILE, full_key)
+ file = FileTuple(file_id, crypto)
+ await self._process_file(scrape_item, file)
- self.downloader.register(scrape_item.url, file.crypto.iv, file.crypto.k, file.crypto.meta_mac, file_size)
+ @error_handling_wrapper
+ async def _process_file(self, scrape_item: ScrapeItem, file: FileTuple, *, folder_id: str | None = None) -> None:
+ file_data = await self._get_file_info(file.id, folder_id)
+ decrypt_data = file.crypto._replace(file_size=file_data["s"])
+ self.downloader.register(scrape_item.url, decrypt_data)
file_url = self.parse_url(file_data["g"])
- attribs_bytes = base64_url_decode(file_data["at"])
- filename = decrypt_attr(attribs_bytes, file.crypto.k)["n"]
+ attribs_bytes = mega.base64_url_decode(file_data["at"])
+ filename = mega.decrypt_attr(attribs_bytes, file.crypto.k)["n"]
filename, ext = self.get_filename_and_ext(filename)
await self.handle_file(scrape_item.url, scrape_item, filename, ext, debrid_link=file_url)
- @error_handling_wrapper
- async def folder(self, scrape_item: ScrapeItem) -> None:
- if "folder" in scrape_item.url.parts:
- folder_id = scrape_item.url.name
- shared_key = scrape_item.url.fragment
-
- elif scrape_item.url.fragment.startswith("!F"):
- folder_id, shared_key = scrape_item.url.fragment.removeprefix("F").rsplit("!", 1)
+ async def _get_file_info(self, file_id: str, folder_id: str | None) -> dict[str, Any]:
+ data = {"a": "g", "g": 1}
+ if folder_id:
+ data = data | {"n": file_id}
+ query_params = {"n": folder_id}
else:
- raise ScrapeError(422)
+ data = data | {"p": file_id}
+ query_params = None
- canonical_url = PRIMARY_URL / "folder" / folder_id / shared_key
- scrape_item.url = canonical_url
- nodes = await self.api.get_nodes_public_folder(folder_id, shared_key)
+ file_data: dict[str, Any] = await self.downloader.api.request(data, query_params)
+ if "g" not in file_data:
+ raise ScrapeError(410, "File not accessible anymore")
+ return file_data
+
+ @error_handling_wrapper
+ async def folder(
+ self, scrape_item: ScrapeItem, folder_id: str, shared_key: str, single_file_id: str | None = None
+ ) -> None:
+ if single_file_id and await self.check_complete_from_referer(scrape_item.url):
+ return
+ nodes = await self.downloader.api.get_nodes_public_folder(folder_id, shared_key)
root_id = next(iter(nodes))
folder_name = nodes[root_id]["attributes"]["n"]
- filesystem = await self.api._build_file_system(nodes, [root_id])
-
+ filesystem = await self.downloader.api.build_file_system(nodes, [root_id])
title = self.create_title(folder_name, folder_id)
scrape_item.setup_as_album(title, album_id=folder_id)
+ canonical_url = (PRIMARY_URL / "folder" / folder_id).with_fragment(shared_key)
+ scrape_item.url = canonical_url
+ await self._process_folder_fs(scrape_item, filesystem, single_file_id)
+ async def _process_folder_fs(
+ self, scrape_item: ScrapeItem, filesystem: dict[Path, mega.Node], single_file_id: str | None
+ ) -> None:
+ folder_id, shared_key = scrape_item.url.name, scrape_item.url.fragment
+ processed_files = 0
for path, node in filesystem.items():
- if node["t"] != NodeType.FILE:
+ if node["t"] != mega.NodeType.FILE:
continue
- file = cast("File", node)
+ file = cast("mega.File", node)
file_id = file["h"]
- canonical_url = PRIMARY_URL / "file" / file_id / shared_key
- new_scrape_item = scrape_item.create_child(canonical_url)
- for part in path.parent.parts:
- if part != folder_name:
- new_scrape_item.add_to_parent_title(part)
-
- file = FileTuple(file_id, DecryptData(file["iv"], file["k_decrypted"], file["meta_mac"]))
- await self.proccess_file(new_scrape_item, file)
+ if single_file_id and file_id != single_file_id:
+ continue
+ file_fragment = f"{shared_key}/file/{file_id}"
+ canonical_url = scrape_item.url.with_fragment(file_fragment)
+ if not single_file_id and await self.check_complete_from_referer(canonical_url):
+ continue
+ new_scrape_item = scrape_item.create_child(canonical_url, possible_datetime=file["ts"])
+ for part in path.parent.parts[1:]:
+ new_scrape_item.add_to_parent_title(part)
+
+ file = FileTuple(file_id, mega.DecryptData(file["k_decrypted"], file["iv"], file["meta_mac"]))
+ self.manager.task_group.create_task(self._process_file(new_scrape_item, file, folder_id=folder_id))
+ processed_files += 1
+ if processed_files % 10 == 0:
+ await asyncio.sleep(0)
scrape_item.add_children()
@error_handling_wrapper
- async def login(self, *_):
- await self.api.login(self.user, self.password)
+ async def login(self, *_) -> None:
+ # This takes a really long time (dozens of seconds)
+ # TODO: Add a way to cache this login
+ # TODO: Show some logging message / UI about login
+ try:
+ await self.downloader.api.login(self.user, self.password)
+ self.logged_in = True
+ except Exception as e:
+ self.disabled = True
+ raise LoginError(f"[MegaNZ] {e}") from e
diff --git a/cyberdrop_dl/downloader/mega_nz.py b/cyberdrop_dl/downloader/mega_nz.py
index f169ad255..23d4e0e8b 100644
--- a/cyberdrop_dl/downloader/mega_nz.py
+++ b/cyberdrop_dl/downloader/mega_nz.py
@@ -57,17 +57,16 @@ import math
import random
import string
import struct
-import time
-from collections.abc import Sequence
+from collections.abc import Coroutine, Sequence
from enum import IntEnum
-from functools import partial
from http import HTTPStatus
from pathlib import Path
-from typing import TYPE_CHECKING, Any, NamedTuple, NotRequired, Self, TypeAlias, TypedDict, TypeVar, cast
+from typing import TYPE_CHECKING, Any, Literal, NamedTuple, NotRequired, TypeAlias, TypedDict, TypeVar, cast
import aiofiles
import aiohttp
-from aiohttp import ClientSession, ClientTimeout
+from aiohttp import ClientTimeout
+from aiolimiter import AsyncLimiter
from Crypto.Cipher import AES
from Crypto.Math.Numbers import Integer
from Crypto.PublicKey import RSA
@@ -75,13 +74,14 @@ from Crypto.Util import Counter
from cyberdrop_dl.clients.download_client import DownloadClient
from cyberdrop_dl.downloader.downloader import Downloader
-from cyberdrop_dl.exceptions import CDLBaseError, DownloadError, SlowDownloadError
+from cyberdrop_dl.exceptions import CDLBaseError, DownloadError
from cyberdrop_dl.utils.logger import log
if TYPE_CHECKING:
- from collections.abc import AsyncGenerator, Generator, Mapping
- from types import TracebackType
+ from collections.abc import AsyncIterable, Generator, Mapping
+ from functools import partial
+ from aiohttp_client_cache.session import CachedSession
from yarl import URL
from cyberdrop_dl.data_structures.url_objects import MediaItem
@@ -89,7 +89,6 @@ if TYPE_CHECKING:
T = TypeVar("T")
Array: TypeAlias = list[T] | tuple[T, ...]
-CMD: TypeAlias = Array[str]
U32Int: TypeAlias = int
U32IntArray: TypeAlias = Array[U32Int]
U32IntSequence: TypeAlias = Sequence[U32Int]
@@ -97,58 +96,62 @@ U32IntTupleArray: TypeAlias = tuple[U32Int, ...]
AnyDict: TypeAlias = dict[str, Any]
-class MegaNzError(CDLBaseError): ...
-
-
-class ValidationError(MegaNzError):
- """Error in validation stage"""
+class MegaNzError(CDLBaseError):
+ def __init__(self, msg: str | int, **kwargs) -> None:
+ super().__init__(f"MegaNZ Error ({msg})", **kwargs)
ERROR_CODES = {
- -1: "EINTERNAL (-1): An internal error has occurred. Please submit a bug report, detailing the exact circumstances in which this error occurred.",
- -2: "EARGS (-2): You have passed invalid arguments to this command.",
- -3: "EAGAIN (-3): A temporary congestion or server malfunction prevented your request from being processed. No data was altered",
- -4: "ERATELIMIT (-4): You have exceeded your command weight per time quota. Please wait a few seconds, then try again (this should never happen in sane real-life applications).",
- -5: "EFAILED (-5): The upload failed. Please restart it from scratch.",
- -6: "ETOOMANY (-6): Too many concurrent IP addresses are accessing this upload target URL.",
- -7: "ERANGE (-7): The upload file packet is out of range or not starting and ending on a chunk boundary.",
- -8: "EEXPIRED (-8): The upload target URL you are trying to access has expired. Please request a fresh one.",
- -9: "ENOENT (-9): Object (typically, node or user) not found. Wrong password?",
- -10: "ECIRCULAR (-10): Circular linkage attempted",
- -11: "EACCESS (-11): Access violation (e.g., trying to write to a read-only share)",
- -12: "EEXIST (-12): Trying to create an object that already exists",
- -13: "EINCOMPLETE (-13): Trying to access an incomplete resource",
- -14: "EKEY (-14): A decryption operation failed (never returned by the API)",
- -15: "ESID (-15): Invalid or expired user session, please relogin",
- -16: "EBLOCKED (-16): User blocked",
- -17: "EOVERQUOTA (-17): Request over quota",
- -18: "ETEMPUNAVAIL (-18): Resource temporarily not available, please try again later",
- -19: "ETOOMANYCONNECTIONS (-19)",
- -24: "EGOINGOVERQUOTA (-24)",
- -25: "EROLLEDBACK (-25)",
- -26: "EMFAREQUIRED (-26): Multi-Factor Authentication Required",
- -27: "EMASTERONLY (-27)",
- -28: "EBUSINESSPASTDUE (-28)",
- -29: "EPAYWALL (-29): ODQ paywall state",
- -400: "ETOOERR (-400)",
- -401: "ESHAREROVERQUOTA (-401)",
+ -1: (
+ "EINTERNAL",
+ "An internal error has occurred. Please submit a bug report, detailing the exact circumstances in which this error occurred",
+ ),
+ -2: ("EARGS", "You have passed invalid arguments to this command"),
+ -3: (
+ "EAGAIN",
+ "A temporary congestion or server malfunction prevented your request from being processed. No data was altered",
+ ),
+ -4: (
+ "ERATELIMIT",
+ "You have exceeded your command weight per time quota. Please wait a few seconds, then try again (this should never happen in sane real-life applications)",
+ ),
+ -5: ("EFAILED", "The upload failed. Please restart it from scratch"),
+ -6: ("ETOOMANY", "Too many concurrent IP addresses are accessing this upload target URL"),
+ -7: ("ERANGE", "The upload file packet is out of range or not starting and ending on a chunk boundary"),
+ -8: ("EEXPIRED", "The upload target URL you are trying to access has expired. Please request a fresh one"),
+ -9: ("ENOENT", "Object (typically, node or user) not found. Wrong password?"),
+ -10: ("ECIRCULAR", "Circular linkage attempted"),
+ -11: ("EACCESS", "Access violation (e.g., trying to write to a read-only share)"),
+ -12: ("EEXIST", "Trying to create an object that already exists"),
+ -13: ("EINCOMPLETE", "Trying to access an incomplete resource"),
+ -14: ("EKEY", "A decryption operation failed (never returned by the API)"),
+ -15: ("ESID", "Invalid or expired user session, please relogin"),
+ -16: ("EBLOCKED", "User blocked"),
+ -17: ("EOVERQUOTA", "Request over quota"),
+ -18: ("ETEMPUNAVAIL", "Resource temporarily not available, please try again later"),
+ -19: ("ETOOMANYCONNECTIONS", ""),
+ -24: ("EGOINGOVERQUOTA", ""),
+ -25: ("EROLLEDBACK", ""),
+ -26: ("EMFAREQUIRED", "Multi-Factor Authentication Required"),
+ -27: ("EMASTERONLY", ""),
+ -28: ("EBUSINESSPASTDUE", ""),
+ -29: ("EPAYWALL", "ODQ paywall state"),
+ -400: ("ETOOERR", ""),
+ -401: ("ESHAREROVERQUOTA", ""),
}
class RequestError(MegaNzError):
- """
- Error in API request
- """
+ """Error in API request."""
def __init__(self, msg: str | int) -> None:
self.code = code = msg if isinstance(msg, int) else None
- if code:
- self.message = ERROR_CODES[code]
+ if code is not None:
+ name, message = ERROR_CODES[code]
+ ui_failure = f"{name}({code})"
else:
- self.message = str(msg)
-
- def __str__(self) -> str:
- return self.message
+ ui_failure = message = f"({msg})"
+ super().__init__(ui_failure, message=message)
CHUNK_BLOCK_LEN = 16 # Hexadecimal
@@ -161,7 +164,7 @@ class Chunk(NamedTuple):
class Attributes(TypedDict):
- n: str # Name
+ n: str # name
class NodeType(IntEnum):
@@ -174,26 +177,26 @@ class NodeType(IntEnum):
class Node(TypedDict):
- t: NodeType
- h: str # Id
- p: str # Parent Id
- a: str # Encrypted attributes (within this: 'n' Name)
- k: str # Node key
- u: str # User Id
- s: int # Size
- ts: int # Timestamp
- g: str # Access URL
- k: str # Public access key (parent folder + file)
+ t: NodeType # type
+ h: str # id (aka handle)
+ p: str # parent id
+ a: str # attributes (within this: 'n' Name)
+ k: str # key
+ u: str # user id
+ s: int # size
+ ts: int # creation date (timestamp)
+ g: NotRequired[str] # Access URL
# Non standard properties, only used internally
attributes: Attributes # Decrypted attributes
k_decrypted: U32IntTupleArray
- key_decrypted: U32IntTupleArray # Decrypted access key (for folders, its values if the same as 'k_decrypted')
+ # full key, computed from value of `k` and the master key of the owner. This is the public access key
+ key_decrypted: U32IntTupleArray
class FileOrFolder(Node):
- su: NotRequired[str] # Shared user Id, only present present in shared files / folder
- sk: NotRequired[str] # Shared key, only present present in shared (public) files / folder
+ su: NotRequired[str] # shared user id, only present in shared files / folder. The id of the owner
+ sk: NotRequired[str] # shared key. It's the base64 of `key_decrypted`
# Non standard properties, only used internally
iv: U32IntTupleArray
@@ -203,6 +206,7 @@ class FileOrFolder(Node):
class File(FileOrFolder):
at: str # File specific attributes (encrypted)
+ fa: str # File attributes
class Folder(FileOrFolder):
@@ -217,8 +221,8 @@ FilesMapping = dict[str, FileOrFolder] # key is parent_id ('p')
class DecryptData(NamedTuple):
- iv: U32IntTupleArray
k: U32IntTupleArray
+ iv: U32IntTupleArray
meta_mac: U32IntTupleArray
file_size: int = 0
@@ -296,12 +300,6 @@ def decrypt_key(array: U32IntSequence, key: U32IntSequence) -> U32IntTupleArray:
return sum((_aes_cbc_decrypt_a32(array[index : index + 4], key) for index in range(0, len(array), 4)), ())
-def encrypt_attr(attr_dict: dict, key: U32IntSequence) -> bytes:
- attr: bytes = f"MEGA{json.dumps(attr_dict)}".encode()
- attr = pad_bytes(attr)
- return _aes_cbc_encrypt(attr, a32_to_bytes(key))
-
-
def decrypt_attr(attr: bytes, key: U32IntSequence) -> AnyDict:
attr_bytes = _aes_cbc_decrypt(attr, a32_to_bytes(key))
try:
@@ -429,11 +427,11 @@ async def generate_hashcash_token(challenge: str) -> str:
for i in range(262144):
buffer[4 + i * 48 : 4 + (i + 1) * 48] = token
- def hash_val(val: bytes):
+ def hash_buffer() -> bytes:
return hashlib.sha256(buffer).digest()
while True:
- digest = await asyncio.to_thread(hash_val, buffer)
+ digest = await asyncio.to_thread(hash_buffer)
view = struct.unpack(">I", digest[:4])[0] # big-endian uint32
if view <= threshold:
return f"1:{token_str}:{base64_url_encode(buffer[:4])}"
@@ -445,37 +443,49 @@ async def generate_hashcash_token(challenge: str) -> str:
break
+def get_decrypt_data(node_type: NodeType, full_key: U32IntTupleArray) -> DecryptData:
+ if node_type == NodeType.FILE:
+ k = (full_key[0] ^ full_key[4], full_key[1] ^ full_key[5], full_key[2] ^ full_key[6], full_key[3] ^ full_key[7])
+ elif node_type == NodeType.FOLDER:
+ k = full_key
+
+ iv: U32IntTupleArray = (*full_key[4:6], 0, 0)
+ meta_mac: U32IntTupleArray = full_key[6:8]
+ return DecryptData(k, iv, meta_mac)
+
+
VALID_REQUEST_ID_CHARS = string.ascii_letters + string.digits
+def _check_response_status(response: aiohttp.ClientResponse) -> None:
+ if response.status > 0 and not (HTTPStatus.OK <= response.status < HTTPStatus.BAD_REQUEST):
+ raise DownloadError(response.status)
+
+
class MegaApi:
def __init__(self, manager: Manager) -> None:
self.manager = manager
- self.schema = "https"
- self.domain = "mega.nz"
- self.api_domain = "g.api.mega.co.nz" # api still uses the old mega.co.nz domain
self.timeout = ClientTimeout(160)
self.sid: str | None = None
self.sequence_num: U32Int = random_u32int()
self.request_id: str = "".join(random.choice(VALID_REQUEST_ID_CHARS) for _ in range(10))
- self.user_agent = manager.config_manager.global_settings_data.general.user_agent
- self.default_headers = {"Content-Type": "application/json", "User-Agent": self.user_agent}
- self.session: ClientSession
- self.entrypoint = f"{self.schema}://{self.api_domain}/cs"
+
+ self.default_headers = {
+ "Content-Type": "application/json",
+ "User-Agent": manager.config_manager.global_settings_data.general.user_agent,
+ }
+ self.entrypoint = "https://g.api.mega.co.nz/cs" # api still uses the old mega.co.nz domain
self.logged_in = False
self.root_id: str = ""
self.inbox_id: str = ""
self.trashbin_id: str = ""
+ self.request_limiter = AsyncLimiter(100, 60)
self._files = {}
+ self.shared_keys: SharedkeysDict
- async def __aenter__(self) -> Self:
- self.session = ClientSession()
- return self
-
- async def __aexit__(
- self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None
- ) -> None:
- await self.session.close()
+ @property
+ def session(self) -> CachedSession:
+ return self.manager.client_manager.scraper_session._session
async def request(self, data_input: list[AnyDict] | AnyDict, add_params: AnyDict | None = None) -> Any:
add_params = add_params or {}
@@ -490,9 +500,10 @@ class MegaApi:
else:
data: list[AnyDict] = data_input
- response = await self.session.post(
- self.entrypoint, params=params, json=data, timeout=self.timeout, headers=self.default_headers
- )
+ async with self.request_limiter, self.session.disabled():
+ response = await self.session.post(
+ self.entrypoint, params=params, json=data, timeout=self.timeout, headers=self.default_headers
+ )
# Since around feb 2025, MEGA requires clients to solve a challenge during each login attempt.
# When that happens, initial responses returns "402 Payment Required".
@@ -501,13 +512,14 @@ class MegaApi:
# See: https://github.com/gpailler/MegaApiClient/issues/248#issuecomment-2692361193
if xhashcash_challenge := response.headers.get("X-Hashcash"):
- log("Solving xhashcash login challenge, this could take a few seconds...")
+ log("[MegaNZ] Solving xhashcash login challenge, this could take a few seconds...")
xhashcash_token = await generate_hashcash_token(xhashcash_challenge)
headers = self.default_headers | {"X-Hashcash": xhashcash_token}
- response = await self.session.post(
- self.entrypoint, params=params, json=data, timeout=self.timeout, headers=headers
- )
-
+ async with self.request_limiter, self.session.disabled():
+ response = await self.session.post(
+ self.entrypoint, params=params, json=data, timeout=self.timeout, headers=headers
+ )
+ _check_response_status(response)
if xhashcash_challenge := response.headers.get("X-Hashcash"):
# Computed token failed
msg = f"Login failed. Mega requested a proof of work with xhashcash: {xhashcash_challenge}"
@@ -515,7 +527,7 @@ class MegaApi:
json_resp: list[Any] | list[int] | int = await response.json()
- def handle_int_resp(int_resp: int):
+ def handle_int_resp(int_resp: int) -> Literal[0]:
if int_resp == 0:
return int_resp
if int_resp == -3:
@@ -537,15 +549,17 @@ class MegaApi:
async def login(self, email: str | None = None, password: str | None = None):
if email and password:
+ log("[MegaNZ] Logging as user [REDACTED]. This may take several seconds...")
await self._login_user(email, password)
else:
+ log("[MegaNZ] Logging as anonymous temporary user. This may take several seconds...")
await self.login_anonymous()
_ = await self.get_files() # This is to set the special folders id
self.logged_in = True
- log("Login complete [Mega]")
+ log("[MegaNZ] Login complete")
return self
- def _process_login(self, resp: AnyDict, password: U32IntArray):
+ def _process_login(self, resp: AnyDict, password: U32IntArray) -> None:
encrypted_master_key = base64_to_a32(resp["k"])
self.master_key = decrypt_key(encrypted_master_key, password)
if b64_tsid := resp.get("tsid"):
@@ -571,10 +585,8 @@ class MegaApi:
self.sid = sid
async def _login_user(self, email: str, password: str) -> None:
- log("Logging in user...")
email = email.lower()
get_user_salt_resp: dict = await self.request({"a": "us0", "user": email})
-
if b64_salt := get_user_salt_resp.get("s"):
# v2 user account
user_salt = base64_to_a32(b64_salt)
@@ -597,7 +609,6 @@ class MegaApi:
self._process_login(resp, password_aes)
async def login_anonymous(self) -> None:
- log("Logging in anonymous temporary user...")
master_key = [random_u32int()] * 4
password_key = [random_u32int()] * 4
session_self_challenge = [random_u32int()] * 4
@@ -645,20 +656,13 @@ class MegaApi:
file["sk_decrypted"] = shared_key
if key is not None:
- # file
- if file["t"] == NodeType.FILE:
- file = cast("File", file)
- k = (key[0] ^ key[4], key[1] ^ key[5], key[2] ^ key[6], key[3] ^ key[7])
- file["iv"] = (*key[4:6], 0, 0)
- file["meta_mac"] = key[6:8]
- # folder
- else:
- k = key
-
+ crypto = get_decrypt_data(file["t"], key)
+ file["k_decrypted"] = crypto.k
+ file["iv"] = crypto.iv
+ file["meta_mac"] = crypto.meta_mac
file["key_decrypted"] = key
- file["k_decrypted"] = k
attributes_bytes = base64_url_decode(file["a"])
- attributes = decrypt_attr(attributes_bytes, k)
+ attributes = decrypt_attr(attributes_bytes, crypto.k)
file["attributes"] = cast("Attributes", attributes)
# other => wrong object
@@ -710,7 +714,7 @@ class MegaApi:
self._files = files_dict
return files_dict
- async def _get_nodes(self) -> AsyncGenerator[Node]:
+ async def _get_nodes(self) -> AsyncIterable[Node]:
files: Folder = await self.request({"a": "f", "c": 1, "r": 1})
shared_keys: SharedkeysDict = {}
self._init_shared_keys(files, shared_keys)
@@ -719,7 +723,7 @@ class MegaApi:
if index % 100 == 0:
await asyncio.sleep(0)
- async def _get_nodes_in_shared_folder(self, folder_id: str) -> AsyncGenerator[Node]:
+ async def _get_nodes_in_shared_folder(self, folder_id: str) -> AsyncIterable[Node]:
files: Folder = await self.request(
{"a": "f", "c": 1, "ca": 1, "r": 1},
{"n": folder_id},
@@ -729,33 +733,27 @@ class MegaApi:
if index % 100 == 0:
await asyncio.sleep(0)
- async def get_nodes_public_folder(self, folder_id: str, b64_share_key: str) -> dict[str, FileOrFolder]:
- shared_key = base64_to_a32(b64_share_key)
+ async def get_nodes_public_folder(self, folder_id: str, share_key: str) -> dict[str, FileOrFolder]:
+ folder_key = base64_to_a32(share_key)
- async def prepare_nodes():
+ async def prepare_nodes() -> AsyncIterable[FileOrFolder]:
async for node in self._get_nodes_in_shared_folder(folder_id):
node = cast("FileOrFolder", node)
encrypted_key = base64_to_a32(node["k"].split(":")[1])
- key = decrypt_key(encrypted_key, shared_key)
- if node["t"] == NodeType.FILE:
- k = (key[0] ^ key[4], key[1] ^ key[5], key[2] ^ key[6], key[3] ^ key[7])
- elif node["t"] == NodeType.FOLDER:
- k = key
-
- iv: U32IntSequence = (*key[4:6], 0, 0)
- meta_mac: U32IntTupleArray = key[6:8]
-
- attrs = decrypt_attr(base64_url_decode(node["a"]), k)
+ full_key = decrypt_key(encrypted_key, folder_key)
+ crypto = get_decrypt_data(node["t"], full_key)
+ attrs = decrypt_attr(base64_url_decode(node["a"]), crypto.k)
node["attributes"] = cast("Attributes", attrs)
- node["k_decrypted"] = k
- node["iv"] = iv
- node["meta_mac"] = meta_mac
+ node["key_decrypted"] = full_key
+ node["k_decrypted"] = crypto.k
+ node["iv"] = crypto.iv
+ node["meta_mac"] = crypto.meta_mac
yield node
nodes = {node["h"]: node async for node in prepare_nodes()}
return nodes
- async def _build_file_system(self, nodes_map: Mapping[str, Node], root_ids: list[str]) -> dict[Path, Node]:
+ def _build_file_system(self, nodes_map: Mapping[str, Node], root_ids: list[str]) -> dict[Path, Node]:
"""Builds a flattened dictionary representing a file system from a list of items.
Returns:
@@ -765,99 +763,39 @@ class MegaApi:
path_mapping: dict[Path, Node] = {}
parents_mapping: dict[str, list[Node]] = {}
- for _, item in nodes_map.items():
+ for item in nodes_map.values():
parent_id = item["p"]
if parent_id not in parents_mapping:
parents_mapping[parent_id] = []
parents_mapping[parent_id].append(item)
- async def build_tree(parent_id: str, current_path: Path) -> None:
+ def build_tree(parent_id: str, current_path: Path) -> None:
for item in parents_mapping.get(parent_id, []):
item_path = current_path / item["attributes"]["n"]
path_mapping[item_path] = item
if item["t"] == NodeType.FOLDER:
- await build_tree(item["h"], item_path)
-
- await asyncio.sleep(0)
+ build_tree(item["h"], item_path)
for root_id in root_ids:
root_item = nodes_map[root_id]
name = root_item["attributes"]["n"]
path = Path(name if name != "Cloud Drive" else ".")
path_mapping[path] = root_item
- await build_tree(root_id, path)
+ build_tree(root_id, path)
sorted_mapping = dict(sorted(path_mapping.items()))
return sorted_mapping
+ async def build_file_system(self, nodes_map: Mapping[str, Node], root_ids: list[str]) -> dict[Path, Node]:
+ return await asyncio.to_thread(self._build_file_system, nodes_map, root_ids)
+
class MegaDownloadClient(DownloadClient):
- def __init__(self, api: MegaApi) -> None:
- super().__init__(api.manager, api.manager.client_manager)
- self.api = api
+ def __init__(self, manager: Manager) -> None:
+ super().__init__(manager, manager.client_manager)
self.decrypt_mapping: dict[URL, DecryptData] = {}
- async def close(self):
- await self.api.__aexit__()
-
- def _decrypt_chunks(
- self,
- iv: U32IntTupleArray,
- k_decrypted: U32IntTupleArray,
- meta_mac: U32IntTupleArray,
- ) -> Generator[bytes, bytes, None]:
- """
- Decrypts chunks of data received via `send()` and yields the decrypted chunks.
- It decrypts chunks indefinitely until a sentinel value (`None`) is sent.
-
- NOTE: You MUST send `None` after decrypting every chunk to execute the mac check
-
- Args:
- iv (AnyArray): Initialization vector (iv) as a list or tuple of two 32-bit unsigned integers.
- k_decrypted (TupleArray): Decryption key as a tuple of four 32-bit unsigned integers.
- meta_mac (AnyArray): The expected MAC value of the final file.
-
- Yields:
- bytes: Decrypted chunk of data. The first `yield` is a blank (`b''`) to initialize generator.
-
- """
- k_bytes = a32_to_bytes(k_decrypted)
- counter = Counter.new(128, initial_value=((iv[0] << 32) + iv[1]) << 64)
- aes = AES.new(k_bytes, AES.MODE_CTR, counter=counter)
-
- # mega.nz improperly uses CBC as a MAC mode, so after each chunk
- # the computed mac_bytes are used as IV for the next chunk MAC accumulation
- mac_bytes = b"\0" * 16
- mac_encryptor = AES.new(k_bytes, AES.MODE_CBC, mac_bytes)
- iv_bytes = a32_to_bytes([iv[0], iv[1], iv[0], iv[1]])
- raw_chunk = yield b""
- while True:
- if raw_chunk is None:
- break
- decrypted_chunk = aes.decrypt(raw_chunk)
- raw_chunk = yield decrypted_chunk
- encryptor = AES.new(k_bytes, AES.MODE_CBC, iv_bytes)
-
- # take last 16-N bytes from chunk (with N between 1 and 16, including extremes)
- mem_view = memoryview(decrypted_chunk) # avoid copying memory for the entire chunk when slicing
- modchunk = len(decrypted_chunk) % CHUNK_BLOCK_LEN
- if modchunk == 0:
- # ensure we reserve the last 16 bytes anyway, we have to feed them into mac_encryptor
- modchunk = CHUNK_BLOCK_LEN
-
- # pad last block to 16 bytes
- last_block = pad_bytes(mem_view[-modchunk:])
- rest_of_chunk = mem_view[:-modchunk]
- _ = encryptor.encrypt(rest_of_chunk)
- input_to_mac = encryptor.encrypt(last_block)
- mac_bytes = mac_encryptor.encrypt(input_to_mac)
-
- file_mac = str_to_a32(mac_bytes)
- computed_mac = file_mac[0] ^ file_mac[1], file_mac[2] ^ file_mac[3]
- if computed_mac != meta_mac:
- raise RuntimeError("Mismatched mac")
-
async def _append_content(
self,
media_item: MediaItem,
@@ -866,69 +804,118 @@ class MegaDownloadClient(DownloadClient):
) -> None:
"""Appends content to a file."""
- check_free_space = partial(self.manager.storage_manager.check_free_space, media_item)
+ check_free_space = self.make_free_space_checker(media_item)
+ check_download_speed = self.make_speed_checker(media_item)
await check_free_space()
+ await self._pre_download_check(media_item)
- media_item.partial_file.parent.mkdir(parents=True, exist_ok=True) # type: ignore
- media_item.partial_file.unlink(missing_ok=True) # type: ignore # We can't resume
- media_item.partial_file.touch() # type: ignore
+ crypto_data = self.decrypt_mapping[media_item.url]
+ chunk_decryptor = MegaDecryptor(crypto_data)
- last_slow_speed_read = None
-
- def check_download_speed():
- nonlocal last_slow_speed_read
- speed = self.manager.progress_manager.file_progress.get_speed(media_item.task_id) # type: ignore
- if speed > self.download_speed_threshold:
- last_slow_speed_read = None
- elif not last_slow_speed_read:
- last_slow_speed_read = time.perf_counter()
- elif time.perf_counter() - last_slow_speed_read > self.slow_download_period:
- raise SlowDownloadError(origin=media_item)
-
- data = self.decrypt_mapping[media_item.url]
- chunk_decryptor = self._decrypt_chunks(data.iv, data.k, data.meta_mac)
- _ = next(chunk_decryptor) # Prime chunk decryptor
-
- async with aiofiles.open(media_item.partial_file, mode="ab") as f: # type: ignore
- for _, chunk_size in get_chunks(data.file_size):
+ async with aiofiles.open(media_item.partial_file, mode="ab") as f:
+ for _, chunk_size in get_chunks(crypto_data.file_size):
await self.manager.states.RUNNING.wait()
raw_chunk = await content.readexactly(chunk_size)
- decrypted_chunk: bytes = chunk_decryptor.send(raw_chunk)
+ chunk = chunk_decryptor.decrypt(raw_chunk)
await check_free_space()
- chunk_size = len(decrypted_chunk)
+ chunk_size = len(chunk)
await self.client_manager.speed_limiter.acquire(chunk_size)
- await f.write(decrypted_chunk)
+ await f.write(chunk)
update_progress(chunk_size)
+ check_download_speed()
- if self.download_speed_threshold:
- check_download_speed()
+ self._post_download_check(media_item, content)
+ chunk_decryptor.check_mac_integrity()
- if not content.total_bytes and not media_item.partial_file.stat().st_size: # type: ignore
- media_item.partial_file.unlink() # type: ignore
- raise DownloadError(status=HTTPStatus.INTERNAL_SERVER_ERROR, message="File is empty")
- try:
- # Stop chunk decryptor and do a mac integrity check
- chunk_decryptor.send(None) # type: ignore
- except StopIteration:
- pass
+ def _pre_download_check(self, media_item: MediaItem) -> Coroutine[Any, Any, None]:
+ def prepare() -> None:
+ media_item.partial_file.parent.mkdir(parents=True, exist_ok=True)
+ media_item.partial_file.unlink(missing_ok=True) # We can't resume
+ media_item.partial_file.touch()
+
+ return asyncio.to_thread(prepare)
class MegaDownloader(Downloader):
- def __init__(self, api: MegaApi, domain: str):
+ def __init__(self, manager: Manager, domain: str) -> None:
+ super().__init__(manager, domain)
+ self.api = MegaApi(manager)
self.client: MegaDownloadClient
- super().__init__(api.manager, domain)
- self.api = api
def startup(self) -> None:
"""Starts the downloader."""
- self.client = MegaDownloadClient(self.api)
+ self.client = MegaDownloadClient(self.manager)
self._semaphore = asyncio.Semaphore(self.manager.download_manager.get_download_limit(self.domain))
- self.manager.path_manager.download_folder.mkdir(parents=True, exist_ok=True)
- if self.manager.config_manager.settings_data.sorting.sort_downloads:
- self.manager.path_manager.sorted_folder.mkdir(parents=True, exist_ok=True)
+ def register(self, url: URL, crypto: DecryptData) -> None:
+ self.client.decrypt_mapping[url] = crypto
- def register(
- self, url: URL, iv: U32IntTupleArray, k_decrypted: U32IntTupleArray, meta_mac: U32IntTupleArray, file_size: int
- ) -> None:
- self.client.decrypt_mapping[url] = DecryptData(iv, k_decrypted, meta_mac, file_size)
+
+class MegaDecryptor:
+ def __init__(self, crypto: DecryptData) -> None:
+ self.chunk_decryptor = _decrypt_chunks(crypto.k, crypto.iv, crypto.meta_mac)
+ _ = next(self.chunk_decryptor) # Prime chunk decryptor
+
+ def decrypt(self, raw_chunk: bytes) -> bytes:
+ return self.chunk_decryptor.send(raw_chunk)
+
+ def check_mac_integrity(self) -> None:
+ try:
+ self.chunk_decryptor.send(None) # type: ignore
+ except StopIteration:
+ pass
+
+
+def _decrypt_chunks(
+ k_decrypted: U32IntTupleArray, iv: U32IntTupleArray, meta_mac: U32IntTupleArray
+) -> Generator[bytes, bytes, None]:
+ """
+ Decrypts chunks of data received via `send()` and yields the decrypted chunks.
+ It decrypts chunks indefinitely until a sentinel value (`None`) is sent.
+
+ NOTE: You MUST send `None` after decrypting every chunk to execute the mac check
+
+ Args:
+ iv (AnyArray): Initialization vector (iv) as a list or tuple of two 32-bit unsigned integers.
+ k_decrypted (TupleArray): Decryption key as a tuple of four 32-bit unsigned integers.
+ meta_mac (AnyArray): The expected MAC value of the final file.
+
+ Yields:
+ bytes: Decrypted chunk of data. The first `yield` is a blank (`b''`) to initialize generator.
+
+ """
+ k_bytes = a32_to_bytes(k_decrypted)
+ counter = Counter.new(128, initial_value=((iv[0] << 32) + iv[1]) << 64)
+ aes = AES.new(k_bytes, AES.MODE_CTR, counter=counter)
+
+ # mega.nz improperly uses CBC as a MAC mode, so after each chunk
+ # the computed mac_bytes are used as IV for the next chunk MAC accumulation
+ mac_bytes = b"\0" * 16
+ mac_encryptor = AES.new(k_bytes, AES.MODE_CBC, mac_bytes)
+ iv_bytes = a32_to_bytes([iv[0], iv[1], iv[0], iv[1]])
+ raw_chunk = yield b""
+ while True:
+ if raw_chunk is None:
+ break
+ decrypted_chunk = aes.decrypt(raw_chunk)
+ raw_chunk = yield decrypted_chunk
+ encryptor = AES.new(k_bytes, AES.MODE_CBC, iv_bytes)
+
+ # take last 16-N bytes from chunk (with N between 1 and 16, including extremes)
+ mem_view = memoryview(decrypted_chunk) # avoid copying memory for the entire chunk when slicing
+ modchunk = len(decrypted_chunk) % CHUNK_BLOCK_LEN
+ if modchunk == 0:
+ # ensure we reserve the last 16 bytes anyway, we have to feed them into mac_encryptor
+ modchunk = CHUNK_BLOCK_LEN
+
+ # pad last block to 16 bytes
+ last_block = pad_bytes(mem_view[-modchunk:])
+ rest_of_chunk = mem_view[:-modchunk]
+ _ = encryptor.encrypt(rest_of_chunk)
+ input_to_mac = encryptor.encrypt(last_block)
+ mac_bytes = mac_encryptor.encrypt(input_to_mac)
+
+ file_mac = str_to_a32(mac_bytes)
+ computed_mac = file_mac[0] ^ file_mac[1], file_mac[2] ^ file_mac[3]
+ if computed_mac != meta_mac:
+ raise RuntimeError("Mismatched mac")
diff --git a/docs/reference/supported-websites.md b/docs/reference/supported-websites.md
index 322d12277..3d769b228 100644
--- a/docs/reference/supported-websites.md
+++ b/docs/reference/supported-websites.md
@@ -28,7 +28,7 @@ Supported domains via Real-Debrid include `mega.nz`, `rapidgator`, `google drive
## Supported sites
-List of sites supported by cyberdrop-dl-patched as of version 7.1.0
+List of sites supported by cyberdrop-dl-patched as of version 7.0.1
| Site | Primary URL | Supported Domains | Supported Paths |
|---------------------------|---------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
@@ -82,6 +82,7 @@ List of sites supported by cyberdrop-dl-patched as of version 7.1.0
| LeakedZone | https://leakedzone.com | leakedzone | Model: <br> - `/<model_id>`<br>Video: <br> - `/<model_id>/video/<video_id>`<br> |
| Luscious | https://members.luscious.net | luscious | Album: <br> - `/albums/...`<br> |
| Mediafire | https://www.mediafire.com/ | mediafire | File: <br> - `/file/...`<br>Folder: <br> - `/folder/...`<br> |
+| MegaNz | https://mega.nz | mega.nz | File: <br> - `/!#<file_id>!<share_key>`<br> - `/file/<file_id>#<share_key>`<br> - `/folder/<folder_id>#<share_key>/file/<file_id>`<br>Folder: <br> - `/F!#<folder_id>!<share_key>`<br> - `/folder/<folder_id>#<share_key>`<br><br><br>**NOTES**<br> - Downloads can not be resumed. Partial downloads will always be deleted and new downloads will start over<br> |
| MissAV | https://missav.ws | missav | Video: <br> - `/...`<br> |
| MixDrop | https://mixdrop.sb | mixdrop<br>mxdrop | File: <br> - `/e/<file_id>`<br> - `/f/<file_id>`<br> |
| Motherless | https://motherless.com | motherless | Group: <br> - `/g/<group_name>`<br> - `/gi/<image>`<br> - `/gv/<video>`<br>Image: <br> - `/...`<br>User: <br> - `/f/...`<br> - `/u/...`<br>Video: <br> - `pending`<br><br><br>**NOTES**<br> - Galleries are NOT supported<br> |