0
# Torrent Operations
1
2
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.
3
4
## Capabilities
5
6
### Torrent Creation
7
8
Create new torrent files from files or directories with automatic piece calculation and hash generation.
9
10
```python { .api }
11
@classmethod
12
def create_from(cls, src_path: Union[str, Path]) -> 'Torrent':
13
"""
14
Create Torrent object from a file or directory.
15
16
Automatically calculates piece hashes and sizes based on file content.
17
Sets creation date and created_by fields automatically.
18
19
Parameters:
20
- src_path (Union[str, Path]): Path to file or directory to create torrent from
21
22
Returns:
23
Torrent: New Torrent object ready for configuration and saving
24
25
Raises:
26
TorrentError: If unable to create torrent (e.g., empty file)
27
"""
28
```
29
30
### Torrent Loading
31
32
Load existing torrent files from disk or from bencoded strings.
33
34
```python { .api }
35
@classmethod
36
def from_file(cls, filepath: Union[str, Path]) -> 'Torrent':
37
"""
38
Load Torrent object from .torrent file.
39
40
Parameters:
41
- filepath (Union[str, Path]): Path to .torrent file
42
43
Returns:
44
Torrent: Torrent object with filepath stored for future saves
45
"""
46
47
@classmethod
48
def from_string(cls, string: str) -> 'Torrent':
49
"""
50
Create Torrent object from bencoded string.
51
52
Takes bencoded data (as string or bytes) and parses it into a Torrent object.
53
The string should contain valid bencoded torrent data.
54
55
Parameters:
56
- string (str): Bencoded torrent data as string or bytes
57
58
Returns:
59
Torrent: Torrent object created from the parsed bencoded data
60
"""
61
```
62
63
### Torrent Initialization
64
65
Create empty torrent objects for manual construction.
66
67
```python { .api }
68
def __init__(self, dict_struct: dict = None):
69
"""
70
Initialize Torrent object.
71
72
Parameters:
73
- dict_struct (dict, optional): Pre-existing torrent dictionary structure.
74
If None, creates empty torrent with basic info structure.
75
"""
76
```
77
78
### Torrent Saving
79
80
Save torrent objects to files or convert to bencoded bytes.
81
82
```python { .api }
83
def to_file(self, filepath: str = None):
84
"""
85
Write Torrent object to file.
86
87
Uses previously set filepath if none provided.
88
89
Parameters:
90
- filepath (str, optional): Output file path. If None, uses stored filepath.
91
92
Raises:
93
TorrentError: If no filepath provided and none previously stored
94
"""
95
96
def to_string(self) -> bytes:
97
"""
98
Convert Torrent object to bencoded bytes.
99
100
Returns:
101
bytes: Bencoded torrent data ready for file writing or network transmission
102
"""
103
```
104
105
### Magnet Link Generation
106
107
Generate magnet links with configurable detail levels.
108
109
```python { .api }
110
def get_magnet(self, detailed: Union[bool, list, tuple, set] = True) -> str:
111
"""
112
Generate magnet link with optional additional information.
113
114
Parameters:
115
- detailed (Union[bool, list, tuple, set]):
116
- True: Include all available info (trackers, webseeds)
117
- False: Basic magnet with just info hash
118
- Iterable: Specific parameters to include ('tr' for trackers, 'ws' for webseeds)
119
120
Returns:
121
str: Magnet link in format: magnet:?xt=urn:btih:<hash>[&tr=<tracker>&ws=<webseed>...]
122
"""
123
124
@property
125
def magnet_link(self) -> str:
126
"""
127
Basic magnet link with info hash only.
128
129
Returns:
130
str: Simple magnet link without additional parameters
131
"""
132
```
133
134
### File Information
135
136
Access information about files contained in the torrent.
137
138
```python { .api }
139
@property
140
def files(self) -> List[TorrentFile]:
141
"""
142
Files in torrent.
143
144
Returns list of TorrentFile namedtuples with name and length.
145
For single-file torrents, returns list with one item.
146
For multi-file torrents, includes full relative paths.
147
148
Returns:
149
List[TorrentFile]: List of files with their sizes
150
"""
151
152
@property
153
def total_size(self) -> int:
154
"""
155
Total size of all files in torrent.
156
157
Returns:
158
int: Sum of all file sizes in bytes
159
"""
160
161
@property
162
def info_hash(self) -> Optional[str]:
163
"""
164
SHA1 hash of torrent info section (torrent identifier).
165
166
Returns None if info section is not present or incomplete.
167
This hash uniquely identifies the torrent content.
168
169
Returns:
170
Optional[str]: 40-character hexadecimal hash string, or None
171
"""
172
```
173
174
### Torrent Metadata Properties
175
176
All torrent metadata properties support both reading and writing.
177
178
```python { .api }
179
@property
180
def name(self) -> Optional[str]:
181
"""Torrent name/title."""
182
183
@name.setter
184
def name(self, val: str): ...
185
186
@property
187
def comment(self) -> Optional[str]:
188
"""Optional free-form textual comment."""
189
190
@comment.setter
191
def comment(self, val: str): ...
192
193
@property
194
def source(self) -> Optional[str]:
195
"""Optional source field, often used by private trackers."""
196
197
@source.setter
198
def source(self, val: str): ...
199
200
@property
201
def creation_date(self) -> Optional[datetime]:
202
"""Creation time of torrent in UTC."""
203
204
@creation_date.setter
205
def creation_date(self, val: datetime): ...
206
207
@property
208
def created_by(self) -> Optional[str]:
209
"""Name and version of program used to create torrent."""
210
211
@created_by.setter
212
def created_by(self, val: str): ...
213
214
@property
215
def private(self) -> bool:
216
"""Whether torrent is private (disables DHT/PEX)."""
217
218
@private.setter
219
def private(self, val: bool): ...
220
```
221
222
### Tracker Management
223
224
Configure announce URLs (trackers) for peer discovery.
225
226
```python { .api }
227
@property
228
def announce_urls(self) -> Optional[List[List[str]]]:
229
"""
230
List of lists of announce (tracker) URLs.
231
232
First inner list is primary trackers, following lists are backups.
233
Follows BEP 12 multi-tracker specification.
234
235
Returns:
236
Optional[List[List[str]]]: Nested list of tracker URLs, or empty list if none
237
"""
238
239
@announce_urls.setter
240
def announce_urls(self, val: List[str]):
241
"""
242
Set announce URLs from flat list or nested list.
243
244
Single URL or list of URLs will be set as primary tracker group.
245
Multiple lists will be treated as tiered tracker groups.
246
247
Parameters:
248
- val (List[str]): Tracker URLs to set
249
"""
250
```
251
252
### Web Seeding
253
254
Configure HTTP/FTP sources for torrent data (web seeds).
255
256
```python { .api }
257
@property
258
def webseeds(self) -> List[str]:
259
"""
260
Web seed URLs for torrent data (BEP 19).
261
262
HTTP/FTP URLs where torrent data can be retrieved.
263
Preferred over httpseeds.
264
265
Returns:
266
List[str]: List of web seed URLs
267
"""
268
269
@webseeds.setter
270
def webseeds(self, val: List[str]): ...
271
272
@property
273
def httpseeds(self) -> List[str]:
274
"""
275
HTTP seed URLs for torrent data (BEP 17).
276
277
Legacy HTTP seeding format. Prefer webseeds for new torrents.
278
279
Returns:
280
List[str]: List of HTTP seed URLs
281
"""
282
283
@httpseeds.setter
284
def httpseeds(self, val: List[str]): ...
285
```
286
287
## Usage Examples
288
289
### Creating a New Torrent
290
291
```python
292
from torrentool.api import Torrent
293
294
# Create from directory
295
torrent = Torrent.create_from('/path/to/my/files')
296
297
# Configure metadata
298
torrent.announce_urls = [
299
'udp://tracker1.example.com:80/announce',
300
'udp://tracker2.example.com:80/announce'
301
]
302
torrent.comment = 'My collection of files'
303
torrent.webseeds = ['http://backup.example.com/files/']
304
torrent.private = True
305
306
# Save to file
307
torrent.to_file('my_torrent.torrent')
308
print(f"Created torrent: {torrent.info_hash}")
309
```
310
311
### Reading and Modifying Existing Torrent
312
313
```python
314
from torrentool.api import Torrent
315
316
# Load existing torrent
317
torrent = Torrent.from_file('existing.torrent')
318
319
# Inspect content
320
print(f"Name: {torrent.name}")
321
print(f"Files: {len(torrent.files)}")
322
for file in torrent.files:
323
print(f" {file.name}: {file.length} bytes")
324
325
print(f"Total size: {torrent.total_size} bytes")
326
print(f"Creation date: {torrent.creation_date}")
327
print(f"Trackers: {torrent.announce_urls}")
328
329
# Modify and save
330
torrent.comment = "Updated comment"
331
torrent.webseeds = ['http://new-mirror.example.com/']
332
torrent.to_file() # Saves to original file
333
334
# Generate magnet link
335
magnet = torrent.get_magnet(detailed=['tr']) # Include only trackers
336
print(f"Magnet: {magnet}")
337
```