0
# Torrentool
1
2
A comprehensive Python library for working with torrent files and bencoding. Torrentool enables developers to create, read, and modify torrent files programmatically, supporting operations like setting tracker URLs, calculating file hashes, and generating magnet links. It also includes bencoding utilities for encoding and decoding BitTorrent data structures and a command-line interface for creating torrents from files or directories.
3
4
## Package Information
5
6
- **Package Name**: torrentool
7
- **Language**: Python
8
- **Installation**: `pip install torrentool`
9
- **CLI Installation**: `pip install torrentool[cli]` (includes Click dependency)
10
11
## Core Imports
12
13
```python
14
from torrentool.api import Torrent, Bencode
15
```
16
17
Individual imports:
18
19
```python
20
from torrentool.torrent import Torrent, TorrentFile
21
from torrentool.bencode import Bencode
22
from torrentool.utils import upload_to_cache_server, get_open_trackers_from_local, get_open_trackers_from_remote, get_app_version, humanize_filesize
23
```
24
25
## Basic Usage
26
27
```python
28
from torrentool.api import Torrent
29
30
# Create a torrent from a file or directory
31
new_torrent = Torrent.create_from('/path/to/file_or_directory')
32
new_torrent.announce_urls = ['udp://tracker.example.com:80/announce']
33
new_torrent.comment = 'My awesome torrent'
34
new_torrent.to_file('my_torrent.torrent')
35
36
# Read and modify an existing torrent
37
existing_torrent = Torrent.from_file('existing.torrent')
38
print(f"Name: {existing_torrent.name}")
39
print(f"Size: {existing_torrent.total_size} bytes")
40
print(f"Hash: {existing_torrent.info_hash}")
41
print(f"Magnet: {existing_torrent.magnet_link}")
42
43
# Modify properties
44
existing_torrent.comment = 'Updated comment'
45
existing_torrent.webseeds = ['http://webseed.example.com/files/']
46
existing_torrent.to_file() # Save changes back to original file
47
48
# Get magnet link with specific details
49
magnet = existing_torrent.get_magnet(detailed=['tr', 'ws']) # Include trackers and webseeds
50
```
51
52
## Architecture
53
54
The library is organized around several key components:
55
56
- **Torrent class**: Main interface for creating, reading, and modifying torrent files
57
- **Bencode utilities**: Low-level encoding/decoding of bencoded data structures
58
- **CLI tools**: Command-line interface for common torrent operations
59
- **Utility functions**: Helper functions for tracker management and file uploads
60
61
## Capabilities
62
63
### Torrent File Operations
64
65
Core functionality for creating, reading, and modifying torrent files. Handles all torrent metadata including file lists, tracker URLs, creation dates, and hash calculations.
66
67
```python { .api }
68
class Torrent:
69
def __init__(self, dict_struct: dict = None): ...
70
71
@classmethod
72
def create_from(cls, src_path: Union[str, Path]) -> 'Torrent': ...
73
74
@classmethod
75
def from_file(cls, filepath: Union[str, Path]) -> 'Torrent': ...
76
77
@classmethod
78
def from_string(cls, string: str) -> 'Torrent': ...
79
80
def to_file(self, filepath: str = None): ...
81
def to_string(self) -> bytes: ...
82
def get_magnet(self, detailed: Union[bool, list, tuple, set] = True) -> str: ...
83
```
84
85
[Torrent Operations](./torrent-operations.md)
86
87
### Bencoding Utilities
88
89
Encoding and decoding functionality for bencoded data structures used in BitTorrent protocol. Supports all bencode data types including strings, integers, lists, and dictionaries.
90
91
```python { .api }
92
class Bencode:
93
@classmethod
94
def encode(cls, value: TypeEncodable) -> bytes: ...
95
96
@classmethod
97
def decode(cls, encoded: bytes, *, byte_keys: Set[str] = None) -> TypeEncodable: ...
98
99
@classmethod
100
def read_string(cls, string: Union[str, bytes], *, byte_keys: Set[str] = None) -> TypeEncodable: ...
101
102
@classmethod
103
def read_file(cls, filepath: Union[str, Path], *, byte_keys: Set[str] = None) -> TypeEncodable: ...
104
```
105
106
[Bencoding](./bencoding.md)
107
108
### Utility Functions
109
110
Helper functions for tracker management, file size formatting, and torrent caching services. Includes both local and remote tracker list management.
111
112
```python { .api }
113
def get_app_version() -> str: ...
114
def humanize_filesize(bytes_size: int) -> str: ...
115
def upload_to_cache_server(fpath: str) -> str: ...
116
def get_open_trackers_from_remote() -> List[str]: ...
117
def get_open_trackers_from_local() -> List[str]: ...
118
```
119
120
[Utilities](./utilities.md)
121
122
### Command Line Interface
123
124
Command-line tools for creating torrents and displaying torrent information. Requires Click package installation with `pip install torrentool[cli]`.
125
126
```bash
127
# Create torrent from file or directory
128
torrentool torrent create /path/to/source [OPTIONS]
129
130
# Display torrent information
131
torrentool torrent info /path/to/file.torrent
132
```
133
134
Available options for `create` command:
135
- `--dest`: Destination directory for .torrent file
136
- `--tracker`: Comma-separated tracker URLs
137
- `--open_trackers`: Add public tracker URLs automatically
138
- `--comment`: Add comment to torrent
139
- `--cache`: Upload to torrent cache service
140
141
## Types
142
143
```python { .api }
144
from typing import Union, List, Optional, Set, Tuple, NamedTuple
145
from pathlib import Path
146
from datetime import datetime
147
148
class TorrentFile(NamedTuple):
149
"""Represents a file in torrent."""
150
name: str
151
length: int
152
153
TypeEncodable = Union[str, int, list, set, tuple, dict, bytes, bytearray]
154
```
155
156
## Exceptions
157
158
```python { .api }
159
class TorrentoolException(Exception):
160
"""Base torrentool exception."""
161
162
class BencodeError(TorrentoolException):
163
"""Base exception for bencode related errors."""
164
165
class BencodeDecodingError(BencodeError):
166
"""Raised when unable to decode bencoded data."""
167
168
class BencodeEncodingError(BencodeError):
169
"""Raised when unable to encode data into bencode."""
170
171
class TorrentError(TorrentoolException):
172
"""Base exception for Torrent object related errors."""
173
174
class RemoteUploadError(TorrentoolException):
175
"""Upload to remote services failed."""
176
177
class RemoteDownloadError(TorrentoolException):
178
"""Download from remote services failed."""
179
```