/*
 *   Famedly Matrix SDK
 *   Copyright (C) 2019, 2020 Famedly GmbH
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as
 *   published by the Free Software Foundation, either version 3 of the
 *   License, or (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see .
 */
import 'dart:convert';
import 'package:olm/olm.dart' as olm;
import './encryption.dart';
import './utils/outbound_group_session.dart';
import './utils/session_key.dart';
import '../famedlysdk.dart';
import '../matrix_api.dart';
import '../src/database/database.dart';
import '../matrix_api/utils/logs.dart';
import '../src/utils/run_in_background.dart';
import '../src/utils/run_in_root.dart';
import '../matrix_api/utils/try_get_map_extension.dart';
const MEGOLM_KEY = EventTypes.MegolmBackup;
class KeyManager {
  final Encryption encryption;
  Client get client => encryption.client;
  final outgoingShareRequests = {};
  final incomingShareRequests = {};
  final _inboundGroupSessions = >{};
  final _outboundGroupSessions = {};
  final Set _loadedOutboundGroupSessions = {};
  final Set _requestedSessionIds = {};
  KeyManager(this.encryption) {
    encryption.ssss.setValidator(MEGOLM_KEY, (String secret) async {
      final keyObj = olm.PkDecryption();
      try {
        final info = await getRoomKeysBackupInfo(false);
        if (info.algorithm != RoomKeysAlgorithmType.v1Curve25519AesSha2) {
          return false;
        }
        return keyObj.init_with_private_key(base64.decode(secret)) ==
            info.authData['public_key'];
      } catch (_) {
        return false;
      } finally {
        keyObj.free();
      }
    });
    encryption.ssss.setCacheCallback(MEGOLM_KEY, (String secret) {
      // we got a megolm key cached, clear our requested keys and try to re-decrypt
      // last events
      _requestedSessionIds.clear();
      for (final room in client.rooms) {
        final lastEvent = room.lastEvent;
        if (lastEvent.type == EventTypes.Encrypted &&
            lastEvent.content['can_request_session'] == true) {
          try {
            maybeAutoRequest(room.id, lastEvent.content['session_id'],
                lastEvent.content['sener_key']);
          } catch (_) {
            // dispose
          }
        }
      }
    });
  }
  bool get enabled => client.accountData[MEGOLM_KEY] != null;
  /// clear all cached inbound group sessions. useful for testing
  void clearInboundGroupSessions() {
    _inboundGroupSessions.clear();
  }
  void setInboundGroupSession(String roomId, String sessionId, String senderKey,
      Map content,
      {bool forwarded = false,
      Map senderClaimedKeys,
      bool uploaded = false,
      Map> allowedAtIndex}) {
    senderClaimedKeys ??= {};
    if (!senderClaimedKeys.containsKey('ed25519')) {
      final device = client.getUserDeviceKeysByCurve25519Key(senderKey);
      if (device != null) {
        senderClaimedKeys['ed25519'] = device.ed25519Key;
      }
    }
    final oldSession =
        getInboundGroupSession(roomId, sessionId, senderKey, otherRooms: false);
    if (content['algorithm'] != AlgorithmTypes.megolmV1AesSha2) {
      return;
    }
    olm.InboundGroupSession inboundGroupSession;
    try {
      inboundGroupSession = olm.InboundGroupSession();
      if (forwarded) {
        inboundGroupSession.import_session(content['session_key']);
      } else {
        inboundGroupSession.create(content['session_key']);
      }
    } catch (e, s) {
      inboundGroupSession.free();
      Logs().e('[LibOlm] Could not create new InboundGroupSession', e, s);
      return;
    }
    final newSession = SessionKey(
      content: content,
      inboundGroupSession: inboundGroupSession,
      indexes: {},
      roomId: roomId,
      sessionId: sessionId,
      key: client.userID,
      senderKey: senderKey,
      senderClaimedKeys: senderClaimedKeys,
      allowedAtIndex: allowedAtIndex,
    );
    final oldFirstIndex =
        oldSession?.inboundGroupSession?.first_known_index() ?? 0;
    final newFirstIndex = newSession.inboundGroupSession.first_known_index();
    if (oldSession == null ||
        newFirstIndex < oldFirstIndex ||
        (oldFirstIndex == newFirstIndex &&
            newSession.forwardingCurve25519KeyChain.length <
                oldSession.forwardingCurve25519KeyChain.length)) {
      // use new session
      oldSession?.dispose();
    } else {
      // we are gonna keep our old session
      newSession.dispose();
      return;
    }
    if (!_inboundGroupSessions.containsKey(roomId)) {
      _inboundGroupSessions[roomId] = {};
    }
    _inboundGroupSessions[roomId][sessionId] = newSession;
    client.database
        ?.storeInboundGroupSession(
      client.id,
      roomId,
      sessionId,
      inboundGroupSession.pickle(client.userID),
      json.encode(content),
      json.encode({}),
      json.encode(allowedAtIndex ?? {}),
      senderKey,
      json.encode(senderClaimedKeys),
    )
        ?.then((_) {
      if (uploaded) {
        client.database
            .markInboundGroupSessionAsUploaded(client.id, roomId, sessionId);
      }
    });
    final room = client.getRoomById(roomId);
    if (room != null) {
      // attempt to decrypt the last event
      final event = room.getState(EventTypes.Encrypted);
      if (event != null && event.content['session_id'] == sessionId) {
        encryption.decryptRoomEvent(roomId, event, store: true);
      }
      // and finally broadcast the new session
      room.onSessionKeyReceived.add(sessionId);
    }
  }
  SessionKey getInboundGroupSession(
      String roomId, String sessionId, String senderKey,
      {bool otherRooms = true}) {
    if (_inboundGroupSessions.containsKey(roomId) &&
        _inboundGroupSessions[roomId].containsKey(sessionId)) {
      final sess = _inboundGroupSessions[roomId][sessionId];
      if (sess.senderKey != senderKey && sess.senderKey.isNotEmpty) {
        return null;
      }
      return sess;
    }
    if (!otherRooms) {
      return null;
    }
    // search if this session id is *somehow* found in another room
    for (final val in _inboundGroupSessions.values) {
      if (val.containsKey(sessionId)) {
        final sess = val[sessionId];
        if (sess.senderKey != senderKey && sess.senderKey.isNotEmpty) {
          return null;
        }
        return sess;
      }
    }
    return null;
  }
  /// Attempt auto-request for a key
  void maybeAutoRequest(String roomId, String sessionId, String senderKey) {
    final room = client.getRoomById(roomId);
    final requestIdent = '$roomId|$sessionId|$senderKey';
    if (client.enableE2eeRecovery &&
        room != null &&
        !_requestedSessionIds.contains(requestIdent) &&
        !client.isUnknownSession) {
      // do e2ee recovery
      _requestedSessionIds.add(requestIdent);
      runInRoot(
          () => request(room, sessionId, senderKey, onlineKeyBackupOnly: true));
    }
  }
  /// Loads an inbound group session
  Future loadInboundGroupSession(
      String roomId, String sessionId, String senderKey) async {
    if (roomId == null || sessionId == null || senderKey == null) {
      return null;
    }
    if (_inboundGroupSessions.containsKey(roomId) &&
        _inboundGroupSessions[roomId].containsKey(sessionId)) {
      final sess = _inboundGroupSessions[roomId][sessionId];
      if (sess.senderKey != senderKey && sess.senderKey.isNotEmpty) {
        return null; // sender keys do not match....better not do anything
      }
      return sess; // nothing to do
    }
    final session = await client.database
        ?.getDbInboundGroupSession(client.id, roomId, sessionId);
    if (session == null) {
      return null;
    }
    if (!_inboundGroupSessions.containsKey(roomId)) {
      _inboundGroupSessions[roomId] = {};
    }
    final sess = SessionKey.fromDb(session, client.userID);
    if (!sess.isValid ||
        (sess.senderKey.isNotEmpty && sess.senderKey != senderKey)) {
      return null;
    }
    _inboundGroupSessions[roomId][sessionId] = sess;
    return sess;
  }
  Map> _getDeviceKeyIdMap(
      List deviceKeys) {
    final deviceKeyIds = >{};
    for (final device in deviceKeys) {
      if (!deviceKeyIds.containsKey(device.userId)) {
        deviceKeyIds[device.userId] = {};
      }
      deviceKeyIds[device.userId][device.deviceId] = !device.encryptToDevice;
    }
    return deviceKeyIds;
  }
  /// clear all cached inbound group sessions. useful for testing
  void clearOutboundGroupSessions() {
    _outboundGroupSessions.clear();
  }
  /// Clears the existing outboundGroupSession but first checks if the participating
  /// devices have been changed. Returns false if the session has not been cleared because
  /// it wasn't necessary. Otherwise returns true.
  Future clearOrUseOutboundGroupSession(String roomId,
      {bool wipe = false}) async {
    final room = client.getRoomById(roomId);
    final sess = getOutboundGroupSession(roomId);
    if (room == null || sess == null) {
      return true;
    }
    if (!wipe) {
      // first check if it needs to be rotated
      final encryptionContent = room.getState(EventTypes.Encryption)?.content;
      final maxMessages = encryptionContent != null &&
              encryptionContent['rotation_period_msgs'] is int
          ? encryptionContent['rotation_period_msgs']
          : 100;
      final maxAge = encryptionContent != null &&
              encryptionContent['rotation_period_ms'] is int
          ? encryptionContent['rotation_period_ms']
          : 604800000; // default of one week
      if (sess.sentMessages >= maxMessages ||
          sess.creationTime
              .add(Duration(milliseconds: maxAge))
              .isBefore(DateTime.now())) {
        wipe = true;
      }
    }
    final inboundSess = await loadInboundGroupSession(room.id,
        sess.outboundGroupSession.session_id(), encryption.identityKey);
    if (!wipe) {
      // next check if the devices in the room changed
      final devicesToReceive = [];
      final newDeviceKeys = await room.getUserDeviceKeys();
      final newDeviceKeyIds = _getDeviceKeyIdMap(newDeviceKeys);
      // first check for user differences
      final oldUserIds = Set.from(sess.devices.keys);
      final newUserIds = Set.from(newDeviceKeyIds.keys);
      if (oldUserIds.difference(newUserIds).isNotEmpty) {
        // a user left the room, we must wipe the session
        wipe = true;
      } else {
        final newUsers = newUserIds.difference(oldUserIds);
        if (newUsers.isNotEmpty) {
          // new user! Gotta send the megolm session to them
          devicesToReceive
              .addAll(newDeviceKeys.where((d) => newUsers.contains(d.userId)));
        }
        // okay, now we must test all the individual user devices, if anything new got blocked
        // or if we need to send to any new devices.
        // for this it is enough if we iterate over the old user Ids, as the new ones already have the needed keys in the list.
        // we also know that all the old user IDs appear in the old one, else we have already wiped the session
        for (final userId in oldUserIds) {
          final oldBlockedDevices = Set.from(sess.devices[userId].entries
              .where((e) => e.value)
              .map((e) => e.key));
          final newBlockedDevices = Set.from(newDeviceKeyIds[userId]
              .entries
              .where((e) => e.value)
              .map((e) => e.key));
          // we don't really care about old devices that got dropped (deleted), we only care if new ones got added and if new ones got blocked
          // check if new devices got blocked
          if (newBlockedDevices.difference(oldBlockedDevices).isNotEmpty) {
            wipe = true;
            break;
          }
          // and now add all the new devices!
          final oldDeviceIds = Set.from(sess.devices[userId].keys);
          final newDeviceIds = Set.from(newDeviceKeyIds[userId].keys);
          final newDevices = newDeviceIds.difference(oldDeviceIds);
          if (newDeviceIds.isNotEmpty) {
            devicesToReceive.addAll(newDeviceKeys.where(
                (d) => d.userId == userId && newDevices.contains(d.deviceId)));
          }
        }
      }
      if (!wipe) {
        // okay, we use the outbound group session!
        sess.sentMessages++;
        sess.devices = newDeviceKeyIds;
        final rawSession = {
          'algorithm': AlgorithmTypes.megolmV1AesSha2,
          'room_id': room.id,
          'session_id': sess.outboundGroupSession.session_id(),
          'session_key': sess.outboundGroupSession.session_key(),
        };
        try {
          devicesToReceive.removeWhere((k) => k.blocked);
          if (devicesToReceive.isNotEmpty) {
            // update allowedAtIndex
            for (final device in devicesToReceive) {
              inboundSess.allowedAtIndex[device.userId] ??= {};
              if (!inboundSess.allowedAtIndex[device.userId]
                      .containsKey(device.deviceId) ||
                  inboundSess.allowedAtIndex[device.userId][device.deviceId] >
                      sess.outboundGroupSession.message_index()) {
                inboundSess.allowedAtIndex[device.userId][device.deviceId] =
                    sess.outboundGroupSession.message_index();
              }
            }
            if (client.database != null) {
              await client.database.updateInboundGroupSessionAllowedAtIndex(
                  json.encode(inboundSess.allowedAtIndex),
                  client.id,
                  room.id,
                  sess.outboundGroupSession.session_id());
            }
            // send out the key
            await client.sendToDeviceEncrypted(
                devicesToReceive, EventTypes.RoomKey, rawSession);
          }
        } catch (e, s) {
          Logs().e(
              '[LibOlm] Unable to re-send the session key at later index to new devices',
              e,
              s);
        }
        return false;
      }
    }
    sess.dispose();
    _outboundGroupSessions.remove(roomId);
    await client.database?.removeOutboundGroupSession(client.id, roomId);
    return true;
  }
  Future storeOutboundGroupSession(
      String roomId, OutboundGroupSession sess) async {
    if (sess == null) {
      return;
    }
    await client.database?.storeOutboundGroupSession(
        client.id,
        roomId,
        sess.outboundGroupSession.pickle(client.userID),
        json.encode(sess.devices),
        sess.creationTime.millisecondsSinceEpoch,
        sess.sentMessages);
  }
  final Map>
      _pendingNewOutboundGroupSessions = {};
  Future createOutboundGroupSession(String roomId) async {
    if (_pendingNewOutboundGroupSessions.containsKey(roomId)) {
      return _pendingNewOutboundGroupSessions[roomId];
    }
    _pendingNewOutboundGroupSessions[roomId] =
        _createOutboundGroupSession(roomId);
    await _pendingNewOutboundGroupSessions[roomId];
    return _pendingNewOutboundGroupSessions.remove(roomId);
  }
  Future _createOutboundGroupSession(
      String roomId) async {
    await clearOrUseOutboundGroupSession(roomId, wipe: true);
    final room = client.getRoomById(roomId);
    if (room == null) {
      return null;
    }
    final deviceKeys = await room.getUserDeviceKeys();
    final deviceKeyIds = _getDeviceKeyIdMap(deviceKeys);
    deviceKeys.removeWhere((k) => !k.encryptToDevice);
    final outboundGroupSession = olm.OutboundGroupSession();
    try {
      outboundGroupSession.create();
    } catch (e, s) {
      outboundGroupSession.free();
      Logs().e('[LibOlm] Unable to create new outboundGroupSession', e, s);
      return null;
    }
    final rawSession = {
      'algorithm': AlgorithmTypes.megolmV1AesSha2,
      'room_id': room.id,
      'session_id': outboundGroupSession.session_id(),
      'session_key': outboundGroupSession.session_key(),
    };
    final allowedAtIndex = >{};
    for (final device in deviceKeys) {
      allowedAtIndex[device.userId] ??= {};
      allowedAtIndex[device.userId][device.deviceId] =
          outboundGroupSession.message_index();
    }
    setInboundGroupSession(
        roomId, rawSession['session_id'], encryption.identityKey, rawSession,
        allowedAtIndex: allowedAtIndex);
    final sess = OutboundGroupSession(
      devices: deviceKeyIds,
      creationTime: DateTime.now(),
      outboundGroupSession: outboundGroupSession,
      sentMessages: 0,
      key: client.userID,
    );
    try {
      await client.sendToDeviceEncrypted(
          deviceKeys, EventTypes.RoomKey, rawSession);
      await storeOutboundGroupSession(roomId, sess);
      _outboundGroupSessions[roomId] = sess;
    } catch (e, s) {
      Logs().e(
          '[LibOlm] Unable to send the session key to the participating devices',
          e,
          s);
      sess.dispose();
      return null;
    }
    return sess;
  }
  OutboundGroupSession getOutboundGroupSession(String roomId) {
    return _outboundGroupSessions[roomId];
  }
  Future loadOutboundGroupSession(String roomId) async {
    if (_loadedOutboundGroupSessions.contains(roomId) ||
        _outboundGroupSessions.containsKey(roomId) ||
        client.database == null) {
      return; // nothing to do
    }
    _loadedOutboundGroupSessions.add(roomId);
    final session =
        await client.database.getDbOutboundGroupSession(client.id, roomId);
    if (session == null) {
      return;
    }
    final sess = OutboundGroupSession.fromDb(session, client.userID);
    if (!sess.isValid) {
      return;
    }
    _outboundGroupSessions[roomId] = sess;
  }
  Future isCached() async {
    if (!enabled) {
      return false;
    }
    return (await encryption.ssss.getCached(MEGOLM_KEY)) != null;
  }
  RoomKeysVersionResponse _roomKeysVersionCache;
  DateTime _roomKeysVersionCacheDate;
  Future getRoomKeysBackupInfo(
      [bool useCache = true]) async {
    if (_roomKeysVersionCache != null &&
        _roomKeysVersionCacheDate != null &&
        useCache &&
        DateTime.now()
            .subtract(Duration(minutes: 5))
            .isBefore(_roomKeysVersionCacheDate)) {
      return _roomKeysVersionCache;
    }
    _roomKeysVersionCache = await client.getRoomKeysBackup();
    _roomKeysVersionCacheDate = DateTime.now();
    return _roomKeysVersionCache;
  }
  Future loadFromResponse(RoomKeys keys) async {
    if (!(await isCached())) {
      return;
    }
    final privateKey =
        base64.decode(await encryption.ssss.getCached(MEGOLM_KEY));
    final decryption = olm.PkDecryption();
    final info = await getRoomKeysBackupInfo();
    String backupPubKey;
    try {
      backupPubKey = decryption.init_with_private_key(privateKey);
      if (backupPubKey == null ||
          info.algorithm != RoomKeysAlgorithmType.v1Curve25519AesSha2 ||
          info.authData['public_key'] != backupPubKey) {
        return;
      }
      for (final roomEntry in keys.rooms.entries) {
        final roomId = roomEntry.key;
        for (final sessionEntry in roomEntry.value.sessions.entries) {
          final sessionId = sessionEntry.key;
          final session = sessionEntry.value;
          final firstMessageIndex = session.firstMessageIndex;
          final forwardedCount = session.forwardedCount;
          final isVerified = session.isVerified;
          final sessionData = session.sessionData;
          if (firstMessageIndex == null ||
              forwardedCount == null ||
              isVerified == null ||
              !(sessionData is Map)) {
            continue;
          }
          Map decrypted;
          try {
            decrypted = json.decode(decryption.decrypt(sessionData['ephemeral'],
                sessionData['mac'], sessionData['ciphertext']));
          } catch (e, s) {
            Logs().e('[LibOlm] Error decrypting room key', e, s);
          }
          if (decrypted != null) {
            decrypted['session_id'] = sessionId;
            decrypted['room_id'] = roomId;
            setInboundGroupSession(
                roomId, sessionId, decrypted['sender_key'], decrypted,
                forwarded: true,
                senderClaimedKeys: decrypted['sender_claimed_keys'] != null
                    ? Map.from(decrypted['sender_claimed_keys'])
                    : null,
                uploaded: true);
          }
        }
      }
    } finally {
      decryption.free();
    }
  }
  Future loadSingleKey(String roomId, String sessionId) async {
    final info = await getRoomKeysBackupInfo();
    final ret =
        await client.getRoomKeysSingleKey(roomId, sessionId, info.version);
    final keys = RoomKeys.fromJson({
      'rooms': {
        roomId: {
          'sessions': {
            sessionId: ret.toJson(),
          },
        },
      },
    });
    await loadFromResponse(keys);
  }
  /// Request a certain key from another device
  Future request(
    Room room,
    String sessionId,
    String senderKey, {
    bool tryOnlineBackup = true,
    bool onlineKeyBackupOnly = false,
  }) async {
    if (tryOnlineBackup && await isCached()) {
      // let's first check our online key backup store thingy...
      var hadPreviously =
          getInboundGroupSession(room.id, sessionId, senderKey) != null;
      try {
        await loadSingleKey(room.id, sessionId);
      } catch (err, stacktrace) {
        if (err is MatrixException && err.errcode == 'M_NOT_FOUND') {
          Logs().i(
              '[KeyManager] Key not in online key backup, requesting it from other devices...');
        } else {
          Logs().e('[KeyManager] Failed to access online key backup', err,
              stacktrace);
        }
      }
      // TODO: also don't request from others if we have an index of 0 now
      if (!hadPreviously &&
          getInboundGroupSession(room.id, sessionId, senderKey) != null) {
        return; // we managed to load the session from online backup, no need to care about it now
      }
    }
    if (onlineKeyBackupOnly) {
      return; // we only want to do the online key backup
    }
    try {
      // while we just send the to-device event to '*', we still need to save the
      // devices themself to know where to send the cancel to after receiving a reply
      final devices = await room.getUserDeviceKeys();
      final requestId = client.generateUniqueTransactionId();
      final request = KeyManagerKeyShareRequest(
        requestId: requestId,
        devices: devices,
        room: room,
        sessionId: sessionId,
        senderKey: senderKey,
      );
      final userList = await room.requestParticipants();
      await client.sendToDevicesOfUserIds(
        userList.map((u) => u.id).toSet(),
        EventTypes.RoomKeyRequest,
        {
          'action': 'request',
          'body': {
            'algorithm': AlgorithmTypes.megolmV1AesSha2,
            'room_id': room.id,
            'sender_key': senderKey,
            'session_id': sessionId,
          },
          'request_id': requestId,
          'requesting_device_id': client.deviceID,
        },
      );
      outgoingShareRequests[request.requestId] = request;
    } catch (e, s) {
      Logs().e('[Key Manager] Sending key verification request failed', e, s);
    }
  }
  bool _isUploadingKeys = false;
  Future backgroundTasks() async {
    if (_isUploadingKeys || client.database == null) {
      return;
    }
    _isUploadingKeys = true;
    try {
      if (!(await isCached())) {
        return; // we can't backup anyways
      }
      final dbSessions =
          await client.database.getInboundGroupSessionsToUpload().get();
      if (dbSessions.isEmpty) {
        return; // nothing to do
      }
      final privateKey =
          base64.decode(await encryption.ssss.getCached(MEGOLM_KEY));
      // decryption is needed to calculate the public key and thus see if the claimed information is in fact valid
      final decryption = olm.PkDecryption();
      final info = await getRoomKeysBackupInfo(false);
      String backupPubKey;
      try {
        backupPubKey = decryption.init_with_private_key(privateKey);
        if (backupPubKey == null ||
            info.algorithm != RoomKeysAlgorithmType.v1Curve25519AesSha2 ||
            info.authData['public_key'] != backupPubKey) {
          return;
        }
        final args = _GenerateUploadKeysArgs(
          pubkey: backupPubKey,
          dbSessions: <_DbInboundGroupSessionBundle>[],
          userId: client.userID,
        );
        // we need to calculate verified beforehand, as else we pass a closure to an isolate
        // with 500 keys they do, however, noticably block the UI, which is why we give brief async suspentions in here
        // so that the event loop can progress
        var i = 0;
        for (final dbSession in dbSessions) {
          final device =
              client.getUserDeviceKeysByCurve25519Key(dbSession.senderKey);
          args.dbSessions.add(_DbInboundGroupSessionBundle(
            dbSession: dbSession,
            verified: device?.verified ?? false,
          ));
          i++;
          if (i > 10) {
            await Future.delayed(Duration(milliseconds: 1));
            i = 0;
          }
        }
        final roomKeys =
            await runInBackground(
                _generateUploadKeys, args);
        Logs().i('[Key Manager] Uploading ${dbSessions.length} room keys...');
        // upload the payload...
        await client.storeRoomKeys(info.version, roomKeys);
        // and now finally mark all the keys as uploaded
        // no need to optimze this, as we only run it so seldomly and almost never with many keys at once
        for (final dbSession in dbSessions) {
          await client.database.markInboundGroupSessionAsUploaded(
              client.id, dbSession.roomId, dbSession.sessionId);
        }
      } finally {
        decryption.free();
      }
    } catch (e, s) {
      Logs().e('[Key Manager] Error uploading room keys', e, s);
    } finally {
      _isUploadingKeys = false;
    }
  }
  /// Handle an incoming to_device event that is related to key sharing
  Future handleToDeviceEvent(ToDeviceEvent event) async {
    if (event.type == EventTypes.RoomKeyRequest) {
      if (!(event.content['request_id'] is String)) {
        return; // invalid event
      }
      if (event.content['action'] == 'request') {
        // we are *receiving* a request
        Logs().i('[KeyManager] Received key sharing request...');
        if (!event.content.containsKey('body')) {
          Logs().i('[KeyManager] No body, doing nothing');
          return; // no body
        }
        if (!client.userDeviceKeys.containsKey(event.sender) ||
            !client.userDeviceKeys[event.sender].deviceKeys
                .containsKey(event.content['requesting_device_id'])) {
          Logs().i('[KeyManager] Device not found, doing nothing');
          return; // device not found
        }
        final device = client.userDeviceKeys[event.sender]
            .deviceKeys[event.content['requesting_device_id']];
        if (device.userId == client.userID &&
            device.deviceId == client.deviceID) {
          Logs().i('[KeyManager] Request is by ourself, ignoring');
          return; // ignore requests by ourself
        }
        final room = client.getRoomById(event.content['body']['room_id']);
        if (room == null) {
          Logs().i('[KeyManager] Unknown room, ignoring');
          return; // unknown room
        }
        final sessionId = event.content['body']['session_id'];
        final senderKey = event.content['body']['sender_key'];
        // okay, let's see if we have this session at all
        final session =
            await loadInboundGroupSession(room.id, sessionId, senderKey);
        if (session == null) {
          Logs().i('[KeyManager] Unknown session, ignoring');
          return; // we don't have this session anyways
        }
        final request = KeyManagerKeyShareRequest(
          requestId: event.content['request_id'],
          devices: [device],
          room: room,
          sessionId: sessionId,
          senderKey: senderKey,
        );
        if (incomingShareRequests.containsKey(request.requestId)) {
          Logs().i('[KeyManager] Already processed this request, ignoring');
          return; // we don't want to process one and the same request multiple times
        }
        incomingShareRequests[request.requestId] = request;
        final roomKeyRequest =
            RoomKeyRequest.fromToDeviceEvent(event, this, request);
        if (device.userId == client.userID &&
            device.verified &&
            !device.blocked) {
          Logs().i('[KeyManager] All checks out, forwarding key...');
          // alright, we can forward the key
          await roomKeyRequest.forwardKey();
        } else if (device.encryptToDevice &&
            session.allowedAtIndex
                    .tryGet