updateMemberCallState method

Future<void> updateMemberCallState([
  1. IGroupCallRoomMemberCallState? memberCallState
])

Implementation

Future<void> updateMemberCallState(
    [IGroupCallRoomMemberCallState? memberCallState]) async {
  final localUserId = client.userID;

  final currentStateEvent = getMemberStateEvent(localUserId!);
  var calls = <IGroupCallRoomMemberCallState>[];

  if (currentStateEvent != null) {
    final memberStateEvent =
        IGroupCallRoomMemberState.fromJson(currentStateEvent);
    final unCheckedCalls = memberStateEvent.calls;

    // don't keep pushing stale devices every update
    final validCalls = <IGroupCallRoomMemberCallState>[];
    for (final call in unCheckedCalls) {
      final validDevices = [];
      for (final device in call.devices) {
        if (device.expires_ts != null &&
            device.expires_ts! >
                DateTime.now()
                    // safety buffer just incase we were slow to process a
                    // call event, if the device is actually dead it should
                    // get removed pretty soon
                    .add(Duration(seconds: 10))
                    .millisecondsSinceEpoch) {
          validDevices.add(device);
        }
      }
      if (validDevices.isNotEmpty) {
        validCalls.add(call);
      }
    }

    calls = validCalls;

    final existingCallIndex =
        calls.indexWhere((element) => groupCallId == element.call_id);

    if (existingCallIndex != -1) {
      if (memberCallState != null) {
        calls[existingCallIndex] = memberCallState;
      } else {
        calls.removeAt(existingCallIndex);
      }
    } else if (memberCallState != null) {
      calls.add(memberCallState);
    }
  } else if (memberCallState != null) {
    calls.add(memberCallState);
  }
  final content = {
    'm.calls': calls.map((e) => e.toJson()).toList(),
  };

  await client.setRoomStateWithKey(
      room.id, EventTypes.GroupCallMemberPrefix, localUserId, content);
}