fromPacket static method

ImPacket fromPacket(
  1. String raw
)
override

fromPacket creates a ImPacket from a string packet in the format of Layrz Protocol v3.

Implementation

static ImPacket fromPacket(String raw) {
  if (!raw.startsWith('<Im>') || !raw.endsWith('</Im>')) {
    throw ParseException('Invalid identification packet, should be <Im>...</Im>');
  }

  final parts = raw.substring(4, raw.length - 5).split(';');
  if (parts.length != 4) {
    throw MalformedException('Invalid packet parts, should have 4 parts');
  }

  int? receivedCrc = int.tryParse(parts.last, radix: 16);
  int? calculatedCrc = calculateCrc("${parts.sublist(0, 3).join(';')};".codeUnits);

  if (receivedCrc != calculatedCrc) {
    throw CrcException('Invalid CRC, received: $receivedCrc, calculated: $calculatedCrc');
  }

  DateTime timestamp;
  try {
    timestamp = DateTime.fromMillisecondsSinceEpoch(int.parse(parts[0]) * 1000, isUtc: true);
  } catch (e) {
    throw MalformedException('Invalid timestamp');
  }

  return ImPacket(
    timestamp: timestamp,
    chatId: parts[1],
    message: parts[2].replaceAll('|||', ';'),
  );
}