Created
September 24, 2017 13:05
-
-
Save DrDougPhD/1c4e1bd6646b2fb4707e8dc75bb315bd to your computer and use it in GitHub Desktop.
Print a quick summary of the files and file sizes in a BitTorrent file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bencoder | |
import sys | |
import os | |
import termcolor | |
def main(args): | |
torrent_path = args[-1] | |
if not os.path.isfile(torrent_path) or not torrent_path.endswith('.torrent'): | |
print('Usage: python {} TORRENT_PATH.torrent'.format(args[0])) | |
sys.exit(1) | |
torrent = load(path=torrent_path) | |
print(torrent) | |
def load(path): | |
with open(path, 'rb') as torrent: | |
decoded_torrent = bencoder.bdecode(torrent.read()) | |
filename = os.path.basename(path) | |
print('Torrent file: {} '.format(termcolor.colored(filename, 'green')), | |
end='') | |
if b'files' not in decoded_torrent[b'info']: | |
print('(single-file torrent)') | |
return SingleFileTorrent(info=decoded_torrent) | |
else: | |
print('(multi-file torrent)') | |
return MultiFileTorrent(info=decoded_torrent) | |
class TorrentFile(object): | |
def __init__(self, info): | |
self.decoded_torrent = info | |
@property | |
def name(self): | |
return self.decode(self.decoded_torrent[b'info'][b'name']) | |
def decode(self, binary_string): | |
try: | |
return binary_string.decode('utf-8') | |
except UnicodeDecodeError: | |
return binary_string.decode('cp1252') | |
def __str__(self): | |
return '\n'.join(['{: ^20} │ {}'.format(s, f) | |
for f,s in self.files]) | |
class SingleFileTorrent(TorrentFile): | |
@property | |
def files(self): | |
info = self.decoded_torrent[b'info'] | |
filename = self.name | |
size = info[b'length'] | |
return [(filename, size)] | |
class MultiFileTorrent(TorrentFile): | |
@property | |
def files(self): | |
info = self.decoded_torrent[b'info'] | |
root = self.name | |
files_dictionary = info[b'files'] | |
files = [] | |
for file_info in files_dictionary: | |
filepath_list = [self.decode(p) for p in file_info[b'path']] | |
filepath = os.path.join(*[root, *filepath_list]) | |
size = file_info[b'length'] | |
files.append((filepath, size)) | |
files.sort(key=lambda x: x[1], reverse=True) | |
return files | |
if __name__ == '__main__': | |
main(sys.argv) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bencoder | |
termcolor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment