### Initialize Torrent and Download Files (Python) Source: https://context7.com/mys7erio/aiotorrent/llms.txt Initializes a torrent from a file path or file-like object and downloads all files to disk. This basic example demonstrates the core `Torrent` class usage for initialization and file downloading. ```python import asyncio from aiotorrent import Torrent async def download_torrent(): # Initialize torrent from file path torrent = Torrent('path/to/file.torrent') # Initialize with tracker communication await torrent.init() # Access files in the torrent (list of File objects) for file in torrent.files: print(f"Downloading: {file.name} ({file.size} bytes)") await torrent.download(file) print("Download complete!") asyncio.run(download_torrent()) ``` -------------------------------- ### Configure HTTP Streaming Host and Port (Python) Source: https://context7.com/mys7erio/aiotorrent/llms.txt Allows configuring the streaming server with a custom host and port, enabling network access. This example sets the server to listen on all interfaces (`0.0.0.0`) on port 9000. ```python import asyncio from aiotorrent import Torrent async def stream_on_network(): torrent = Torrent('video.torrent') await torrent.init(dht_enabled=True) video = torrent.files[0] # Stream on all interfaces, port 9000 # Access via: http://:9000/ await torrent.stream(video, host="0.0.0.0", port=9000) asyncio.run(stream_on_network()) ``` -------------------------------- ### Bash: Get Torrent Info via aioTorrent CLI Source: https://context7.com/mys7erio/aiotorrent/llms.txt This bash script demonstrates using the aiotorrent CLI's 'info' command to display torrent metadata without initiating a download. It covers showing basic information, verbose details including piece hashes, and specifying JSON output format. ```bash # Show basic torrent information aiotorrent info file.torrent # Show verbose information with piece hashes aiotorrent info --verbose file.torrent # Specify output format aiotorrent info --format json debian.torrent ``` -------------------------------- ### Download Specific File from Torrent in Python Source: https://github.com/mys7erio/aiotorrent/blob/main/README.md Provides an example of how to download a specific file from a torrent. Files are accessed via the `Torrent.files` attribute using list indexing. This example downloads the third file in the list (index 2). ```python # To download the third file await torrent.download(torrent.files[2]) ``` -------------------------------- ### Get Torrent File Download Progress in Python Source: https://github.com/mys7erio/aiotorrent/blob/main/README.md Shows how to retrieve download statistics for a specific torrent file. The example demonstrates using `get_bytes_downloaded()`, `get_bytes_written()`, and `get_download_progress()` methods to get information about the download status of the first file (index 0). ```python file = torrent.files[0] print(f"Total bytes downloaded: {file.get_bytes_downloaded()} bytes") # Additional methods: file.get_bytes_written(), file.get_download_progress() ``` -------------------------------- ### Bash: Stream Torrents via aioTorrent CLI Source: https://context7.com/mys7erio/aiotorrent/llms.txt This bash script shows how to use the aiotorrent CLI to stream torrent files over HTTP. Examples include streaming to the default host and port, and configuring custom host and port settings, along with verbosity flags. ```bash # Stream on default localhost:8080 aiotorrent stream video.torrent # Stream on custom host and port aiotorrent stream --host 192.168.1.100 --port 9000 movie.torrent # Short form with verbosity aiotorrent stream -H 0.0.0.0 -p 8888 -vv series.torrent ``` -------------------------------- ### Stream Torrent File over HTTP in Python Source: https://github.com/mys7erio/aiotorrent/blob/main/README.md Illustrates how to stream a specific torrent file over HTTP using the `stream()` coroutine. This feature utilizes `uvicorn` and `starlette` to serve files without downloading them to disk. This example streams the second file (index 1). ```python # To stream the second file, etc await torrent.stream(torrent.files[1]) ``` -------------------------------- ### Utilize Download Strategies (Python) Source: https://context7.com/mys7erio/aiotorrent/llms.txt Demonstrates how to control the piece download order using different `DownloadStrategy` options. The `DEFAULT` strategy is suitable for general downloading, while `SEQUENTIAL` is necessary for streaming. ```python import asyncio from aiotorrent import Torrent, DownloadStrategy async def download_with_strategy(): torrent = Torrent('movie.torrent') await torrent.init(dht_enabled=True) # DEFAULT strategy: pseudo-sequential, may yield pieces out of order # Best for general downloading where order doesn't matter video_file = torrent.files[0] await torrent.download(video_file, strategy=DownloadStrategy.DEFAULT) # SEQUENTIAL strategy: always yields pieces in order # Required for streaming, slower but guarantees sequential delivery subtitle_file = torrent.files[1] await torrent.download(subtitle_file, strategy=DownloadStrategy.SEQUENTIAL) asyncio.run(download_with_strategy()) ``` -------------------------------- ### Python: Initialize Torrent from File-like Object with aioTorrent Source: https://context7.com/mys7erio/aiotorrent/llms.txt This Python script demonstrates initializing aiotorrent.Torrent objects from file-like objects, such as BytesIO streams derived from file content or network responses. It shows how to load a torrent from bytes and from an HTTP response. Requires aiotorrent and httpx libraries. ```python import asyncio import io from aiotorrent import Torrent async def from_bytes(): # Load torrent from bytes with open('example.torrent', 'rb') as f: torrent_data = f.read() # Initialize from BytesIO object torrent_stream = io.BytesIO(torrent_data) torrent = Torrent(torrent_stream) await torrent.init() await torrent.download(torrent.files[0]) # From network response async def from_url(): import httpx async with httpx.AsyncClient() as client: response = await client.get('https://example.com/file.torrent') torrent_stream = io.BytesIO(response.content) torrent = Torrent(torrent_stream) await torrent.init(dht_enabled=True) await torrent.download(torrent.files[0]) asyncio.run(from_bytes()) ``` -------------------------------- ### Bash: Download Torrents via aioTorrent CLI Source: https://context7.com/mys7erio/aiotorrent/llms.txt This bash script demonstrates various ways to use the aiotorrent command-line interface for downloading torrent files. It covers basic downloads, specifying save locations, and controlling output verbosity using flags like -v. ```bash # Basic download to current directory aiotorrent download path/to/file.torrent # Download to specific location aiotorrent download movie.torrent /path/to/save/location # Download with verbose output (logging levels: -v to -vvvvv) aiotorrent download -v file.torrent # Maximum verbosity (DEBUG level) aiotorrent download -vvvvv debian.torrent ./downloads ``` -------------------------------- ### Bash: aiotorrent CLI Usage Source: https://github.com/mys7erio/aiotorrent/blob/main/README.md This bash script demonstrates the command-line interface (CLI) for aiotorrent, available from version 0.9.0. It outlines the available commands such as 'download', 'stream', and 'info', along with help and verbose output options. ```bash aiotorrent usage: aiotorrent [-h] [-v] {download,stream,info} ... aiotorrent CLI for downloading and streaming torrents. positional arguments: {download,stream,info} Available commands download Download torrent files stream Stream files over HTTP info Parse and show torrent metadata options: -h, --help show this help message and exit -v, --verbose Show verbose output. Use -vv, -vvv, etc for increased verbosity ``` -------------------------------- ### Python: Selective File Download from Torrents with aioTorrent Source: https://context7.com/mys7erio/aiotorrent/llms.txt This Python script illustrates how to select and download specific files from a multi-file torrent using aiotorrent. It shows how to list available files, access them by index, and initiate downloads for individual or all files. Requires the aiotorrent library and DHT enabled for initialization. ```python import asyncio from aiotorrent import Torrent async def selective_download(): torrent = Torrent('album.torrent') await torrent.init(dht_enabled=True) # List all files print("Available files:") for idx, file in enumerate(torrent.files): print(f" [{idx}] {file.name} - {file.size:,} bytes") # Download specific file by index first_track = torrent.files[0] print(f"\nDownloading: {first_track.name}") await torrent.download(first_track) # Download last file last_track = torrent.files[-1] print(f"Downloading: {last_track.name}") await torrent.download(last_track) # Download all files for file in torrent.files: await torrent.download(file) asyncio.run(selective_download()) ``` -------------------------------- ### Initialize Torrent Object in Python Source: https://github.com/mys7erio/aiotorrent/blob/main/README.md Demonstrates how to import the Torrent class and initialize a torrent object by passing the path to a .torrent file. The init() coroutine must be called to complete the initialization process. ```python from aiotorrent import Torrent torrent = Torrent('path/to/file.torrent') # To initialise the torrent, you need to call the init() coroutine. await torrent.init() ``` -------------------------------- ### Robust Torrent Download with Error Handling (Python) Source: https://context7.com/mys7erio/aiotorrent/llms.txt This Python snippet demonstrates how to download files from a torrent with robust error handling and connection management. It includes timeouts for initialization and individual file downloads, checks for active peers, and gracefully handles potential exceptions like file not found or network issues. It utilizes the `aiotorrent` library and `asyncio` for asynchronous operations. ```python import asyncio import logging from aiotorrent import Torrent logging.basicConfig(level=logging.INFO) async def robust_download(): try: torrent = Torrent('example.torrent') # Initialize with timeout handling await asyncio.wait_for(torrent.init(dht_enabled=True), timeout=60) if not torrent.files: print("No files found in torrent") return # Check active peers active_peers = [p for p in torrent.peers if p.has_handshaked] print(f"Connected to {len(active_peers)} active peers") if len(active_peers) == 0: print("No active peers available") return # Download with error handling for file in torrent.files: try: await torrent.download(file) progress = file.get_download_progress() print(f"Downloaded {file.name}: {progress}%") except Exception as e: print(f"Failed to download {file.name}: {e}") continue except asyncio.TimeoutError: print("Initialization timed out") except FileNotFoundError: print("Torrent file not found") except Exception as e: print(f"Unexpected error: {e}") asyncio.run(robust_download()) ``` -------------------------------- ### Monitor Download Progress (Python) Source: https://context7.com/mys7erio/aiotorrent/llms.txt Shows how to track the download progress of a torrent file in real-time. It monitors bytes downloaded, bytes written, and the completion percentage, updating every second. ```python import asyncio from aiotorrent import Torrent async def monitor_download(): torrent = Torrent('large-file.torrent') await torrent.init(dht_enabled=True) file = torrent.files[0] # Start download in background download_task = asyncio.create_task(torrent.download(file)) # Monitor progress while downloading while not download_task.done(): bytes_downloaded = file.get_bytes_downloaded() bytes_written = file.get_bytes_written() progress = file.get_download_progress(precision=2) print(f"Progress: {progress}% | " f"Downloaded: {bytes_downloaded:,} bytes | " f"Written: {bytes_written:,} / {file.size:,} bytes") await asyncio.sleep(1) await download_task print(f"Final progress: {file.get_download_progress()}%") asyncio.run(monitor_download()) ``` -------------------------------- ### Enable DHT Peer Discovery in Python Source: https://github.com/mys7erio/aiotorrent/blob/main/README.md Shows how to enable Distributed Hash Table (DHT) for peer discovery during torrent initialization. Passing `dht_enabled=True` to the `init()` coroutine allows the library to fetch peers via DHT, potentially improving retrieval speeds. Note that a minimum of 100 peers are fetched, which might cause initialization issues if insufficient peers are available. ```python await torrent.init(dht_enabled=True) ``` -------------------------------- ### Enable DHT for Peer Discovery (Python) Source: https://context7.com/mys7erio/aiotorrent/llms.txt Enables Distributed Hash Table (DHT) for enhanced peer discovery, which can improve download speeds. This snippet shows how to initialize the `Torrent` class with `dht_enabled=True`. ```python import asyncio from aiotorrent import Torrent async def download_with_dht(): torrent = Torrent('ubuntu-22.04.torrent') # Enable DHT for peer discovery (minimum 100 peers) await torrent.init(dht_enabled=True) # Download first file in the torrent if torrent.files: file = torrent.files[0] await torrent.download(file) asyncio.run(download_with_dht()) ``` -------------------------------- ### Stream Torrent Files Over HTTP (Python) Source: https://context7.com/mys7erio/aiotorrent/llms.txt Demonstrates streaming a torrent file over HTTP without saving it to disk. This requires `aiotorrent[stream-support]` and uses the `Torrent.stream()` method, which defaults to the `SEQUENTIAL` download strategy. ```python import asyncio from aiotorrent import Torrent async def stream_video(): # Requires: pip install aiotorrent[stream-support] torrent = Torrent('big-buck-bunny.torrent') await torrent.init(dht_enabled=True) # Select video file to stream video_file = torrent.files[0] # Start HTTP server on localhost:8080 # Automatically uses SEQUENTIAL download strategy # Access via: http://127.0.0.1:8080/ await torrent.stream(video_file, host="127.0.0.1", port=8080) asyncio.run(stream_video()) ``` -------------------------------- ### Download File with Sequential Strategy in Python Source: https://github.com/mys7erio/aiotorrent/blob/main/README.md Demonstrates how to download a specific file using the `SEQUENTIAL` download strategy. This strategy ensures that file pieces are always yielded in order. The `DownloadStrategy` enum is used to specify the strategy when calling the `download()` coroutine. ```python from aiotorrent import DownloadStrategy from aiotorrent import Torrent torrent = Torrent("path/to/file.torrent") file = torrent.files[1] # The download strategies available are: DownloadStrategy.DEFAULT and DownloadStrategy.SEQUENTIAL await torrent.download(file, strategy=DownloadStrategy.SEQUENTIAL) ``` -------------------------------- ### Concurrent Torrent File Downloads (Python) Source: https://context7.com/mys7erio/aiotorrent/llms.txt This Python code snippet shows how to download multiple files from a torrent concurrently using the `aiotorrent` library and `asyncio`. It creates asynchronous tasks for each file download and then waits for all tasks to complete, reporting success or failure for each. This approach significantly improves download speed by leveraging parallel processing. ```python import asyncio from aiotorrent import Torrent async def concurrent_downloads(): torrent = Torrent('multi-file.torrent') await torrent.init(dht_enabled=True) # Create download tasks for all files tasks = [] for file in torrent.files: task = asyncio.create_task(torrent.download(file)) tasks.append((file.name, task)) # Wait for all downloads to complete for name, task in tasks: try: await task print(f"✓ Completed: {name}") except Exception as e: print(f"✗ Failed: {name} - {e}") asyncio.run(concurrent_downloads()) ``` -------------------------------- ### Python: Extract Torrent Metadata with aioTorrent Source: https://context7.com/mys7erio/aiotorrent/llms.txt This Python script demonstrates how to extract basic and verbose metadata from a torrent file using the aiotorrent library. It shows how to access torrent name, size, piece length, info hash, trackers, and piece hashes. Requires the aiotorrent library. ```python import asyncio import json from aiotorrent import Torrent async def show_metadata(): # Initialize without calling init() - no network required torrent = Torrent('example.torrent') # Get basic metadata metadata = torrent.get_torrent_info(format='json', verbose=False) info = json.loads(metadata) print(f"Torrent: {info['name']}") print(f"Size: {info['size']:,} bytes") print(f"Piece length: {info['piece_len']:,} bytes") print(f"Info hash: {info['info_hash']}") print(f"Trackers: {len(info['trackers'])}") # Get verbose metadata (includes piece hashes and peer list) verbose_metadata = torrent.get_torrent_info(format='json', verbose=True) verbose_info = json.loads(verbose_metadata) print(f"Total pieces: {len(verbose_info['piece_hashmap'])}") asyncio.run(show_metadata()) ``` -------------------------------- ### Python: Display Download Progress Source: https://github.com/mys7erio/aiotorrent/blob/main/README.md This Python code snippet shows how to display the total bytes downloaded and the download progress percentage for a file using the aiotorrent library. It assumes a 'file' object with methods like get_bytes_written(), size, and get_download_progress(). ```python print(f"Download progress: {file.get_bytes_written()} / {file.size} bytes") # Output: Download progress: 1048576 / 5242880 bytes print(f"Download progress: {file.get_download_progress(precision=3)}%") # Output: Download progress: 20.152% ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.