-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPieceInfo.py
177 lines (157 loc) · 6.79 KB
/
PieceInfo.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
from torrent import Torrent
from math import ceil
from BlockandPiece import Piece
import random
import colorama
from colorama import Fore, Back, Style
import heapq as hq
import time, shutil
import hashlib
import sys,os
colorama.init(autoreset=True)#auto resets your settings after every output
class PieceInfo:
def __init__(self, torrent):
self.torrent:Torrent = torrent
self.number_of_pieces = ceil(torrent.total_length / torrent.piece_length)
self.pieces = []
self.pieces_SHA1 = []
self.getSHA1()
self.generate_piece()
self.totalBlocks = self.getTotalBlocks()
self.files = self._load_files()
def generate_piece(self):
last_piece = self.number_of_pieces - 1
for i in range(self.number_of_pieces):
if i == last_piece:
piece_length = self.torrent.total_length - (self.number_of_pieces - 1) * self.torrent.piece_length
self.pieces.append(Piece(i, piece_length, self.pieces_SHA1[i]))
else:
self.pieces.append(Piece(i, self.torrent.piece_length, self.pieces_SHA1[i]))
def getSHA1(self):
for i in range(self.number_of_pieces):
start = i * 20
end = start + 20
self.pieces_SHA1.append(self.torrent.pieces[start : end])
def merge_blocks(self, index):
res = b""
for block in self.pieces[index].blocks:
res += block.data
return res
def all_piece_complete(self):
for piece in self.pieces:
if piece.is_complete() == False:
return False
return True
def getRandomPiece(self):
piece = None
while True:
piece : Piece = random.choice(self.pieces)
if piece.is_complete() == False:
return piece
def _load_files(self):
files = []
piece_offset = 0
piece_size_used = 0
for f in self.torrent.files:
current_size_file = f["length"]
file_offset = 0
while current_size_file > 0:
id_piece = int(piece_offset / self.torrent.piece_length)
piece_size = self.pieces[id_piece].piece_size - piece_size_used
if current_size_file - piece_size < 0:
file = {"length": current_size_file,
"idPiece": id_piece,
"fileOffset": file_offset,
"pieceOffset": piece_size_used,
"path": f["path"]
}
piece_offset += current_size_file
file_offset += current_size_file
piece_size_used += current_size_file
current_size_file = 0
else:
current_size_file -= piece_size
file = {"length": piece_size,
"idPiece": id_piece,
"fileOffset": file_offset,
"pieceOffset": piece_size_used,
"path": f["path"]
}
piece_offset += piece_size
file_offset += piece_size
piece_size_used = 0
files.append(file)
return files
def write_into_file(self):
master_i = 0
n = len(self.files)
if self.torrent.multipleFiles:
while master_i < n:
piece_index = self.files[master_i]['idPiece']
length = self.files[master_i]['length']
file_offset = self.files[master_i]['fileOffset']
piece_offset = self.files[master_i]['pieceOffset']
path = self.files[master_i]['path']
if self.pieces[piece_index].is_complete() == False:
continue
path_to_file = os.path.join(self.torrent.total_path, "//".join(path))
# path_to_file = self.torrent.name + "//" + path_to_file
try:
f = open(path_to_file, 'r+b') # Already existing file
except IOError:
f = open(path_to_file, 'wb') # New file
if hashlib.sha1(self.merge_blocks(master_i)).digest() == self.pieces_SHA1[master_i]:
data_to_be_written = self.merge_blocks(piece_index)[piece_offset : piece_offset + length]
f.seek(file_offset)
f.write(data_to_be_written)
master_i += 1
else:
n = self.number_of_pieces
f = open(os.path.join(self.torrent.total_path, self.torrent.name), 'wb') # New file
while master_i < n:
if self.pieces[master_i].is_complete() == False:
continue
if hashlib.sha1(self.merge_blocks(master_i)).digest() == self.pieces_SHA1[master_i]:
data_to_be_written = self.merge_blocks(master_i)
f.write(data_to_be_written)
master_i += 1
def piecesDownloaded(self):
done = 0
for piece in self.pieces:
if piece.is_complete(): done += 1
return done
def getTotalBlocks(self):
total = 0
for piece in self.pieces:
total += len(piece.blocks)
return total
def downloadBlocks(self):
blocksDone = 0
for piece in self.pieces:
for block in piece.blocks:
if block.status == 1 : blocksDone += 1
return blocksDone
def getRarestPieceMinHeap(self, connectedPeers):
piece_numberOfpeers = {}
for i in range(self.number_of_pieces):
piece_numberOfpeers[i] = 0
for peer in connectedPeers:
if peer.bit_field:
for index, piece in enumerate(peer.bit_field):
if peer.bit_field[index]:
piece_numberOfpeers[index] += 1
piece_numberOfpeers = (sorted(piece_numberOfpeers.items(), key =
lambda kv:(kv[1], kv[0])))
return piece_numberOfpeers
def printProgressBar (self, iteration, total, prefix = 'Progress', suffix = 'Complete', decimals = 1, length = 100, fill = '█', autosize = True):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
styling = '%s |%s| %s%% %s' % (prefix, fill, percent, suffix)
if autosize:
cols, _ = shutil.get_terminal_size(fallback = (length, 1))
length = cols - len(styling)
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print('\r%s' % styling.replace(fill, bar), end = '\r')
# Print New Line on Complete
if iteration == total:
print()