import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
/*
Copyright 2023 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { logger as rootLogger } from "../logger.js";
import { TypedEventEmitter } from "../models/typed-event-emitter.js";
import { EventTimeline } from "../models/event-timeline.js";
import { EventType } from "../@types/event.js";
import { UpdateDelayedEventAction } from "../@types/requests.js";
import { CallMembership, isLegacyCallMembershipData } from "./CallMembership.js";
import { RoomStateEvent } from "../models/room-state.js";
import { randomString, secureRandomBase64Url } from "../randomstring.js";
import { decodeBase64, encodeUnpaddedBase64 } from "../base64.js";
import { KnownMembership } from "../@types/membership.js";
import { isLivekitFocusActive } from "./LivekitFocus.js";
var logger = rootLogger.getChild("MatrixRTCSession");
var MEMBERSHIP_EXPIRY_TIME = 60 * 60 * 1000;
var MEMBER_EVENT_CHECK_PERIOD = 2 * 60 * 1000; // How often we check to see if we need to re-send our member event
var CALL_MEMBER_EVENT_RETRY_DELAY_MIN = 3000;
var UPDATE_ENCRYPTION_KEY_THROTTLE = 3000;

// A delay after a member leaves before we create and publish a new key, because people
// tend to leave calls at the same time
var MAKE_KEY_DELAY = 3000;
// The delay between creating and sending a new key and starting to encrypt with it. This gives others
// a chance to receive the new key to minimise the chance they don't get media they can't decrypt.
// The total time between a member leaving and the call switching to new keys is therefore
// MAKE_KEY_DELAY + SEND_KEY_DELAY
var USE_KEY_DELAY = 5000;
var getParticipantId = (userId, deviceId) => "".concat(userId, ":").concat(deviceId);
var getParticipantIdFromMembership = m => getParticipantId(m.sender, m.deviceId);
function keysEqual(a, b) {
  if (a === b) return true;
  return !!a && !!b && a.length === b.length && a.every((x, i) => x === b[i]);
}
export var MatrixRTCSessionEvent = /*#__PURE__*/function (MatrixRTCSessionEvent) {
  MatrixRTCSessionEvent["MembershipsChanged"] = "memberships_changed";
  MatrixRTCSessionEvent["JoinStateChanged"] = "join_state_changed";
  MatrixRTCSessionEvent["EncryptionKeyChanged"] = "encryption_key_changed";
  return MatrixRTCSessionEvent;
}({});
/**
 * A MatrixRTCSession manages the membership & properties of a MatrixRTC session.
 * This class doesn't deal with media at all, just membership & properties of a session.
 */
export class MatrixRTCSession extends TypedEventEmitter {
  /**
   * The callId (sessionId) of the call.
   *
   * It can be undefined since the callId is only known once the first membership joins.
   * The callId is the property that, per definition, groups memberships into one call.
   */
  get callId() {
    return this._callId;
  }
  /**
   * Returns all the call memberships for a room, oldest first
   */
  static callMembershipsForRoom(room) {
    var roomState = room.getLiveTimeline().getState(EventTimeline.FORWARDS);
    if (!roomState) {
      logger.warn("Couldn't get state for room " + room.roomId);
      throw new Error("Could't get state for room " + room.roomId);
    }
    var callMemberEvents = roomState.getStateEvents(EventType.GroupCallMemberPrefix);
    var callMemberships = [];
    for (var memberEvent of callMemberEvents) {
      var content = memberEvent.getContent();
      var eventKeysCount = Object.keys(content).length;
      // Dont even bother about empty events (saves us from costly type/"key in" checks in bigger rooms)
      if (eventKeysCount === 0) continue;
      var membershipContents = [];

      // We first decide if its a MSC4143 event (per device state key)
      if (eventKeysCount > 1 && "focus_active" in content) {
        // We have a MSC4143 event membership event
        membershipContents.push(content);
      } else if (eventKeysCount === 1 && "memberships" in content) {
        // we have a legacy (one event for all devices) event
        if (!Array.isArray(content["memberships"])) {
          logger.warn("Malformed member event from ".concat(memberEvent.getSender(), ": memberships is not an array"));
          continue;
        }
        membershipContents = content["memberships"];
      }
      if (membershipContents.length === 0) continue;
      for (var membershipData of membershipContents) {
        try {
          var _membership$sender;
          var membership = new CallMembership(memberEvent, membershipData);
          if (membership.callId !== "" || membership.scope !== "m.room") {
            // for now, just ignore anything that isn't a room scope call
            logger.info("Ignoring user-scoped call");
            continue;
          }
          if (membership.isExpired()) {
            logger.info("Ignoring expired device membership ".concat(membership.sender, "/").concat(membership.deviceId));
            continue;
          }
          if (!room.hasMembershipState((_membership$sender = membership.sender) !== null && _membership$sender !== void 0 ? _membership$sender : "", KnownMembership.Join)) {
            logger.info("Ignoring membership of user ".concat(membership.sender, " who is not in the room."));
            continue;
          }
          callMemberships.push(membership);
        } catch (e) {
          logger.warn("Couldn't construct call membership: ", e);
        }
      }
    }
    callMemberships.sort((a, b) => a.createdTs() - b.createdTs());
    if (callMemberships.length > 1) {
      logger.debug("Call memberships in room ".concat(room.roomId, ", in order: "), callMemberships.map(m => [m.createdTs(), m.sender]));
    }
    return callMemberships;
  }

  /**
   * Return the MatrixRTC session for the room, whether there are currently active members or not
   */
  static roomSessionForRoom(client, room) {
    var callMemberships = MatrixRTCSession.callMembershipsForRoom(room);
    return new MatrixRTCSession(client, room, callMemberships);
  }
  constructor(client, room, memberships) {
    var _this, _memberships$;
    super();
    _this = this;
    this.client = client;
    this.room = room;
    this.memberships = memberships;
    // The session Id of the call, this is the call_id of the call Member event.
    _defineProperty(this, "_callId", void 0);
    // How many ms after we joined the call, that our membership should expire, or undefined
    // if we're not yet joined
    _defineProperty(this, "relativeExpiry", void 0);
    // An identifier for our membership of the call. This will allow us to easily recognise
    // whether a membership was sent by this session or is stale from some other time.
    // It also forces our membership events to be unique, because otherwise we could try
    // to overwrite a membership from a previous session but it would do nothing because the
    // event content would be identical. We need the origin_server_ts to update though, so
    // forcing unique content fixes this.
    _defineProperty(this, "membershipId", void 0);
    _defineProperty(this, "memberEventTimeout", void 0);
    _defineProperty(this, "expiryTimeout", void 0);
    _defineProperty(this, "keysEventUpdateTimeout", void 0);
    _defineProperty(this, "makeNewKeyTimeout", void 0);
    _defineProperty(this, "setNewKeyTimeouts", new Set());
    // This is a Focus with the specified fields for an ActiveFocus (e.g. LivekitFocusActive for type="livekit")
    _defineProperty(this, "ownFocusActive", void 0);
    // This is a Foci array that contains the Focus objects this user is aware of and proposes to use.
    _defineProperty(this, "ownFociPreferred", void 0);
    _defineProperty(this, "updateCallMembershipRunning", false);
    _defineProperty(this, "needCallMembershipUpdate", false);
    _defineProperty(this, "manageMediaKeys", false);
    _defineProperty(this, "useLegacyMemberEvents", true);
    // userId:deviceId => array of (key, timestamp)
    _defineProperty(this, "encryptionKeys", new Map());
    _defineProperty(this, "lastEncryptionKeyUpdateRequest", void 0);
    // We use this to store the last membership fingerprints we saw, so we can proactively re-send encryption keys
    // if it looks like a membership has been updated.
    _defineProperty(this, "lastMembershipFingerprints", void 0);
    _defineProperty(this, "currentEncryptionKeyIndex", -1);
    /**
     * The statistics for this session.
     */
    _defineProperty(this, "statistics", {
      counters: {
        /**
         * The number of times we have sent a room event containing encryption keys.
         */
        roomEventEncryptionKeysSent: 0,
        /**
         * The number of times we have received a room event containing encryption keys.
         */
        roomEventEncryptionKeysReceived: 0
      },
      totals: {
        /**
         * The total age (in milliseconds) of all room events containing encryption keys that we have received.
         * We track the total age so that we can later calculate the average age of all keys received.
         */
        roomEventEncryptionKeysReceivedTotalAge: 0
      }
    });
    /**
     * Re-sends the encryption keys room event
     */
    _defineProperty(this, "sendEncryptionKeysEvent", /*#__PURE__*/function () {
      var _ref = _asyncToGenerator(function* (indexToSend) {
        if (_this.keysEventUpdateTimeout !== undefined) {
          clearTimeout(_this.keysEventUpdateTimeout);
          _this.keysEventUpdateTimeout = undefined;
        }
        _this.lastEncryptionKeyUpdateRequest = Date.now();
        if (!_this.isJoined()) return;
        logger.info("Sending encryption keys event. indexToSend=".concat(indexToSend));
        var userId = _this.client.getUserId();
        var deviceId = _this.client.getDeviceId();
        if (!userId) throw new Error("No userId");
        if (!deviceId) throw new Error("No deviceId");
        var myKeys = _this.getKeysForParticipant(userId, deviceId);
        if (!myKeys) {
          logger.warn("Tried to send encryption keys event but no keys found!");
          return;
        }
        if (typeof indexToSend !== "number" && _this.currentEncryptionKeyIndex === -1) {
          logger.warn("Tried to send encryption keys event but no current key index found!");
          return;
        }
        var keyIndexToSend = indexToSend !== null && indexToSend !== void 0 ? indexToSend : _this.currentEncryptionKeyIndex;
        var keyToSend = myKeys[keyIndexToSend];
        try {
          var content = {
            keys: [{
              index: keyIndexToSend,
              key: encodeUnpaddedBase64(keyToSend)
            }],
            device_id: deviceId,
            call_id: "",
            sent_ts: Date.now()
          };
          _this.statistics.counters.roomEventEncryptionKeysSent += 1;
          yield _this.client.sendEvent(_this.room.roomId, EventType.CallEncryptionKeysPrefix, content);
          logger.debug("Embedded-E2EE-LOG updateEncryptionKeyEvent participantId=".concat(userId, ":").concat(deviceId, " numKeys=").concat(myKeys.length, " currentKeyIndex=").concat(_this.currentEncryptionKeyIndex, " keyIndexToSend=").concat(keyIndexToSend), _this.encryptionKeys);
        } catch (error) {
          var matrixError = error;
          if (matrixError.event) {
            // cancel the pending event: we'll just generate a new one with our latest
            // keys when we resend
            _this.client.cancelPendingEvent(matrixError.event);
          }
          if (_this.keysEventUpdateTimeout === undefined) {
            var _matrixError$data$ret, _matrixError$data;
            var resendDelay = (_matrixError$data$ret = (_matrixError$data = matrixError.data) === null || _matrixError$data === void 0 ? void 0 : _matrixError$data.retry_after_ms) !== null && _matrixError$data$ret !== void 0 ? _matrixError$data$ret : 5000;
            logger.warn("Failed to send m.call.encryption_key, retrying in ".concat(resendDelay), error);
            _this.keysEventUpdateTimeout = setTimeout(_this.sendEncryptionKeysEvent, resendDelay);
          } else {
            logger.info("Not scheduling key resend as another re-send is already pending");
          }
        }
      });
      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }());
    /**
     * Process `m.call.encryption_keys` events to track the encryption keys for call participants.
     * This should be called each time the relevant event is received from a room timeline.
     * If the event is malformed then it will be logged and ignored.
     *
     * @param event the event to process
     */
    _defineProperty(this, "onCallEncryption", event => {
      var userId = event.getSender();
      var content = event.getContent();
      var deviceId = content["device_id"];
      var callId = content["call_id"];
      if (!userId) {
        logger.warn("Received m.call.encryption_keys with no userId: callId=".concat(callId));
        return;
      }

      // We currently only handle callId = "" (which is the default for room scoped calls)
      if (callId !== "") {
        logger.warn("Received m.call.encryption_keys with unsupported callId: userId=".concat(userId, ", deviceId=").concat(deviceId, ", callId=").concat(callId));
        return;
      }
      if (!Array.isArray(content.keys)) {
        logger.warn("Received m.call.encryption_keys where keys wasn't an array: callId=".concat(callId));
        return;
      }
      if (userId === this.client.getUserId() && deviceId === this.client.getDeviceId()) {
        // We store our own sender key in the same set along with keys from others, so it's
        // important we don't allow our own keys to be set by one of these events (apart from
        // the fact that we don't need it anyway because we already know our own keys).
        logger.info("Ignoring our own keys event");
        return;
      }
      this.statistics.counters.roomEventEncryptionKeysReceived += 1;
      var age = Date.now() - (typeof content.sent_ts === "number" ? content.sent_ts : event.getTs());
      this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge += age;
      for (var key of content.keys) {
        if (!key) {
          logger.info("Ignoring false-y key in keys event");
          continue;
        }
        var encryptionKey = key.key;
        var encryptionKeyIndex = key.index;
        if (!encryptionKey || encryptionKeyIndex === undefined || encryptionKeyIndex === null || callId === undefined || callId === null || typeof deviceId !== "string" || typeof callId !== "string" || typeof encryptionKey !== "string" || typeof encryptionKeyIndex !== "number") {
          logger.warn("Malformed call encryption_key: userId=".concat(userId, ", deviceId=").concat(deviceId, ", encryptionKeyIndex=").concat(encryptionKeyIndex, " callId=").concat(callId));
        } else {
          logger.debug("Embedded-E2EE-LOG onCallEncryption userId=".concat(userId, ":").concat(deviceId, " encryptionKeyIndex=").concat(encryptionKeyIndex, " age=").concat(age, "ms"), this.encryptionKeys);
          this.setEncryptionKey(userId, deviceId, encryptionKeyIndex, encryptionKey, event.getTs());
        }
      }
    });
    _defineProperty(this, "isMyMembership", m => m.sender === this.client.getUserId() && m.deviceId === this.client.getDeviceId());
    /**
     * Examines the latest call memberships and handles any encryption key sending or rotation that is needed.
     *
     * This function should be called when the room members or call memberships might have changed.
     */
    _defineProperty(this, "onMembershipUpdate", () => {
      var _this$_callId, _this$memberships$;
      var oldMemberships = this.memberships;
      this.memberships = MatrixRTCSession.callMembershipsForRoom(this.room);
      this._callId = (_this$_callId = this._callId) !== null && _this$_callId !== void 0 ? _this$_callId : (_this$memberships$ = this.memberships[0]) === null || _this$memberships$ === void 0 ? void 0 : _this$memberships$.callId;
      var changed = oldMemberships.length != this.memberships.length || oldMemberships.some((m, i) => !CallMembership.equal(m, this.memberships[i]));
      if (changed) {
        logger.info("Memberships for call in room ".concat(this.room.roomId, " have changed: emitting"));
        this.emit(MatrixRTCSessionEvent.MembershipsChanged, oldMemberships, this.memberships);
      }
      if (this.manageMediaKeys && this.isJoined() && this.makeNewKeyTimeout === undefined) {
        var oldMembershipIds = new Set(oldMemberships.filter(m => !this.isMyMembership(m)).map(getParticipantIdFromMembership));
        var newMembershipIds = new Set(this.memberships.filter(m => !this.isMyMembership(m)).map(getParticipantIdFromMembership));

        // We can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/symmetricDifference
        // for this once available
        var anyLeft = Array.from(oldMembershipIds).some(x => !newMembershipIds.has(x));
        var anyJoined = Array.from(newMembershipIds).some(x => !oldMembershipIds.has(x));
        var oldFingerprints = this.lastMembershipFingerprints;
        // always store the fingerprints of these latest memberships
        this.storeLastMembershipFingerprints();
        if (anyLeft) {
          logger.debug("Member(s) have left: queueing sender key rotation");
          this.makeNewKeyTimeout = setTimeout(this.onRotateKeyTimeout, MAKE_KEY_DELAY);
        } else if (anyJoined) {
          logger.debug("New member(s) have joined: re-sending keys");
          this.requestKeyEventSend();
        } else if (oldFingerprints) {
          // does it look like any of the members have updated their memberships?
          var newFingerprints = this.lastMembershipFingerprints;

          // We can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/symmetricDifference
          // for this once available
          var candidateUpdates = Array.from(oldFingerprints).some(x => !newFingerprints.has(x)) || Array.from(newFingerprints).some(x => !oldFingerprints.has(x));
          if (candidateUpdates) {
            logger.debug("Member(s) have updated/reconnected: re-sending keys");
            this.requestKeyEventSend();
          }
        }
      }
      this.setExpiryTimer();
    });
    _defineProperty(this, "triggerCallMembershipEventUpdate", /*#__PURE__*/_asyncToGenerator(function* () {
      if (_this.updateCallMembershipRunning) {
        _this.needCallMembershipUpdate = true;
        return;
      }
      _this.updateCallMembershipRunning = true;
      try {
        // if anything triggers an update while the update is running, do another update afterwards
        do {
          _this.needCallMembershipUpdate = false;
          yield _this.updateCallMembershipEvent();
        } while (_this.needCallMembershipUpdate);
      } finally {
        _this.updateCallMembershipRunning = false;
      }
    }));
    _defineProperty(this, "onRotateKeyTimeout", () => {
      if (!this.manageMediaKeys) return;
      this.makeNewKeyTimeout = undefined;
      logger.info("Making new sender key for key rotation");
      var newKeyIndex = this.makeNewSenderKey(true);
      // send immediately: if we're about to start sending with a new key, it's
      // important we get it out to others as soon as we can.
      this.sendEncryptionKeysEvent(newKeyIndex);
    });
    this._callId = (_memberships$ = memberships[0]) === null || _memberships$ === void 0 ? void 0 : _memberships$.callId;
    var roomState = this.room.getLiveTimeline().getState(EventTimeline.FORWARDS);
    roomState === null || roomState === void 0 || roomState.on(RoomStateEvent.Members, this.onMembershipUpdate);
    this.setExpiryTimer();
  }

  /*
   * Returns true if we intend to be participating in the MatrixRTC session.
   * This is determined by checking if the relativeExpiry has been set.
   */
  isJoined() {
    return this.relativeExpiry !== undefined;
  }

  /**
   * Performs cleanup & removes timers for client shutdown
   */
  stop() {
    var _this2 = this;
    return _asyncToGenerator(function* () {
      yield _this2.leaveRoomSession(1000);
      if (_this2.expiryTimeout) {
        clearTimeout(_this2.expiryTimeout);
        _this2.expiryTimeout = undefined;
      }
      if (_this2.memberEventTimeout) {
        clearTimeout(_this2.memberEventTimeout);
        _this2.memberEventTimeout = undefined;
      }
      var roomState = _this2.room.getLiveTimeline().getState(EventTimeline.FORWARDS);
      roomState === null || roomState === void 0 || roomState.off(RoomStateEvent.Members, _this2.onMembershipUpdate);
    })();
  }

  /**
   * Announces this user and device as joined to the MatrixRTC session,
   * and continues to update the membership event to keep it valid until
   * leaveRoomSession() is called
   * This will not subscribe to updates: remember to call subscribe() separately if
   * desired.
   * This method will return immediately and the session will be joined in the background.
   *
   * @param fociActive - The object representing the active focus. (This depends on the focus type.)
   * @param fociPreferred - The list of preferred foci this member proposes to use/knows/has access to.
   *                        For the livekit case this is a list of foci generated from the homeserver well-known, the current rtc session,
   *                        or optionally other room members homeserver well known.
   * @param joinConfig - Additional configuration for the joined session.
   */
  joinRoomSession(fociPreferred, fociActive, joinConfig) {
    var _joinConfig$manageMed, _joinConfig$useLegacy;
    if (this.isJoined()) {
      logger.info("Already joined to session in room ".concat(this.room.roomId, ": ignoring join call"));
      return;
    }
    this.ownFocusActive = fociActive;
    this.ownFociPreferred = fociPreferred;
    this.relativeExpiry = MEMBERSHIP_EXPIRY_TIME;
    this.manageMediaKeys = (_joinConfig$manageMed = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.manageMediaKeys) !== null && _joinConfig$manageMed !== void 0 ? _joinConfig$manageMed : this.manageMediaKeys;
    this.useLegacyMemberEvents = (_joinConfig$useLegacy = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.useLegacyMemberEvents) !== null && _joinConfig$useLegacy !== void 0 ? _joinConfig$useLegacy : this.useLegacyMemberEvents;
    this.membershipId = randomString(5);
    logger.info("Joining call session in room ".concat(this.room.roomId, " with manageMediaKeys=").concat(this.manageMediaKeys));
    if (joinConfig !== null && joinConfig !== void 0 && joinConfig.manageMediaKeys) {
      this.makeNewSenderKey();
      this.requestKeyEventSend();
    }
    // We don't wait for this, mostly because it may fail and schedule a retry, so this
    // function returning doesn't really mean anything at all.
    this.triggerCallMembershipEventUpdate();
    this.emit(MatrixRTCSessionEvent.JoinStateChanged, true);
  }

  /**
   * Announces this user and device as having left the MatrixRTC session
   * and stops scheduled updates.
   * This will not unsubscribe from updates: remember to call unsubscribe() separately if
   * desired.
   * The membership update required to leave the session will retry if it fails.
   * Without network connection the promise will never resolve.
   * A timeout can be provided so that there is a guarantee for the promise to resolve.
   */
  leaveRoomSession() {
    var _arguments = arguments,
      _this3 = this;
    return _asyncToGenerator(function* () {
      var timeout = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : undefined;
      if (!_this3.isJoined()) {
        logger.info("Not joined to session in room ".concat(_this3.room.roomId, ": ignoring leave call"));
        return new Promise(resolve => resolve(false));
      }
      var userId = _this3.client.getUserId();
      var deviceId = _this3.client.getDeviceId();
      if (!userId) throw new Error("No userId");
      if (!deviceId) throw new Error("No deviceId");

      // clear our encryption keys as we're done with them now (we'll
      // make new keys if we rejoin). We leave keys for other participants
      // as they may still be using the same ones.
      _this3.encryptionKeys.set(getParticipantId(userId, deviceId), []);
      if (_this3.makeNewKeyTimeout !== undefined) {
        clearTimeout(_this3.makeNewKeyTimeout);
        _this3.makeNewKeyTimeout = undefined;
      }
      for (var t of _this3.setNewKeyTimeouts) {
        clearTimeout(t);
      }
      _this3.setNewKeyTimeouts.clear();
      logger.info("Leaving call session in room ".concat(_this3.room.roomId));
      _this3.relativeExpiry = undefined;
      _this3.ownFocusActive = undefined;
      _this3.manageMediaKeys = false;
      _this3.membershipId = undefined;
      _this3.emit(MatrixRTCSessionEvent.JoinStateChanged, false);
      var timeoutPromise = new Promise(r => {
        if (timeout) {
          // will never resolve if timeout is not set
          setTimeout(r, timeout, "timeout");
        }
      });
      return new Promise(resolve => {
        Promise.race([_this3.triggerCallMembershipEventUpdate(), timeoutPromise]).then(value => {
          // The timeoutPromise returns the string 'timeout' and the membership update void
          // A success implies that the membership update was quicker then the timeout.
          resolve(value != "timeout");
        });
      });
    })();
  }
  getActiveFocus() {
    if (this.ownFocusActive && isLivekitFocusActive(this.ownFocusActive)) {
      // A livekit active focus
      if (this.ownFocusActive.focus_selection === "oldest_membership") {
        var oldestMembership = this.getOldestMembership();
        return oldestMembership === null || oldestMembership === void 0 ? void 0 : oldestMembership.getPreferredFoci()[0];
      }
    }
    if (!this.ownFocusActive) {
      // we use the legacy call.member events so default to oldest member
      var _oldestMembership = this.getOldestMembership();
      return _oldestMembership === null || _oldestMembership === void 0 ? void 0 : _oldestMembership.getPreferredFoci()[0];
    }
  }

  /**
   * Get the known encryption keys for a given participant device.
   *
   * @param userId the user ID of the participant
   * @param deviceId the device ID of the participant
   * @returns The encryption keys for the given participant, or undefined if they are not known.
   */
  getKeysForParticipant(userId, deviceId) {
    var _this$encryptionKeys$;
    return (_this$encryptionKeys$ = this.encryptionKeys.get(getParticipantId(userId, deviceId))) === null || _this$encryptionKeys$ === void 0 ? void 0 : _this$encryptionKeys$.map(entry => entry.key);
  }

  /**
   * A map of keys used to encrypt and decrypt (we are using a symmetric
   * cipher) given participant's media. This also includes our own key
   */
  getEncryptionKeys() {
    // the returned array doesn't contain the timestamps
    return Array.from(this.encryptionKeys.entries()).map(_ref3 => {
      var [participantId, keys] = _ref3;
      return [participantId, keys.map(k => k.key)];
    }).values();
  }
  getNewEncryptionKeyIndex() {
    var _this$getKeysForParti, _this$getKeysForParti2;
    var userId = this.client.getUserId();
    var deviceId = this.client.getDeviceId();
    if (!userId) throw new Error("No userId!");
    if (!deviceId) throw new Error("No deviceId!");
    return ((_this$getKeysForParti = (_this$getKeysForParti2 = this.getKeysForParticipant(userId, deviceId)) === null || _this$getKeysForParti2 === void 0 ? void 0 : _this$getKeysForParti2.length) !== null && _this$getKeysForParti !== void 0 ? _this$getKeysForParti : 0) % 16;
  }

  /**
   * Sets an encryption key at a specified index for a participant.
   * The encryption keys for the local participant are also stored here under the
   * user and device ID of the local participant.
   * If the key is older than the existing key at the index, it will be ignored.
   * @param userId - The user ID of the participant
   * @param deviceId - Device ID of the participant
   * @param encryptionKeyIndex - The index of the key to set
   * @param encryptionKeyString - The string representation of the key to set in base64
   * @param timestamp - The timestamp of the key. We assume that these are monotonic for each participant device.
   * @param delayBeforeUse - If true, delay before emitting a key changed event. Useful when setting
   *                         encryption keys for the local participant to allow time for the key to
   *                         be distributed.
   */
  setEncryptionKey(userId, deviceId, encryptionKeyIndex, encryptionKeyString, timestamp) {
    var delayBeforeUse = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
    var keyBin = decodeBase64(encryptionKeyString);
    var participantId = getParticipantId(userId, deviceId);
    if (!this.encryptionKeys.has(participantId)) {
      this.encryptionKeys.set(participantId, []);
    }
    var participantKeys = this.encryptionKeys.get(participantId);
    var existingKeyAtIndex = participantKeys[encryptionKeyIndex];
    if (existingKeyAtIndex) {
      if (existingKeyAtIndex.timestamp > timestamp) {
        logger.info("Ignoring new key at index ".concat(encryptionKeyIndex, " for ").concat(participantId, " as it is older than existing known key"));
        return;
      }
      if (keysEqual(existingKeyAtIndex.key, keyBin)) {
        existingKeyAtIndex.timestamp = timestamp;
        return;
      }
    }
    participantKeys[encryptionKeyIndex] = {
      key: keyBin,
      timestamp
    };
    if (delayBeforeUse) {
      var useKeyTimeout = setTimeout(() => {
        this.setNewKeyTimeouts.delete(useKeyTimeout);
        logger.info("Delayed-emitting key changed event for ".concat(participantId, " idx ").concat(encryptionKeyIndex));
        if (userId === this.client.getUserId() && deviceId === this.client.getDeviceId()) {
          this.currentEncryptionKeyIndex = encryptionKeyIndex;
        }
        this.emit(MatrixRTCSessionEvent.EncryptionKeyChanged, keyBin, encryptionKeyIndex, participantId);
      }, USE_KEY_DELAY);
      this.setNewKeyTimeouts.add(useKeyTimeout);
    } else {
      if (userId === this.client.getUserId() && deviceId === this.client.getDeviceId()) {
        this.currentEncryptionKeyIndex = encryptionKeyIndex;
      }
      this.emit(MatrixRTCSessionEvent.EncryptionKeyChanged, keyBin, encryptionKeyIndex, participantId);
    }
  }

  /**
   * Generate a new sender key and add it at the next available index
   * @param delayBeforeUse - If true, wait for a short period before setting the key for the
   *                         media encryptor to use. If false, set the key immediately.
   * @returns The index of the new key
   */
  makeNewSenderKey() {
    var delayBeforeUse = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    var userId = this.client.getUserId();
    var deviceId = this.client.getDeviceId();
    if (!userId) throw new Error("No userId");
    if (!deviceId) throw new Error("No deviceId");
    var encryptionKey = secureRandomBase64Url(16);
    var encryptionKeyIndex = this.getNewEncryptionKeyIndex();
    logger.info("Generated new key at index " + encryptionKeyIndex);
    this.setEncryptionKey(userId, deviceId, encryptionKeyIndex, encryptionKey, Date.now(), delayBeforeUse);
    return encryptionKeyIndex;
  }

  /**
   * Requests that we resend our keys to the room. May send a keys event immediately
   * or queue for alter if one has already been sent recently.
   */
  requestKeyEventSend() {
    if (!this.manageMediaKeys) return;
    if (this.lastEncryptionKeyUpdateRequest && this.lastEncryptionKeyUpdateRequest + UPDATE_ENCRYPTION_KEY_THROTTLE > Date.now()) {
      logger.info("Last encryption key event sent too recently: postponing");
      if (this.keysEventUpdateTimeout === undefined) {
        this.keysEventUpdateTimeout = setTimeout(this.sendEncryptionKeysEvent, UPDATE_ENCRYPTION_KEY_THROTTLE);
      }
      return;
    }
    this.sendEncryptionKeysEvent();
  }
  /**
   * Sets a timer for the soonest membership expiry
   */
  setExpiryTimer() {
    if (this.expiryTimeout) {
      clearTimeout(this.expiryTimeout);
      this.expiryTimeout = undefined;
    }
    var soonestExpiry;
    for (var membership of this.memberships) {
      var thisExpiry = membership.getMsUntilExpiry();
      // If getMsUntilExpiry is undefined we have a MSC4143 (MatrixRTC) compliant event - it never expires
      // but will be reliably resent on disconnect.
      if (thisExpiry !== undefined && (soonestExpiry === undefined || thisExpiry < soonestExpiry)) {
        soonestExpiry = thisExpiry;
      }
    }
    if (soonestExpiry != undefined) {
      this.expiryTimeout = setTimeout(this.onMembershipUpdate, soonestExpiry);
    }
  }
  getOldestMembership() {
    return this.memberships[0];
  }
  getFocusInUse() {
    var oldestMembership = this.getOldestMembership();
    if ((oldestMembership === null || oldestMembership === void 0 ? void 0 : oldestMembership.getFocusSelection()) === "oldest_membership") {
      return oldestMembership.getPreferredFoci()[0];
    }
  }
  storeLastMembershipFingerprints() {
    this.lastMembershipFingerprints = new Set(this.memberships.filter(m => !this.isMyMembership(m)).map(m => "".concat(getParticipantIdFromMembership(m), ":").concat(m.membershipID, ":").concat(m.createdTs())));
  }

  /**
   * Constructs our own membership
   * @param prevMembership - The previous value of our call membership, if any
   */
  makeMyMembershipLegacy(deviceId, prevMembership) {
    if (this.relativeExpiry === undefined) {
      throw new Error("Tried to create our own membership event when we're not joined!");
    }
    if (this.membershipId === undefined) {
      throw new Error("Tried to create our own membership event when we have no membership ID!");
    }
    var createdTs = prevMembership === null || prevMembership === void 0 ? void 0 : prevMembership.createdTs();
    return _objectSpread({
      call_id: "",
      scope: "m.room",
      application: "m.call",
      device_id: deviceId,
      expires: this.relativeExpiry,
      // TODO: Date.now() should be the origin_server_ts (now).
      expires_ts: this.relativeExpiry + (createdTs !== null && createdTs !== void 0 ? createdTs : Date.now()),
      // we use the fociPreferred since this is the list of foci.
      // it is named wrong in the Legacy events.
      foci_active: this.ownFociPreferred,
      membershipID: this.membershipId
    }, createdTs ? {
      created_ts: createdTs
    } : {});
  }
  /**
   * Constructs our own membership
   */
  makeMyMembership(deviceId) {
    var _this$ownFociPreferre;
    return {
      call_id: "",
      scope: "m.room",
      application: "m.call",
      device_id: deviceId,
      focus_active: {
        type: "livekit",
        focus_selection: "oldest_membership"
      },
      foci_preferred: (_this$ownFociPreferre = this.ownFociPreferred) !== null && _this$ownFociPreferre !== void 0 ? _this$ownFociPreferre : []
    };
  }

  /**
   * Returns true if our membership event needs to be updated
   */
  membershipEventNeedsUpdate(myPrevMembershipData, myPrevMembership) {
    if (myPrevMembership && myPrevMembership.getMsUntilExpiry() === undefined) return false;

    // Need to update if there's a membership for us but we're not joined (valid or otherwise)
    if (!this.isJoined()) return !!myPrevMembershipData;

    // ...or if we are joined, but there's no valid membership event
    if (!myPrevMembership) return true;
    var expiryTime = myPrevMembership.getMsUntilExpiry();
    if (expiryTime !== undefined && expiryTime < MEMBERSHIP_EXPIRY_TIME / 2) {
      // ...or if the expiry time needs bumping
      this.relativeExpiry += MEMBERSHIP_EXPIRY_TIME;
      return true;
    }
    return false;
  }
  makeNewMembership(deviceId) {
    // If we're joined, add our own
    if (this.isJoined()) {
      return this.makeMyMembership(deviceId);
    }
    return {};
  }
  /**
   * Makes a new membership list given the old list alonng with this user's previous membership event
   * (if any) and this device's previous membership (if any)
   */
  makeNewLegacyMemberships(oldMemberships, localDeviceId, myCallMemberEvent, myPrevMembership) {
    var filterExpired = m => {
      var membershipObj;
      try {
        membershipObj = new CallMembership(myCallMemberEvent, m);
      } catch (e) {
        return false;
      }
      return !membershipObj.isExpired();
    };
    var transformMemberships = m => {
      if (m.created_ts === undefined) {
        // we need to fill this in with the origin_server_ts from its original event
        m.created_ts = myCallMemberEvent.getTs();
      }
      return m;
    };

    // Filter our any invalid or expired memberships, and also our own - we'll add that back in next
    var newMemberships = oldMemberships.filter(filterExpired).filter(m => m.device_id !== localDeviceId);

    // Fix up any memberships that need their created_ts adding
    newMemberships = newMemberships.map(transformMemberships);

    // If we're joined, add our own
    if (this.isJoined()) {
      newMemberships.push(this.makeMyMembershipLegacy(localDeviceId, myPrevMembership));
    }
    return {
      memberships: newMemberships
    };
  }
  updateCallMembershipEvent() {
    var _this4 = this;
    return _asyncToGenerator(function* () {
      if (_this4.memberEventTimeout) {
        clearTimeout(_this4.memberEventTimeout);
        _this4.memberEventTimeout = undefined;
      }
      var roomState = _this4.room.getLiveTimeline().getState(EventTimeline.FORWARDS);
      if (!roomState) throw new Error("Couldn't get room state for room " + _this4.room.roomId);
      var localUserId = _this4.client.getUserId();
      var localDeviceId = _this4.client.getDeviceId();
      if (!localUserId || !localDeviceId) throw new Error("User ID or device ID was null!");
      var callMemberEvents = roomState.events.get(EventType.GroupCallMemberPrefix);
      var legacy = _this4.stateEventsContainOngoingLegacySession(callMemberEvents);
      var newContent = {};
      if (legacy) {
        var _myCallMemberEvent$ge;
        var myCallMemberEvent = callMemberEvents === null || callMemberEvents === void 0 ? void 0 : callMemberEvents.get(localUserId);
        var content = (_myCallMemberEvent$ge = myCallMemberEvent === null || myCallMemberEvent === void 0 ? void 0 : myCallMemberEvent.getContent()) !== null && _myCallMemberEvent$ge !== void 0 ? _myCallMemberEvent$ge : {};
        var myPrevMembership;
        // We know its CallMembershipDataLegacy
        var _memberships = Array.isArray(content["memberships"]) ? content["memberships"] : [];
        var myPrevMembershipData = _memberships.find(m => m.device_id === localDeviceId);
        try {
          if (myCallMemberEvent && myPrevMembershipData && isLegacyCallMembershipData(myPrevMembershipData) && myPrevMembershipData.membershipID === _this4.membershipId) {
            myPrevMembership = new CallMembership(myCallMemberEvent, myPrevMembershipData);
          }
        } catch (e) {
          // This would indicate a bug or something weird if our own call membership
          // wasn't valid
          logger.warn("Our previous call membership was invalid - this shouldn't happen.", e);
        }
        if (myPrevMembership) {
          logger.debug("".concat(myPrevMembership.getMsUntilExpiry(), " until our membership expires"));
        }
        if (!_this4.membershipEventNeedsUpdate(myPrevMembershipData, myPrevMembership)) {
          // nothing to do - reschedule the check again
          _this4.memberEventTimeout = setTimeout(_this4.triggerCallMembershipEventUpdate, MEMBER_EVENT_CHECK_PERIOD);
          return;
        }
        newContent = _this4.makeNewLegacyMemberships(_memberships, localDeviceId, myCallMemberEvent, myPrevMembership);
      } else {
        newContent = _this4.makeNewMembership(localDeviceId);
      }
      var stateKey = legacy ? localUserId : _this4.makeMembershipStateKey(localUserId, localDeviceId);
      try {
        yield _this4.client.sendStateEvent(_this4.room.roomId, EventType.GroupCallMemberPrefix, newContent, stateKey);
        logger.info("Sent updated call member event.");

        // check periodically to see if we need to refresh our member event
        if (_this4.isJoined()) {
          if (legacy) {
            _this4.memberEventTimeout = setTimeout(_this4.triggerCallMembershipEventUpdate, MEMBER_EVENT_CHECK_PERIOD);
          } else {
            try {
              // TODO: If delayed event times out, re-join!
              var res = yield _this4.client._unstable_sendDelayedStateEvent(_this4.room.roomId, {
                delay: 8000
              }, EventType.GroupCallMemberPrefix, {},
              // leave event
              stateKey);
              _this4.scheduleDelayDisconnection(res.delay_id);
            } catch (e) {
              logger.error("Failed to send delayed event:", e);
            }
          }
        }
      } catch (e) {
        var resendDelay = CALL_MEMBER_EVENT_RETRY_DELAY_MIN + Math.random() * 2000;
        logger.warn("Failed to send call member event (retrying in ".concat(resendDelay, "): ").concat(e));
        yield new Promise(resolve => setTimeout(resolve, resendDelay));
        yield _this4.triggerCallMembershipEventUpdate();
      }
    })();
  }
  scheduleDelayDisconnection(delayId) {
    this.memberEventTimeout = setTimeout(() => this.delayDisconnection(delayId), 5000);
  }
  delayDisconnection(delayId) {
    var _this5 = this;
    return _asyncToGenerator(function* () {
      try {
        yield _this5.client._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Restart);
        _this5.scheduleDelayDisconnection(delayId);
      } catch (e) {
        logger.error("Failed to delay our disconnection event", e);
      }
    })();
  }
  stateEventsContainOngoingLegacySession(callMemberEvents) {
    if (!(callMemberEvents !== null && callMemberEvents !== void 0 && callMemberEvents.size)) {
      return this.useLegacyMemberEvents;
    }
    var containsAnyOngoingSession = false;
    var containsUnknownOngoingSession = false;
    for (var callMemberEvent of callMemberEvents.values()) {
      var content = callMemberEvent.getContent();
      if (Array.isArray(content["memberships"])) {
        for (var membership of content.memberships) {
          if (!new CallMembership(callMemberEvent, membership).isExpired()) {
            return true;
          }
        }
      } else if (Object.keys(content).length > 0) {
        containsAnyOngoingSession || (containsAnyOngoingSession = true);
        containsUnknownOngoingSession || (containsUnknownOngoingSession = !("focus_active" in content));
      }
    }
    return containsAnyOngoingSession && !containsUnknownOngoingSession ? false : this.useLegacyMemberEvents;
  }
  makeMembershipStateKey(localUserId, localDeviceId) {
    var stateKey = "".concat(localUserId, "_").concat(localDeviceId);
    if (/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())) {
      return stateKey;
    } else {
      return "_".concat(stateKey);
    }
  }
}
//# sourceMappingURL=MatrixRTCSession.js.map