import Packets.Packet as p import Packets.HeaderPacket as h import lzma import msgpack import random import sys import math # Reassemble method # Test # Polymorph to accept payload array, done # Create packet instance with payload # Add to and from node ids # Node id generation, random, checked against existing ids # DO NOT CHANGE DATA SIZE UNLESS YOU KNOW WHAT YOURE DOING class Packets: def __init__( self, bytesObject, sender, senderDisplayName, recipient, recipientNode, dataSize=128, wantFullResponse=False, packetsClass=None, ): if isinstance(bytesObject, list): # TODO: instantiating HeaderPacket correctly packets = [h.Header(bytesObject[0])] for packet in bytesObject: packets.append( p.Packet( packet["data"], packetsID=packet["packetsID"], packetNumber=packet["packetNumber"], packetsClass=packetsClass, ) ) self.packets = packets else: bytesObject = lzma.compress(bytesObject) packets = [] self.packetsID = random.randrange(0, 999999) pnum = 1 blen = math.ceil(len(bytesObject) / dataSize) tb = b"" for it in range(blen): if it >= (blen - 1): b = bytesObject[it * dataSize :] else: b = bytesObject[it * dataSize : (it * dataSize + dataSize)] packets.append( p.Packet(b, self.packetsID, pnum, packetsClass=packetsClass) ) pnum += 1 tb += b packets.insert( 0, h.Header( self.packetsID, pnum, sender, senderDisplayName, recipient, recipientNode, wantFullResponse=wantFullResponse, packetsClass=packetsClass, ), ) for it in range(pnum): packet = msgpack.loads(packets[it].dump()) packet["packetCount"] = pnum packets[it] = msgpack.dumps(packet) self.packets = packets def get(self): return self.packets def reassemble(self, cm): data = b"" for it in range(1, int(cm["packetCount"])): data += cm["data"][cm["dataOrder"].index(it)] res = msgpack.loads(lzma.decompress(data)) return res