or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

bencoding.mdindex.mdtorrent-operations.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Helper functions for common torrent-related operations including file size formatting, version information, tracker management, and torrent caching services.

3

4

## Capabilities

5

6

### Version Information

7

8

Get torrentool version information for torrent metadata.

9

10

```python { .api }

11

def get_app_version() -> str:

12

"""

13

Return full version string suitable for Torrent.created_by field.

14

15

Combines application name with version number in standard format.

16

Automatically used by Torrent.create_from() method.

17

18

Returns:

19

str: Version string in format "torrentool/X.Y.Z"

20

"""

21

```

22

23

### File Size Formatting

24

25

Convert byte sizes to human-readable format.

26

27

```python { .api }

28

def humanize_filesize(bytes_size: int) -> str:

29

"""

30

Convert bytes to human-readable file size format.

31

32

Uses binary (1024-based) units: B, KB, MB, GB, TB, PB, EB, ZB, YB.

33

Rounds to 2 decimal places for readability.

34

35

Parameters:

36

- bytes_size (int): Size in bytes

37

38

Returns:

39

str: Formatted size string (e.g., "1.5 GB", "512 MB", "0 B")

40

"""

41

```

42

43

### Torrent Caching

44

45

Upload torrent files to caching services for immediate sharing.

46

47

```python { .api }

48

def upload_to_cache_server(fpath: str) -> str:

49

"""

50

Upload .torrent file to torrage.info cache server.

51

52

Provides immediate torrent sharing capability without requiring

53

a web server. Returns direct download URL for the cached torrent.

54

55

Parameters:

56

- fpath (str): Path to .torrent file to upload

57

58

Returns:

59

str: Direct download URL for the cached torrent file

60

61

Raises:

62

RemoteUploadError: If upload fails due to network issues or server errors

63

ImportError: If 'requests' package is not installed

64

"""

65

```

66

67

### Tracker List Management

68

69

Access curated lists of open (public) BitTorrent trackers.

70

71

```python { .api }

72

def get_open_trackers_from_remote() -> List[str]:

73

"""

74

Fetch current list of open tracker URLs from remote repository.

75

76

Downloads up-to-date list of public trackers from the torrentool

77

GitHub repository. Recommended for getting latest tracker information.

78

79

Returns:

80

List[str]: List of tracker announce URLs

81

82

Raises:

83

RemoteDownloadError: If download fails due to network issues

84

ImportError: If 'requests' package is not installed

85

"""

86

87

def get_open_trackers_from_local() -> List[str]:

88

"""

89

Get list of open tracker URLs from local backup.

90

91

Returns bundled list of public trackers. Used as fallback when

92

remote list cannot be retrieved. May be less current than remote list.

93

94

Returns:

95

List[str]: List of tracker announce URLs from local backup

96

"""

97

```

98

99

## Usage Examples

100

101

### Version Information

102

103

```python

104

from torrentool.utils import get_app_version

105

from torrentool.api import Torrent

106

107

# Get version for manual metadata setting

108

version = get_app_version()

109

print(f"Using: {version}") # Output: "torrentool/1.2.0"

110

111

# Version is automatically set when creating new torrents

112

torrent = Torrent.create_from('/path/to/file')

113

print(f"Created by: {torrent.created_by}") # Output: "torrentool/1.2.0"

114

```

115

116

### File Size Formatting

117

118

```python

119

from torrentool.utils import humanize_filesize

120

from torrentool.api import Torrent

121

122

# Format file sizes for display

123

sizes = [0, 512, 1024, 1536, 1048576, 1073741824, 1099511627776]

124

125

for size in sizes:

126

formatted = humanize_filesize(size)

127

print(f"{size:>12} bytes = {formatted}")

128

129

# Output:

130

# 0 bytes = 0 B

131

# 512 bytes = 512 B

132

# 1024 bytes = 1.0 KB

133

# 1536 bytes = 1.5 KB

134

# 1048576 bytes = 1.0 MB

135

# 1073741824 bytes = 1.0 GB

136

# 1099511627776 bytes = 1.0 TB

137

138

# Use with torrent file information

139

torrent = Torrent.from_file('example.torrent')

140

print(f"Total size: {humanize_filesize(torrent.total_size)}")

141

142

for file in torrent.files:

143

size_str = humanize_filesize(file.length)

144

print(f"{file.name}: {size_str}")

145

```

146

147

### Torrent Caching

148

149

```python

150

from torrentool.utils import upload_to_cache_server

151

from torrentool.api import Torrent

152

from torrentool.exceptions import RemoteUploadError

153

154

# Create and cache a torrent for immediate sharing

155

torrent = Torrent.create_from('/path/to/my/files')

156

torrent.announce_urls = ['udp://tracker.example.com:80/announce']

157

torrent.to_file('my_files.torrent')

158

159

try:

160

# Upload to cache server

161

cache_url = upload_to_cache_server('my_files.torrent')

162

print(f"Torrent cached at: {cache_url}")

163

print("Ready for immediate download and sharing!")

164

165

# Cache URL can be shared directly with others

166

# They can download the .torrent file immediately

167

168

except RemoteUploadError as e:

169

print(f"Upload failed: {e}")

170

print("Torrent file saved locally but not cached online")

171

172

except ImportError:

173

print("Install 'requests' package to use caching: pip install requests")

174

```

175

176

### Tracker Management

177

178

```python

179

from torrentool.utils import get_open_trackers_from_remote, get_open_trackers_from_local

180

from torrentool.api import Torrent

181

from torrentool.exceptions import RemoteDownloadError

182

183

# Get tracker list for new torrent

184

try:

185

# Try to get latest tracker list from remote

186

trackers = get_open_trackers_from_remote()

187

print(f"Retrieved {len(trackers)} trackers from remote")

188

189

except RemoteDownloadError:

190

# Fall back to local list if remote fails

191

print("Remote download failed, using local tracker list")

192

trackers = get_open_trackers_from_local()

193

print(f"Using {len(trackers)} local trackers")

194

195

except ImportError:

196

print("Install 'requests' package for remote trackers: pip install requests")

197

trackers = get_open_trackers_from_local()

198

199

# Create torrent with tracker list

200

torrent = Torrent.create_from('/path/to/share')

201

torrent.announce_urls = trackers[:10] # Use first 10 trackers

202

torrent.comment = 'Torrent with public trackers'

203

torrent.to_file('public_torrent.torrent')

204

205

print("Torrent created with public trackers:")

206

for i, tracker in enumerate(torrent.announce_urls[0][:5]): # Show first 5

207

print(f" {i+1}. {tracker}")

208

```

209

210

### Combining Utilities

211

212

```python

213

from torrentool.api import Torrent

214

from torrentool.utils import (

215

get_open_trackers_from_remote,

216

get_open_trackers_from_local,

217

upload_to_cache_server,

218

humanize_filesize

219

)

220

from torrentool.exceptions import RemoteDownloadError, RemoteUploadError

221

222

def create_and_share_torrent(path, comment=None, cache=True):

223

"""Complete workflow for creating and sharing a torrent."""

224

225

# Create torrent

226

print(f"Creating torrent from: {path}")

227

torrent = Torrent.create_from(path)

228

229

# Add metadata

230

if comment:

231

torrent.comment = comment

232

233

# Get tracker list

234

try:

235

trackers = get_open_trackers_from_remote()

236

print(f"Added {len(trackers)} remote trackers")

237

except (RemoteDownloadError, ImportError):

238

trackers = get_open_trackers_from_local()

239

print(f"Added {len(trackers)} local trackers")

240

241

torrent.announce_urls = trackers

242

243

# Save torrent

244

filename = f"{torrent.name}.torrent"

245

torrent.to_file(filename)

246

247

# Display info

248

size_str = humanize_filesize(torrent.total_size)

249

print(f"Torrent created: {filename}")

250

print(f"Name: {torrent.name}")

251

print(f"Size: {size_str}")

252

print(f"Hash: {torrent.info_hash}")

253

print(f"Files: {len(torrent.files)}")

254

255

# Optional caching

256

if cache:

257

try:

258

cache_url = upload_to_cache_server(filename)

259

print(f"Cached at: {cache_url}")

260

return filename, cache_url

261

except (RemoteUploadError, ImportError) as e:

262

print(f"Caching failed: {e}")

263

264

return filename, None

265

266

# Usage

267

torrent_file, cache_url = create_and_share_torrent(

268

'/path/to/my/collection',

269

comment='My awesome collection',

270

cache=True

271

)

272

```

273

274

## Dependencies

275

276

Most utility functions have optional dependencies:

277

278

- **requests**: Required for `upload_to_cache_server()` and `get_open_trackers_from_remote()`

279

- **Installation**: `pip install requests` or `pip install torrentool[cli]`

280

281

Functions gracefully handle missing dependencies by raising ImportError with helpful messages.