encryptGroupMessagePayload method

Future<Map<String, dynamic>> encryptGroupMessagePayload(
  1. String roomId,
  2. Map<String, dynamic> payload, {
  3. String type = EventTypes.Message,
})

Encrypts the given json payload and creates a send-ready m.room.encrypted payload. This will create a new outgoingGroupSession if necessary.

Implementation

Future<Map<String, dynamic>> encryptGroupMessagePayload(
    String roomId, Map<String, dynamic> payload,
    {String type = EventTypes.Message}) async {
  payload = copyMap(payload);
  final Map<String, dynamic>? mRelatesTo = payload.remove('m.relates_to');

  // Events which only contain a m.relates_to like reactions don't need to
  // be encrypted.
  if (payload.isEmpty && mRelatesTo != null) {
    return {'m.relates_to': mRelatesTo};
  }
  final room = client.getRoomById(roomId);
  if (room == null || !room.encrypted || !enabled) {
    return payload;
  }
  if (room.encryptionAlgorithm != AlgorithmTypes.megolmV1AesSha2) {
    throw ('Unknown encryption algorithm');
  }
  if (keyManager.getOutboundGroupSession(roomId)?.isValid != true) {
    await keyManager.loadOutboundGroupSession(roomId);
  }
  await keyManager.clearOrUseOutboundGroupSession(roomId);
  if (keyManager.getOutboundGroupSession(roomId)?.isValid != true) {
    await keyManager.createOutboundGroupSession(roomId);
  }
  final sess = keyManager.getOutboundGroupSession(roomId);
  if (sess?.isValid != true) {
    throw ('Unable to create new outbound group session');
  }
  // we clone the payload as we do not want to remove 'm.relates_to' from the
  // original payload passed into this function
  payload = payload.copy();
  final payloadContent = {
    'content': payload,
    'type': type,
    'room_id': roomId,
  };
  final encryptedPayload = <String, dynamic>{
    'algorithm': AlgorithmTypes.megolmV1AesSha2,
    'ciphertext':
        sess!.outboundGroupSession!.encrypt(json.encode(payloadContent)),
    // device_id + sender_key should be removed at some point in future since
    // they're deprecated. Just left here for compatibility
    'device_id': client.deviceID,
    'sender_key': identityKey,
    'session_id': sess.outboundGroupSession!.session_id(),
    if (mRelatesTo != null) 'm.relates_to': mRelatesTo,
  };
  await keyManager.storeOutboundGroupSession(roomId, sess);
  return encryptedPayload;
}