This library still works with some duct tape and love, but it has been unmaintained for about 5 years already and it's showing its age quite a bit.
Not only it's unmaintained, but the code is so old that it's pretty much unmaintainable, so it's time for a new library.
This library has quite a few outstanding bugs, like a badly indented line that subtly breaks a with block; like the fact that it still only supports ASCII; and even the name of the library itself, mega.py is not great, since with such a generic name, it's bound to cause conflicts with software that tries to import the library but that also contain a file with the same name. So it's time for a rewrite (not a refactor).
Please write me a very detailed plan on how to rewrite this library to be in line with modern python (3.10+), modern design patterns, and a more organized and maintainable codebase.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, I understand. The mega.py library is showing its age, is difficult to maintain, and needs a complete rewrite. Here's a detailed plan to create a modern, maintainable, and robust replacement:
I. Goals for the New Library
Modern Python: Utilize Python 3.10+ features (type hints, match/case, etc.).
Maintainability:
Clear and consistent code style (PEP 8, potentially with a tool like Black).
Well-organized modules and packages.
Comprehensive documentation (docstrings, Sphinx).
Test-driven development (TDD) approach, with comprehensive unit and integration tests.
Robustness:
Proper error handling and logging.
Retries with exponential backoff for transient API errors.
Input validation to prevent common issues.
User-Friendly API:
Intuitive and consistent naming.
Clear parameter definitions and return types.
Support for both synchronous and asynchronous operations (using asyncio).
Extensibility:
Modular design to allow for future extensions.
Modern tooling:
Use of poetry or pdm for dependency management and packaging.
Github Actions for CI/CD.
No name clashes: Pick a more specific and less generic name for the library, like megapy_api_client or similar.
Unicode support: Full unicode support to handle non-ASCII characters in file names.
II. Project Structure
A well-defined structure will be critical. Here's a proposed layout:
code
megapy_api_client/ (or similar name)
├── pyproject.toml (or pdm.toml)
├── src/
│ └── megapy_api_client/
│ ├── __init__.py
│ ├── api/ # API interaction logic
│ │ ├── client.py # Handles requests/responses to Mega API
│ │ ├── endpoints.py # Defines API endpoints
│ │ ├── exceptions.py # Custom exceptions
│ │ ├── models.py # Data models (Node, User, etc.)
│ │ ├── crypto.py # Cryptographic functions
│ │ ├── auth.py # Authentication logic
│ │ └── utils.py # Utility functions
│ ├── core/ # Core logic
│ │ ├── mega.py # Main Mega class
│ │ ├── file.py # File operations (upload, download)
│ │ └── folder.py # Folder operations (create, delete)
│ ├── cli/ # Command-line interface (optional)
│ │ ├── __init__.py
│ │ └── main.py # CLI entry point
│ └── types/ # Type definitions (if needed)
│
├── tests/
│ ├── __init__.py
│ ├── api/
│ │ └── test_client.py # Tests for client.py
│ ├── core/
│ │ └── test_mega.py # Tests for main Mega class
│ ├── conftest.py # Fixtures
│ └── integration/ # Integration tests
│
├── docs/ # Documentation
│ ├── conf.py
│ ├── index.rst
│ └── ...
├── requirements.txt (legacy support if needed)
├── requirements-dev.txt (legacy support if needed)
└── .gitignore
III. Implementation Steps
Setup the Environment:
Initialize a new poetry (or pdm) project: poetry new megapy_api_client (or pdm init)
exceptions.py: Define custom exceptions for different API errors (e.g., RequestError, AuthenticationError, NotFoundError).
models.py: Define dataclasses/Pydantic models for API responses (e.g., Node, User, Quota). This will provide type safety and data validation.
crypto.py: Refactor the existing crypto functions into this module. Ensure it's well-tested and handles byte/string conversions correctly for unicode support.
endpoints.py: Centralize API endpoint URLs and parameters.
auth.py: Handle login, session management (sid/csid), and master key generation. Use a dedicated class for this.
client.py: Create a class (MegaAPIClient) that handles all communication with the MEGA API:
Use requests for HTTP calls.
Implement exponential backoff retries for EAGAIN errors.
Handle API response parsing and error handling.
Use type hints throughout the code.
Core Logic (src/megapy_api_client/core/)
mega.py: Create the main Mega class:
Instantiate MegaAPIClient.
Implement high-level methods (login, upload, download, etc.) by orchestrating calls to the API client.
Implement error handling and logging.
file.py: Implement File class to encapsulate file operations like:
upload method that takes a file path. Implement chunked uploads using the logic of the original library.
IV. Code Improvements and Modern Practices
Type Hints: Use type hints for all functions and variables.
asyncio Support: Introduce asynchronous API client calls with asyncio. Provide both synchronous and asynchronous versions of the high-level methods.
Error Handling: Use specific exception classes and informative error messages. Catch and handle requests exceptions gracefully. Log errors.
Logging: Use Python's logging module instead of print statements.
Unicode: Ensure all string operations handle Unicode correctly, especially file names.
Code Style: Enforce PEP 8 using a formatter like Black and a linter like Flake8.
DRY: Avoid code duplication. Extract common logic to utility functions.
V. Example Code Snippets (Illustrative)
API Client (Rough):
python
# src/megapy_api_client/api/client.py
import requests
import json
import logging
from tenacity import retry, wait_exponential, retry_if_exception_type
from .exceptions import RequestError
logger = logging.getLogger(__name__)
class MegaAPIClient:
def __init__(self, domain: str = "mega.co.nz", schema: str = 'https', timeout: int = 160):
self.domain = domain
self.schema = schema
self.timeout = timeout
self.sequence_num = random.randint(0, 0xFFFFFFFF)
self.sid = None #session id
@retry(retry=retry_if_exception_type(RuntimeError),
wait=wait_exponential(multiplier=2, min=2, max=60))
def _api_request(self, data: dict) -> dict | int:
params = {'id': self.sequence_num}
self.sequence_num += 1
if self.sid:
params.update({'sid': self.sid})
# ensure input data is a list
if not isinstance(data, list):
data = [data]
url = f'{self.schema}://g.api.{self.domain}/cs'
response = requests.post(
url,
params=params,
data=json.dumps(data),
timeout=self.timeout,
)
json_resp = json.loads(response.text)
try:
if isinstance(json_resp, list):
int_resp = json_resp[0] if isinstance(json_resp[0],
int) else None
[Redacted Person] isinstance(json_resp, int):
int_resp = json_resp
except IndexError:
int_resp = None
if int_resp is not None:
if int_resp == 0:
return int_resp
if int_resp == -3:
msg = 'Request failed, retrying'
logger.info(msg)
raise RuntimeError(msg)
raise RequestError(int_resp)
return json_resp[0]
# Implement other request methods (e.g., get, post)
VI. Timeline and Team
Initial Setup: 1-2 days.
API Layer: 5-7 days.
Core Logic: 7-10 days.
CLI (Optional): 2-3 days.
Testing: 5-7 days.
Documentation: 2-3 days.
This is a rough estimate.
VII. Important Considerations
API Changes: The MEGA API is not officially documented, so it can change, so the endpoints.py should be checked and updated accordingly.
Crypto: Pay careful attention to the crypto functions, as any mistake will cause data corruption. Thoroughly test them.
Testing: Invest heavily in tests. They will be critical to ensuring the library works correctly.
VIII. Summary
Rewriting mega.py is a significant undertaking, but by following this detailed plan, you can build a modern, maintainable, and robust library for interacting with the MEGA API. Remember to prioritize clear code, comprehensive tests, and proper documentation to ensure the long-term success of the project. Let me know if you have any further questions.
get_chunks()
download method that downloads a file. Implement checksum verification using the meta mac from the API.
folder.py: Implement Folder class to encapsulate folder operations:
create_folder method that creates a folder using the _mkdir logic from the original library
delete_folder method that moves a folder to the trashbin.
CLI Layer (src/megapy_api_client/cli/)
main.py: If you want a CLI, implement it with argparse or click.
Implement subcommands for common actions like upload, download, list files, etc.
Handle user input and pass data to the core logic.
Testing (tests/)
Unit Tests: Write thorough unit tests for each module and class (API client, crypto, auth, core, etc.). Use pytest and pytest-mock to mock API responses and isolate tests.
Integration Tests: Add integration tests to cover the interaction between different components (e.g. upload and download a file through the API).
Fixtures: Create test fixtures in conftest.py to avoid repetition in tests.
Documentation (docs/)
Use Sphinx to generate API documentation from docstrings and RST files.
Create a "getting started" guide and API reference.
Modern Tooling:
Use Github Actions for CI/CD: set up linting checks, unit tests, integration tests and document generation
Use poetry publish or pdm publish to publish the package to pypi.