CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-torrentool

A Python library for creating, reading, and modifying torrent files with bencoding utilities and CLI tools.

Overview
Eval results
Files

torrent-operations.mddocs/

Torrent Operations

Comprehensive functionality for creating, reading, and modifying torrent files. The Torrent class provides the main interface for all torrent file operations, supporting both single files and directories, with full control over torrent metadata.

Capabilities

Torrent Creation

Create new torrent files from files or directories with automatic piece calculation and hash generation.

@classmethod
def create_from(cls, src_path: Union[str, Path]) -> 'Torrent':
    """
    Create Torrent object from a file or directory.
    
    Automatically calculates piece hashes and sizes based on file content.
    Sets creation date and created_by fields automatically.
    
    Parameters:
    - src_path (Union[str, Path]): Path to file or directory to create torrent from
    
    Returns:
    Torrent: New Torrent object ready for configuration and saving
    
    Raises:
    TorrentError: If unable to create torrent (e.g., empty file)
    """

Torrent Loading

Load existing torrent files from disk or from bencoded strings.

@classmethod
def from_file(cls, filepath: Union[str, Path]) -> 'Torrent':
    """
    Load Torrent object from .torrent file.
    
    Parameters:
    - filepath (Union[str, Path]): Path to .torrent file
    
    Returns:
    Torrent: Torrent object with filepath stored for future saves
    """

@classmethod
def from_string(cls, string: str) -> 'Torrent':
    """
    Create Torrent object from bencoded string.
    
    Takes bencoded data (as string or bytes) and parses it into a Torrent object.
    The string should contain valid bencoded torrent data.
    
    Parameters:
    - string (str): Bencoded torrent data as string or bytes
    
    Returns:
    Torrent: Torrent object created from the parsed bencoded data
    """

Torrent Initialization

Create empty torrent objects for manual construction.

def __init__(self, dict_struct: dict = None):
    """
    Initialize Torrent object.
    
    Parameters:
    - dict_struct (dict, optional): Pre-existing torrent dictionary structure.
                                   If None, creates empty torrent with basic info structure.
    """

Torrent Saving

Save torrent objects to files or convert to bencoded bytes.

def to_file(self, filepath: str = None):
    """
    Write Torrent object to file.
    
    Uses previously set filepath if none provided.
    
    Parameters:
    - filepath (str, optional): Output file path. If None, uses stored filepath.
    
    Raises:
    TorrentError: If no filepath provided and none previously stored
    """

def to_string(self) -> bytes:
    """
    Convert Torrent object to bencoded bytes.
    
    Returns:
    bytes: Bencoded torrent data ready for file writing or network transmission
    """

Magnet Link Generation

Generate magnet links with configurable detail levels.

def get_magnet(self, detailed: Union[bool, list, tuple, set] = True) -> str:
    """
    Generate magnet link with optional additional information.
    
    Parameters:
    - detailed (Union[bool, list, tuple, set]): 
        - True: Include all available info (trackers, webseeds)
        - False: Basic magnet with just info hash
        - Iterable: Specific parameters to include ('tr' for trackers, 'ws' for webseeds)
    
    Returns:
    str: Magnet link in format: magnet:?xt=urn:btih:<hash>[&tr=<tracker>&ws=<webseed>...]
    """

@property
def magnet_link(self) -> str:
    """
    Basic magnet link with info hash only.
    
    Returns:
    str: Simple magnet link without additional parameters
    """

File Information

Access information about files contained in the torrent.

@property
def files(self) -> List[TorrentFile]:
    """
    Files in torrent.
    
    Returns list of TorrentFile namedtuples with name and length.
    For single-file torrents, returns list with one item.
    For multi-file torrents, includes full relative paths.
    
    Returns:
    List[TorrentFile]: List of files with their sizes
    """

@property
def total_size(self) -> int:
    """
    Total size of all files in torrent.
    
    Returns:
    int: Sum of all file sizes in bytes
    """

@property
def info_hash(self) -> Optional[str]:
    """
    SHA1 hash of torrent info section (torrent identifier).
    
    Returns None if info section is not present or incomplete.
    This hash uniquely identifies the torrent content.
    
    Returns:
    Optional[str]: 40-character hexadecimal hash string, or None
    """

Torrent Metadata Properties

All torrent metadata properties support both reading and writing.

@property
def name(self) -> Optional[str]:
    """Torrent name/title."""

@name.setter
def name(self, val: str): ...

@property
def comment(self) -> Optional[str]:
    """Optional free-form textual comment."""

@comment.setter
def comment(self, val: str): ...

@property
def source(self) -> Optional[str]:
    """Optional source field, often used by private trackers."""

@source.setter
def source(self, val: str): ...

@property
def creation_date(self) -> Optional[datetime]:
    """Creation time of torrent in UTC."""

@creation_date.setter
def creation_date(self, val: datetime): ...

@property
def created_by(self) -> Optional[str]:
    """Name and version of program used to create torrent."""

@created_by.setter
def created_by(self, val: str): ...

@property
def private(self) -> bool:
    """Whether torrent is private (disables DHT/PEX)."""

@private.setter
def private(self, val: bool): ...

Tracker Management

Configure announce URLs (trackers) for peer discovery.

@property
def announce_urls(self) -> Optional[List[List[str]]]:
    """
    List of lists of announce (tracker) URLs.
    
    First inner list is primary trackers, following lists are backups.
    Follows BEP 12 multi-tracker specification.
    
    Returns:
    Optional[List[List[str]]]: Nested list of tracker URLs, or empty list if none
    """

@announce_urls.setter
def announce_urls(self, val: List[str]):
    """
    Set announce URLs from flat list or nested list.
    
    Single URL or list of URLs will be set as primary tracker group.
    Multiple lists will be treated as tiered tracker groups.
    
    Parameters:
    - val (List[str]): Tracker URLs to set
    """

Web Seeding

Configure HTTP/FTP sources for torrent data (web seeds).

@property
def webseeds(self) -> List[str]:
    """
    Web seed URLs for torrent data (BEP 19).
    
    HTTP/FTP URLs where torrent data can be retrieved.
    Preferred over httpseeds.
    
    Returns:
    List[str]: List of web seed URLs
    """

@webseeds.setter
def webseeds(self, val: List[str]): ...

@property
def httpseeds(self) -> List[str]:
    """
    HTTP seed URLs for torrent data (BEP 17).
    
    Legacy HTTP seeding format. Prefer webseeds for new torrents.
    
    Returns:
    List[str]: List of HTTP seed URLs
    """

@httpseeds.setter
def httpseeds(self, val: List[str]): ...

Usage Examples

Creating a New Torrent

from torrentool.api import Torrent

# Create from directory
torrent = Torrent.create_from('/path/to/my/files')

# Configure metadata
torrent.announce_urls = [
    'udp://tracker1.example.com:80/announce',
    'udp://tracker2.example.com:80/announce'
]
torrent.comment = 'My collection of files'
torrent.webseeds = ['http://backup.example.com/files/']
torrent.private = True

# Save to file
torrent.to_file('my_torrent.torrent')
print(f"Created torrent: {torrent.info_hash}")

Reading and Modifying Existing Torrent

from torrentool.api import Torrent

# Load existing torrent
torrent = Torrent.from_file('existing.torrent')

# Inspect content
print(f"Name: {torrent.name}")
print(f"Files: {len(torrent.files)}")
for file in torrent.files:
    print(f"  {file.name}: {file.length} bytes")

print(f"Total size: {torrent.total_size} bytes")
print(f"Creation date: {torrent.creation_date}")
print(f"Trackers: {torrent.announce_urls}")

# Modify and save
torrent.comment = "Updated comment"
torrent.webseeds = ['http://new-mirror.example.com/']
torrent.to_file()  # Saves to original file

# Generate magnet link
magnet = torrent.get_magnet(detailed=['tr'])  # Include only trackers
print(f"Magnet: {magnet}")

Install with Tessl CLI

npx tessl i tessl/pypi-torrentool

docs

bencoding.md

index.md

torrent-operations.md

utilities.md

tile.json