Metadata-Version: 2.4
Name: aio-dl-manager
Version: 0.1.2
Summary: Universal asynchronous download manager for HTTP, Torrents, YouTube, Google Drive, Mega, Gofile, Buzzheavier, Pixeldrain, MediaFire, and more — with Rich CLI and JSON-RPC 2.0 daemon.
Author-email: Amine EL AZZOUZI <simo.20052011@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/aminelazz/aio-dl
Project-URL: Repository, https://github.com/aminelazz/aio-dl
Project-URL: Issues, https://github.com/aminelazz/aio-dl/issues
Keywords: async,downloader,torrent,aria2,yt-dlp,gdrive,mega,gofile,jsonrpc
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: End Users/Desktop
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: aiofiles>=23.2.0
Requires-Dist: cryptography>=41.0.0
Requires-Dist: yt-dlp>=2024.1.0
Requires-Dist: typer>=0.12.0
Requires-Dist: rich>=13.7.0
Requires-Dist: pydantic>=2.6.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"

# `aio-dl`

Universal asynchronous Python (`>=3.10`) download manager for HTTP/HTTPS, BitTorrent, YouTube/media sites, Google Drive, Mega.nz, Gofile.io, Buzzheavier, FuckingFast, Pixeldrain, MediaFire, 1Fichier, KrakenFiles, Dropbox, OneDrive, GitHub, and HuggingFace — featuring universal multi-file inspection & selection, a Rich/Typer CLI, and a JSON-RPC 2.0 HTTP + WebSocket daemon.

---

## Key Features

- **Python >= 3.10 Native Async Core**: Built on `asyncio`, `aiohttp`, `aiofiles`, `cryptography`, and `pydantic` v2 with configurable concurrency (`max_concurrent`), cooperative pause/resume/cancel, and optional JSON session persistence.
- **Multi-Segment HTTP/HTTPS**: Automatic `Accept-Ranges` detection, concurrent byte-range workers, exponential-backoff retries, speed limiting, and crash-safe `.part` + `.part.aio.json` resume state.
- **Universal Multi-File Inspection & Selection**: Inspect and selectively download files across BitTorrent (`.torrent` & `magnet:`), Google Drive folders, Mega.nz folders, Gofile folders, Pixeldrain lists, MediaFire folders, GitHub Releases, and YouTube playlists using 1-based index ranges (`"1,3,5-8"`), glob `--include`/`--exclude` filters, an interactive Rich CLI picker (`-S` / `--select`), or two-phase JSON-RPC selection (`WAITING_SELECTION` -> `dl.select_files`).
- **JSON-RPC 2.0 Daemon (`HTTP POST /jsonrpc` & `WebSocket /ws`)**: Single & batch JSON-RPC 2.0 requests, real-time WebSocket event notifications (`dl.on_added`, `dl.on_progress`, `dl.on_state_change`, `dl.on_complete`, `dl.on_error`), Bearer/query secret authentication, and `aria2.*` method aliases.
- **Rich CLI**: Standalone multi-task progress dashboard, `inspect` command, daemon server (`serve`), and remote client subcommands (`rpc add|inspect|files|select|list|status|pause|resume|cancel|stats|watch`).

---

## Supported Engines & Providers

| Engine (`SourceType`) | Supported Sources & Capabilities |
| :--- | :--- |
| **`HttpEngine`** (`http`) | Any direct `http://` / `https://` URL; multi-connection range workers, `.part.aio.json` resume, single-stream fallback |
| **`TorrentEngine`** (`torrent`) | `magnet:?` links, local `.torrent` files, and remote `.torrent` URLs via managed background `aria2c` RPC + built-in pure-Python `bencode` metadata parser (`select-file` support) |
| **`YtDlpEngine`** (`youtube`) | YouTube, Twitch, Vimeo, SoundCloud, TikTok, Twitter/X, Bilibili, Reddit, Instagram, Facebook, Rumble, etc. via `yt-dlp` with format selection & playlist item selection |
| **`GDriveEngine`** (`gdrive`) | Google Drive public files (`/file/d/<id>`, `/open?id=<id>`, `/uc?id=<id>`, `drive.usercontent.google.com`) with automatic large-file virus-scan bypass, plus recursive public folders (`/drive/folders/<id>`) |
| **`MegaEngine`** (`mega`) | Native async Mega.nz client for files (`mega.nz/file/...`, `#!...`) and folders (`mega.nz/folder/...`, `#F!...`) with AES-128-CBC attribute decryption and streaming AES-128-CTR file decryption |
| **`GofileEngine`** (`gofile`) | `gofile.io/d/<id>` with automatic guest token minting, dynamic `X-Website-Token` & `X-BL` auth, SHA-256 `--password` support, and recursive folder traversal |
| **`BuzzheavierEngine`** (`buzzheavier`) | `buzzheavier.com`, `bzzhr.co`, `buzzheavier.org` (`HX-Request` / `hx-redirect` resolution) and `fuckingfast.co` |
| **`PixeldrainEngine`** (`pixeldrain`) | `pixeldrain.com/u/<id>` single files and `pixeldrain.com/l/<id>` multi-file albums/lists |
| **`MediafireEngine`** (`mediafire`) | `mediafire.com/file/...` (including `data-scrambled-url` Base64 decoding) and `mediafire.com/folder/...` |
| **`FileHostEngine`** (`filehost`) | `1fichier.com` (form POST + optional `--password`, single-connection throttling guard) and `krakenfiles.com` |
| **`CloudDevEngine`** (`cloud_dev`) | Dropbox (`dl=1`), OneDrive (`1drv.ms` / `onedrive.live.com` shares API), GitHub (`blob` raw files & `releases` assets), and HuggingFace (`/resolve/`) |

---

## Requirements & Installation

- **Python**: `>= 3.10`
- **BitTorrent downloads**: Requires `aria2c` available in `PATH` (optional if you do not download torrents; pure-Python `.torrent` bencode inspection works without `aria2c`).

```powershell
# Install from PyPI
pip install aio-dl-manager

# Or clone and install in editable mode with dev/test dependencies
pip install -e ".[dev]"
```

Run the automated test suite:
```powershell
pytest -v
```

---

## CLI Usage

### 1. Download Targets (`aio-dl download`)

```powershell
# Direct HTTP download with 16 segments
aio-dl download "https://example.com/archive.zip" -o ./downloads -c 16

# BitTorrent (.torrent or magnet)
aio-dl download "./release.torrent" -o ./downloads
aio-dl download "magnet:?xt=urn:btih:..." -o ./downloads

# YouTube / Media with format selector
aio-dl download "https://www.youtube.com/watch?v=dQw4w9WgXcQ" --format "bestvideo+bestaudio/best"

# Password-protected Gofile or 1Fichier link
aio-dl download "https://gofile.io/d/<ID>" --password "secret"

# Override auto-detected engine
aio-dl download "https://example.com/custom-video" --engine youtube
```

Key options for `aio-dl download`:
- `-o, --output-dir`: Destination directory (default `./downloads`)
- `-n, --filename`: Override output filename
- `-c, --connections`: HTTP connections per file (default `8`, range `1..64`)
- `--engine`: Force a specific `SourceType` (`http`, `torrent`, `youtube`, `gdrive`, `mega`, `gofile`, `buzzheavier`, `pixeldrain`, `mediafire`, `filehost`, `cloud_dev`)
- `--format`: `yt-dlp` format selector (default `bestvideo+bestaudio/best`)
- `--password`: Password for protected links
- `--select-files`: 1-based file index/range filter (e.g. `"1,3-5"`)
- `--include`: Comma-separated glob include filter (e.g. `"*.mkv,*.srt"`)
- `--exclude`: Comma-separated glob exclude filter (e.g. `"*.txt,*sample*"`)
- `-S, --select`: Interactive Rich table picker before starting downloads
- `--rpc`, `--rpc-url`, `--rpc-secret`: Forward downloads to a running JSON-RPC daemon

### 2. Inspect & Select Files (`aio-dl inspect`)

Inspect any multi-file container without downloading its payload:

```powershell
# Inspect a .torrent, Google Drive folder, Mega folder, Gofile folder, GitHub release, or playlist
aio-dl inspect "./release.torrent"
aio-dl inspect "https://drive.google.com/drive/folders/<FOLDER_ID>"
aio-dl inspect "https://gofile.io/d/<CONTENT_ID>"
aio-dl inspect "https://github.com/owner/repo/releases/latest"

# Preview selection filters before downloading
aio-dl inspect "./release.torrent" --include "*.mkv,*.srt" --exclude "*sample*"
```

Combine with `download` to grab only what you need:

```powershell
# Interactive file picker
aio-dl download "https://drive.google.com/drive/folders/<FOLDER_ID>" -S

# Non-interactive index and glob selection
aio-dl download "./release.torrent" --select-files "1,3-5" --exclude "*.nfo"
```

---

## JSON-RPC 2.0 Daemon (`serve` & `rpc`)

> See the complete [JSON-RPC 2.0 API Reference](docs/jsonrpc.md) for full request/response schemas, error codes, two-phase selection flows, `aria2.*` aliases, and `curl`/Python/JS examples.

Start the JSON-RPC 2.0 server (exposes `POST /jsonrpc`, `GET /ws`, and `GET /health`):

```powershell
aio-dl serve --host 127.0.0.1 --port 6801 --rpc-secret mysecret --max-concurrent 5 --session-file ./session.json
```

Control the daemon from the CLI:

```powershell
aio-dl rpc add "https://example.com/file.iso" -o ./downloads --rpc-secret mysecret
aio-dl rpc add "./release.torrent" --pause-for-selection --rpc-secret mysecret
aio-dl rpc inspect "https://gofile.io/d/<ID>" --rpc-secret mysecret
aio-dl rpc files <TASK_ID> --rpc-secret mysecret
aio-dl rpc select <TASK_ID> --select-files "1,3" --rpc-secret mysecret
aio-dl rpc list --rpc-secret mysecret
aio-dl rpc status <TASK_ID> --rpc-secret mysecret
aio-dl rpc pause <TASK_ID> --rpc-secret mysecret
aio-dl rpc resume <TASK_ID> --rpc-secret mysecret
aio-dl rpc cancel <TASK_ID> --delete-files --rpc-secret mysecret
aio-dl rpc stats --rpc-secret mysecret
aio-dl rpc watch --rpc-secret mysecret
```

### Supported JSON-RPC 2.0 Methods

| Method | `aria2` Alias | Description |
| :--- | :--- | :--- |
| `dl.add` | `aria2.addUri` | Enqueue a target URL/magnet with optional `DownloadOptions` |
| `dl.add_torrent` | `aria2.addTorrent` | Enqueue a `.torrent` file path or base64-encoded `.torrent` bytes |
| `dl.inspect` | — | Inspect selectable files inside a target without downloading |
| `dl.get_files` | `aria2.getFiles` | Get the `SelectableFile` list for a task |
| `dl.select_files` | `aria2.changeOption` | Update selected files for a task and resume if `waiting_selection` |
| `dl.status` | `aria2.tellStatus` | Get full status of a task by `task_id` |
| `dl.list` | `aria2.tellActive` | List tasks (optionally filtered by `status`) |
| `dl.pause` | `aria2.pause` | Pause an active or queued task |
| `dl.resume` | `aria2.unpause` | Resume a paused, waiting-selection, or failed task |
| `dl.cancel` | `aria2.remove` | Cancel a task (optionally `delete_files: true`) |
| `dl.remove` | — | Remove a task from manager state |
| `dl.stats` | `aria2.getGlobalStat` | Return `GlobalStats` (counts, aggregate speed, total bytes) |
| `dl.shutdown` | `aria2.shutdown` | Gracefully shut down the daemon |

### WebSocket Notifications (`GET /ws`)

Clients connected to `/ws` can both send JSON-RPC 2.0 requests and receive real-time notifications:
- `dl.on_added`
- `dl.on_progress`
- `dl.on_state_change`
- `dl.on_complete`
- `dl.on_error`

Example HTTP JSON-RPC call:

```powershell
curl -X POST http://127.0.0.1:6801/jsonrpc `
  -H "Authorization: Bearer mysecret" `
  -H "Content-Type: application/json" `
  -d '{"jsonrpc":"2.0","id":1,"method":"dl.add","params":{"url":"https://example.com/file.zip","options":{"connections":8}}}'
```

---

## Python Async SDK

```python
import asyncio
from aio_dl import DownloadManager, DownloadOptions, JsonRpcClient, download, inspect


async def main() -> None:
    # 1. Quick one-shot inspect & download
    files = await inspect("https://github.com/cli/cli/releases/latest")
    for item in files:
        print(f"[{item.index}] {item.path} ({item.size_bytes} bytes)")

    result = await download(
        "https://example.com/file.zip",
        DownloadOptions(output_dir="./downloads", connections=8),
    )
    print("Downloaded to:", result.output_path)

    # 2. Full DownloadManager with events and two-phase selection
    async with DownloadManager(max_concurrent=4, persist_session=True) as manager:
        manager.events.subscribe(
            "dl.on_progress",
            lambda evt, task: print(f"{task.name}: {task.progress_pct:.1f}%"),
        )
        task = await manager.add(
            "https://gofile.io/d/<ID>",
            DownloadOptions(output_dir="./downloads", pause_for_selection=True),
        )
        await manager.wait(task.task_id)  # Pauses in waiting_selection
        await manager.select_files(task.task_id, select_files="1,2")
        finished = await manager.wait(task.task_id)
        print("Status:", finished.status)

    # 3. Talk to a remote daemon via JsonRpcClient
    async with JsonRpcClient("http://127.0.0.1:6801", secret="mysecret") as client:
        stats = await client.stats()
        print("Global stats:", stats)


asyncio.run(main())
```

---

## Project Structure

```text
aio-dl/
├── pyproject.toml
├── README.md
├── .gitignore
├── src/aio_dl/
│   ├── __init__.py
│   ├── cli.py              # Typer + Rich CLI
│   ├── events.py           # Async EventBus
│   ├── manager.py          # Central DownloadManager
│   ├── models.py           # Pydantic v2 models & enums
│   ├── router.py           # Target-to-engine router
│   ├── selector.py         # Universal FileSelector
│   ├── storage.py          # JSON SessionStore
│   ├── engines/
│   │   ├── base.py         # BaseEngine & BaseResolverEngine
│   │   ├── bencode.py      # Pure-Python bencode & .torrent parser
│   │   ├── buzzheavier.py  # Buzzheavier & FuckingFast
│   │   ├── cloud_dev.py    # Dropbox, OneDrive, GitHub, HuggingFace
│   │   ├── filehosts.py    # 1Fichier & KrakenFiles
│   │   ├── gdrive.py       # Google Drive files & folders
│   │   ├── gofile.py       # Gofile.io
│   │   ├── http.py         # Native multi-segment HTTP/HTTPS
│   │   ├── mediafire.py    # MediaFire files & folders
│   │   ├── mega.py         # Native Mega.nz AES-CBC / AES-CTR
│   │   ├── pixeldrain.py   # Pixeldrain files & lists
│   │   ├── torrent.py      # Managed aria2c RPC BitTorrent engine
│   │   └── ytdlp.py        # Async yt-dlp wrapper
│   └── rpc/
│       ├── protocol.py     # JSON-RPC 2.0 schemas & error codes
│       ├── server.py       # aiohttp HTTP POST & WebSocket server
│       └── client.py       # Async JSON-RPC 2.0 client
└── tests/                  # Automated pytest suite
```
