-
Notifications
You must be signed in to change notification settings - Fork 0
/
torrent.py
71 lines (56 loc) · 2.29 KB
/
torrent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import math
import hashlib
import time
from bcoding import bencode, bdecode
import logging
import os
class Torrent(object):
def __init__(self):
self.torrent_file = {}
self.total_length: int = 0
self.piece_length: int = 0
self.pieces: int = 0
self.info_hash: str = ''
self.peer_id: str = ''
self.announce_list = ''
self.file_names = []
self.number_of_pieces: int = 0
def init_files(self):
root = self.torrent_file['info']['name']
if 'files' in self.torrent_file['info']:
if not os.path.exists(root):
os.mkdir(root, 0o0766 )
for file in self.torrent_file['info']['files']:
path_file = os.path.join(root, *file["path"])
if not os.path.exists(os.path.dirname(path_file)):
os.makedirs(os.path.dirname(path_file))
self.file_names.append({"path": path_file , "length": file["length"]})
self.total_length += file["length"]
else :
self.file_names.append({"path": root , "length": self.torrent_file['info']['length']})
self.total_length = self.torrent_file['info']['length']
def load_from_path(self, path):
with open(path, 'rb') as file:
contents = bdecode(file)
self.torrent_file = contents
self.piece_length = self.torrent_file['info']['piece length']
self.pieces = self.torrent_file['info']['pieces']
raw_info_hash = bencode(self.torrent_file['info'])
self.info_hash = hashlib.sha1(raw_info_hash).digest()
self.peer_id = self.generate_peer_id()
self.announce_list = self.get_trakers()
self.init_files()
self.number_of_pieces = math.ceil(self.total_length / self.piece_length)
logging.debug(self.announce_list)
logging.debug(self.file_names)
assert(self.total_length > 0)
assert(len(self.file_names) > 0)
return self
def get_trakers(self):
if 'announce-list' in self.torrent_file:
return self.torrent_file['announce-list']
else:
return [[self.torrent_file['announce']]]
def generate_peer_id(self):
seed = str(time.time())
return hashlib.sha1(seed.encode('utf-8')).digest()