encryptToDeviceMessagePayload method

Future<Map<String, dynamic>> encryptToDeviceMessagePayload(
  1. DeviceKeys device,
  2. String type,
  3. Map<String, dynamic> payload, {
  4. bool getFromDb = true,
})

Encryptes a ToDeviceMessage for the given device with an existing olm session. Throws NoOlmSessionFoundException if there is no olm session with this device and none could be created.

Implementation

Future<Map<String, dynamic>> encryptToDeviceMessagePayload(
    DeviceKeys device, String type, Map<String, dynamic> payload,
    {bool getFromDb = true}) async {
  final sess =
      await getOlmSessions(device.curve25519Key!, getFromDb: getFromDb);
  if (sess.isEmpty) {
    throw NoOlmSessionFoundException(device);
  }
  final fullPayload = {
    'type': type,
    'content': payload,
    'sender': client.userID,
    'keys': {'ed25519': fingerprintKey},
    'recipient': device.userId,
    'recipient_keys': {'ed25519': device.ed25519Key},
  };
  final encryptResult = sess.first.session!.encrypt(json.encode(fullPayload));
  await storeOlmSession(sess.first);
  if (encryption.olmDatabase != null) {
    await runInRoot(
        () async => encryption.olmDatabase?.setLastSentMessageUserDeviceKey(
            json.encode({
              'type': type,
              'content': payload,
            }),
            device.userId,
            device.deviceId!));
  }
  final encryptedBody = <String, dynamic>{
    'algorithm': AlgorithmTypes.olmV1Curve25519AesSha2,
    'sender_key': identityKey,
    'ciphertext': <String, dynamic>{},
  };
  encryptedBody['ciphertext'][device.curve25519Key] = {
    'type': encryptResult.type,
    'body': encryptResult.body,
  };
  return encryptedBody;
}