def process_long_header(self, packet: bytes, packet_ct: Optional[bytes] = None ) -> None: """Process first packet of long transmission.""" if self.long_active: self.add_masking_packet_to_log_file(increase=len(self.assembly_pt_list)) if self.type == FILE: self.new_file_packet() try: lh, no_p_bytes, time_bytes, size_bytes, packet \ = separate_headers(packet, [ASSEMBLY_PACKET_HEADER_LENGTH] + 3*[ENCODED_INTEGER_LENGTH]) self.packets = bytes_to_int(no_p_bytes) # added by transmitter.packet.split_to_assembly_packets self.time = str(timedelta(seconds=bytes_to_int(time_bytes))) self.size = readable_size(bytes_to_int(size_bytes)) self.name = packet.split(US_BYTE)[0].decode() packet = lh + packet m_print([f'Receiving file from {self.contact.nick}:', f'{self.name} ({self.size})', f'ETA {self.time} ({self.packets} packets)'], bold=True) except (struct.error, UnicodeError, ValueError): self.add_masking_packet_to_log_file() raise FunctionReturn("Error: Received file packet had an invalid header.") self.assembly_pt_list = [packet] self.long_active = True self.is_complete = False if packet_ct is not None: self.log_ct_list = [packet_ct]
def process_long_header(self, packet: bytes) -> None: """Process first packet of long transmission.""" if self.long_active: self.add_masking_packet_to_logfile( increase=len(self.assembly_pt_list)) if self.type == FILE: self.new_file_packet() try: self.packets = bytes_to_int(packet[1:9]) self.time = str( datetime.timedelta(seconds=bytes_to_int(packet[9:17]))) self.size = readable_size(bytes_to_int(packet[17:25])) self.name = packet[25:].split(US_BYTE)[0].decode() packet = self.lh + packet[25:] box_print([ f'Receiving file from {self.contact.nick}:', f'{self.name} ({self.size})', f'ETA {self.time} ({self.packets} packets)' ]) except (struct.error, UnicodeError, ValueError): self.add_masking_packet_to_logfile() raise FunctionReturn( "Error: Received file packet had an invalid header.") self.assembly_pt_list = [packet] self.long_active = True self.is_complete = False
def get_size(path: str) -> Tuple[bytes, str]: """Get size of file in bytes and in human readable form.""" byte_size = os.path.getsize(path) if byte_size == 0: raise SoftError("Error: Target file is empty.", head_clear=True) size = int_to_bytes(byte_size) size_hr = readable_size(byte_size) return size, size_hr
def load_file_data(self) -> None: """Load file name, size and data from specified path.""" if not os.path.isfile(self.path): raise FunctionReturn("Error: File not found.") self.name = (self.path.split('/')[-1]).encode() self.name_length_check() byte_size = os.path.getsize(self.path) if byte_size == 0: raise FunctionReturn("Error: Target file is empty.") self.size = int_to_bytes(byte_size) self.size_print = readable_size(byte_size) with open(self.path, 'rb') as f: self.data = f.read()
def test_readable_size(self): sizes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] for i in range(0, 9): size = readable_size(1024**i) self.assertEqual(size, f'1.0{sizes[i]}B')