class ActiveTorrent(Torrent): """Represents a torrent that is in the process of being downloaded. Responsible for figuring out which strategies the factory should be passing down to the protocols and for handling all writing of file data.""" def __init__(self, client, filename): super(ActiveTorrent, self).__init__(filename) self.client = client self.uploaded = 0 self.downloaded = 0 self.factory = PeerProtocolFactory(client, self) self.tempfile = tempfile.TemporaryFile() self.to_dl = set(range(self.n_pieces)) self.tracker_url = None # set by client, need to test various urls def add_block(self, index, offset, block): piece = self.pieces[index] if piece.has_block(offset): return # same block coming in again piece.add(offset, block) if piece.is_full(): if piece.check_hash(): self.write_piece(index) self.factory.update_successful_piece(index) if not self.left: self.factory.strategy = self.factory.stop self.finish() else: # hash didn't match, reset the piece piece.clear() def write_piece(self, index): data = self.pieces[index].full_data self.tempfile.seek(self.piece_length * index) self.tempfile.write(data) self.downloaded += len(data) self.to_dl.remove(index) def next_block(self): if not self.to_dl: return index, = sample(self.to_dl, 1) offset_index = self.pieces[index].next_piece return index, offset_index def fetch_block(self, index, offset, size): self.tempfile.seek(self.piece_length * index + offset) self.uploaded += size return self.tempfile.read(size) def finish(self): self.write_files() self.client.delete_torrent(self) def connect_to_peer(self, (host, port)): from twisted.internet import reactor reactor.connectTCP(host, port, self.factory)
def __init__(self, client, filename): super(ActiveTorrent, self).__init__(filename) self.client = client self.uploaded = 0 self.downloaded = 0 self.factory = PeerProtocolFactory(client, self) self.tempfile = tempfile.TemporaryFile() self.to_dl = set(range(self.n_pieces)) self.tracker_url = None # set by client, need to test various urls