diff --git a/ElementX/Sources/Services/ElementCall/ElementCallService.swift b/ElementX/Sources/Services/ElementCall/ElementCallService.swift index 3343081f8..e39d345f8 100644 --- a/ElementX/Sources/Services/ElementCall/ElementCallService.swift +++ b/ElementX/Sources/Services/ElementCall/ElementCallService.swift @@ -53,6 +53,8 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe } private var endUnansweredCallTask: Task? + /// The ringing call was answered for the web view, which has yet to set its call session up. + private var isIncomingCallAnswered = false /// A call answered for the native stack, until the stack takes it over. private var answeredNativeCallID: CallID? @@ -241,6 +243,13 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe return } + // Otherwise it would count as a call in progress, and every call after it would be missed. + if isIncomingCallAnswered, incomingCallID?.roomID == roomID { + MXLog.warning("Dropping an answered call that never opened") + clearIncomingCallState() + return + } + MXLog.info("Not tearing down the call session, no call for room \(roomID)") } @@ -358,6 +367,24 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe return } + guard incomingCallID?.rtcNotificationID != rtcNotificationID else { + MXLog.info("Already ringing for this call, reporting the duplicate push as handled") + reportImmediatelyEndedCall(reason: .answeredElsewhere, + callerInfo: (roomID: roomID, roomDisplayName: roomDisplayName), + completion: completion) + return + } + + // An ongoing native call is tracked by CallKit, which offers its own call waiting. + let isBusy = (incomingCallID != nil && answeredNativeCallID == nil) || ongoingCallID?.isNative == false + guard !isBusy else { + MXLog.info("Another call is ringing or ongoing, reporting the call for room \(roomID) as missed") + reportImmediatelyEndedCall(reason: .unanswered, + callerInfo: (roomID: roomID, roomDisplayName: roomDisplayName), + completion: completion) + return + } + let isVoiceCall = payload.dictionaryPayload[ElementCallServiceNotificationKey.isVoiceCall.rawValue] as? Bool ?? false let callID = CallID(callKitID: UUID(), roomID: roomID, rtcNotificationID: rtcNotificationID, isVoiceCall: isVoiceCall) @@ -479,6 +506,10 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe return } + // Cancelled now rather than after the delay, by when it may belong to a call that rang since. + endUnansweredCallTask?.cancel() + isIncomingCallAnswered = true + // And delay ending the call so that the app has enough time // to get deeplinked into DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { @@ -486,7 +517,6 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe provider.reportCall(with: incomingCallID.callKitID, endedAt: nil, reason: .remoteEnded) self.actionsSubject.send(.startCall(roomID: incomingCallID.roomID, isVoiceCall: incomingCallID.isVoiceCall)) - self.endUnansweredCallTask?.cancel() } } @@ -729,6 +759,7 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe endPendingCallTask?.cancel() endPendingCallTask = nil answeredNativeCallID = nil + isIncomingCallAnswered = false declineListenerHandle?.cancel() declineListenerHandle = nil incomingCallRoomInfoCancellable = nil diff --git a/UnitTests/Sources/ElementCallServiceTests.swift b/UnitTests/Sources/ElementCallServiceTests.swift index 9856cf009..0e6e224c6 100644 --- a/UnitTests/Sources/ElementCallServiceTests.swift +++ b/UnitTests/Sources/ElementCallServiceTests.swift @@ -328,6 +328,91 @@ final class ElementCallServiceTests { #expect(service.ongoingCallRoomIDPublisher.value == nil) } + // MARK: - Busy + + @Test + func aCallWhileAnotherRingsIsReportedAsMissed() async throws { + await reportIncomingPush(isVoiceCall: false) + let ringingUUID = try #require(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid) + + let otherCall = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) + .updatingRoomID("!other:example.com") + .updatingRTCNotificationID("$111") + await expectImmediatelyEndedCallReported(forPayload: otherCall, expectedReason: .unanswered) + + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update.remoteHandle?.value == "!other:example.com") + #expect(!callProvider.reportCallWithEndedAtReasonReceivedInvocations.contains { $0.uuid == ringingUUID }) + } + + @Test + func aCallDuringAWebViewCallIsReportedAsMissed() async { + await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true) + + let otherCall = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) + .updatingRoomID("!other:example.com") + await expectImmediatelyEndedCallReported(forPayload: otherCall, expectedReason: .unanswered) + } + + @Test + func aCallDuringANativeCallStillRings() async { + // An ongoing native call is tracked by CallKit, which offers its own call waiting. + enableNativeCalls() + await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true) + + await reportIncomingPush(isVoiceCall: false, roomID: "!other:example.com") + + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update.remoteHandle?.value == "!other:example.com") + #expect(!callProvider.reportCallWithEndedAtReasonCalled) + } + + @Test + func theSameRingPushedTwiceIsReportedAsHandled() async throws { + await reportIncomingPush(isVoiceCall: false) + let ringingUUID = try #require(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid) + + await expectImmediatelyEndedCallReported(forPayload: PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60), + expectedReason: .answeredElsewhere) + + #expect(!callProvider.reportCallWithEndedAtReasonReceivedInvocations.contains { $0.uuid == ringingUUID }) + } + + @Test + func anAnsweredCallThatNeverOpensStopsBlockingNewCalls() async throws { + await reportIncomingPush(isVoiceCall: false) + try await answerReportedCall() + + // The call screen couldn't open, e.g. because the room isn't joined. + service.tearDownCallSession(roomID: "!room:example.com") + + await reportIncomingPush(isVoiceCall: false, roomID: "!other:example.com") + + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update.remoteHandle?.value == "!other:example.com") + #expect(!callProvider.reportCallWithEndedAtReasonReceivedInvocations.contains { $0.reason == .unanswered }) + } + + @Test + func aCallAfterADroppedAnsweredCallStillTimesOut() async throws { + await reportIncomingPush(isVoiceCall: false) + try await answerReportedCall() + service.tearDownCallSession(roomID: "!room:example.com") + + await reportIncomingPush(isVoiceCall: false, roomID: "!other:example.com") + let newCallUUID = try #require(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid) + await clock.waitForScheduledSleep() + + let (endedCalls, endedCallsContinuation) = AsyncStream<(UUID, CXCallEndedReason)>.makeStream() + callProvider.reportCallWithEndedAtReasonClosure = { uuid, _, reason in + endedCallsContinuation.yield((uuid, reason)) + } + let deferredTimeout = deferFulfillment(endedCalls) { $0 == newCallUUID && $1 == .unanswered } + + // The answer hands over to the web view a second later, which must leave the new call's timeout alone. + try await Task.sleep(for: .seconds(1.5)) + clock.advance(by: .seconds(70)) + + try await deferredTimeout.fulfill() + } + // MARK: - Native calls @Test @@ -493,10 +578,11 @@ final class ElementCallServiceTests { } /// Delivers a VoIP push and waits for it to be reported, returning once the call is ringing. - private func reportIncomingPush(isVoiceCall: Bool) async { + private func reportIncomingPush(isVoiceCall: Bool, roomID: String = "!room:example.com") async { await waitForConfirmation { confirmation in let payload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) .updateIsVoice(isVoiceCall) + .updatingRoomID(roomID) service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: payload, for: .voIP) { confirmation() @@ -559,4 +645,14 @@ private nonisolated class PKPushPayloadMock: PKPushPayload { dict[ElementCallServiceNotificationKey.isVoiceCall.rawValue] = isVoice return self } + + func updatingRoomID(_ roomID: String) -> Self { + dict[ElementCallServiceNotificationKey.roomID.rawValue] = roomID + return self + } + + func updatingRTCNotificationID(_ rtcNotificationID: String) -> Self { + dict[ElementCallServiceNotificationKey.rtcNotifyEventID.rawValue] = rtcNotificationID + return self + } }