From 1bfc219d0d2a38a769d78ab206850d0ca037b979 Mon Sep 17 00:00:00 2001 From: Mauro <34335419+Velin92@users.noreply.github.com> Date: Wed, 28 Oct 2026 23:53:54 +0100 Subject: [PATCH] Split CallKit and VoIP push handling out of the Element Call service (#6429) * Move CallKit and VoIP pushes into a new Element Call manager The new app-wide ElementCallManager owns PushKit, CallKit, the ring and busy rules, the native watchdog and the ongoing and ringing call state. ElementCallService keeps the session's side: the room watch for a ringing call (also when it was requested before the session), declines, the ongoing room and the native call stack, and relays the call screens' calls up with a set-up handshake. AppCoordinator listens to the manager through its actions. No behaviour change. * Let ManualClock cancel only the cancelling task's sleep A task cancelled before it started sleeping ran its cancellation handler on arrival and removed whatever sleep was pending, even another task's. A test that cancels one timer while another starts could then wait forever, which showed up as a flaky answered-call watchdog test. Each sleep now has an identifier and cancelling only removes its own. * Drop answered calls that never open and keep web mutes out of CallKit A web call answered with no call screen to take it now stops blocking later calls after 30 seconds, like the native path, and dropAnsweredCall(roomID:) is there for the coming call coordinator. Web calls were never tracked by CallKit, so relaying their mutes there only logged errors. * Keep CallKit and call package types out of the Element Call service The service now speaks app-owned CallEndReason and NativeCallEvent types: the manager maps them to CallKit's end reasons, and NativeCallSystem maps them to and from the call package's types. * Apply review suggestions to the Element Call manager split - Add a TODO on AppCoordinator's app-wide ElementCallService, which goes once each account's UserSession has its own. - Remove CallScreenViewModelTests. - Rename the tests this branch adds to short subject + outcome names, with Given/When/Then where a name alone loses context. - Drop the caller-role MARKs from the service, its protocol and its tests, and add Helpers MARKs to the test files. - Build NativeCallSystemTests' mock and system once, in init. --- ElementX.xcodeproj/project.pbxproj | 20 + .../Sources/Application/AppCoordinator.swift | 42 +- .../UserSessionFlowCoordinator.swift | 21 +- .../Mocks/ElementCallServiceMock.swift | 22 +- .../Mocks/Generated/GeneratedMocks.swift | 289 ++++++- .../CallScreen/CallScreenViewModel.swift | 43 +- .../ElementCall/ElementCallManager.swift | 653 +++++++++++++++ .../ElementCallManagerProtocol.swift | 23 + .../ElementCall/ElementCallService.swift | 677 +++------------ .../ElementCallServiceProtocol.swift | 70 +- .../NativeCall/NativeCallSystem.swift | 44 +- .../Sources/ElementCallManagerTests.swift | 770 +++++++++++++++++ .../Sources/ElementCallServiceTests.swift | 778 +++++------------- UnitTests/Sources/ManualClockTests.swift | 16 + UnitTests/Sources/NativeCallSystemTests.swift | 65 ++ .../Extensions/ElementCallSystemEvent.swift | 23 + .../Sources/TestUtilities/ManualClock.swift | 22 +- .../UserSessionFlowCoordinatorTests.swift | 2 +- 18 files changed, 2305 insertions(+), 1275 deletions(-) create mode 100644 ElementX/Sources/Services/ElementCall/ElementCallManager.swift create mode 100644 ElementX/Sources/Services/ElementCall/ElementCallManagerProtocol.swift create mode 100644 UnitTests/Sources/ElementCallManagerTests.swift create mode 100644 UnitTests/Sources/NativeCallSystemTests.swift create mode 100644 UnitTests/Sources/TestUtilities/Extensions/ElementCallSystemEvent.swift diff --git a/ElementX.xcodeproj/project.pbxproj b/ElementX.xcodeproj/project.pbxproj index ce633c67f..931fb4183 100644 --- a/ElementX.xcodeproj/project.pbxproj +++ b/ElementX.xcodeproj/project.pbxproj @@ -417,6 +417,7 @@ 4060D5B90302C93F5617B290 /* Macros in Frameworks */ = {isa = PBXBuildFile; productRef = 45CF0AEC68C170C55A613370 /* Macros */; }; 407DCE030E0F9B7C9861D38A /* KZFileWatchers in Frameworks */ = {isa = PBXBuildFile; productRef = 81DB3AB6CE996AB3954F4F03 /* KZFileWatchers */; }; 40839665086F5DAFA55D0EED /* AnalyticsConsentState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 353024006CB726E9F9187B3A /* AnalyticsConsentState.swift */; }; + 40FB21A7DCE318CD415552A0 /* NativeCallSystemTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E98E867750C6744330F7D0D0 /* NativeCallSystemTests.swift */; }; 414F50CFCFEEE2611127DCFB /* RestorationToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3558A15CFB934F9229301527 /* RestorationToken.swift */; }; 41B84DF733BE6CB0180D1CC1 /* NotificationContentBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F0AF1A13D358CA0BDA6065F /* NotificationContentBuilderTests.swift */; }; 41C5DA0C06F30311A221E85B /* ClientSDKMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EAF4A49F3ACD8BB8B0D2371 /* ClientSDKMock.swift */; }; @@ -1181,6 +1182,7 @@ B47213F07A67CE3A8D49CEC9 /* TimelineControllerFactoryProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AC1E3FE9B59EA094867863E /* TimelineControllerFactoryProtocol.swift */; }; B4A0C69370E6008A971463E7 /* BugReportScreenViewModelProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4C89820BB2B88D4EA28131C /* BugReportScreenViewModelProtocol.swift */; }; B4AAB3257A83B73F53FB2689 /* StateStoreViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F3DFE5B444F131648066F05 /* StateStoreViewModel.swift */; }; + B4E5C2B59C1BF98E1CCBC5A5 /* ElementCallSystemEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = D33F8BA996B9D8B06D1FB4EC /* ElementCallSystemEvent.swift */; }; B5321A1F5B26A0F3EC54909E /* CollapsibleFlowLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC5F5209279A752D98AAC4B2 /* CollapsibleFlowLayoutTests.swift */; }; B5479997ECC516C121E6625E /* LocationMarkerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFECCE59967018204876D0A5 /* LocationMarkerView.swift */; }; B5899F18AD6C56CE08FE532B /* RoomSummaryProviderMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC83F47D2173B7538AA72E0E /* RoomSummaryProviderMock.swift */; }; @@ -1406,6 +1408,7 @@ D69CCEC785E6C819551B402F /* SearchScreenViewModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5413213B56FB76C1071E2BFB /* SearchScreenViewModelTests.swift */; }; D6C6B955768521400E39CA03 /* MediaUploadQualitySettingsScreenViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9346C59026725968B8C319B /* MediaUploadQualitySettingsScreenViewModel.swift */; }; D6DE764B17FB4A9A12C33BF4 /* MessageComposer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F1DF3FFFE5ED2B8133F43A7 /* MessageComposer.swift */; }; + D747830D492912EB509AB372 /* ElementCallManagerProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4783DC628255B65CCF0386B /* ElementCallManagerProtocol.swift */; }; D75C591C44C2510FDFA9C3D8 /* Macros in Frameworks */ = {isa = PBXBuildFile; productRef = AF574A0FC6F3A83D3BFFC9B3 /* Macros */; }; D7A26828D8715A17A1D52E66 /* AppSettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A11D53EE8E666C25F97B4369 /* AppSettingsTests.swift */; }; D7CC123DC5138C3BF1F9999D /* MapLibreAnnotation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B50642DAE43672897C0BBAE2 /* MapLibreAnnotation.swift */; }; @@ -1442,6 +1445,7 @@ DDE7B4771452300C103B1EB8 /* RoomDirectoryCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F6210134203BE1F2DD5C679 /* RoomDirectoryCell.swift */; }; DDFBDEE1DC32BDD5488F898C /* ClientProxyMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2F96CCBEAAA7F2185BFA354 /* ClientProxyMock.swift */; }; DE3BF0ED68E56BF625591D49 /* LinkNewDeviceScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72C4A2D279386A811BDC6DAE /* LinkNewDeviceScreen.swift */; }; + DE4D85A7D0D96B69AB7C2F08 /* ElementCallManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DE0FC9A9F9974A13A2581C0 /* ElementCallManagerTests.swift */; }; DE4F8C4E0F1DB4832F09DE97 /* HomeScreenViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31D6764D6976D235926FE5FC /* HomeScreenViewModel.swift */; }; DE5102C95985AFB3F63E807B /* SecurityAndPrivacyScreenHook.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00C4628208584D251CCDAC0A /* SecurityAndPrivacyScreenHook.swift */; }; DEDBD3E9CFCC9F20CAC79881 /* JoinRoomScreenModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 136F80A613B55BDD071DCEA5 /* JoinRoomScreenModels.swift */; }; @@ -1532,6 +1536,7 @@ EB5B79DD2BCAF8F3B8B01F2F /* LiveLocationSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C454F35D8884C0A952FF2F84 /* LiveLocationSheet.swift */; }; EB87DF90CF6F8D5D12404C6E /* SecureBackupLogoutConfirmationScreenViewModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848F69921527D31CAACB93AF /* SecureBackupLogoutConfirmationScreenViewModelTests.swift */; }; EB88DBD77221E2CFE463018C /* NSE.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 0D8F620C8B314840D8602E3F /* NSE.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + EB8BB937B48E5855BA148730 /* ElementCallManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AD494FB2877FA64EF737008 /* ElementCallManager.swift */; }; EB9F4688006B52E69DF5358F /* BlankFormCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C7F63EB1525E697CAEB002B /* BlankFormCoordinator.swift */; }; EBE13FAB4E29738AC41BD3E5 /* InfoPlistReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A580295A56B55A856CC4084 /* InfoPlistReader.swift */; }; EC09E502A21E4EAA8B367AB8 /* ReportContentScreenViewModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30EA681527A8FE65E4C8E9A9 /* ReportContentScreenViewModelTests.swift */; }; @@ -1893,6 +1898,7 @@ 0D8F620C8B314840D8602E3F /* NSE.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = NSE.appex; sourceTree = BUILT_PRODUCTS_DIR; }; 0DBB08A95EFA668F2CF27211 /* AppLockSetupFlowCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLockSetupFlowCoordinator.swift; sourceTree = ""; }; 0DD16CE9A66C9040B066AD60 /* vi */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = vi; path = vi.lproj/Localizable.stringsdict; sourceTree = ""; }; + 0DE0FC9A9F9974A13A2581C0 /* ElementCallManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ElementCallManagerTests.swift; sourceTree = ""; }; 0DF5CBAF69BDF5DF31C661E1 /* IntentionalMentions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IntentionalMentions.swift; sourceTree = ""; }; 0E8BDC092D817B68CD9040C5 /* UserSessionStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserSessionStore.swift; sourceTree = ""; }; 0E95B3BDB80531C85CD50AE6 /* InvitedRoomProxy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InvitedRoomProxy.swift; sourceTree = ""; }; @@ -2278,6 +2284,7 @@ 4A5B4CD611DE7E94F5BA87B2 /* AppLockTimerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLockTimerTests.swift; sourceTree = ""; }; 4AB29A2D95D3469B5F016655 /* SecureBackupControllerMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureBackupControllerMock.swift; sourceTree = ""; }; 4AC3F28DECDF8665E8EBC76E /* ClassicAppMediaLoaderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClassicAppMediaLoaderTests.swift; sourceTree = ""; }; + 4AD494FB2877FA64EF737008 /* ElementCallManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ElementCallManager.swift; sourceTree = ""; }; 4B1F71AC585827E6C416C15A /* AppIcon.icon */ = {isa = PBXFileReference; lastKnownFileType = wrapper.icon; path = AppIcon.icon; sourceTree = ""; }; 4B2B564CA6570E1487A7C7CC /* SpaceRoomListProxy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpaceRoomListProxy.swift; sourceTree = ""; }; 4B2D4EEBE8C098BBADD10939 /* SecureBackupKeyBackupScreenCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureBackupKeyBackupScreenCoordinator.swift; sourceTree = ""; }; @@ -3097,6 +3104,7 @@ D2C513A6CD99E6C3C163DA1E /* RowDivider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDivider.swift; sourceTree = ""; }; D316BB02636AF2174F2580E6 /* SoftLogoutScreenViewModelProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SoftLogoutScreenViewModelProtocol.swift; sourceTree = ""; }; D33116993D54FADC0C721C1F /* Application.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Application.swift; sourceTree = ""; }; + D33F8BA996B9D8B06D1FB4EC /* ElementCallSystemEvent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ElementCallSystemEvent.swift; sourceTree = ""; }; D38391154120264910D19528 /* PollMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PollMock.swift; sourceTree = ""; }; D39D7F513A36C9C1951DB44C /* AnalyticsSettingsScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnalyticsSettingsScreen.swift; sourceTree = ""; }; D3F219838588C62198E726E3 /* LABiometryType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LABiometryType.swift; sourceTree = ""; }; @@ -3199,6 +3207,7 @@ E44E35AA87F49503E7B3BF6E /* AudioConverter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioConverter.swift; sourceTree = ""; }; E45EBAFF1A83538D54ABDF92 /* ServerSelectionScreenViewModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerSelectionScreenViewModelTests.swift; sourceTree = ""; }; E461B3C8BBBFCA400B268D14 /* AppRouteURLParserTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppRouteURLParserTests.swift; sourceTree = ""; }; + E4783DC628255B65CCF0386B /* ElementCallManagerProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ElementCallManagerProtocol.swift; sourceTree = ""; }; E48C91C8BE55CAE1A3DBC3BC /* TimelineItemIdentifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimelineItemIdentifier.swift; sourceTree = ""; }; E5272BC4A60B6AD7553BACA1 /* BlurHashDecode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlurHashDecode.swift; sourceTree = ""; }; E53BFB7E4F329621C844E8C3 /* AnalyticsPromptScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnalyticsPromptScreen.swift; sourceTree = ""; }; @@ -3227,6 +3236,7 @@ E944F717FC10A428D027074D /* RoomPowerLevelsProxyMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomPowerLevelsProxyMock.swift; sourceTree = ""; }; E96792E7EE6742172DA3A35E /* AccountUserDefaultsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountUserDefaultsTests.swift; sourceTree = ""; }; E9773983346838AABFAA914D /* UserSessionHook.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserSessionHook.swift; sourceTree = ""; }; + E98E867750C6744330F7D0D0 /* NativeCallSystemTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeCallSystemTests.swift; sourceTree = ""; }; E992D7B8BE54B2AB454613AF /* XCUIElement.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = XCUIElement.swift; sourceTree = ""; }; E994322F10D20ECE68683683 /* GalleryRoomTimelineItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GalleryRoomTimelineItem.swift; sourceTree = ""; }; E9A3D3CFA199FA7897364547 /* CallInviteRoomTimelineItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CallInviteRoomTimelineItem.swift; sourceTree = ""; }; @@ -3546,6 +3556,7 @@ 0345B849A6A802EB2F72C44A /* Extensions */ = { isa = PBXGroup; children = ( + D33F8BA996B9D8B06D1FB4EC /* ElementCallSystemEvent.swift */, 79351405CD99312A182B2488 /* NavigationCoordinators.swift */, 1A98F895BD60A4448E2A278C /* SessionDirectories.swift */, ); @@ -5375,6 +5386,7 @@ 2ADF12A50186B75C68017B61 /* DeclineAndBlockScreenViewModelTests.swift */, DEBB74427E24AF30CDB131B7 /* DeferredFulfillmentTests.swift */, 906451FB8CF27C628152BF7A /* EditRoomAddressScreenViewModelTests.swift */, + 0DE0FC9A9F9974A13A2581C0 /* ElementCallManagerTests.swift */, 7EA2AFF6EB59FE25234D29F3 /* ElementCallServiceTests.swift */, A1087DCC491CD4C027173DDA /* EmojiPickerScreenViewModelTests.swift */, 099F2D36C141D845A445B1E6 /* EmojiProviderTests.swift */, @@ -5407,6 +5419,7 @@ 6F6E6EDC4BBF962B2ED595A4 /* MessageForwardingScreenViewModelTests.swift */, CEB871BDED6DBCE6554082E4 /* MessageTextViewTests.swift */, 53D4EE9E5F3E5BF651869242 /* NativeCallStackTests.swift */, + E98E867750C6744330F7D0D0 /* NativeCallSystemTests.swift */, F875D71347DC81EAE7687446 /* NavigationRootCoordinatorTests.swift */, 78913D6E120D46138E97C107 /* NavigationSplitCoordinatorTests.swift */, 9C698E30698EC59302A8EEBD /* NavigationStackCoordinatorTests.swift */, @@ -6064,6 +6077,8 @@ E6943C2B0925AB90ECAFE59F /* CXCallControllerProtocol.swift */, 5E68CA59F66CE43B66D129E9 /* CXProviderProtocol.swift */, CC437C491EA6996513B1CEAB /* ElementCallConfiguration.swift */, + 4AD494FB2877FA64EF737008 /* ElementCallManager.swift */, + E4783DC628255B65CCF0386B /* ElementCallManagerProtocol.swift */, 33AE897D86784CCA5E4E9227 /* ElementCallService.swift */, 406C90AF8C3E98DF5D4E5430 /* ElementCallServiceConstants.swift */, 6FC8B21E86B137BE4E91F82A /* ElementCallServiceProtocol.swift */, @@ -8549,7 +8564,9 @@ CBEE2AA8B0C9BDDB3FDD4C81 /* DeferredFulfillment.swift in Sources */, A583B70939707197B0B21DFC /* DeferredFulfillmentTests.swift in Sources */, EDB6915EC953BB2A44AA608E /* EditRoomAddressScreenViewModelTests.swift in Sources */, + DE4D85A7D0D96B69AB7C2F08 /* ElementCallManagerTests.swift in Sources */, D820B3C223E4C2E77BB2A2BF /* ElementCallServiceTests.swift in Sources */, + B4E5C2B59C1BF98E1CCBC5A5 /* ElementCallSystemEvent.swift in Sources */, 7AE25D29734267271106D732 /* EmojiPickerScreenViewModelTests.swift in Sources */, 25618589E0DE0F1E95FC7B5C /* EmojiProviderTests.swift in Sources */, 71B62C48B8079D49F3FBC845 /* ExpiringTaskRunnerTests.swift in Sources */, @@ -8589,6 +8606,7 @@ DC68E866D6E664B0D2B06E74 /* MockImageCache.swift in Sources */, 3F791C4E0F7B373DB217EC90 /* NSItemProviderTests.swift in Sources */, FBFFABBDCDEC3C0C03430E19 /* NativeCallStackTests.swift in Sources */, + 40FB21A7DCE318CD415552A0 /* NativeCallSystemTests.swift in Sources */, 4F51C7C8131D060108B80575 /* NavigationCoordinators.swift in Sources */, 981853650217B6C8ECDD998C /* NavigationRootCoordinatorTests.swift in Sources */, 69C7B956B74BEC3DB88224EA /* NavigationSplitCoordinatorTests.swift in Sources */, @@ -9037,6 +9055,8 @@ AE1160076F663BF14E0E893A /* EffectsView.swift in Sources */, FE4593FC2A02AAF92E089565 /* ElementAnimations.swift in Sources */, 3118D9ABFD4BE5A3492FF88A /* ElementCallConfiguration.swift in Sources */, + EB8BB937B48E5855BA148730 /* ElementCallManager.swift in Sources */, + D747830D492912EB509AB372 /* ElementCallManagerProtocol.swift in Sources */, 5732395A4F71F51F9C754C5A /* ElementCallService.swift in Sources */, 3895969759E68FAB90C63EF7 /* ElementCallServiceConstants.swift in Sources */, 8E7A902CA16E24928F83646C /* ElementCallServiceMock.swift in Sources */, diff --git a/ElementX/Sources/Application/AppCoordinator.swift b/ElementX/Sources/Application/AppCoordinator.swift index bb019545a..9da6c786f 100644 --- a/ElementX/Sources/Application/AppCoordinator.swift +++ b/ElementX/Sources/Application/AppCoordinator.swift @@ -30,7 +30,9 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg private let appDelegate: AppDelegate private let appHooks: AppHooks private let bugReportService: BugReportServiceProtocol + // TODO: Each account's UserSession gets its own ElementCallService, which removes this one. private let elementCallService: ElementCallServiceProtocol + private let elementCallManager: ElementCallManagerProtocol /// Common background task to continue long-running tasks in the background. private var backgroundTask: UIBackgroundTaskIdentifier? @@ -114,6 +116,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg userIndicatorController = UserIndicatorController() elementCallService = ElementCallService(appSettings: appSettings) + elementCallManager = ElementCallManager(service: elementCallService, appSettings: appSettings) navigationRootCoordinator = NavigationRootCoordinator() @@ -178,25 +181,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg } .store(in: &cancellables) - elementCallService.actions - .receive(on: DispatchQueue.main) - .sink { [weak self] action in - switch action { - case .startCall(let roomID, let isVoiceCall): - self?.handleAppRoute(.call(roomID: roomID, isVoiceCall: isVoiceCall), windowType: nil) - case .receivedIncomingCallRequest: - // When reporting a VoIP call through the CXProvider's `reportNewIncomingVoIPPushPayload` - // the UIApplication states don't change and services are neither started nor ran on - // a background task. Handle both manually here. - Task { - await self?.resumeClientServices() - self?.scheduleDelayedPauseServices() - } - default: - break - } - } - .store(in: &cancellables) + configureCalls() windowManager.secondaryWindowsEnabled = !appLockService.isEnabled appLockService.isEnabledPublisher.sink { [weak windowManager] appLockEnabled in @@ -1034,6 +1019,25 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg } } + private func configureCalls() { + elementCallManager.actionsPublisher + .sink { [weak self] action in + switch action { + case .incomingCallReported: + // When reporting a VoIP call through the CXProvider's `reportNewIncomingVoIPPushPayload` + // the UIApplication states don't change and services are neither started nor ran on + // a background task. Handle both manually here. + Task { + await self?.resumeClientServices() + self?.scheduleDelayedPauseServices() + } + case .callAnswered(let roomID, let isVoiceCall): + self?.handleAppRoute(.call(roomID: roomID, isVoiceCall: isVoiceCall), windowType: nil) + } + } + .store(in: &cancellables) + } + private func observeUserSessionChanges() { userSessionManager.callbacksPublisher .receive(on: DispatchQueue.main) diff --git a/ElementX/Sources/FlowCoordinators/UserSessionFlowCoordinator.swift b/ElementX/Sources/FlowCoordinators/UserSessionFlowCoordinator.swift index 34844901f..b679cb76a 100644 --- a/ElementX/Sources/FlowCoordinators/UserSessionFlowCoordinator.swift +++ b/ElementX/Sources/FlowCoordinators/UserSessionFlowCoordinator.swift @@ -554,19 +554,24 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol { // MARK: - Native calls private func setupCallObservers() { - flowParameters.elementCallService.actions + flowParameters.elementCallService.nativeCallPresentationPublisher .receive(on: DispatchQueue.main) - .sink { [weak self] action in + .sink { [weak self] presentation in + self?.handleNativeCall(presentation) + } + .store(in: &cancellables) + + flowParameters.elementCallService.nativeCallEventsPublisher + .receive(on: DispatchQueue.main) + .sink { [weak self] event in guard let self else { return } - switch action { - case .endCall: - // A native call comes down on `.nativeCall(.dismiss)` instead, once it has - // actually left the room. + + switch event { + case .endCallRequested: + // A native call comes down on `.dismiss` instead, once it has actually left the room. if navigationTabCoordinator.overlayCoordinator is CallScreenCoordinator { dismissCallScreenIfNeeded() } - case .nativeCall(let presentation): - handleNativeCall(presentation) default: break } diff --git a/ElementX/Sources/Mocks/ElementCallServiceMock.swift b/ElementX/Sources/Mocks/ElementCallServiceMock.swift index 982f24575..3e58df518 100644 --- a/ElementX/Sources/Mocks/ElementCallServiceMock.swift +++ b/ElementX/Sources/Mocks/ElementCallServiceMock.swift @@ -9,16 +9,24 @@ import Combine import Foundation -struct ElementCallServiceMockConfiguration { - var ongoingCallRoomID: String? -} - extension ElementCallServiceMock { - convenience init(_ configuration: ElementCallServiceMockConfiguration) { + struct Configuration { + var ongoingCallRoomID: String? + } + + convenience init(_ configuration: Configuration) { self.init() - actions = PassthroughSubject().eraseToAnyPublisher() - ongoingCallRoomIDPublisher = .init(.init(configuration.ongoingCallRoomID)) + actionsPublisher = PassthroughSubject().eraseToAnyPublisher() + nativeCallEventsPublisher = PassthroughSubject().eraseToAnyPublisher() + nativeCallPresentationPublisher = PassthroughSubject().eraseToAnyPublisher() + + let ongoingCallRoomIDSubject = CurrentValueSubject(configuration.ongoingCallRoomID) + ongoingCallRoomIDPublisher = ongoingCallRoomIDSubject.asCurrentValuePublisher() + ongoingCallChangedRoomIDClosure = { roomID in + ongoingCallRoomIDSubject.send(roomID) + } + handleNativeCallRequestRoomProxyIsVoiceCallReturnValue = false } } diff --git a/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift b/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift index daacbf66b..6125f79b8 100644 --- a/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift +++ b/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift @@ -5066,17 +5066,66 @@ nonisolated class ContentScannerServiceMock: ContentScannerServiceProtocol, @unc } } } -nonisolated class ElementCallServiceMock: ElementCallServiceProtocol, @unchecked Sendable { - var actions: AnyPublisher { - get { return underlyingActions } - set(value) { underlyingActions = value } +nonisolated class ElementCallManagerMock: ElementCallManagerProtocol, @unchecked Sendable { + var actionsPublisher: AnyPublisher { + get { return underlyingActionsPublisher } + set(value) { underlyingActionsPublisher = value } } - nonisolated(unsafe) var underlyingActions: AnyPublisher! + nonisolated(unsafe) var underlyingActionsPublisher: AnyPublisher! + + //MARK: - dropAnsweredCall + + private let dropAnsweredCallRoomIDCallsCountLock = NSLock() + private nonisolated(unsafe) var dropAnsweredCallRoomIDUnderlyingCallsCount = 0 + var dropAnsweredCallRoomIDCallsCount: Int { + get { dropAnsweredCallRoomIDCallsCountLock.withLock { dropAnsweredCallRoomIDUnderlyingCallsCount } } + set { dropAnsweredCallRoomIDCallsCountLock.withLock { dropAnsweredCallRoomIDUnderlyingCallsCount = newValue } } + } + var dropAnsweredCallRoomIDCalled: Bool { + return dropAnsweredCallRoomIDCallsCount > 0 + } + private let dropAnsweredCallRoomIDReceivedRoomIDLock = NSLock() + private nonisolated(unsafe) var dropAnsweredCallRoomIDUnderlyingReceivedRoomID: String? + var dropAnsweredCallRoomIDReceivedRoomID: String? { + get { dropAnsweredCallRoomIDReceivedRoomIDLock.withLock { dropAnsweredCallRoomIDUnderlyingReceivedRoomID } } + set { dropAnsweredCallRoomIDReceivedRoomIDLock.withLock { dropAnsweredCallRoomIDUnderlyingReceivedRoomID = newValue } } + } + private let dropAnsweredCallRoomIDReceivedInvocationsLock = NSLock() + private nonisolated(unsafe) var dropAnsweredCallRoomIDUnderlyingReceivedInvocations: [String] = [] + var dropAnsweredCallRoomIDReceivedInvocations: [String] { + get { dropAnsweredCallRoomIDReceivedInvocationsLock.withLock { dropAnsweredCallRoomIDUnderlyingReceivedInvocations } } + set { dropAnsweredCallRoomIDReceivedInvocationsLock.withLock { dropAnsweredCallRoomIDUnderlyingReceivedInvocations = newValue } } + } + nonisolated(unsafe) var dropAnsweredCallRoomIDClosure: ((String) -> Void)? + + func dropAnsweredCall(roomID: String) { + dropAnsweredCallRoomIDCallsCountLock.withLock { dropAnsweredCallRoomIDUnderlyingCallsCount += 1 } + dropAnsweredCallRoomIDReceivedRoomID = roomID + dropAnsweredCallRoomIDReceivedInvocationsLock.withLock { dropAnsweredCallRoomIDUnderlyingReceivedInvocations.append(roomID) } + dropAnsweredCallRoomIDClosure?(roomID) + } +} +nonisolated class ElementCallServiceMock: ElementCallServiceProtocol, @unchecked Sendable { + var actionsPublisher: AnyPublisher { + get { return underlyingActionsPublisher } + set(value) { underlyingActionsPublisher = value } + } + nonisolated(unsafe) var underlyingActionsPublisher: AnyPublisher! var ongoingCallRoomIDPublisher: CurrentValuePublisher { get { return underlyingOngoingCallRoomIDPublisher } set(value) { underlyingOngoingCallRoomIDPublisher = value } } nonisolated(unsafe) var underlyingOngoingCallRoomIDPublisher: CurrentValuePublisher! + var nativeCallEventsPublisher: AnyPublisher { + get { return underlyingNativeCallEventsPublisher } + set(value) { underlyingNativeCallEventsPublisher = value } + } + nonisolated(unsafe) var underlyingNativeCallEventsPublisher: AnyPublisher! + var nativeCallPresentationPublisher: AnyPublisher { + get { return underlyingNativeCallPresentationPublisher } + set(value) { underlyingNativeCallPresentationPublisher = value } + } + nonisolated(unsafe) var underlyingNativeCallPresentationPublisher: AnyPublisher! nonisolated(unsafe) var nativeCallController: ElementCallController? //MARK: - setUserSession @@ -5189,34 +5238,34 @@ nonisolated class ElementCallServiceMock: ElementCallServiceProtocol, @unchecked } //MARK: - setupCallSession - private let setupCallSessionRoomIDRoomDisplayNameIsVideoCallsCountLock = NSLock() - private nonisolated(unsafe) var setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingCallsCount = 0 - var setupCallSessionRoomIDRoomDisplayNameIsVideoCallsCount: Int { - get { setupCallSessionRoomIDRoomDisplayNameIsVideoCallsCountLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingCallsCount } } - set { setupCallSessionRoomIDRoomDisplayNameIsVideoCallsCountLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingCallsCount = newValue } } + private let setupCallSessionRoomIDRoomDisplayNameIsVideoKindCallsCountLock = NSLock() + private nonisolated(unsafe) var setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingCallsCount = 0 + var setupCallSessionRoomIDRoomDisplayNameIsVideoKindCallsCount: Int { + get { setupCallSessionRoomIDRoomDisplayNameIsVideoKindCallsCountLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingCallsCount } } + set { setupCallSessionRoomIDRoomDisplayNameIsVideoKindCallsCountLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingCallsCount = newValue } } } - var setupCallSessionRoomIDRoomDisplayNameIsVideoCalled: Bool { - return setupCallSessionRoomIDRoomDisplayNameIsVideoCallsCount > 0 + var setupCallSessionRoomIDRoomDisplayNameIsVideoKindCalled: Bool { + return setupCallSessionRoomIDRoomDisplayNameIsVideoKindCallsCount > 0 } - private let setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedArgumentsLock = NSLock() - private nonisolated(unsafe) var setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingReceivedArguments: (roomID: String, roomDisplayName: String, isVideo: Bool)? - var setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedArguments: (roomID: String, roomDisplayName: String, isVideo: Bool)? { - get { setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedArgumentsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingReceivedArguments } } - set { setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedArgumentsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingReceivedArguments = newValue } } + private let setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedArgumentsLock = NSLock() + private nonisolated(unsafe) var setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingReceivedArguments: (roomID: String, roomDisplayName: String, isVideo: Bool, kind: ElementCallSessionKind)? + var setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedArguments: (roomID: String, roomDisplayName: String, isVideo: Bool, kind: ElementCallSessionKind)? { + get { setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedArgumentsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingReceivedArguments } } + set { setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedArgumentsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingReceivedArguments = newValue } } } - private let setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedInvocationsLock = NSLock() - private nonisolated(unsafe) var setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingReceivedInvocations: [(roomID: String, roomDisplayName: String, isVideo: Bool)] = [] - var setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedInvocations: [(roomID: String, roomDisplayName: String, isVideo: Bool)] { - get { setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedInvocationsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingReceivedInvocations } } - set { setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedInvocationsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingReceivedInvocations = newValue } } + private let setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedInvocationsLock = NSLock() + private nonisolated(unsafe) var setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingReceivedInvocations: [(roomID: String, roomDisplayName: String, isVideo: Bool, kind: ElementCallSessionKind)] = [] + var setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedInvocations: [(roomID: String, roomDisplayName: String, isVideo: Bool, kind: ElementCallSessionKind)] { + get { setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedInvocationsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingReceivedInvocations } } + set { setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedInvocationsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingReceivedInvocations = newValue } } } - nonisolated(unsafe) var setupCallSessionRoomIDRoomDisplayNameIsVideoClosure: ((String, String, Bool) async -> Void)? + nonisolated(unsafe) var setupCallSessionRoomIDRoomDisplayNameIsVideoKindClosure: ((String, String, Bool, ElementCallSessionKind) async -> Void)? - @concurrent func setupCallSession(roomID: String, roomDisplayName: String, isVideo: Bool) async { - setupCallSessionRoomIDRoomDisplayNameIsVideoCallsCountLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingCallsCount += 1 } - setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedArguments = (roomID: roomID, roomDisplayName: roomDisplayName, isVideo: isVideo) - setupCallSessionRoomIDRoomDisplayNameIsVideoReceivedInvocationsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoUnderlyingReceivedInvocations.append((roomID: roomID, roomDisplayName: roomDisplayName, isVideo: isVideo)) } - await setupCallSessionRoomIDRoomDisplayNameIsVideoClosure?(roomID, roomDisplayName, isVideo) + @concurrent func setupCallSession(roomID: String, roomDisplayName: String, isVideo: Bool, kind: ElementCallSessionKind) async { + setupCallSessionRoomIDRoomDisplayNameIsVideoKindCallsCountLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingCallsCount += 1 } + setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedArguments = (roomID: roomID, roomDisplayName: roomDisplayName, isVideo: isVideo, kind: kind) + setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedInvocationsLock.withLock { setupCallSessionRoomIDRoomDisplayNameIsVideoKindUnderlyingReceivedInvocations.append((roomID: roomID, roomDisplayName: roomDisplayName, isVideo: isVideo, kind: kind)) } + await setupCallSessionRoomIDRoomDisplayNameIsVideoKindClosure?(roomID, roomDisplayName, isVideo, kind) } //MARK: - reportCallSessionConnected @@ -5292,20 +5341,20 @@ nonisolated class ElementCallServiceMock: ElementCallServiceProtocol, @unchecked return reportCallSessionEndedRoomIDReasonCallsCount > 0 } private let reportCallSessionEndedRoomIDReasonReceivedArgumentsLock = NSLock() - private nonisolated(unsafe) var reportCallSessionEndedRoomIDReasonUnderlyingReceivedArguments: (roomID: String, reason: CXCallEndedReason)? - var reportCallSessionEndedRoomIDReasonReceivedArguments: (roomID: String, reason: CXCallEndedReason)? { + private nonisolated(unsafe) var reportCallSessionEndedRoomIDReasonUnderlyingReceivedArguments: (roomID: String, reason: CallEndReason)? + var reportCallSessionEndedRoomIDReasonReceivedArguments: (roomID: String, reason: CallEndReason)? { get { reportCallSessionEndedRoomIDReasonReceivedArgumentsLock.withLock { reportCallSessionEndedRoomIDReasonUnderlyingReceivedArguments } } set { reportCallSessionEndedRoomIDReasonReceivedArgumentsLock.withLock { reportCallSessionEndedRoomIDReasonUnderlyingReceivedArguments = newValue } } } private let reportCallSessionEndedRoomIDReasonReceivedInvocationsLock = NSLock() - private nonisolated(unsafe) var reportCallSessionEndedRoomIDReasonUnderlyingReceivedInvocations: [(roomID: String, reason: CXCallEndedReason)] = [] - var reportCallSessionEndedRoomIDReasonReceivedInvocations: [(roomID: String, reason: CXCallEndedReason)] { + private nonisolated(unsafe) var reportCallSessionEndedRoomIDReasonUnderlyingReceivedInvocations: [(roomID: String, reason: CallEndReason)] = [] + var reportCallSessionEndedRoomIDReasonReceivedInvocations: [(roomID: String, reason: CallEndReason)] { get { reportCallSessionEndedRoomIDReasonReceivedInvocationsLock.withLock { reportCallSessionEndedRoomIDReasonUnderlyingReceivedInvocations } } set { reportCallSessionEndedRoomIDReasonReceivedInvocationsLock.withLock { reportCallSessionEndedRoomIDReasonUnderlyingReceivedInvocations = newValue } } } - nonisolated(unsafe) var reportCallSessionEndedRoomIDReasonClosure: ((String, CXCallEndedReason) -> Void)? + nonisolated(unsafe) var reportCallSessionEndedRoomIDReasonClosure: ((String, CallEndReason) -> Void)? - func reportCallSessionEnded(roomID: String, reason: CXCallEndedReason) { + func reportCallSessionEnded(roomID: String, reason: CallEndReason) { reportCallSessionEndedRoomIDReasonCallsCountLock.withLock { reportCallSessionEndedRoomIDReasonUnderlyingCallsCount += 1 } reportCallSessionEndedRoomIDReasonReceivedArguments = (roomID: roomID, reason: reason) reportCallSessionEndedRoomIDReasonReceivedInvocationsLock.withLock { reportCallSessionEndedRoomIDReasonUnderlyingReceivedInvocations.append((roomID: roomID, reason: reason)) } @@ -5342,6 +5391,178 @@ nonisolated class ElementCallServiceMock: ElementCallServiceProtocol, @unchecked setAudioEnabledRoomIDReceivedInvocationsLock.withLock { setAudioEnabledRoomIDUnderlyingReceivedInvocations.append((enabled: enabled, roomID: roomID)) } setAudioEnabledRoomIDClosure?(enabled, roomID) } + //MARK: - observeIncomingCall + + private let observeIncomingCallRoomIDRtcNotificationIDCallsCountLock = NSLock() + private nonisolated(unsafe) var observeIncomingCallRoomIDRtcNotificationIDUnderlyingCallsCount = 0 + var observeIncomingCallRoomIDRtcNotificationIDCallsCount: Int { + get { observeIncomingCallRoomIDRtcNotificationIDCallsCountLock.withLock { observeIncomingCallRoomIDRtcNotificationIDUnderlyingCallsCount } } + set { observeIncomingCallRoomIDRtcNotificationIDCallsCountLock.withLock { observeIncomingCallRoomIDRtcNotificationIDUnderlyingCallsCount = newValue } } + } + var observeIncomingCallRoomIDRtcNotificationIDCalled: Bool { + return observeIncomingCallRoomIDRtcNotificationIDCallsCount > 0 + } + private let observeIncomingCallRoomIDRtcNotificationIDReceivedArgumentsLock = NSLock() + private nonisolated(unsafe) var observeIncomingCallRoomIDRtcNotificationIDUnderlyingReceivedArguments: (roomID: String, rtcNotificationID: String?)? + var observeIncomingCallRoomIDRtcNotificationIDReceivedArguments: (roomID: String, rtcNotificationID: String?)? { + get { observeIncomingCallRoomIDRtcNotificationIDReceivedArgumentsLock.withLock { observeIncomingCallRoomIDRtcNotificationIDUnderlyingReceivedArguments } } + set { observeIncomingCallRoomIDRtcNotificationIDReceivedArgumentsLock.withLock { observeIncomingCallRoomIDRtcNotificationIDUnderlyingReceivedArguments = newValue } } + } + private let observeIncomingCallRoomIDRtcNotificationIDReceivedInvocationsLock = NSLock() + private nonisolated(unsafe) var observeIncomingCallRoomIDRtcNotificationIDUnderlyingReceivedInvocations: [(roomID: String, rtcNotificationID: String?)] = [] + var observeIncomingCallRoomIDRtcNotificationIDReceivedInvocations: [(roomID: String, rtcNotificationID: String?)] { + get { observeIncomingCallRoomIDRtcNotificationIDReceivedInvocationsLock.withLock { observeIncomingCallRoomIDRtcNotificationIDUnderlyingReceivedInvocations } } + set { observeIncomingCallRoomIDRtcNotificationIDReceivedInvocationsLock.withLock { observeIncomingCallRoomIDRtcNotificationIDUnderlyingReceivedInvocations = newValue } } + } + nonisolated(unsafe) var observeIncomingCallRoomIDRtcNotificationIDClosure: ((String, String?) async -> Void)? + + @concurrent func observeIncomingCall(roomID: String, rtcNotificationID: String?) async { + observeIncomingCallRoomIDRtcNotificationIDCallsCountLock.withLock { observeIncomingCallRoomIDRtcNotificationIDUnderlyingCallsCount += 1 } + observeIncomingCallRoomIDRtcNotificationIDReceivedArguments = (roomID: roomID, rtcNotificationID: rtcNotificationID) + observeIncomingCallRoomIDRtcNotificationIDReceivedInvocationsLock.withLock { observeIncomingCallRoomIDRtcNotificationIDUnderlyingReceivedInvocations.append((roomID: roomID, rtcNotificationID: rtcNotificationID)) } + await observeIncomingCallRoomIDRtcNotificationIDClosure?(roomID, rtcNotificationID) + } + //MARK: - stopObservingIncomingCall + + private let stopObservingIncomingCallCallsCountLock = NSLock() + private nonisolated(unsafe) var stopObservingIncomingCallUnderlyingCallsCount = 0 + var stopObservingIncomingCallCallsCount: Int { + get { stopObservingIncomingCallCallsCountLock.withLock { stopObservingIncomingCallUnderlyingCallsCount } } + set { stopObservingIncomingCallCallsCountLock.withLock { stopObservingIncomingCallUnderlyingCallsCount = newValue } } + } + var stopObservingIncomingCallCalled: Bool { + return stopObservingIncomingCallCallsCount > 0 + } + nonisolated(unsafe) var stopObservingIncomingCallClosure: (() -> Void)? + + func stopObservingIncomingCall() { + stopObservingIncomingCallCallsCountLock.withLock { stopObservingIncomingCallUnderlyingCallsCount += 1 } + stopObservingIncomingCallClosure?() + } + //MARK: - declineCall + + private let declineCallRoomIDRtcNotificationIDCallsCountLock = NSLock() + private nonisolated(unsafe) var declineCallRoomIDRtcNotificationIDUnderlyingCallsCount = 0 + var declineCallRoomIDRtcNotificationIDCallsCount: Int { + get { declineCallRoomIDRtcNotificationIDCallsCountLock.withLock { declineCallRoomIDRtcNotificationIDUnderlyingCallsCount } } + set { declineCallRoomIDRtcNotificationIDCallsCountLock.withLock { declineCallRoomIDRtcNotificationIDUnderlyingCallsCount = newValue } } + } + var declineCallRoomIDRtcNotificationIDCalled: Bool { + return declineCallRoomIDRtcNotificationIDCallsCount > 0 + } + private let declineCallRoomIDRtcNotificationIDReceivedArgumentsLock = NSLock() + private nonisolated(unsafe) var declineCallRoomIDRtcNotificationIDUnderlyingReceivedArguments: (roomID: String, rtcNotificationID: String)? + var declineCallRoomIDRtcNotificationIDReceivedArguments: (roomID: String, rtcNotificationID: String)? { + get { declineCallRoomIDRtcNotificationIDReceivedArgumentsLock.withLock { declineCallRoomIDRtcNotificationIDUnderlyingReceivedArguments } } + set { declineCallRoomIDRtcNotificationIDReceivedArgumentsLock.withLock { declineCallRoomIDRtcNotificationIDUnderlyingReceivedArguments = newValue } } + } + private let declineCallRoomIDRtcNotificationIDReceivedInvocationsLock = NSLock() + private nonisolated(unsafe) var declineCallRoomIDRtcNotificationIDUnderlyingReceivedInvocations: [(roomID: String, rtcNotificationID: String)] = [] + var declineCallRoomIDRtcNotificationIDReceivedInvocations: [(roomID: String, rtcNotificationID: String)] { + get { declineCallRoomIDRtcNotificationIDReceivedInvocationsLock.withLock { declineCallRoomIDRtcNotificationIDUnderlyingReceivedInvocations } } + set { declineCallRoomIDRtcNotificationIDReceivedInvocationsLock.withLock { declineCallRoomIDRtcNotificationIDUnderlyingReceivedInvocations = newValue } } + } + nonisolated(unsafe) var declineCallRoomIDRtcNotificationIDClosure: ((String, String) async -> Void)? + + @concurrent func declineCall(roomID: String, rtcNotificationID: String) async { + declineCallRoomIDRtcNotificationIDCallsCountLock.withLock { declineCallRoomIDRtcNotificationIDUnderlyingCallsCount += 1 } + declineCallRoomIDRtcNotificationIDReceivedArguments = (roomID: roomID, rtcNotificationID: rtcNotificationID) + declineCallRoomIDRtcNotificationIDReceivedInvocationsLock.withLock { declineCallRoomIDRtcNotificationIDUnderlyingReceivedInvocations.append((roomID: roomID, rtcNotificationID: rtcNotificationID)) } + await declineCallRoomIDRtcNotificationIDClosure?(roomID, rtcNotificationID) + } + //MARK: - ongoingCallChanged + + private let ongoingCallChangedRoomIDCallsCountLock = NSLock() + private nonisolated(unsafe) var ongoingCallChangedRoomIDUnderlyingCallsCount = 0 + var ongoingCallChangedRoomIDCallsCount: Int { + get { ongoingCallChangedRoomIDCallsCountLock.withLock { ongoingCallChangedRoomIDUnderlyingCallsCount } } + set { ongoingCallChangedRoomIDCallsCountLock.withLock { ongoingCallChangedRoomIDUnderlyingCallsCount = newValue } } + } + var ongoingCallChangedRoomIDCalled: Bool { + return ongoingCallChangedRoomIDCallsCount > 0 + } + private let ongoingCallChangedRoomIDReceivedRoomIDLock = NSLock() + private nonisolated(unsafe) var ongoingCallChangedRoomIDUnderlyingReceivedRoomID: String? + var ongoingCallChangedRoomIDReceivedRoomID: String? { + get { ongoingCallChangedRoomIDReceivedRoomIDLock.withLock { ongoingCallChangedRoomIDUnderlyingReceivedRoomID } } + set { ongoingCallChangedRoomIDReceivedRoomIDLock.withLock { ongoingCallChangedRoomIDUnderlyingReceivedRoomID = newValue } } + } + private let ongoingCallChangedRoomIDReceivedInvocationsLock = NSLock() + private nonisolated(unsafe) var ongoingCallChangedRoomIDUnderlyingReceivedInvocations: [String?] = [] + var ongoingCallChangedRoomIDReceivedInvocations: [String?] { + get { ongoingCallChangedRoomIDReceivedInvocationsLock.withLock { ongoingCallChangedRoomIDUnderlyingReceivedInvocations } } + set { ongoingCallChangedRoomIDReceivedInvocationsLock.withLock { ongoingCallChangedRoomIDUnderlyingReceivedInvocations = newValue } } + } + nonisolated(unsafe) var ongoingCallChangedRoomIDClosure: ((String?) -> Void)? + + func ongoingCallChanged(roomID: String?) { + ongoingCallChangedRoomIDCallsCountLock.withLock { ongoingCallChangedRoomIDUnderlyingCallsCount += 1 } + ongoingCallChangedRoomIDReceivedRoomID = roomID + ongoingCallChangedRoomIDReceivedInvocationsLock.withLock { ongoingCallChangedRoomIDUnderlyingReceivedInvocations.append(roomID) } + ongoingCallChangedRoomIDClosure?(roomID) + } + //MARK: - callSessionSetUp + + private let callSessionSetUpRoomIDIsAcceptedCallsCountLock = NSLock() + private nonisolated(unsafe) var callSessionSetUpRoomIDIsAcceptedUnderlyingCallsCount = 0 + var callSessionSetUpRoomIDIsAcceptedCallsCount: Int { + get { callSessionSetUpRoomIDIsAcceptedCallsCountLock.withLock { callSessionSetUpRoomIDIsAcceptedUnderlyingCallsCount } } + set { callSessionSetUpRoomIDIsAcceptedCallsCountLock.withLock { callSessionSetUpRoomIDIsAcceptedUnderlyingCallsCount = newValue } } + } + var callSessionSetUpRoomIDIsAcceptedCalled: Bool { + return callSessionSetUpRoomIDIsAcceptedCallsCount > 0 + } + private let callSessionSetUpRoomIDIsAcceptedReceivedArgumentsLock = NSLock() + private nonisolated(unsafe) var callSessionSetUpRoomIDIsAcceptedUnderlyingReceivedArguments: (roomID: String, isAccepted: Bool)? + var callSessionSetUpRoomIDIsAcceptedReceivedArguments: (roomID: String, isAccepted: Bool)? { + get { callSessionSetUpRoomIDIsAcceptedReceivedArgumentsLock.withLock { callSessionSetUpRoomIDIsAcceptedUnderlyingReceivedArguments } } + set { callSessionSetUpRoomIDIsAcceptedReceivedArgumentsLock.withLock { callSessionSetUpRoomIDIsAcceptedUnderlyingReceivedArguments = newValue } } + } + private let callSessionSetUpRoomIDIsAcceptedReceivedInvocationsLock = NSLock() + private nonisolated(unsafe) var callSessionSetUpRoomIDIsAcceptedUnderlyingReceivedInvocations: [(roomID: String, isAccepted: Bool)] = [] + var callSessionSetUpRoomIDIsAcceptedReceivedInvocations: [(roomID: String, isAccepted: Bool)] { + get { callSessionSetUpRoomIDIsAcceptedReceivedInvocationsLock.withLock { callSessionSetUpRoomIDIsAcceptedUnderlyingReceivedInvocations } } + set { callSessionSetUpRoomIDIsAcceptedReceivedInvocationsLock.withLock { callSessionSetUpRoomIDIsAcceptedUnderlyingReceivedInvocations = newValue } } + } + nonisolated(unsafe) var callSessionSetUpRoomIDIsAcceptedClosure: ((String, Bool) -> Void)? + + func callSessionSetUp(roomID: String, isAccepted: Bool) { + callSessionSetUpRoomIDIsAcceptedCallsCountLock.withLock { callSessionSetUpRoomIDIsAcceptedUnderlyingCallsCount += 1 } + callSessionSetUpRoomIDIsAcceptedReceivedArguments = (roomID: roomID, isAccepted: isAccepted) + callSessionSetUpRoomIDIsAcceptedReceivedInvocationsLock.withLock { callSessionSetUpRoomIDIsAcceptedUnderlyingReceivedInvocations.append((roomID: roomID, isAccepted: isAccepted)) } + callSessionSetUpRoomIDIsAcceptedClosure?(roomID, isAccepted) + } + //MARK: - systemEventReceived + + private let systemEventReceivedCallsCountLock = NSLock() + private nonisolated(unsafe) var systemEventReceivedUnderlyingCallsCount = 0 + var systemEventReceivedCallsCount: Int { + get { systemEventReceivedCallsCountLock.withLock { systemEventReceivedUnderlyingCallsCount } } + set { systemEventReceivedCallsCountLock.withLock { systemEventReceivedUnderlyingCallsCount = newValue } } + } + var systemEventReceivedCalled: Bool { + return systemEventReceivedCallsCount > 0 + } + private let systemEventReceivedReceivedEventLock = NSLock() + private nonisolated(unsafe) var systemEventReceivedUnderlyingReceivedEvent: NativeCallEvent? + var systemEventReceivedReceivedEvent: NativeCallEvent? { + get { systemEventReceivedReceivedEventLock.withLock { systemEventReceivedUnderlyingReceivedEvent } } + set { systemEventReceivedReceivedEventLock.withLock { systemEventReceivedUnderlyingReceivedEvent = newValue } } + } + private let systemEventReceivedReceivedInvocationsLock = NSLock() + private nonisolated(unsafe) var systemEventReceivedUnderlyingReceivedInvocations: [NativeCallEvent] = [] + var systemEventReceivedReceivedInvocations: [NativeCallEvent] { + get { systemEventReceivedReceivedInvocationsLock.withLock { systemEventReceivedUnderlyingReceivedInvocations } } + set { systemEventReceivedReceivedInvocationsLock.withLock { systemEventReceivedUnderlyingReceivedInvocations = newValue } } + } + nonisolated(unsafe) var systemEventReceivedClosure: ((NativeCallEvent) -> Void)? + + func systemEventReceived(_ event: NativeCallEvent) { + systemEventReceivedCallsCountLock.withLock { systemEventReceivedUnderlyingCallsCount += 1 } + systemEventReceivedReceivedEvent = event + systemEventReceivedReceivedInvocationsLock.withLock { systemEventReceivedUnderlyingReceivedInvocations.append(event) } + systemEventReceivedClosure?(event) + } } nonisolated class ElementCallWidgetDriverMock: ElementCallWidgetDriverProtocol, @unchecked Sendable { var widgetID: String { diff --git a/ElementX/Sources/Screens/CallScreen/CallScreenViewModel.swift b/ElementX/Sources/Screens/CallScreen/CallScreenViewModel.swift index 45a33a64e..fb24505d1 100644 --- a/ElementX/Sources/Screens/CallScreen/CallScreenViewModel.swift +++ b/ElementX/Sources/Screens/CallScreen/CallScreenViewModel.swift @@ -30,12 +30,6 @@ class CallScreenViewModel: CallScreenViewModelType, CallScreenViewModelProtocol @CancellableTask private var timeoutTask: Task? - /// Designated initialiser - /// - Parameters: - /// - elementCallService: service responsible for setting up CallKit - /// - roomProxy: The room in which the call should be created - /// - callBaseURL: Which Element Call instance should be used - /// - clientID: Something to identify the current client on the Element Call side init(elementCallService: ElementCallServiceProtocol, configuration: ElementCallConfiguration, allowPictureInPicture: Bool, @@ -54,27 +48,6 @@ class CallScreenViewModel: CallScreenViewModelType, CallScreenViewModelProtocol state.swiftUICallViewCoordinator = .init(viewModelContext: context) - elementCallService.actions - .receive(on: DispatchQueue.main) - .sink { [weak self] action in - guard let self else { return } - - switch action { - case let .setAudioEnabled(enabled, roomID): - guard roomID == configuration.callRoomID else { - MXLog.error("Received mute request for a different room: \(roomID) != \(configuration.callRoomID)") - return - } - - Task { - await self.setAudioEnabled(enabled) - } - default: - break - } - } - .store(in: &cancellables) - widgetDriver.messagePublisher .receive(on: DispatchQueue.main) .sink { [weak self] receivedMessage in @@ -94,8 +67,9 @@ class CallScreenViewModel: CallScreenViewModelType, CallScreenViewModelProtocol switch action { case .callEnded: actionsSubject.send(.dismiss) - case .mediaStateChanged(let audioEnabled, _): - elementCallService.setAudioEnabled(audioEnabled, roomID: configuration.callRoomID) + case .mediaStateChanged: + // CallKit never tracks web calls, so their mute isn't relayed. + break } } .store(in: &cancellables) @@ -197,7 +171,8 @@ class CallScreenViewModel: CallScreenViewModelType, CallScreenViewModelProtocol await elementCallService.setupCallSession(roomID: configuration.roomProxy.id, roomDisplayName: configuration.roomProxy.infoPublisher.value.displayNameOrID, - isVideo: !configuration.voiceOnly) + isVideo: !configuration.voiceOnly, + kind: .webView) } timeoutTask = Task { [weak self] in @@ -237,14 +212,6 @@ class CallScreenViewModel: CallScreenViewModelType, CallScreenViewModelProtocol } } - private func setAudioEnabled(_ enabled: Bool) async { - let message = ElementCallWidgetMessage(direction: .toWidget, - action: .mediaState, - data: .init(audioEnabled: enabled), - widgetId: widgetDriver.widgetID) - await postMessageToWidget(message) - } - func hangup() async { let message = ElementCallWidgetMessage(direction: .fromWidget, action: .hangup, diff --git a/ElementX/Sources/Services/ElementCall/ElementCallManager.swift b/ElementX/Sources/Services/ElementCall/ElementCallManager.swift new file mode 100644 index 000000000..fcb6d912e --- /dev/null +++ b/ElementX/Sources/Services/ElementCall/ElementCallManager.swift @@ -0,0 +1,653 @@ +// +// Copyright 2025 Element Creations Ltd. +// Copyright 2024-2025 New Vector Ltd. +// +// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. +// Please see LICENSE files in the repository root for full details. +// + +import AVFoundation +import CallKit +import Combine +import Foundation +import PushKit +import UIKit + +/// Keep this class testable +struct TimeProvider { + var clock: any Clock + var now: () -> Date +} + +final class ElementCallManager: NSObject, ElementCallManagerProtocol, PKPushRegistryDelegate, CXProviderDelegate { + private struct CallID: Equatable { + let callKitID: UUID + let roomID: String + let rtcNotificationID: String? + let isVoiceCall: Bool + var isNative = false + } + + private let service: ElementCallServiceProtocol + private let appSettings: AppSettings + private let pushRegistry: PKPushRegistry + private let callController: CXCallControllerProtocol + private let callProvider: CXProviderProtocol + private let timeProvider: TimeProvider + + private let actionsSubject = PassthroughSubject() + var actionsPublisher: AnyPublisher { + actionsSubject.eraseToAnyPublisher() + } + + private var incomingCallID: CallID? { + didSet { + guard incomingCallID != oldValue else { return } + + if oldValue != nil { + service.stopObservingIncomingCall() + } + + if let incomingCallID { + Task { [weak self] in + guard let self, self.incomingCallID == incomingCallID else { return } + await service.observeIncomingCall(roomID: incomingCallID.roomID, rtcNotificationID: incomingCallID.rtcNotificationID) + } + } + } + } + + 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? + private var endPendingCallTask: Task? + + private var ongoingCallID: CallID? { + didSet { service.ongoingCallChanged(roomID: ongoingCallID?.roomID) } + } + + private var cancellables = Set() + + init(service: ElementCallServiceProtocol, + appSettings: AppSettings, + callProvider: CXProviderProtocol? = nil, + callController: CXCallControllerProtocol? = nil, + timeProvider: TimeProvider? = nil) { + self.service = service + self.appSettings = appSettings + self.callController = callController ?? CXCallController() + pushRegistry = PKPushRegistry(queue: nil) + + self.timeProvider = timeProvider ?? TimeProvider(clock: ContinuousClock(), now: Date.init) + + if let callProvider { + self.callProvider = callProvider + } else { + let configuration = CXProviderConfiguration() + configuration.supportsVideo = true + configuration.includesCallsInRecents = true + + if let callKitIcon = UIImage(named: "images/app-logo") { + configuration.iconTemplateImageData = callKitIcon.pngData() + } + + // https://stackoverflow.com/a/46077628/730924 + configuration.supportedHandleTypes = [.generic] + + self.callProvider = CXProvider(configuration: configuration) + } + + super.init() + + pushRegistry.delegate = self + pushRegistry.desiredPushTypes = [.voIP] + + self.callProvider.setDelegate(self, queue: nil) + + // Synchronous: a call screen's set-up waits on the reply, which a web call gets straight away. + service.actionsPublisher + .sink { [weak self] action in + self?.handleServiceAction(action) + } + .store(in: &cancellables) + } + + private func handleServiceAction(_ action: ElementCallServiceAction) { + switch action { + case let .callSessionStarted(roomID, roomDisplayName, isVideo, kind): + setupCallSession(roomID: roomID, roomDisplayName: roomDisplayName, isVideo: isVideo, isNative: kind != .webView) + case .callSessionConnected(let roomID): + reportCallSessionConnected(roomID: roomID) + case .callSessionEnded(let roomID, .none): + tearDownCallSession(roomID: roomID) + case .callSessionEnded(let roomID, .some(let reason)): + reportCallSessionEnded(roomID: roomID, reason: reason) + case let .audioEnabledChanged(enabled, roomID): + setAudioEnabled(enabled, roomID: roomID) + case let .incomingCallEnded(roomID, reason): + incomingCallEnded(roomID: roomID, reason: reason) + } + } + + /// Replies to the service exactly once, when the call is set up: at once, or for a new native + /// call once CallKit knows about it. + private func setupCallSession(roomID: String, roomDisplayName: String, isVideo: Bool, isNative: Bool) { + MXLog.info("Setting up a call session, native: \(isNative), video: \(isVideo), replacing an ongoing call: \(ongoingCallID != nil)") + + // Drop any ongoing calls when starting a new one + if ongoingCallID != nil { + tearDownCallSession(sendEndCallAction: true) + } + + // If this starting from a ring reuse those identifiers + // Make sure the roomID matches + var callID = if let incomingCallID, incomingCallID.roomID == roomID { + incomingCallID + } else { + CallID(callKitID: UUID(), roomID: roomID, rtcNotificationID: nil, isVoiceCall: !isVideo) + } + callID.isNative = isNative + let isAnsweringIncomingCall = callID.rtcNotificationID != nil + + clearIncomingCallState() + ongoingCallID = callID + + // A web view call must not be tracked by CallKit, as that gives this process exclusive + // access to media and the web view runs in another (see `CXAnswerCallAction`). + // https://developer.apple.com/forums//thread/767949?answerId=812951022#812951022 + guard isNative else { + service.callSessionSetUp(roomID: roomID, isAccepted: true) + return + } + + // Answering the ringing call: it is already reported, keep it. + guard !isAnsweringIncomingCall else { + service.callSessionSetUp(roomID: roomID, isAccepted: true) + return + } + + let handle = CXHandle(type: .generic, value: roomID) + let startCallAction = CXStartCallAction(call: callID.callKitID, handle: handle) + startCallAction.contactIdentifier = roomDisplayName + startCallAction.isVideo = isVideo + + Task { [weak self, service] in + // Awaited because our membership goes out straight after: a peer that sees it before the + // system knows about the call reads the call as answered elsewhere. + await self?.requestTransaction(CXTransaction(action: startCallAction), describedAs: "start call") + + // Without this the system call UI shows the handle, i.e. the room ID. + let update = CXCallUpdate() + update.localizedCallerName = roomDisplayName + update.remoteHandle = handle + update.hasVideo = isVideo + self?.callProvider.reportCall(with: callID.callKitID, updated: update) + + service.callSessionSetUp(roomID: roomID, isAccepted: true) + } + } + + private func reportCallSessionConnected(roomID: String) { + guard let ongoingCallID, ongoingCallID.roomID == roomID else { + // The system ends an outgoing call that never reports connecting, so a silent guard + // here shows up much later as a call that hangs itself up. + MXLog.warning("Not reporting the call as connected, no matching ongoing call") + return + } + + guard ongoingCallID.isNative else { + MXLog.info("Not reporting a web view call as connected, CallKit doesn't track it") + return + } + + MXLog.info("Reporting the call as connected") + callProvider.reportOutgoingCall(with: ongoingCallID.callKitID, connectedAt: nil) + } + + private func tearDownCallSession(roomID: String) { + if ongoingCallID?.roomID == roomID { + tearDownCallSession(sendEndCallAction: true) + return + } + + dropAnsweredCall(roomID: roomID) + } + + func dropAnsweredCall(roomID: String) { + // Answered and handed over, but the stack couldn't take it. Ending it here rather than + // waiting for the watchdog takes the system call UI away straight away. + if answeredNativeCallID?.roomID == roomID { + MXLog.warning("Ending an answered call the native call stack didn't take over") + endPendingCall() + 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 dropping an answered call, none for room \(roomID)") + } + + private func reportCallSessionEnded(roomID: String, reason: CallEndReason) { + guard let ongoingCallID, ongoingCallID.roomID == roomID else { + MXLog.info("Not reporting the end of a call for \(roomID), it isn't the ongoing call") + return + } + + // A web view call is not tracked by CallKit, as in `reportCallSessionConnected`. + if ongoingCallID.isNative { + MXLog.info("Reporting the call as ended without us: \(reason)") + callProvider.reportCall(with: ongoingCallID.callKitID, endedAt: nil, reason: CXCallEndedReason(reason)) + } + + self.ongoingCallID = nil + } + + private func setAudioEnabled(_ enabled: Bool, roomID: String) { + guard let ongoingCallID else { + MXLog.error("Failed toggling call microphone, no calls running") + return + } + + guard ongoingCallID.roomID == roomID else { + MXLog.error("Failed toggling call microphone, rooms don't match: \(ongoingCallID.roomID) != \(roomID)") + return + } + + let transaction = CXTransaction(action: CXSetMutedCallAction(call: ongoingCallID.callKitID, muted: !enabled)) + callController.request(transaction) { error in + if let error { + MXLog.error("Failed toggling call microphone with error: \(error)") + } + } + } + + /// The service saw the ringing call end elsewhere: hung up, or answered or declined on another device. + private func incomingCallEnded(roomID: String, reason: CallEndReason) { + guard let incomingCallID, incomingCallID.roomID == roomID else { + MXLog.info("Not ending the incoming call, no call ringing for room \(roomID)") + return + } + + reportEndedCall(incomingCallID: incomingCallID, reason: CXCallEndedReason(reason)) + } + + // MARK: - PKPushRegistryDelegate + + func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) { } + + func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) { + guard let roomID = payload.dictionaryPayload[ElementCallServiceNotificationKey.roomID.rawValue] as? String else { + MXLog.error("Something went wrong, missing room identifier for incoming voip call: \(payload)") + assertionFailure("Incoming voip push is missing the room identifier") + reportImmediatelyEndedCall(reason: .failed, completion: completion) + return + } + + guard let rtcNotificationID = payload.dictionaryPayload[ElementCallServiceNotificationKey.rtcNotifyEventID.rawValue] as? String else { + MXLog.error("Something went wrong, missing rtc notification event identifier for incoming voip call: \(payload)") + assertionFailure("Incoming voip push is missing the rtc notification event identifier") + reportImmediatelyEndedCall(reason: .failed, completion: completion) + return + } + + let roomDisplayName = payload.dictionaryPayload[ElementCallServiceNotificationKey.roomDisplayName.rawValue] as? String + + guard ongoingCallID?.roomID != roomID else { + MXLog.warning("Call already ongoing for room \(roomID), reporting the duplicate push as handled") + reportImmediatelyEndedCall(reason: .answeredElsewhere, + callerInfo: (roomID: roomID, roomDisplayName: roomDisplayName), + completion: completion) + 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) + incomingCallID = callID + + guard let expirationDate = (payload.dictionaryPayload[ElementCallServiceNotificationKey.expirationDate.rawValue] as? Date) else { + MXLog.error("Something went wrong, missing expiration timestamp for incoming voip call: \(payload)") + assertionFailure("Incoming voip push is missing the expiration timestamp") + clearIncomingCallState() + reportImmediatelyEndedCall(reason: .failed, completion: completion) + return + } + + let nowDate = timeProvider.now() + + guard nowDate < expirationDate else { + MXLog.warning("Call expired for room \(roomID), reporting it as missed") + clearIncomingCallState() + reportImmediatelyEndedCall(reason: .unanswered, + callerInfo: (roomID: roomID, roomDisplayName: roomDisplayName), + completion: completion) + return + } + + let ringDuration: Duration = .seconds(min(expirationDate.timeIntervalSince1970 - nowDate.timeIntervalSince1970, 90)) + + let update = CXCallUpdate() + // Work Around: Always set video to true! https://github.com/element-hq/element-x-ios/issues/5335 + // If not for audio call the app will not be put to foreground and the webview won't be able to handle the call... + // Consequence: The call will be presented to the user as a video call in CallKit UI, + // but once Element Call is launched it will correctly route to a voice-only call. + update.hasVideo = appSettings.nativeCallEnabled ? !isVoiceCall : true + update.localizedCallerName = roomDisplayName + // https://stackoverflow.com/a/41230020/730924 + update.remoteHandle = .init(type: .generic, value: roomID) + + // The push registry uses the main queue so the completion is main actor bound, + // whereas CallKit invokes its completion on a background queue. + let mainActorCompletion = { @MainActor @Sendable in completion() } + callProvider.reportNewIncomingCall(with: callID.callKitID, update: update) { [weak self] error in + if let error { + MXLog.error("Failed reporting new incoming call with error: \(error)") + } + + Task { @MainActor in + self?.actionsSubject.send(.incomingCallReported) + + mainActorCompletion() + } + } + + endUnansweredCallTask = Task { [weak self] in + try? await self?.timeProvider.clock.sleep(for: ringDuration) + + guard let self, !Task.isCancelled else { + return + } + + if let incomingCallID, incomingCallID.callKitID == callID.callKitID { + callProvider.reportCall(with: incomingCallID.callKitID, endedAt: nil, reason: .unanswered) + clearIncomingCallState() + } + } + } + + // MARK: - CXProviderDelegate + + func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) { + MXLog.info("Call provider did activate audio session") + service.systemEventReceived(.audioSessionActivated) + } + + func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) { + MXLog.info("Call provider did deactivate audio session") + service.systemEventReceived(.audioSessionDeactivated) + } + + func provider(_ provider: CXProvider, perform action: CXStartCallAction) { + // The native controller configured the audio session already; CallKit activates it and + // reports back through `didActivate`. + action.fulfill() + callProvider.reportOutgoingCall(with: action.callUUID, startedConnectingAt: nil) + } + + func providerDidReset(_ provider: CXProvider) { + MXLog.info("Call provider did reset: \(provider)") + } + + func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) { + guard let incomingCallID else { + MXLog.error("Failed answering incoming call, missing incomingCallID") + return + } + + // Fixes broken videos on EC web when a CallKit session is established. + // + // Reporting an ongoing call through `reportNewIncomingCall` + `CXAnswerCallAction` + // or `reportOutgoingCall:connectedAt:` will give exclusive access for media to the + // ongoing process, which is different than the WKWebKit is running on, making EC + // unable to aquire media streams. + // Reporting the call as ended imediately after answering it works around that + // as EC gets access to media again and EX builds the right UI in `setupCallSession` + // + // https://developer.apple.com/forums//thread/767949?answerId=812951022#812951022 + // + // https://github.com/element-hq/element-x-ios/issues/3041 + // https://forums.developer.apple.com/forums/thread/685268 + // https://stackoverflow.com/questions/71483732/webrtc-running-from-wkwebview-avaudiosession-development-roadblock + + // First fullfill the action + action.fulfill() + + if appSettings.nativeCallEnabled { + // The native stack owns media in this process, so the CallKit call stays up: the + // controller attaches to it in `setupCallSession`. + endUnansweredCallTask?.cancel() + endCallIfLeftPending(incomingCallID) + actionsSubject.send(.callAnswered(roomID: incomingCallID.roomID, isVoiceCall: incomingCallID.isVoiceCall)) + return + } + + // Cancelled now rather than after the delay, by when it may belong to a call that rang since. + endUnansweredCallTask?.cancel() + isIncomingCallAnswered = true + dropAnsweredCallIfItNeverOpens(incomingCallID) + + // And delay ending the call so that the app has enough time + // to get deeplinked into + DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { + // Then end the and call rely on `setupCallSession` to create a new one + provider.reportCall(with: incomingCallID.callKitID, endedAt: nil, reason: .remoteEnded) + + self.actionsSubject.send(.callAnswered(roomID: incomingCallID.roomID, isVoiceCall: incomingCallID.isVoiceCall)) + } + } + + func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) { + if ongoingCallID != nil { + service.systemEventReceived(.microphoneMuteChanged(isMuted: action.isMuted)) + } else { + MXLog.info("Ignoring a mute action without an ongoing call") + } + + action.fulfill() + } + + func provider(_ provider: CXProvider, perform action: CXEndCallAction) { + #if targetEnvironment(simulator) + // This gets called for no reason on simulators, where CallKit + // isn't even supported, ignore it. + #else + endCall(withCallKitID: action.callUUID) + action.fulfill() + #endif + } + + /// Ends the call the system identified, whether that's the ongoing one, the ringing one, or + /// neither because it has already been replaced. + /// + /// Kept out of the delegate method so that it's reachable on the simulator, where the provider + /// performs end call actions of its own and the delegate has to ignore them. + func endCall(withCallKitID callKitID: UUID) { + MXLog.info("Ending the call for \(callKitID), ongoing: \(ongoingCallID != nil), incoming: \(incomingCallID != nil)") + + // Both branches are gated on the identifier. Leaving a call to start one in another room + // requests an end call action for the old call and replaces `ongoingCallID` before the + // system gets round to performing it, so an ungated handler reads it as the new call ending + // and hangs up the call that was just started. + if let ongoingCallID, ongoingCallID.callKitID == callKitID { + service.systemEventReceived(.endCallRequested(roomID: ongoingCallID.roomID)) + tearDownCallSession(sendEndCallAction: false) + } + + if let incomingCallID, incomingCallID.callKitID == callKitID { + if let rtcNotificationID = incomingCallID.rtcNotificationID { + Task { [service] in + await service.declineCall(roomID: incomingCallID.roomID, rtcNotificationID: rtcNotificationID) + } + } else { + MXLog.info("No rtc notification event to decline.") + } + + clearIncomingCallState() + } + } + + // MARK: - Private + + /// Bridges the controller's completion handler, which is all ``CXCallControllerProtocol`` can + /// carry, back to an awaitable call. + private func requestTransaction(_ transaction: CXTransaction, describedAs description: String) async { + await withCheckedContinuation { continuation in + callController.request(transaction) { error in + if let error { + MXLog.error("Failed requesting \(description) action with error: \(error)") + } + + continuation.resume() + } + } + } + + private func tearDownCallSession(sendEndCallAction: Bool = true) { + if sendEndCallAction, let ongoingCallID { + MXLog.info("Requesting an end call action for the ongoing call") + let transaction = CXTransaction(action: CXEndCallAction(call: ongoingCallID.callKitID)) + callController.request(transaction) { error in + if let error { + MXLog.error("Failed transaction with error: \(error)") + } + } + } + + ongoingCallID = nil + } + + /// Every VoIP push must be reported to CallKit via `reportNewIncomingCall`, otherwise iOS + /// terminates the app with `NSInternalInconsistencyException`. On early-return paths we report + /// a call and immediately end it. `callerInfo` names the call after the room so the brief + /// system UI and the Recents entry show the room rather than "Unknown", and the entry can be + /// tapped to call back. + private func reportImmediatelyEndedCall(reason: CXCallEndedReason, + callerInfo: (roomID: String, roomDisplayName: String?)? = nil, + completion: @escaping () -> Void) { + let callID = UUID() + let update = CXCallUpdate() + // Never answered through CallKit, so the hasVideo workaround for #5335 isn't needed. + update.hasVideo = false + + if let callerInfo { + update.localizedCallerName = callerInfo.roomDisplayName + update.remoteHandle = .init(type: .generic, value: callerInfo.roomID) + } + + // CallKit invokes the completion on a background queue, so hop back to the main actor + // to report the ended call and to run the (main actor bound) completion. + let mainActorCompletion = { @MainActor @Sendable in completion() } + callProvider.reportNewIncomingCall(with: callID, update: update) { [weak self] error in + if let error { + MXLog.error("Failed reporting immediately ended call with error: \(error)") + } + + Task { @MainActor in + self?.callProvider.reportCall(with: callID, endedAt: nil, reason: reason) + mainActorCompletion() + } + } + } + + /// Ends an answered call that the native stack never took over, which nothing else would: the + /// call is deliberately left up for the controller to attach to in `setupCallSession`. + private func endCallIfLeftPending(_ callID: CallID) { + answeredNativeCallID = callID + + endPendingCallTask = Task { [weak self] in + try? await self?.timeProvider.clock.sleep(for: .seconds(30)) + + guard let self, !Task.isCancelled, answeredNativeCallID == callID else { + return + } + + MXLog.error("The native call stack never took over the answered call, ending it") + endPendingCall() + } + } + + /// Drops a call answered for the web view that no call screen took over, e.g. one answered while signed out. + private func dropAnsweredCallIfItNeverOpens(_ callID: CallID) { + endPendingCallTask = Task { [weak self] in + try? await self?.timeProvider.clock.sleep(for: .seconds(30)) + + guard let self, !Task.isCancelled, isIncomingCallAnswered, incomingCallID == callID else { + return + } + + MXLog.error("No call screen took over the answered call, dropping it") + clearIncomingCallState() + } + } + + private func endPendingCall() { + guard let answeredNativeCallID else { + return + } + + callProvider.reportCall(with: answeredNativeCallID.callKitID, endedAt: nil, reason: .failed) + clearIncomingCallState() + } + + private func reportEndedCall(incomingCallID: CallID, reason: CXCallEndedReason) { + callProvider.reportCall(with: incomingCallID.callKitID, endedAt: nil, reason: reason) + clearIncomingCallState() + } + + /// Cancels every task tied to a ringing incoming call and nils `incomingCallID`, which stops the + /// service watching its room. Call this on every path that ends the incoming-call state (answered, + /// declined, timed out, cancelled by remote, answered/declined elsewhere) so that follow-up calls + /// to the same room start from a clean slate and the SDK decline-listener subscription doesn't leak. + private func clearIncomingCallState() { + endUnansweredCallTask?.cancel() + endUnansweredCallTask = nil + endPendingCallTask?.cancel() + endPendingCallTask = nil + answeredNativeCallID = nil + isIncomingCallAnswered = false + incomingCallID = nil + } +} + +private extension CXCallEndedReason { + init(_ reason: CallEndReason) { + self = switch reason { + case .remoteEnded: + .remoteEnded + case .answeredElsewhere: + .answeredElsewhere + case .declinedElsewhere: + .declinedElsewhere + case .unanswered: + .unanswered + case .failed: + .failed + } + } +} diff --git a/ElementX/Sources/Services/ElementCall/ElementCallManagerProtocol.swift b/ElementX/Sources/Services/ElementCall/ElementCallManagerProtocol.swift new file mode 100644 index 000000000..b52a66ac5 --- /dev/null +++ b/ElementX/Sources/Services/ElementCall/ElementCallManagerProtocol.swift @@ -0,0 +1,23 @@ +// +// Copyright 2026 Element Creations Ltd. +// +// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. +// Please see LICENSE files in the repository root for full details. +// + +import Combine + +enum ElementCallManagerAction: Equatable { + /// A VoIP push rang, which iOS delivers without starting the app's services. + case incomingCallReported + case callAnswered(roomID: String, isVoiceCall: Bool) +} + +// sourcery: AutoMockable +/// The app's single owner of VoIP pushes and CallKit: decides what rings, and tracks the ringing and ongoing calls. +protocol ElementCallManagerProtocol: AnyObject { + var actionsPublisher: AnyPublisher { get } + + /// Forgets a call that was answered but never opened, which would otherwise count as a call in progress. + func dropAnsweredCall(roomID: String) +} diff --git a/ElementX/Sources/Services/ElementCall/ElementCallService.swift b/ElementX/Sources/Services/ElementCall/ElementCallService.swift index e39d345f8..db7665dae 100644 --- a/ElementX/Sources/Services/ElementCall/ElementCallService.swift +++ b/ElementX/Sources/Services/ElementCall/ElementCallService.swift @@ -6,120 +6,62 @@ // Please see LICENSE files in the repository root for full details. // -import AVFoundation -import CallKit import Combine import ElementCall -import Foundation import MatrixRustSDK -import PushKit -import UIKit -/// Keep this class testable -struct TimeProvider { - var clock: any Clock - var now: () -> Date -} - -class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDelegate, CXProviderDelegate { - private struct CallID: Equatable { - let callKitID: UUID +/// The account's side of its calls: the ringing call's room, its decline, the ongoing call and the +/// native call stack. Relays what the call screens report up to the `ElementCallManager`. +final class ElementCallService: ElementCallServiceProtocol { + private struct ObservedCall: Equatable { let roomID: String let rtcNotificationID: String? - let isVoiceCall: Bool - var isNative = false } private let appSettings: AppSettings - private let pushRegistry: PKPushRegistry - private let callController: CXCallControllerProtocol - private let callProvider: CXProviderProtocol - private let timeProvider: TimeProvider - private weak var clientProxy: ClientProxyProtocol? { - didSet { - // There's a race condition where a call starts when the app has been killed and the - // observation set in `incomingCallID` occurs *before* the user session is restored. - // So observe when the client proxy is set to fix this (the method guards for the call). - Task { await observeIncomingCall() } - } + private weak var clientProxy: ClientProxyProtocol? + private var mediaProvider: MediaProviderProtocol? + + private let actionsSubject = PassthroughSubject() + var actionsPublisher: AnyPublisher { + actionsSubject.eraseToAnyPublisher() } - private var incomingCallRoomInfoCancellable: AnyCancellable? - private var incomingCallID: CallID? { - didSet { - Task { await observeIncomingCall() } - } - } - - 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? - private var endPendingCallTask: Task? - - private var ongoingCallID: CallID? { - didSet { ongoingCallRoomIDSubject.send(ongoingCallID?.roomID) } - } - - let ongoingCallRoomIDSubject = CurrentValueSubject(nil) + private let ongoingCallRoomIDSubject = CurrentValueSubject(nil) var ongoingCallRoomIDPublisher: CurrentValuePublisher { ongoingCallRoomIDSubject.asCurrentValuePublisher() } - private let actionsSubject: PassthroughSubject = .init() - var actions: AnyPublisher { - actionsSubject.eraseToAnyPublisher() + private let nativeCallEventsSubject = PassthroughSubject() + var nativeCallEventsPublisher: AnyPublisher { + nativeCallEventsSubject.eraseToAnyPublisher() } - private var declineListenerHandle: TaskHandle? + private let nativeCallPresentationSubject = PassthroughSubject() + var nativeCallPresentationPublisher: AnyPublisher { + nativeCallPresentationSubject.eraseToAnyPublisher() + } /// The native call stack, for as long as there's a session running calls through it. private var nativeCallStack: NativeCallStack? private var nativeCallCancellable: AnyCancellable? - private var mediaProvider: MediaProviderProtocol? var nativeCallController: ElementCallController? { nativeCallStack?.controller } + /// Call screens waiting in `setupCallSession` for the manager's reply, by room. + private var callSessionSetUpContinuations: [String: CheckedContinuation] = [:] + + private var observedCall: ObservedCall? + private var incomingCallRoomInfoCancellable: AnyCancellable? + private var declineListenerHandle: TaskHandle? + private var cancellables = Set() - init(appSettings: AppSettings, - callProvider: CXProviderProtocol? = nil, - callController: CXCallControllerProtocol? = nil, - timeProvider: TimeProvider? = nil) { + init(appSettings: AppSettings) { self.appSettings = appSettings - self.callController = callController ?? CXCallController() - pushRegistry = PKPushRegistry(queue: nil) - - self.timeProvider = timeProvider ?? TimeProvider(clock: ContinuousClock(), now: Date.init) - - if let callProvider { - self.callProvider = callProvider - } else { - let configuration = CXProviderConfiguration() - configuration.supportsVideo = true - configuration.includesCallsInRecents = true - - if let callKitIcon = UIImage(named: "images/app-logo") { - configuration.iconTemplateImageData = callKitIcon.pngData() - } - - // https://stackoverflow.com/a/46077628/730924 - configuration.supportedHandleTypes = [.generic] - - self.callProvider = CXProvider(configuration: configuration) - } - - super.init() - - pushRegistry.delegate = self - pushRegistry.desiredPushTypes = [.voIP] - - self.callProvider.setDelegate(self, queue: nil) appSettings.nativeCallEnabledPublisher .sink { [weak self] _ in @@ -129,15 +71,22 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe } func setUserSession(_ userSession: UserSessionProtocol?) { + let isNewClient = userSession?.clientProxy !== clientProxy + // A stack is built against one client proxy and can't be handed to another, which is what a // soft logout or a cache clear brings: a new session without the sign out that drops this one. - if userSession?.clientProxy !== clientProxy { + if isNewClient { stopNativeCallStack() + stopWatchingRoom() } clientProxy = userSession?.clientProxy mediaProvider = userSession?.mediaProvider + if isNewClient { + resumeObservingIncomingCall() + } + updateNativeCallStack() } @@ -159,132 +108,79 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe nativeCallStack?.restore() } - func setupCallSession(roomID: String, roomDisplayName: String, isVideo: Bool) async { - // Unlike the push handling below, this always runs with a session, so the stack itself is - // the answer rather than the setting that would have built one. - let isNative = nativeCallStack != nil - MXLog.info("Setting up a call session, native: \(isNative), video: \(isVideo), replacing an ongoing call: \(ongoingCallID != nil)") - - // Drop any ongoing calls when starting a new one - if ongoingCallID != nil { - tearDownCallSession(sendEndCallAction: true) + func setupCallSession(roomID: String, roomDisplayName: String, isVideo: Bool, kind: ElementCallSessionKind) async { + await withCheckedContinuation { continuation in + if let staleContinuation = callSessionSetUpContinuations.removeValue(forKey: roomID) { + MXLog.warning("Releasing a call session set-up for room \(roomID) that the manager never answered") + staleContinuation.resume() + } + + // Registered before sending, as the manager can answer from within the send. + callSessionSetUpContinuations[roomID] = continuation + actionsSubject.send(.callSessionStarted(roomID: roomID, roomDisplayName: roomDisplayName, isVideo: isVideo, kind: kind)) } - - // If this starting from a ring reuse those identifiers - // Make sure the roomID matches - var callID = if let incomingCallID, incomingCallID.roomID == roomID { - incomingCallID - } else { - CallID(callKitID: UUID(), roomID: roomID, rtcNotificationID: nil, isVoiceCall: !isVideo) - } - callID.isNative = isNative - let isAnsweringIncomingCall = callID.rtcNotificationID != nil - - clearIncomingCallState() - ongoingCallID = callID - - // A web view call must not be tracked by CallKit, as that gives this process exclusive - // access to media and the web view runs in another (see `CXAnswerCallAction`). - // https://developer.apple.com/forums//thread/767949?answerId=812951022#812951022 - guard isNative else { - return - } - - // Answering the ringing call: it is already reported, keep it. - guard !isAnsweringIncomingCall else { - return - } - - let handle = CXHandle(type: .generic, value: roomID) - let startCallAction = CXStartCallAction(call: callID.callKitID, handle: handle) - startCallAction.contactIdentifier = roomDisplayName - startCallAction.isVideo = isVideo - - // Awaited because our membership goes out straight after: a peer that sees it before the - // system knows about the call reads the call as answered elsewhere. - await requestTransaction(CXTransaction(action: startCallAction), describedAs: "start call") - - // Without this the system call UI shows the handle, i.e. the room ID. - let update = CXCallUpdate() - update.localizedCallerName = roomDisplayName - update.remoteHandle = handle - update.hasVideo = isVideo - callProvider.reportCall(with: callID.callKitID, updated: update) } func reportCallSessionConnected(roomID: String) { - guard let ongoingCallID, ongoingCallID.roomID == roomID else { - // The system ends an outgoing call that never reports connecting, so a silent guard - // here shows up much later as a call that hangs itself up. - MXLog.warning("Not reporting the call as connected, no matching ongoing call") - return - } - - guard ongoingCallID.isNative else { - MXLog.info("Not reporting a web view call as connected, CallKit doesn't track it") - return - } - - MXLog.info("Reporting the call as connected") - callProvider.reportOutgoingCall(with: ongoingCallID.callKitID, connectedAt: nil) + actionsSubject.send(.callSessionConnected(roomID: roomID)) } func tearDownCallSession(roomID: String) { - if ongoingCallID?.roomID == roomID { - tearDownCallSession(sendEndCallAction: true) - return - } - - // Answered and handed over, but the stack couldn't take it. Ending it here rather than - // waiting for the watchdog takes the system call UI away straight away. - if answeredNativeCallID?.roomID == roomID { - MXLog.warning("Ending an answered call the native call stack didn't take over") - endPendingCall() - 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)") + actionsSubject.send(.callSessionEnded(roomID: roomID, reason: nil)) } - func reportCallSessionEnded(roomID: String, reason: CXCallEndedReason) { - guard let ongoingCallID, ongoingCallID.roomID == roomID else { - MXLog.info("Not reporting the end of a call for \(roomID), it isn't the ongoing call") - return - } - - // A web view call is not tracked by CallKit, as in `reportCallSessionConnected`. - if ongoingCallID.isNative { - MXLog.info("Reporting the call as ended without us: \(reason.rawValue)") - callProvider.reportCall(with: ongoingCallID.callKitID, endedAt: nil, reason: reason) - } - - self.ongoingCallID = nil + func reportCallSessionEnded(roomID: String, reason: CallEndReason) { + actionsSubject.send(.callSessionEnded(roomID: roomID, reason: reason)) } func setAudioEnabled(_ enabled: Bool, roomID: String) { - guard let ongoingCallID else { - MXLog.error("Failed toggling call microphone, no calls running") + actionsSubject.send(.audioEnabledChanged(enabled, roomID: roomID)) + } + + func observeIncomingCall(roomID: String, rtcNotificationID: String?) async { + stopObservingIncomingCall() + + // Kept without a client too, as the push can come before the session does. + let call = ObservedCall(roomID: roomID, rtcNotificationID: rtcNotificationID) + observedCall = call + + await watch(call) + } + + func stopObservingIncomingCall() { + observedCall = nil + stopWatchingRoom() + } + + func declineCall(roomID: String, rtcNotificationID: String) async { + guard let clientProxy else { + MXLog.warning("A ClientProxy is needed to fetch the room.") return } - guard ongoingCallID.roomID == roomID else { - MXLog.error("Failed toggling call microphone, rooms don't match: \(ongoingCallID.roomID) != \(roomID)") + guard case let .joined(roomProxy) = await clientProxy.roomForIdentifier(roomID) else { + MXLog.warning("Failed to fetch a joined room to decline the incoming call.") return } - let transaction = CXTransaction(action: CXSetMutedCallAction(call: ongoingCallID.callKitID, muted: !enabled)) - callController.request(transaction) { error in - if let error { - MXLog.error("Failed toggling call microphone with error: \(error)") - } + _ = await roomProxy.declineCall(notificationID: rtcNotificationID) + } + + func ongoingCallChanged(roomID: String?) { + ongoingCallRoomIDSubject.send(roomID) + } + + func callSessionSetUp(roomID: String, isAccepted: Bool) { + guard let continuation = callSessionSetUpContinuations.removeValue(forKey: roomID) else { + MXLog.info("No call session set-up waiting for room \(roomID)") + return } + + continuation.resume() + } + + func systemEventReceived(_ event: NativeCallEvent) { + nativeCallEventsSubject.send(event) } // MARK: - Native calls @@ -323,7 +219,7 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe nativeCallCancellable = stack.actions .sink { [weak self] presentation in - self?.actionsSubject.send(.nativeCall(presentation)) + self?.nativeCallPresentationSubject.send(presentation) } Task { await stack.start() } @@ -335,362 +231,34 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe nativeCallCancellable = nil nativeCallStack.stop() - actionsSubject.send(.nativeCall(.dismiss)) - } - - // MARK: - PKPushRegistryDelegate - - func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) { } - - func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) { - guard let roomID = payload.dictionaryPayload[ElementCallServiceNotificationKey.roomID.rawValue] as? String else { - MXLog.error("Something went wrong, missing room identifier for incoming voip call: \(payload)") - assertionFailure("Incoming voip push is missing the room identifier") - reportImmediatelyEndedCall(reason: .failed, completion: completion) - return - } - - guard let rtcNotificationID = payload.dictionaryPayload[ElementCallServiceNotificationKey.rtcNotifyEventID.rawValue] as? String else { - MXLog.error("Something went wrong, missing rtc notification event identifier for incoming voip call: \(payload)") - assertionFailure("Incoming voip push is missing the rtc notification event identifier") - reportImmediatelyEndedCall(reason: .failed, completion: completion) - return - } - - let roomDisplayName = payload.dictionaryPayload[ElementCallServiceNotificationKey.roomDisplayName.rawValue] as? String - - guard ongoingCallID?.roomID != roomID else { - MXLog.warning("Call already ongoing for room \(roomID), reporting the duplicate push as handled") - reportImmediatelyEndedCall(reason: .answeredElsewhere, - callerInfo: (roomID: roomID, roomDisplayName: roomDisplayName), - completion: completion) - 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) - incomingCallID = callID - - guard let expirationDate = (payload.dictionaryPayload[ElementCallServiceNotificationKey.expirationDate.rawValue] as? Date) else { - MXLog.error("Something went wrong, missing expiration timestamp for incoming voip call: \(payload)") - assertionFailure("Incoming voip push is missing the expiration timestamp") - clearIncomingCallState() - reportImmediatelyEndedCall(reason: .failed, completion: completion) - return - } - - let nowDate = timeProvider.now() - - guard nowDate < expirationDate else { - MXLog.warning("Call expired for room \(roomID), reporting it as missed") - clearIncomingCallState() - reportImmediatelyEndedCall(reason: .unanswered, - callerInfo: (roomID: roomID, roomDisplayName: roomDisplayName), - completion: completion) - return - } - - let ringDuration: Duration = .seconds(min(expirationDate.timeIntervalSince1970 - nowDate.timeIntervalSince1970, 90)) - - let update = CXCallUpdate() - // Work Around: Always set video to true! https://github.com/element-hq/element-x-ios/issues/5335 - // If not for audio call the app will not be put to foreground and the webview won't be able to handle the call... - // Consequence: The call will be presented to the user as a video call in CallKit UI, - // but once Element Call is launched it will correctly route to a voice-only call. - update.hasVideo = appSettings.nativeCallEnabled ? !isVoiceCall : true - update.localizedCallerName = roomDisplayName - // https://stackoverflow.com/a/41230020/730924 - update.remoteHandle = .init(type: .generic, value: roomID) - - // The push registry uses the main queue so the completion is main actor bound, - // whereas CallKit invokes its completion on a background queue. - let mainActorCompletion = { @MainActor @Sendable in completion() } - callProvider.reportNewIncomingCall(with: callID.callKitID, update: update) { [weak self] error in - if let error { - MXLog.error("Failed reporting new incoming call with error: \(error)") - } - - Task { @MainActor in - self?.actionsSubject.send(.receivedIncomingCallRequest) - - mainActorCompletion() - } - } - - endUnansweredCallTask = Task { [weak self] in - try? await self?.timeProvider.clock.sleep(for: ringDuration) - - guard let self, !Task.isCancelled else { - return - } - - if let incomingCallID, incomingCallID.callKitID == callID.callKitID { - callProvider.reportCall(with: incomingCallID.callKitID, endedAt: nil, reason: .unanswered) - clearIncomingCallState() - } - } - } - - // MARK: - CXProviderDelegate - - func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) { - MXLog.info("Call provider did activate audio session") - actionsSubject.send(.audioSessionActivated) - } - - func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) { - MXLog.info("Call provider did deactivate audio session") - actionsSubject.send(.audioSessionDeactivated) - } - - func provider(_ provider: CXProvider, perform action: CXStartCallAction) { - // The native controller configured the audio session already; CallKit activates it and - // reports back through `didActivate`. - action.fulfill() - callProvider.reportOutgoingCall(with: action.callUUID, startedConnectingAt: nil) - } - - func providerDidReset(_ provider: CXProvider) { - MXLog.info("Call provider did reset: \(provider)") - } - - func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) { - guard let incomingCallID else { - MXLog.error("Failed answering incoming call, missing incomingCallID") - return - } - - // Fixes broken videos on EC web when a CallKit session is established. - // - // Reporting an ongoing call through `reportNewIncomingCall` + `CXAnswerCallAction` - // or `reportOutgoingCall:connectedAt:` will give exclusive access for media to the - // ongoing process, which is different than the WKWebKit is running on, making EC - // unable to aquire media streams. - // Reporting the call as ended imediately after answering it works around that - // as EC gets access to media again and EX builds the right UI in `setupCallSession` - // - // https://developer.apple.com/forums//thread/767949?answerId=812951022#812951022 - // - // https://github.com/element-hq/element-x-ios/issues/3041 - // https://forums.developer.apple.com/forums/thread/685268 - // https://stackoverflow.com/questions/71483732/webrtc-running-from-wkwebview-avaudiosession-development-roadblock - - // First fullfill the action - action.fulfill() - - if appSettings.nativeCallEnabled { - // The native stack owns media in this process, so the CallKit call stays up: the - // controller attaches to it in `setupCallSession`. - endUnansweredCallTask?.cancel() - endCallIfLeftPending(incomingCallID) - actionsSubject.send(.startCall(roomID: incomingCallID.roomID, isVoiceCall: incomingCallID.isVoiceCall)) - 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) { - // Then end the and call rely on `setupCallSession` to create a new one - provider.reportCall(with: incomingCallID.callKitID, endedAt: nil, reason: .remoteEnded) - - self.actionsSubject.send(.startCall(roomID: incomingCallID.roomID, isVoiceCall: incomingCallID.isVoiceCall)) - } - } - - func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) { - if let ongoingCallID { - actionsSubject.send(.setAudioEnabled(!action.isMuted, roomID: ongoingCallID.roomID)) - } else { - MXLog.info("Ignoring a mute action without an ongoing call") - } - - action.fulfill() - } - - func provider(_ provider: CXProvider, perform action: CXEndCallAction) { - #if targetEnvironment(simulator) - // This gets called for no reason on simulators, where CallKit - // isn't even supported, ignore it. - #else - endCall(withCallKitID: action.callUUID) - action.fulfill() - #endif - } - - /// Ends the call the system identified, whether that's the ongoing one, the ringing one, or - /// neither because it has already been replaced. - /// - /// Kept out of the delegate method so that it's reachable on the simulator, where the provider - /// performs end call actions of its own and the delegate has to ignore them. - func endCall(withCallKitID callKitID: UUID) { - MXLog.info("Ending the call for \(callKitID), ongoing: \(ongoingCallID != nil), incoming: \(incomingCallID != nil)") - - // Both branches are gated on the identifier. Leaving a call to start one in another room - // requests an end call action for the old call and replaces `ongoingCallID` before the - // system gets round to performing it, so an ungated handler reads it as the new call ending - // and hangs up the call that was just started. - if let ongoingCallID, ongoingCallID.callKitID == callKitID { - actionsSubject.send(.endCall(roomID: ongoingCallID.roomID)) - tearDownCallSession(sendEndCallAction: false) - } - - if let incomingCallID, incomingCallID.callKitID == callKitID { - Task { - await sendDeclineCallEvent(incomingCallID) - } - - clearIncomingCallState() - } + nativeCallPresentationSubject.send(.dismiss) } // MARK: - Private - /// Bridges the controller's completion handler, which is all ``CXCallControllerProtocol`` can - /// carry, back to an awaitable call. - private func requestTransaction(_ transaction: CXTransaction, describedAs description: String) async { - await withCheckedContinuation { continuation in - callController.request(transaction) { error in - if let error { - MXLog.error("Failed requesting \(description) action with error: \(error)") - } - - continuation.resume() - } + /// Watches the ringing call with the new client, which also covers a call requested before any session. + private func resumeObservingIncomingCall() { + guard let call = observedCall, clientProxy != nil else { return } + + Task { [weak self] in + guard let self, observedCall == call else { return } + await watch(call) } } - private func tearDownCallSession(sendEndCallAction: Bool = true) { - if sendEndCallAction, let ongoingCallID { - MXLog.info("Requesting an end call action for the ongoing call") - let transaction = CXTransaction(action: CXEndCallAction(call: ongoingCallID.callKitID)) - callController.request(transaction) { error in - if let error { - MXLog.error("Failed transaction with error: \(error)") - } - } - } - - ongoingCallID = nil - } - - /// Every VoIP push must be reported to CallKit via `reportNewIncomingCall`, otherwise iOS - /// terminates the app with `NSInternalInconsistencyException`. On early-return paths we report - /// a call and immediately end it. `callerInfo` names the call after the room so the brief - /// system UI and the Recents entry show the room rather than "Unknown", and the entry can be - /// tapped to call back. - private func reportImmediatelyEndedCall(reason: CXCallEndedReason, - callerInfo: (roomID: String, roomDisplayName: String?)? = nil, - completion: @escaping () -> Void) { - let callID = UUID() - let update = CXCallUpdate() - // Never answered through CallKit, so the hasVideo workaround for #5335 isn't needed. - update.hasVideo = false - - if let callerInfo { - update.localizedCallerName = callerInfo.roomDisplayName - update.remoteHandle = .init(type: .generic, value: callerInfo.roomID) - } - - // CallKit invokes the completion on a background queue, so hop back to the main actor - // to report the ended call and to run the (main actor bound) completion. - let mainActorCompletion = { @MainActor @Sendable in completion() } - callProvider.reportNewIncomingCall(with: callID, update: update) { [weak self] error in - if let error { - MXLog.error("Failed reporting immediately ended call with error: \(error)") - } - - Task { @MainActor in - self?.callProvider.reportCall(with: callID, endedAt: nil, reason: reason) - mainActorCompletion() - } - } - } - - /// Ends an answered call that the native stack never took over, which nothing else would: the - /// call is deliberately left up for the controller to attach to in `setupCallSession`. - private func endCallIfLeftPending(_ callID: CallID) { - answeredNativeCallID = callID - - endPendingCallTask = Task { [weak self] in - try? await self?.timeProvider.clock.sleep(for: .seconds(30)) - - guard let self, !Task.isCancelled, answeredNativeCallID == callID else { - return - } - - MXLog.error("The native call stack never took over the answered call, ending it") - endPendingCall() - } - } - - private func endPendingCall() { - guard let answeredNativeCallID else { - return - } - - callProvider.reportCall(with: answeredNativeCallID.callKitID, endedAt: nil, reason: .failed) - clearIncomingCallState() - } - - private func sendDeclineCallEvent(_ incomingCallID: CallID) async { - guard let rtcNotificationID = incomingCallID.rtcNotificationID else { - MXLog.info("No rtc notification event to decline.") - return - } - + private func watch(_ call: ObservedCall) async { guard let clientProxy else { - MXLog.warning("A ClientProxy is needed to fetch the room.") + MXLog.info("No session yet to watch the incoming call with") return } - guard case let .joined(roomProxy) = await clientProxy.roomForIdentifier(incomingCallID.roomID) else { + guard case let .joined(roomProxy) = await clientProxy.roomForIdentifier(call.roomID) else { MXLog.warning("Failed to fetch a joined room for the incoming call.") return } - _ = await roomProxy.declineCall(notificationID: rtcNotificationID) - } - - private func observeIncomingCall() async { - incomingCallRoomInfoCancellable = nil - - guard let incomingCallID else { - MXLog.info("No incoming call to observe for.") - return - } - - guard let clientProxy else { - MXLog.warning("A ClientProxy is needed to fetch the room.") - return - } - - guard case let .joined(roomProxy) = await clientProxy.roomForIdentifier(incomingCallID.roomID) else { - MXLog.warning("Failed to fetch a joined room for the incoming call.") - return - } + // Stopped, another call started ringing, or the session changed while the room was being fetched. + guard observedCall == call, self.clientProxy === clientProxy else { return } roomProxy.subscribeToRoomInfoUpdates() @@ -706,18 +274,16 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe .sink { [weak self] hasOngoingCall, activeRoomCallParticipants in guard let self else { return } - let participants: [String] = activeRoomCallParticipants - if !hasOngoingCall { MXLog.info("Call cancelled by remote") - reportEndedCall(incomingCallID: incomingCallID, reason: .remoteEnded) - } else if participants.contains(roomProxy.ownUserID) { + incomingCallEnded(call, reason: .remoteEnded) + } else if activeRoomCallParticipants.contains(roomProxy.ownUserID) { MXLog.info("Call answered elsewhere") - reportEndedCall(incomingCallID: incomingCallID, reason: .answeredElsewhere) + incomingCallEnded(call, reason: .answeredElsewhere) } } - guard let rtcNotificationID = incomingCallID.rtcNotificationID else { + guard let rtcNotificationID = call.rtcNotificationID else { MXLog.warning("Decline: No RTC notification ID found for the incoming call.") return } @@ -730,9 +296,8 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe MXLog.debug("Call declined event received from \(senderID)") if senderID == roomProxy.ownUserID { - // Stop ringing! MXLog.debug("Call declined elsewhere") - reportEndedCall(incomingCallID: incomingCallID, reason: .declinedElsewhere) + incomingCallEnded(call, reason: .declinedElsewhere) } } @@ -744,25 +309,17 @@ class ElementCallService: NSObject, ElementCallServiceProtocol, PKPushRegistryDe declineListenerHandle = handle } - private func reportEndedCall(incomingCallID: CallID, reason: CXCallEndedReason) { - callProvider.reportCall(with: incomingCallID.callKitID, endedAt: nil, reason: reason) - clearIncomingCallState() - } - - /// Cancels every subscription and task tied to a ringing incoming call and nils `incomingCallID`. - /// Call this on every path that ends the incoming-call state (answered, declined, timed out, - /// cancelled by remote, answered/declined elsewhere) so that follow-up calls to the same room - /// start from a clean slate and the SDK decline-listener subscription doesn't leak. - private func clearIncomingCallState() { - endUnansweredCallTask?.cancel() - endUnansweredCallTask = nil - endPendingCallTask?.cancel() - endPendingCallTask = nil - answeredNativeCallID = nil - isIncomingCallAnswered = false + /// Drops the room subscriptions and keeps the ringing call, which a session can pick up again. + private func stopWatchingRoom() { + incomingCallRoomInfoCancellable = nil declineListenerHandle?.cancel() declineListenerHandle = nil - incomingCallRoomInfoCancellable = nil - incomingCallID = nil + } + + /// Reports the end once, as the room and the decline listener can both see it. + private func incomingCallEnded(_ call: ObservedCall, reason: CallEndReason) { + guard observedCall == call else { return } + stopObservingIncomingCall() + actionsSubject.send(.incomingCallEnded(roomID: call.roomID, reason: reason)) } } diff --git a/ElementX/Sources/Services/ElementCall/ElementCallServiceProtocol.swift b/ElementX/Sources/Services/ElementCall/ElementCallServiceProtocol.swift index a0e4abfcb..76ff1eb2c 100644 --- a/ElementX/Sources/Services/ElementCall/ElementCallServiceProtocol.swift +++ b/ElementX/Sources/Services/ElementCall/ElementCallServiceProtocol.swift @@ -6,7 +6,6 @@ // Please see LICENSE files in the repository root for full details. // -import CallKit import Combine import ElementCall @@ -18,24 +17,54 @@ enum NativeCallPresentation: Equatable { case dismiss } -enum ElementCallServiceAction { - case receivedIncomingCallRequest - case startCall(roomID: String, isVoiceCall: Bool) - case endCall(roomID: String) - case setAudioEnabled(_ enabled: Bool, roomID: String) - /// CallKit activated the audio session: a native call may start its audio engine now. +/// What CallKit asks of the native call. +enum NativeCallEvent: Equatable { case audioSessionActivated case audioSessionDeactivated - /// The native call's screen needs presenting, minimizing, restoring or dismissing. - case nativeCall(NativeCallPresentation) + /// The mute changed outside the call screen, from the lock screen or the system call UI. + case microphoneMuteChanged(isMuted: Bool) + /// The system ended the call, from the lock screen or because the user hung up elsewhere. + case endCallRequested(roomID: String) +} + +/// Why a call ended without us, which the system shows in the call log. +enum CallEndReason: Equatable { + case remoteEnded + case answeredElsewhere + case declinedElsewhere + case unanswered + case failed +} + +enum ElementCallSessionKind: Equatable { + case webView + case native + case nativeAnswer +} + +/// What the service asks of the `ElementCallManager`, which owns CallKit and the VoIP pushes. +enum ElementCallServiceAction: Equatable { + case callSessionStarted(roomID: String, roomDisplayName: String, isVideo: Bool, kind: ElementCallSessionKind) + case callSessionConnected(roomID: String) + /// A `nil` reason means the call ended here: our hang-up, or the call screen closing. + case callSessionEnded(roomID: String, reason: CallEndReason?) + case audioEnabledChanged(_ enabled: Bool, roomID: String) + /// The ringing call ended without the user: hung up, or answered or declined on another device. + case incomingCallEnded(roomID: String, reason: CallEndReason) } // sourcery: AutoMockable protocol ElementCallServiceProtocol: AnyObject { - var actions: AnyPublisher { get } + var actionsPublisher: AnyPublisher { get } var ongoingCallRoomIDPublisher: CurrentValuePublisher { get } + /// What CallKit asks of the native call: audio session changes, mutes and hang-ups. + var nativeCallEventsPublisher: AnyPublisher { get } + + /// The native call's screen needs presenting, minimizing, restoring or dismissing. + var nativeCallPresentationPublisher: AnyPublisher { get } + /// The controller for this session's native call stack, `nil` when native calls are unavailable. var nativeCallController: ElementCallController? { get } @@ -44,7 +73,7 @@ protocol ElementCallServiceProtocol: AnyObject { func setUserSession(_ userSession: UserSessionProtocol?) /// Starts, or returns to, a native call in the room, driving its screen through - /// ``ElementCallServiceAction/nativeCall(_:)``. + /// ``nativeCallPresentationPublisher``. /// /// Returns `false` when there's no native call stack and the caller should present the Element /// Call web view instead. @@ -52,14 +81,15 @@ protocol ElementCallServiceProtocol: AnyObject { func handleNativeCallRequest(roomProxy: JoinedRoomProxyProtocol, isVoiceCall: Bool) -> Bool /// Asks the native call to minimize. The screen only comes down once a system window has - /// started, which arrives as ``ElementCallServiceAction/nativeCall(_:)``. + /// started, which arrives through ``nativeCallPresentationPublisher``. func minimizeNativeCall() /// Brings the native call back out of its system window. func restoreNativeCall() /// Registers the call with CallKit, adopting the ringing incoming call for the room if there is one. - func setupCallSession(roomID: String, roomDisplayName: String, isVideo: Bool) async + /// Returns once the manager has set the call up. + func setupCallSession(roomID: String, roomDisplayName: String, isVideo: Bool, kind: ElementCallSessionKind) async /// Tells CallKit the call is connected. Does nothing for web view calls, which CallKit never tracks. func reportCallSessionConnected(roomID: String) @@ -70,7 +100,19 @@ protocol ElementCallServiceProtocol: AnyObject { /// The call for the room ended without us: declined, unanswered, the other side gone, or failed. /// Reported to the system as such rather than as an end call action, which would log it as one /// we hung up and ask the call stack to end a call it already has. - func reportCallSessionEnded(roomID: String, reason: CXCallEndedReason) + func reportCallSessionEnded(roomID: String, reason: CallEndReason) + /// Mirrors the native call's mute into CallKit. Web view calls aren't tracked there, so they + /// never call this. func setAudioEnabled(_ enabled: Bool, roomID: String) + + /// Watches the room of the ringing call, reporting when it stops ringing elsewhere. + func observeIncomingCall(roomID: String, rtcNotificationID: String?) async + func stopObservingIncomingCall() + func declineCall(roomID: String, rtcNotificationID: String) async + func ongoingCallChanged(roomID: String?) + /// Completes the room's `setupCallSession`. + func callSessionSetUp(roomID: String, isAccepted: Bool) + /// CallKit's side of the native call: the audio session, mutes and hang-ups. + func systemEventReceived(_ event: NativeCallEvent) } diff --git a/ElementX/Sources/Services/NativeCall/NativeCallSystem.swift b/ElementX/Sources/Services/NativeCall/NativeCallSystem.swift index 0d92adad2..bb0980f37 100644 --- a/ElementX/Sources/Services/NativeCall/NativeCallSystem.swift +++ b/ElementX/Sources/Services/NativeCall/NativeCallSystem.swift @@ -5,7 +5,6 @@ // Please see LICENSE files in the repository root for full details. // -import CallKit import Combine import ElementCall @@ -19,37 +18,17 @@ final class NativeCallSystem: ElementCallSystemProvidingProtocol { /// Stored so the events keep flowing off the subject itself, without reaching back through the /// weak reference on every subscription. - private let serviceActions: AnyPublisher + let events: AnyPublisher init(service: ElementCallServiceProtocol) { self.service = service - serviceActions = service.actions - } - - var events: AnyPublisher { - serviceActions - .compactMap { action in - switch action { - case .audioSessionActivated: - .audioSessionActivated - case .audioSessionDeactivated: - .audioSessionDeactivated - case .setAudioEnabled(let enabled, _): - // The system reports what the microphone should be; the port speaks in mutes. - .microphoneMuteChanged(isMuted: !enabled) - case .endCall(let roomID): - .endCallRequested(roomID: roomID) - // All navigation, handled by the flow coordinator. The call reaches this port later, - // as an ordinary start. - case .startCall, .receivedIncomingCallRequest, .nativeCall: - nil - } - } + events = service.nativeCallEventsPublisher + .map { ElementCallSystemEvent($0) } .eraseToAnyPublisher() } func startCall(roomID: String, displayName: String, isVideo: Bool) async { - await service?.setupCallSession(roomID: roomID, roomDisplayName: displayName, isVideo: isVideo) + await service?.setupCallSession(roomID: roomID, roomDisplayName: displayName, isVideo: isVideo, kind: .native) } func reportConnected(roomID: String) { @@ -75,3 +54,18 @@ final class NativeCallSystem: ElementCallSystemProvidingProtocol { service?.setAudioEnabled(enabled, roomID: roomID) } } + +private extension ElementCallSystemEvent { + init(_ event: NativeCallEvent) { + self = switch event { + case .audioSessionActivated: + .audioSessionActivated + case .audioSessionDeactivated: + .audioSessionDeactivated + case .microphoneMuteChanged(let isMuted): + .microphoneMuteChanged(isMuted: isMuted) + case .endCallRequested(let roomID): + .endCallRequested(roomID: roomID) + } + } +} diff --git a/UnitTests/Sources/ElementCallManagerTests.swift b/UnitTests/Sources/ElementCallManagerTests.swift new file mode 100644 index 000000000..cc5909497 --- /dev/null +++ b/UnitTests/Sources/ElementCallManagerTests.swift @@ -0,0 +1,770 @@ +// +// Copyright 2025 New Vector Ltd. +// +// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial +// Please see LICENSE files in the repository root for full details. +// + +import AVFoundation +import CallKit +import Combine +@testable import ElementX +import PushKit +import Testing + +@MainActor +final class ElementCallManagerTests { + private var appSettings: AppSettings! + private var callProvider: CXProviderMock! + private var callController: CXCallControllerMock! + private var currentDate: Date! + private var clock: ManualClock! + private var pushRegistry: PKPushRegistry! + private var service: ElementCallServiceMock! + private var serviceActions: PassthroughSubject! + private var manager: ElementCallManager! + + init() { + appSettings = AppSettings.volatile() + pushRegistry = PKPushRegistry(queue: nil) + callProvider = CXProviderMock(.init()) + callController = CXCallControllerMock(.init()) + currentDate = Date() + clock = ManualClock() + let dateProvider: () -> Date = { + self.currentDate + } + service = ElementCallServiceMock(.init()) + serviceActions = .init() + service.actionsPublisher = serviceActions.eraseToAnyPublisher() + manager = ElementCallManager(service: service, + appSettings: appSettings, + callProvider: callProvider, + callController: callController, + timeProvider: TimeProvider(clock: clock, now: dateProvider)) + } + + isolated deinit { + appSettings = nil + callProvider = nil + callController = nil + currentDate = nil + clock = nil + pushRegistry = nil + } + + @Test + func incomingCall() async throws { + #expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled) + let deferredReport = deferFulfillment(manager.actionsPublisher) { $0 == .incomingCallReported } + + await waitForConfirmation { confirmation in + let pkPushPayloadMock = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 30) + + manager.pushRegistry(pushRegistry, didReceiveIncomingPushWith: pkPushPayloadMock, for: .voIP) { + confirmation() + } + } + + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionCalled) + // Verify the provider was called with a CXCallUpdate that has video enabled + if let args = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments { + #expect(args.update.hasVideo == true) + } else { + Issue.record("Expected reportNewIncomingCallWithUpdateCompletionReceivedArguments to be captured") + } + try await deferredReport.fulfill() + } + + @Test + func incomingVoiceCall() async { + #expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled) + + await waitForConfirmation { confirmation in + let pkPushPayloadMock = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 30) + .updateIsVoice(true) + + manager.pushRegistry(pushRegistry, didReceiveIncomingPushWith: pkPushPayloadMock, for: .voIP) { + confirmation() + } + } + + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionCalled) + // Verify the provider was called with a CXCallUpdate that has video enabled + if let args = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments { + // Due to a limitation on Callkit and Webviews, we currently have to report voice calls as having video, + // even if they are voice calls :/ If not the webview is not started and the call is not shown to the user. + #expect(args.update.hasVideo == true) + } else { + Issue.record("Expected reportNewIncomingCallWithUpdateCompletionReceivedArguments to be captured") + } + } + + @Test + func callIsTimingOut() async throws { + #expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled) + + let (endedCalls, endedCallsContinuation) = AsyncStream.makeStream() + callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in + endedCallsContinuation.yield(reason) + } + let deferredEndedCall = deferFulfillment(endedCalls) { _ in true } + + await waitForConfirmation { confirmation in + let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 20) + + manager.pushRegistry(pushRegistry, + didReceiveIncomingPushWith: pushPayload, + for: .voIP) { + confirmation() + } + } + + await clock.waitForScheduledSleep() + + // advance past the timeout + clock.advance(by: .seconds(30)) + + let reason = try await deferredEndedCall.fulfill() + #expect(reason == .unanswered, "Call should have ended as unanswered") + } + + @Test + func lifetimeIsCapped() async throws { + #expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled) + + let (endedCalls, endedCallsContinuation) = AsyncStream.makeStream() + callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in + endedCallsContinuation.yield(reason) + } + let deferredEndedCall = deferFulfillment(endedCalls, timeout: .seconds(30)) { _ in true } + + let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 300) + + manager.pushRegistry(pushRegistry, + didReceiveIncomingPushWith: pushPayload, + for: .voIP) { } + + // The ring duration is capped, no matter how far away the push's expiration is. + #expect(await clock.waitForScheduledSleep() == .seconds(90)) + + // Advance past the max timeout but below the 300 + clock.advance(by: .seconds(100)) + + let reason = try await deferredEndedCall.fulfill() + #expect(reason == .unanswered, "Call should have ended as unanswered") + } + + @Test + func callIntentRawValues() { + // Test to ensure that the implicit rawValue of the string enum matches the MSC values + #expect(CallIntent.audio.rawValue == "audio") + #expect(CallIntent.video.rawValue == "video") + } + + @Test + func timeoutClearsIncomingCallStateBeforeNextPush() async throws { + // Drive push #1 to its 60s unanswered timeout + let (endedCalls, endedCallsContinuation) = AsyncStream.makeStream() + callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in + endedCallsContinuation.yield(reason) + } + let deferredEndedCall = deferFulfillment(endedCalls, timeout: .seconds(30)) { $0 == .unanswered } + + let firstPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) + manager.pushRegistry(pushRegistry, didReceiveIncomingPushWith: firstPayload, for: .voIP) { } + + await clock.waitForScheduledSleep() + clock.advance(by: .seconds(70)) + try await deferredEndedCall.fulfill() + + callProvider.reportCallWithEndedAtReasonClosure = nil + let firstCallUUID = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid + + // Send push #2 for the same room; the previous incoming state must be cleared, + // so the second push gets a fresh CallID. + await waitForConfirmation { confirmation in + let secondPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) + manager.pushRegistry(pushRegistry, didReceiveIncomingPushWith: secondPayload, for: .voIP) { + confirmation() + } + } + + let secondCallUUID = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid + + #expect(firstCallUUID != nil) + #expect(secondCallUUID != nil) + #expect(firstCallUUID != secondCallUUID) + + let unansweredCount = callProvider.reportCallWithEndedAtReasonReceivedInvocations.filter { $0.reason == .unanswered }.count + #expect(unansweredCount == 1) + } + + @Test + func setupCallSessionCancelsPendingUnansweredTimeout() async throws { + // Schedule the 60s unanswered timer via an incoming push + await waitForConfirmation { confirmation in + let payload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) + manager.pushRegistry(pushRegistry, didReceiveIncomingPushWith: payload, for: .voIP) { + confirmation() + } + } + + // Make sure the cancellation below exercises a scheduled timer rather than one that never started. + await clock.waitForScheduledSleep() + + // Simulate the answer flow handing off to setupCallSession, which must cancel + // the pending endUnansweredCallTask as part of clearing the incoming state. + await startCallSession(kind: .webView) + + let (endedCalls, endedCallsContinuation) = AsyncStream.makeStream() + callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in + endedCallsContinuation.yield(reason) + } + let deferredUnansweredCall = deferFailure(endedCalls, + timeout: .milliseconds(100), + message: "endUnansweredCallTask should have been cancelled by setupCallSession") { $0 == .unanswered } + + // Advance past what would have been the 60s unanswered timeout + clock.advance(by: .seconds(120)) + + try await deferredUnansweredCall.fulfill() + } + + @Test + func expiredPushReportsMissedCall() async throws { + // An expired push is a real call we missed, so it should show up in Recents as one. + let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 20) + currentDate = currentDate.addingTimeInterval(60) + let deferredReport = deferFailure(manager.actionsPublisher, timeout: .milliseconds(100)) { $0 == .incomingCallReported } + await expectImmediatelyEndedCallReported(forPayload: pushPayload, expectedReason: .unanswered) + + let update = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update + #expect(update?.localizedCallerName == "welcome") + #expect(update?.remoteHandle?.value == "!room:example.com") + try await deferredReport.fulfill() + + await Task.yield() + #expect(!service.observeIncomingCallRoomIDRtcNotificationIDCalled) + } + + @Test + func duplicateRoomPushReportsCallAsHandled() async { + // A duplicate push for an ongoing call is reported as handled, leaving the ongoing call alone. + await startCallSession(kind: .webView) + let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 30) + await expectImmediatelyEndedCallReported(forPayload: pushPayload, expectedReason: .answeredElsewhere) + + // The call should be named so neither the brief system UI nor the Recents entry shows "Unknown". + let update = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update + #expect(update?.localizedCallerName == "welcome") + + #expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com") + } + + @Test + func webViewCallSessionIsNotTrackedByCallKit() async { + // CallKit tracking a call gives this process exclusive media access, which starves the web + // view. So a web view call is only ever tracked on the app side. + await startCallSession(kind: .webView) + serviceActions.send(.callSessionConnected(roomID: "!room:example.com")) + + #expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com") + #expect(!callProvider.reportCallWithUpdatedCalled) + #expect(!callProvider.reportOutgoingCallWithConnectedAtCalled) + } + + @Test + func endingAReplacedCallLeavesTheCallThatReplacedItUp() async throws { + appSettings.nativeCallEnabled = true + + // Leaving a call to start one in another room requests an end call action for the first, + // then starts the second before the system performs it. + await startCallSession(roomID: "!first:example.com", roomDisplayName: "first", kind: .native) + let firstCallID = try #require(callProvider.reportCallWithUpdatedReceivedArguments?.uuid) + + serviceActions.send(.callSessionEnded(roomID: "!first:example.com", reason: nil)) + await startCallSession(roomID: "!second:example.com", roomDisplayName: "second", kind: .native) + + manager.endCall(withCallKitID: firstCallID) + + #expect(service.systemEventReceivedReceivedInvocations.isEmpty, "The first call's end action must not hang up the second call") + #expect(service.ongoingCallRoomIDPublisher.value == "!second:example.com") + + // And the second call still ends when it's the one the system means. + let secondCallID = try #require(callProvider.reportCallWithUpdatedReceivedArguments?.uuid) + manager.endCall(withCallKitID: secondCallID) + + #expect(service.systemEventReceivedReceivedInvocations == [.endCallRequested(roomID: "!second:example.com")]) + #expect(service.ongoingCallRoomIDPublisher.value == nil) + #expect(service.callSessionSetUpRoomIDIsAcceptedCallsCount == 2) + } + + /// A declined or unanswered call is the system's to log as such: reported with its reason, and + /// never as an end call action, which would log it as one we hung up. + @Test(arguments: [(CallEndReason.remoteEnded, CXCallEndedReason.remoteEnded), + (.unanswered, .unanswered), + (.failed, .failed)]) + func aCallThatEndedWithoutUsIsReportedRatherThanEnded(reason: CallEndReason, callKitReason: CXCallEndedReason) async throws { + appSettings.nativeCallEnabled = true + await startCallSession(kind: .native) + let callID = try #require(callProvider.reportCallWithUpdatedReceivedArguments?.uuid) + let requestsBeforeTheEnd = callController.requestCompletionCallsCount + + serviceActions.send(.callSessionEnded(roomID: "!other:example.com", reason: reason)) + #expect(!callProvider.reportCallWithEndedAtReasonCalled, "Another room's end is not this call's") + + serviceActions.send(.callSessionEnded(roomID: "!room:example.com", reason: reason)) + + #expect(callProvider.reportCallWithEndedAtReasonReceivedArguments?.uuid == callID) + #expect(callProvider.reportCallWithEndedAtReasonReceivedArguments?.reason == callKitReason) + #expect(callController.requestCompletionCallsCount == requestsBeforeTheEnd) + #expect(service.ongoingCallRoomIDPublisher.value == nil) + } + + @Test + func tearingDownAnotherRoomLeavesTheOngoingCallUp() async { + // A call screen that is dismissed after another room's call replaced it must not take the + // new call down with it. + await startCallSession(kind: .webView) + + serviceActions.send(.callSessionEnded(roomID: "!other:example.com", reason: nil)) + #expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com") + + serviceActions.send(.callSessionEnded(roomID: "!room:example.com", reason: nil)) + #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 startCallSession(kind: .webView) + + 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. + appSettings.nativeCallEnabled = true + await startCallSession(kind: .native) + + 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. + serviceActions.send(.callSessionEnded(roomID: "!room:example.com", reason: nil)) + + await reportIncomingPush(isVoiceCall: false, roomID: "!other:example.com", rtcNotificationID: "$111") + + #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() + serviceActions.send(.callSessionEnded(roomID: "!room:example.com", reason: nil)) + + 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() + } + + @Test + func unopenedAnsweredCallIsDropped() async throws { + await reportIncomingPush(isVoiceCall: false) + await clock.waitForScheduledSleep() + try await answerReportedCall() + + // Nothing opens the call, e.g. it was answered while signed out. + #expect(await clock.waitForScheduledSleep() == .seconds(30)) + await waitForConfirmation("The dropped call stops being watched") { confirmation in + service.stopObservingIncomingCallClosure = { confirmation() } + clock.advance(by: .seconds(30)) + } + service.stopObservingIncomingCallClosure = nil + + await reportIncomingPush(isVoiceCall: false, roomID: "!other:example.com", rtcNotificationID: "$111") + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update.remoteHandle?.value == "!other:example.com") + #expect(!callProvider.reportCallWithEndedAtReasonReceivedInvocations.contains { $0.reason == .unanswered }) + } + + @Test + func droppedAnsweredCallUnblocksNewCalls() async throws { + await reportIncomingPush(isVoiceCall: false) + try await answerReportedCall() + + manager.dropAnsweredCall(roomID: "!room:example.com") + + await reportIncomingPush(isVoiceCall: false, roomID: "!other:example.com", rtcNotificationID: "$111") + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update.remoteHandle?.value == "!other:example.com") + #expect(!callProvider.reportCallWithEndedAtReasonReceivedInvocations.contains { $0.reason == .unanswered }) + } + + // MARK: - Native calls + + @Test + func nativeModeReportsVoiceCallsWithoutVideo() async { + appSettings.nativeCallEnabled = true + + await reportIncomingPush(isVoiceCall: true) + + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update.hasVideo == false) + } + + @Test + func nativeModeStillReportsVideoCallsWithVideo() async { + appSettings.nativeCallEnabled = true + + await reportIncomingPush(isVoiceCall: false) + + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update.hasVideo == true) + } + + @Test + func answeringInNativeModeKeepsTheCallUp() async throws { + appSettings.nativeCallEnabled = true + await reportIncomingPush(isVoiceCall: false) + await clock.waitForScheduledSleep() + let deferredAnswer = deferFulfillment(manager.actionsPublisher) { $0 == .callAnswered(roomID: "!room:example.com", isVoiceCall: false) } + + try await answerReportedCall() + try await deferredAnswer.fulfill() + + // The webview path ends the call a second after answering so that `setupCallSession` can + // start a new one. The native stack takes this one over instead, so it has to survive. + #expect(!callProvider.reportCallWithEndedAtReasonCalled) + } + + @Test + func answeredNativeCallEndsWhenNothingTakesItOver() async throws { + appSettings.nativeCallEnabled = true + await reportIncomingPush(isVoiceCall: false) + await clock.waitForScheduledSleep() + + let answeredUUID = try await answerReportedCall() + + let (endedCalls, endedCallsContinuation) = AsyncStream<(UUID, CXCallEndedReason)>.makeStream() + callProvider.reportCallWithEndedAtReasonClosure = { uuid, _, reason in + endedCallsContinuation.yield((uuid, reason)) + } + let deferredEndedCall = deferFulfillment(endedCalls) { _ in true } + + // Answering swaps the unanswered timer for the watchdog that catches a hand-off that never + // happens — the room isn't joined, there's no transport, a call is already running. + #expect(await clock.waitForScheduledSleep() == .seconds(30)) + clock.advance(by: .seconds(30)) + + let (uuid, reason) = try await deferredEndedCall.fulfill() + #expect(uuid == answeredUUID) + #expect(reason == .failed) + } + + @Test + func droppedAnsweredNativeCallEndsAsFailed() async throws { + appSettings.nativeCallEnabled = true + await reportIncomingPush(isVoiceCall: false) + let answeredUUID = try await answerReportedCall() + + manager.dropAnsweredCall(roomID: "!other:example.com") + #expect(!callProvider.reportCallWithEndedAtReasonCalled) + + manager.dropAnsweredCall(roomID: "!room:example.com") + #expect(callProvider.reportCallWithEndedAtReasonReceivedArguments?.uuid == answeredUUID) + #expect(callProvider.reportCallWithEndedAtReasonReceivedArguments?.reason == .failed) + } + + @Test + func nativeCallStackTakesOverTheAnsweredCall() async throws { + appSettings.nativeCallEnabled = true + await reportIncomingPush(isVoiceCall: false) + await clock.waitForScheduledSleep() + + try await answerReportedCall() + + // Answering starts the watchdog, so wait for it before asserting that the hand-over stops it. + await clock.waitForScheduledSleep() + + await startCallSession(kind: .native) + + // Taking the answered call over means keeping its identifier rather than reporting a new + // outgoing call, which is what the update below would be part of. + #expect(!callProvider.reportCallWithUpdatedCalled) + #expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com") + #expect(service.callSessionSetUpRoomIDIsAcceptedCallsCount == 1) + + // And the watchdog must be gone, otherwise it ends the call that was just taken over. + #expect(!clock.hasPendingSleep, "The watchdog must not outlive the hand-over") + } + + @Test + func nativeCallStackForAnotherRoomReportsANewCall() async throws { + appSettings.nativeCallEnabled = true + await reportIncomingPush(isVoiceCall: false) + await clock.waitForScheduledSleep() + + let answeredUUID = try await answerReportedCall() + + await startCallSession(roomID: "!other:example.com", roomDisplayName: "other", kind: .native) + + let update = try #require(callProvider.reportCallWithUpdatedReceivedArguments) + #expect(update.uuid != answeredUUID) + #expect(update.update.localizedCallerName == "other") + #expect(service.ongoingCallRoomIDPublisher.value == "!other:example.com") + + // Unlike a web view call, a native one is tracked by CallKit, so it gets the connected report too. + serviceActions.send(.callSessionConnected(roomID: "!other:example.com")) + #expect(callProvider.reportOutgoingCallWithConnectedAtReceivedArguments?.uuid == update.uuid) + } + + // MARK: - Service + + @Test + func ringingCallIsWatched() async { + await waitForConfirmation { confirmation in + service.observeIncomingCallRoomIDRtcNotificationIDClosure = { _, _ in confirmation() } + let payload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) + manager.pushRegistry(pushRegistry, didReceiveIncomingPushWith: payload, for: .voIP) { } + } + + #expect(service.observeIncomingCallRoomIDRtcNotificationIDReceivedArguments?.roomID == "!room:example.com") + #expect(service.observeIncomingCallRoomIDRtcNotificationIDReceivedArguments?.rtcNotificationID == "$000") + } + + @Test(arguments: [(CallEndReason.remoteEnded, CXCallEndedReason.remoteEnded), + (.answeredElsewhere, .answeredElsewhere), + (.declinedElsewhere, .declinedElsewhere)]) + func incomingCallEndReportsReason(reason: CallEndReason, callKitReason: CXCallEndedReason) async throws { + await reportIncomingPush(isVoiceCall: false) + let ringingUUID = try #require(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid) + + serviceActions.send(.incomingCallEnded(roomID: "!other:example.com", reason: reason)) + #expect(!callProvider.reportCallWithEndedAtReasonCalled) + + serviceActions.send(.incomingCallEnded(roomID: "!room:example.com", reason: reason)) + #expect(callProvider.reportCallWithEndedAtReasonReceivedArguments?.uuid == ringingUUID) + #expect(callProvider.reportCallWithEndedAtReasonReceivedArguments?.reason == callKitReason) + #expect(service.stopObservingIncomingCallCalled) + } + + @Test + func declineGoesThroughService() async throws { + await reportIncomingPush(isVoiceCall: false) + let callID = try #require(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid) + + await waitForConfirmation { confirmation in + service.declineCallRoomIDRtcNotificationIDClosure = { _, _ in confirmation() } + manager.endCall(withCallKitID: callID) + } + + #expect(service.declineCallRoomIDRtcNotificationIDReceivedArguments?.roomID == "!room:example.com") + #expect(service.declineCallRoomIDRtcNotificationIDReceivedArguments?.rtcNotificationID == "$000") + } + + @Test + func answeredWebCallOpens() async throws { + await reportIncomingPush(isVoiceCall: false) + let uuid = try #require(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid) + let deferredAnswer = deferFulfillment(manager.actionsPublisher) { $0 == .callAnswered(roomID: "!room:example.com", isVoiceCall: false) } + + manager.provider(CXProvider(configuration: CXProviderConfiguration()), perform: CXAnswerCallAction(call: uuid)) + + try await deferredAnswer.fulfill() + } + + @Test + func webCallSetupIsImmediate() { + serviceActions.send(.callSessionStarted(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true, kind: .webView)) + + #expect(service.callSessionSetUpRoomIDIsAcceptedReceivedArguments?.roomID == "!room:example.com") + #expect(service.callSessionSetUpRoomIDIsAcceptedReceivedArguments?.isAccepted == true) + #expect(service.callSessionSetUpRoomIDIsAcceptedCallsCount == 1) + #expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com") + } + + @Test + func nativeCallSetupWaitsForCallKit() async { + await waitForConfirmation { confirmation in + service.callSessionSetUpRoomIDIsAcceptedClosure = { [callProvider] _, _ in + #expect(callProvider?.reportCallWithUpdatedCalled == true) + confirmation() + } + serviceActions.send(.callSessionStarted(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true, kind: .native)) + } + + #expect(service.callSessionSetUpRoomIDIsAcceptedCallsCount == 1) + } + + @Test + func failedNativeCallStartIsStillSetUp() async { + callController.requestCompletionClosure = { _, completion in + completion(NSError(domain: "CallKit", code: 1)) + } + + await startCallSession(kind: .native) + + #expect(service.callSessionSetUpRoomIDIsAcceptedReceivedArguments?.isAccepted == true) + #expect(service.callSessionSetUpRoomIDIsAcceptedCallsCount == 1) + } + + @Test + func callKitEventsReachService() async throws { + await startCallSession(kind: .native) + let callID = try #require(callProvider.reportCallWithUpdatedReceivedArguments?.uuid) + let provider = CXProvider(configuration: CXProviderConfiguration()) + + manager.provider(provider, didActivate: AVAudioSession.sharedInstance()) + manager.provider(provider, perform: CXSetMutedCallAction(call: callID, muted: true)) + + #expect(service.systemEventReceivedReceivedInvocations == [.audioSessionActivated, .microphoneMuteChanged(isMuted: true)]) + } + + @Test + func nativeCallMuteReachesCallKit() async { + await startCallSession(kind: .native) + + serviceActions.send(.audioEnabledChanged(false, roomID: "!room:example.com")) + + #expect((callController.requestCompletionReceivedArguments?.transaction.actions.first as? CXSetMutedCallAction)?.isMuted == true) + } + + // MARK: - Helpers + + /// Starts a call session the way a call screen does, returning once the manager has set it up. + private func startCallSession(roomID: String = "!room:example.com", roomDisplayName: String = "welcome", kind: ElementCallSessionKind) async { + await waitForConfirmation { confirmation in + service.callSessionSetUpRoomIDIsAcceptedClosure = { _, _ in confirmation() } + serviceActions.send(.callSessionStarted(roomID: roomID, roomDisplayName: roomDisplayName, isVideo: true, kind: kind)) + } + } + + /// Delivers a VoIP push and waits for it to be reported, returning once the call is ringing. + private func reportIncomingPush(isVoiceCall: Bool, roomID: String = "!room:example.com", rtcNotificationID: String = "$000") async { + await waitForConfirmation { confirmation in + let payload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) + .updateIsVoice(isVoiceCall) + .updatingRoomID(roomID) + .updatingRTCNotificationID(rtcNotificationID) + + manager.pushRegistry(pushRegistry, didReceiveIncomingPushWith: payload, for: .voIP) { + confirmation() + } + } + } + + /// Answers the call the provider last reported, returning its identifier. + @discardableResult + private func answerReportedCall() async throws -> UUID { + let uuid = try #require(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid) + let provider = CXProvider(configuration: CXProviderConfiguration()) + + manager.provider(provider, perform: CXAnswerCallAction(call: uuid)) + + return uuid + } + + private func expectImmediatelyEndedCallReported(forPayload payload: PKPushPayloadMock, + expectedReason: CXCallEndedReason) async { + let baselineNewIncomingCount = callProvider.reportNewIncomingCallWithUpdateCompletionCallsCount + let baselineEndedCount = callProvider.reportCallWithEndedAtReasonCallsCount + + await waitForConfirmation { confirmation in + manager.pushRegistry(pushRegistry, didReceiveIncomingPushWith: payload, for: .voIP) { + confirmation() + } + } + + #expect(callProvider.reportNewIncomingCallWithUpdateCompletionCallsCount == baselineNewIncomingCount + 1) + #expect(callProvider.reportCallWithEndedAtReasonCallsCount == baselineEndedCount + 1) + + let reportedCall = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments + let endedCall = callProvider.reportCallWithEndedAtReasonReceivedArguments + #expect(reportedCall?.uuid == endedCall?.uuid) + #expect(endedCall?.reason == expectedReason) + } +} + +private nonisolated class PKPushPayloadMock: PKPushPayload { + var dict: [AnyHashable: Any] = [:] + + override init() { + dict[ElementCallServiceNotificationKey.roomID.rawValue] = "!room:example.com" + dict[ElementCallServiceNotificationKey.roomDisplayName.rawValue] = "welcome" + dict[ElementCallServiceNotificationKey.rtcNotifyEventID.rawValue] = "$000" + dict[ElementCallServiceNotificationKey.expirationDate.rawValue] = Date(timeIntervalSince1970: 10) + } + + override var dictionaryPayload: [AnyHashable: Any] { + dict + } + + func updatingExpiration(_ from: Date, lifetime: TimeInterval) -> Self { + dict[ElementCallServiceNotificationKey.expirationDate.rawValue] = from.addingTimeInterval(lifetime) + return self + } + + func updateIsVoice(_ isVoice: Bool) -> Self { + 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 + } +} diff --git a/UnitTests/Sources/ElementCallServiceTests.swift b/UnitTests/Sources/ElementCallServiceTests.swift index 0e6e224c6..89ccdc308 100644 --- a/UnitTests/Sources/ElementCallServiceTests.swift +++ b/UnitTests/Sources/ElementCallServiceTests.swift @@ -1,521 +1,257 @@ // -// Copyright 2025 New Vector Ltd. +// Copyright 2026 Element Creations Ltd. // -// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial +// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. // Please see LICENSE files in the repository root for full details. // -import CallKit +import Combine import ElementCall @testable import ElementX -import PushKit +import MatrixRustSDK +import MatrixRustSDKMocks import Testing -@MainActor final class ElementCallServiceTests { - private var appSettings: AppSettings! - private var callProvider: CXProviderMock! - private var callController: CXCallControllerMock! - private var currentDate: Date! - private var clock: ManualClock! - private var pushRegistry: PKPushRegistry! - private var service: ElementCallService! - private var userSession: UserSessionMock! + private let appSettings = AppSettings.volatile() + private let clientProxy = ClientProxyMock(.init(userID: "@alice:matrix.org")) + private let roomProxy = JoinedRoomProxyMock(.init(id: "!room:example.com", hasOngoingCall: true, ownUserID: "@alice:matrix.org")) + private let roomInfoSubject = CurrentValueSubject(RoomInfoProxyMock(.init(id: "!room:example.com", hasOngoingCall: true))) + /// Held here because the service only keeps a weak reference to its client, as the app owns the session. + private let userSession: UserSessionMock + private var nativeSession: UserSessionMock? + private let service: ElementCallService init() { - appSettings = AppSettings.volatile() - pushRegistry = PKPushRegistry(queue: nil) - callProvider = CXProviderMock(.init()) - callController = CXCallControllerMock(.init()) - currentDate = Date() - clock = ManualClock() - let dateProvider: () -> Date = { - self.currentDate - } - service = ElementCallService(appSettings: appSettings, - callProvider: callProvider, - callController: callController, - timeProvider: TimeProvider(clock: clock, now: dateProvider)) + roomProxy.infoPublisher = roomInfoSubject.asCurrentValuePublisher() + roomProxy.subscribeToCallDeclineEventsRtcNotificationEventIDListenerReturnValue = .success(TaskHandleSDKMock()) + roomProxy.declineCallNotificationIDReturnValue = .success(()) + clientProxy.roomForIdentifierClosure = { [roomProxy] _ in .joined(roomProxy) } + userSession = UserSessionMock(.init(clientProxy: clientProxy)) + + service = ElementCallService(appSettings: appSettings) + service.setUserSession(userSession) } - isolated deinit { - appSettings = nil - callProvider = nil - callController = nil - currentDate = nil - clock = nil - pushRegistry = nil - userSession = nil + // MARK: - Ringing call + + @Test + func remoteHangUpEndsRinging() async throws { + await service.observeIncomingCall(roomID: "!room:example.com", rtcNotificationID: "$000") + + let deferred = deferFulfillment(service.actionsPublisher) { $0 == .incomingCallEnded(roomID: "!room:example.com", reason: .remoteEnded) } + roomInfoSubject.send(RoomInfoProxyMock(.init(id: "!room:example.com", hasOngoingCall: false))) + try await deferred.fulfill() } @Test - func incomingCall() async { - #expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled) + func joinElsewhereEndsRinging() async throws { + await service.observeIncomingCall(roomID: "!room:example.com", rtcNotificationID: "$000") + + let deferred = deferFulfillment(service.actionsPublisher) { $0 == .incomingCallEnded(roomID: "!room:example.com", reason: .answeredElsewhere) } + roomInfoSubject.send(RoomInfoProxyMock(.init(id: "!room:example.com", hasOngoingCall: true, activeRoomCallParticipants: ["@alice:matrix.org"]))) + try await deferred.fulfill() + } + + @Test + func declineElsewhereEndsRinging() async throws { + await service.observeIncomingCall(roomID: "!room:example.com", rtcNotificationID: "$000") + let listener = try #require(roomProxy.subscribeToCallDeclineEventsRtcNotificationEventIDListenerReceivedArguments?.listener) + #expect(roomProxy.subscribeToCallDeclineEventsRtcNotificationEventIDListenerReceivedArguments?.rtcNotificationEventID == "$000") + + let deferredFailure = deferFailure(service.actionsPublisher, timeout: .milliseconds(100)) { _ in true } + listener.call(declinerUserId: "@bob:matrix.org") + try await deferredFailure.fulfill() + + let deferred = deferFulfillment(service.actionsPublisher) { $0 == .incomingCallEnded(roomID: "!room:example.com", reason: .declinedElsewhere) } + listener.call(declinerUserId: "@alice:matrix.org") + try await deferred.fulfill() + } + + @Test + func stoppedWatchIgnoresRoom() async throws { + await service.observeIncomingCall(roomID: "!room:example.com", rtcNotificationID: "$000") + service.stopObservingIncomingCall() + + let deferredFailure = deferFailure(service.actionsPublisher, timeout: .milliseconds(100)) { _ in true } + roomInfoSubject.send(RoomInfoProxyMock(.init(id: "!room:example.com", hasOngoingCall: false))) + try await deferredFailure.fulfill() + } + + @Test + func declineCallSendsDecline() async { + await service.declineCall(roomID: "!room:example.com", rtcNotificationID: "$000") + + #expect(clientProxy.roomForIdentifierReceivedIdentifier == "!room:example.com") + #expect(roomProxy.declineCallNotificationIDReceivedNotificationID == "$000") + } + + @Test + func watchWaitsForSession() async throws { + // Given a watch requested before there is any session. + let service = ElementCallService(appSettings: appSettings) + await service.observeIncomingCall(roomID: "!room:example.com", rtcNotificationID: "$000") + #expect(!clientProxy.roomForIdentifierCalled) + + // When the session arrives, then the room is watched with it. + await waitForConfirmation { confirmation in + roomProxy.subscribeToCallDeclineEventsRtcNotificationEventIDListenerClosure = { _, _ in + confirmation() + return .success(TaskHandleSDKMock()) + } + service.setUserSession(userSession) + } + + let deferred = deferFulfillment(service.actionsPublisher) { $0 == .incomingCallEnded(roomID: "!room:example.com", reason: .remoteEnded) } + roomInfoSubject.send(RoomInfoProxyMock(.init(id: "!room:example.com", hasOngoingCall: false))) + try await deferred.fulfill() + } + + @Test + func stoppedWatchSkipsLateSession() async { + // Given a watch requested and stopped before there is any session. + let service = ElementCallService(appSettings: appSettings) + await service.observeIncomingCall(roomID: "!room:example.com", rtcNotificationID: "$000") + service.stopObservingIncomingCall() + + // When the session arrives, then the room is never fetched. + await waitForConfirmation(expectedCount: 0, timeout: .milliseconds(100)) { confirmation in + clientProxy.roomForIdentifierClosure = { [roomProxy] _ in + confirmation() + return .joined(roomProxy) + } + service.setUserSession(userSession) + } + } + + @Test + func watchSurvivesSessionChange() async throws { + await service.observeIncomingCall(roomID: "!room:example.com", rtcNotificationID: "$000") + + service.setUserSession(nil) + let deferredFailure = deferFailure(service.actionsPublisher, timeout: .milliseconds(100)) { _ in true } + roomInfoSubject.send(RoomInfoProxyMock(.init(id: "!room:example.com", hasOngoingCall: false))) + try await deferredFailure.fulfill() + + let otherRoomProxy = JoinedRoomProxyMock(.init(id: "!room:example.com", hasOngoingCall: true, ownUserID: "@bob:matrix.org")) + let otherRoomInfoSubject = CurrentValueSubject(RoomInfoProxyMock(.init(id: "!room:example.com", hasOngoingCall: true))) + otherRoomProxy.infoPublisher = otherRoomInfoSubject.asCurrentValuePublisher() + let otherClientProxy = ClientProxyMock(.init(userID: "@bob:matrix.org")) + otherClientProxy.roomForIdentifierClosure = { _ in .joined(otherRoomProxy) } + let otherUserSession = UserSessionMock(.init(clientProxy: otherClientProxy)) await waitForConfirmation { confirmation in - let pkPushPayloadMock = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 30) + otherRoomProxy.subscribeToCallDeclineEventsRtcNotificationEventIDListenerClosure = { _, _ in + confirmation() + return .success(TaskHandleSDKMock()) + } + service.setUserSession(otherUserSession) + } + + let deferred = deferFulfillment(service.actionsPublisher) { $0 == .incomingCallEnded(roomID: "!room:example.com", reason: .remoteEnded) } + otherRoomInfoSubject.send(RoomInfoProxyMock(.init(id: "!room:example.com", hasOngoingCall: false))) + try await deferred.fulfill() + + withExtendedLifetime(otherUserSession) { } + } + + // MARK: - Call sessions + + @Test(arguments: [false, true]) + func callSetupWaitsForManager(repliesLater: Bool) async { + var order: [String] = [] + let cancellable = service.actionsPublisher.sink { [service] action in + guard case let .callSessionStarted(roomID, _, _, _) = action else { return } + order.append("sent") - service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: pkPushPayloadMock, for: .voIP) { - confirmation() - } - } - - #expect(callProvider.reportNewIncomingCallWithUpdateCompletionCalled) - // Verify the provider was called with a CXCallUpdate that has video enabled - if let args = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments { - #expect(args.update.hasVideo == true) - } else { - Issue.record("Expected reportNewIncomingCallWithUpdateCompletionReceivedArguments to be captured") - } - } - - @Test - func incomingVoiceCall() async { - #expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled) - - await waitForConfirmation { confirmation in - let pkPushPayloadMock = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 30) - .updateIsVoice(true) - - service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: pkPushPayloadMock, for: .voIP) { - confirmation() - } - } - - #expect(callProvider.reportNewIncomingCallWithUpdateCompletionCalled) - // Verify the provider was called with a CXCallUpdate that has video enabled - if let args = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments { - // Due to a limitation on Callkit and Webviews, we currently have to report voice calls as having video, - // even if they are voice calls :/ If not the webview is not started and the call is not shown to the user. - #expect(args.update.hasVideo == true) - } else { - Issue.record("Expected reportNewIncomingCallWithUpdateCompletionReceivedArguments to be captured") - } - } - - @Test - func callIsTimingOut() async throws { - #expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled) - - let (endedCalls, endedCallsContinuation) = AsyncStream.makeStream() - callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in - endedCallsContinuation.yield(reason) - } - let deferredEndedCall = deferFulfillment(endedCalls) { _ in true } - - await waitForConfirmation { confirmation in - let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 20) - - service.pushRegistry(pushRegistry, - didReceiveIncomingPushWith: pushPayload, - for: .voIP) { - confirmation() - } - } - - await clock.waitForScheduledSleep() - - // advance past the timeout - clock.advance(by: .seconds(30)) - - let reason = try await deferredEndedCall.fulfill() - #expect(reason == .unanswered, "Call should have ended as unanswered") - } - - @Test - func lifetimeIsCapped() async throws { - #expect(!callProvider.reportNewIncomingCallWithUpdateCompletionCalled) - - let (endedCalls, endedCallsContinuation) = AsyncStream.makeStream() - callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in - endedCallsContinuation.yield(reason) - } - let deferredEndedCall = deferFulfillment(endedCalls, timeout: .seconds(30)) { _ in true } - - let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 300) - - service.pushRegistry(pushRegistry, - didReceiveIncomingPushWith: pushPayload, - for: .voIP) { } - - // The ring duration is capped, no matter how far away the push's expiration is. - #expect(await clock.waitForScheduledSleep() == .seconds(90)) - - // Advance past the max timeout but below the 300 - clock.advance(by: .seconds(100)) - - let reason = try await deferredEndedCall.fulfill() - #expect(reason == .unanswered, "Call should have ended as unanswered") - } - - @Test - func callIntentRawValues() { - // Test to ensure that the implicit rawValue of the string enum matches the MSC values - #expect(CallIntent.audio.rawValue == "audio") - #expect(CallIntent.video.rawValue == "video") - } - - @Test - func timeoutClearsIncomingCallStateBeforeNextPush() async throws { - // Drive push #1 to its 60s unanswered timeout - let (endedCalls, endedCallsContinuation) = AsyncStream.makeStream() - callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in - endedCallsContinuation.yield(reason) - } - let deferredEndedCall = deferFulfillment(endedCalls, timeout: .seconds(30)) { $0 == .unanswered } - - let firstPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) - service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: firstPayload, for: .voIP) { } - - await clock.waitForScheduledSleep() - clock.advance(by: .seconds(70)) - try await deferredEndedCall.fulfill() - - callProvider.reportCallWithEndedAtReasonClosure = nil - let firstCallUUID = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid - - // Send push #2 for the same room; the previous incoming state must be cleared, - // so the second push gets a fresh CallID. - await waitForConfirmation { confirmation in - let secondPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) - service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: secondPayload, for: .voIP) { - confirmation() - } - } - - let secondCallUUID = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid - - #expect(firstCallUUID != nil) - #expect(secondCallUUID != nil) - #expect(firstCallUUID != secondCallUUID) - - let unansweredCount = callProvider.reportCallWithEndedAtReasonReceivedInvocations.filter { $0.reason == .unanswered }.count - #expect(unansweredCount == 1) - } - - @Test - func setupCallSessionCancelsPendingUnansweredTimeout() async throws { - // Schedule the 60s unanswered timer via an incoming push - await waitForConfirmation { confirmation in - let payload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 60) - service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: payload, for: .voIP) { - confirmation() - } - } - - // Make sure the cancellation below exercises a scheduled timer rather than one that never started. - await clock.waitForScheduledSleep() - - // Simulate the answer flow handing off to setupCallSession, which must cancel - // the pending endUnansweredCallTask as part of clearing the incoming state. - await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true) - - let (endedCalls, endedCallsContinuation) = AsyncStream.makeStream() - callProvider.reportCallWithEndedAtReasonClosure = { _, _, reason in - endedCallsContinuation.yield(reason) - } - let deferredUnansweredCall = deferFailure(endedCalls, - timeout: .milliseconds(100), - message: "endUnansweredCallTask should have been cancelled by setupCallSession") { $0 == .unanswered } - - // Advance past what would have been the 60s unanswered timeout - clock.advance(by: .seconds(120)) - - try await deferredUnansweredCall.fulfill() - } - - @Test - func expiredPushReportsMissedCall() async { - // An expired push is a real call we missed, so it should show up in Recents as one. - let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 20) - currentDate = currentDate.addingTimeInterval(60) - await expectImmediatelyEndedCallReported(forPayload: pushPayload, expectedReason: .unanswered) - - let update = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update - #expect(update?.localizedCallerName == "welcome") - #expect(update?.remoteHandle?.value == "!room:example.com") - } - - @Test - func duplicateRoomPushReportsCallAsHandled() async { - // A duplicate push for an ongoing call is reported as handled, leaving the ongoing call alone. - await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true) - let pushPayload = PKPushPayloadMock().updatingExpiration(currentDate, lifetime: 30) - await expectImmediatelyEndedCallReported(forPayload: pushPayload, expectedReason: .answeredElsewhere) - - // The call should be named so neither the brief system UI nor the Recents entry shows "Unknown". - let update = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update - #expect(update?.localizedCallerName == "welcome") - - #expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com") - } - - @Test - func webViewCallSessionIsNotTrackedByCallKit() async { - // CallKit tracking a call gives this process exclusive media access, which starves the web - // view. So a web view call is only ever tracked on the app side. - await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true) - service.reportCallSessionConnected(roomID: "!room:example.com") - - #expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com") - #expect(!callProvider.reportCallWithUpdatedCalled) - #expect(!callProvider.reportOutgoingCallWithConnectedAtCalled) - } - - @Test - func endingAReplacedCallLeavesTheCallThatReplacedItUp() async throws { - enableNativeCalls() - - // Leaving a call to start one in another room requests an end call action for the first, - // then starts the second before the system performs it. - await service.setupCallSession(roomID: "!first:example.com", roomDisplayName: "first", isVideo: true) - let firstCallID = try #require(callProvider.reportCallWithUpdatedReceivedArguments?.uuid) - - service.tearDownCallSession(roomID: "!first:example.com") - await service.setupCallSession(roomID: "!second:example.com", roomDisplayName: "second", isVideo: true) - - var endedRooms: [String] = [] - let cancellable = service.actions.sink { action in - if case .endCall(let roomID) = action { - endedRooms.append(roomID) + if repliesLater { + Task { + order.append("set up") + service.callSessionSetUp(roomID: roomID, isAccepted: true) + } + } else { + order.append("set up") + service.callSessionSetUp(roomID: roomID, isAccepted: true) } } defer { cancellable.cancel() } - service.endCall(withCallKitID: firstCallID) + await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true, kind: .native) + order.append("returned") - #expect(endedRooms.isEmpty, "The first call's end action must not hang up the second call") - #expect(service.ongoingCallRoomIDPublisher.value == "!second:example.com") - - // And the second call still ends when it's the one the system means. - let secondCallID = try #require(callProvider.reportCallWithUpdatedReceivedArguments?.uuid) - service.endCall(withCallKitID: secondCallID) - - #expect(endedRooms == ["!second:example.com"]) - #expect(service.ongoingCallRoomIDPublisher.value == nil) - } - - /// A declined or unanswered call is the system's to log as such: reported with its reason, and - /// never as an end call action, which would log it as one we hung up. - @Test - func aCallThatEndedWithoutUsIsReportedRatherThanEnded() async throws { - enableNativeCalls() - await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true) - let callID = try #require(callProvider.reportCallWithUpdatedReceivedArguments?.uuid) - let requestsBeforeTheEnd = callController.requestCompletionCallsCount - - service.reportCallSessionEnded(roomID: "!other:example.com", reason: .unanswered) - #expect(!callProvider.reportCallWithEndedAtReasonCalled, "Another room's end is not this call's") - - service.reportCallSessionEnded(roomID: "!room:example.com", reason: .unanswered) - - #expect(callProvider.reportCallWithEndedAtReasonReceivedArguments?.uuid == callID) - #expect(callProvider.reportCallWithEndedAtReasonReceivedArguments?.reason == .unanswered) - #expect(callController.requestCompletionCallsCount == requestsBeforeTheEnd) - #expect(service.ongoingCallRoomIDPublisher.value == nil) + #expect(order == ["sent", "set up", "returned"]) } @Test - func tearingDownAnotherRoomLeavesTheOngoingCallUp() async { - // A call screen that is dismissed after another room's call replaced it must not take the - // new call down with it. - await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true) + func secondSetupReleasesFirst() async throws { + var returned: [String] = [] - service.tearDownCallSession(roomID: "!other:example.com") + let firstStarted = deferFulfillment(service.actionsPublisher) { $0 == .callSessionStarted(roomID: "!room:example.com", roomDisplayName: "first", isVideo: true, kind: .native) } + let first = Task { + await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "first", isVideo: true, kind: .native) + returned.append("first") + } + try await firstStarted.fulfill() + + let secondStarted = deferFulfillment(service.actionsPublisher) { $0 == .callSessionStarted(roomID: "!room:example.com", roomDisplayName: "second", isVideo: true, kind: .native) } + let second = Task { + await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "second", isVideo: true, kind: .native) + returned.append("second") + } + try await secondStarted.fulfill() + + await first.value + #expect(returned == ["first"]) + + service.callSessionSetUp(roomID: "!room:example.com", isAccepted: true) + await second.value + #expect(returned == ["first", "second"]) + } + + @Test + func callScreenReportsReachManager() { + var actions: [ElementCallServiceAction] = [] + let cancellable = service.actionsPublisher.sink { actions.append($0) } + defer { cancellable.cancel() } + + service.reportCallSessionConnected(roomID: "!room:example.com") + service.tearDownCallSession(roomID: "!room:example.com") + service.reportCallSessionEnded(roomID: "!room:example.com", reason: .remoteEnded) + service.setAudioEnabled(false, roomID: "!room:example.com") + + #expect(actions == [.callSessionConnected(roomID: "!room:example.com"), + .callSessionEnded(roomID: "!room:example.com", reason: nil), + .callSessionEnded(roomID: "!room:example.com", reason: .remoteEnded), + .audioEnabledChanged(false, roomID: "!room:example.com")]) + } + + @Test + func ongoingCallIsPublished() { + service.ongoingCallChanged(roomID: "!room:example.com") #expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com") - service.tearDownCallSession(roomID: "!room:example.com") + service.ongoingCallChanged(roomID: nil) #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 - func nativeModeReportsVoiceCallsWithoutVideo() async { - appSettings.nativeCallEnabled = true - - await reportIncomingPush(isVoiceCall: true) - - #expect(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update.hasVideo == false) - } - - @Test - func nativeModeStillReportsVideoCallsWithVideo() async { - appSettings.nativeCallEnabled = true - - await reportIncomingPush(isVoiceCall: false) - - #expect(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.update.hasVideo == true) - } - - @Test - func answeringInNativeModeKeepsTheCallUp() async throws { - appSettings.nativeCallEnabled = true - await reportIncomingPush(isVoiceCall: false) - await clock.waitForScheduledSleep() - - try await answerReportedCall() - - // The webview path ends the call a second after answering so that `setupCallSession` can - // start a new one. The native stack takes this one over instead, so it has to survive. - #expect(!callProvider.reportCallWithEndedAtReasonCalled) - } - - @Test - func answeredNativeCallEndsWhenNothingTakesItOver() async throws { - appSettings.nativeCallEnabled = true - await reportIncomingPush(isVoiceCall: false) - await clock.waitForScheduledSleep() - - let answeredUUID = try await answerReportedCall() - - let (endedCalls, endedCallsContinuation) = AsyncStream<(UUID, CXCallEndedReason)>.makeStream() - callProvider.reportCallWithEndedAtReasonClosure = { uuid, _, reason in - endedCallsContinuation.yield((uuid, reason)) - } - let deferredEndedCall = deferFulfillment(endedCalls) { _ in true } - - // Answering swaps the unanswered timer for the watchdog that catches a hand-off that never - // happens — the room isn't joined, there's no transport, a call is already running. - #expect(await clock.waitForScheduledSleep() == .seconds(30)) - clock.advance(by: .seconds(30)) - - let (uuid, reason) = try await deferredEndedCall.fulfill() - #expect(uuid == answeredUUID) - #expect(reason == .failed) - } - - @Test - func nativeCallStackTakesOverTheAnsweredCall() async throws { - enableNativeCalls() - await reportIncomingPush(isVoiceCall: false) - await clock.waitForScheduledSleep() - - try await answerReportedCall() - - // Answering starts the watchdog, so wait for it before asserting that the hand-over stops it. - await clock.waitForScheduledSleep() - - await service.setupCallSession(roomID: "!room:example.com", roomDisplayName: "welcome", isVideo: true) - - // Taking the answered call over means keeping its identifier rather than reporting a new - // outgoing call, which is what the update below would be part of. - #expect(!callProvider.reportCallWithUpdatedCalled) - #expect(service.ongoingCallRoomIDPublisher.value == "!room:example.com") - - // And the watchdog must be gone, otherwise it ends the call that was just taken over. - #expect(!clock.hasPendingSleep, "The watchdog must not outlive the hand-over") - } - - @Test - func nativeCallStackForAnotherRoomReportsANewCall() async throws { - enableNativeCalls() - await reportIncomingPush(isVoiceCall: false) - await clock.waitForScheduledSleep() - - let answeredUUID = try await answerReportedCall() - - await service.setupCallSession(roomID: "!other:example.com", roomDisplayName: "other", isVideo: true) - - let update = try #require(callProvider.reportCallWithUpdatedReceivedArguments) - #expect(update.uuid != answeredUUID) - #expect(update.update.localizedCallerName == "other") - #expect(service.ongoingCallRoomIDPublisher.value == "!other:example.com") - - // Unlike a web view call, a native one is tracked by CallKit, so it gets the connected report too. - service.reportCallSessionConnected(roomID: "!other:example.com") - #expect(callProvider.reportOutgoingCallWithConnectedAtReceivedArguments?.uuid == update.uuid) + func systemEventsReachNativeCall() async throws { + let deferred = deferFulfillment(service.nativeCallEventsPublisher) { $0 == .endCallRequested(roomID: "!room:example.com") } + service.systemEventReceived(.endCallRequested(roomID: "!room:example.com")) + try await deferred.fulfill() } @Test func nativeCallStackNeedsBothTheSettingAndASession() { - #expect(service.nativeCallController == nil) + var presentations: [NativeCallPresentation] = [] + let cancellable = service.nativeCallPresentationPublisher.sink { presentations.append($0) } + defer { cancellable.cancel() } + #expect(service.nativeCallController == nil, "A session alone doesn't build a stack") + + service.setUserSession(nil) appSettings.nativeCallEnabled = true #expect(service.nativeCallController == nil, "The setting alone has no transport to run a call over") @@ -524,6 +260,7 @@ final class ElementCallServiceTests { service.setUserSession(nil) #expect(service.nativeCallController == nil, "Signing out has to release the stack's to-device subscription") + #expect(presentations == [.dismiss]) } @Test @@ -561,98 +298,15 @@ final class ElementCallServiceTests { #expect(service.handleNativeCallRequest(roomProxy: roomProxy, isVoiceCall: false)) } + // MARK: - Helpers + /// Builds a session whose client proxy can serve the native call stack, and holds on to it: the /// service only keeps a weak reference, as the app owns the session. private func nativeUserSession() -> UserSessionMock { let clientProxy = ClientProxyMock(.init()) clientProxy.makeNativeCallTransportReturnValue = ElementCallFakeTransport() let session = UserSessionMock(.init(clientProxy: clientProxy)) - userSession = session + nativeSession = session return session } - - /// Puts the service in native mode, with the stack the CallKit paths check for. - private func enableNativeCalls() { - appSettings.nativeCallEnabled = true - service.setUserSession(nativeUserSession()) - } - - /// Delivers a VoIP push and waits for it to be reported, returning once the call is ringing. - 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() - } - } - } - - /// Answers the call the provider last reported, returning its identifier. - @discardableResult - private func answerReportedCall() async throws -> UUID { - let uuid = try #require(callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments?.uuid) - let provider = CXProvider(configuration: CXProviderConfiguration()) - - service.provider(provider, perform: CXAnswerCallAction(call: uuid)) - - return uuid - } - - private func expectImmediatelyEndedCallReported(forPayload payload: PKPushPayloadMock, - expectedReason: CXCallEndedReason) async { - let baselineNewIncomingCount = callProvider.reportNewIncomingCallWithUpdateCompletionCallsCount - let baselineEndedCount = callProvider.reportCallWithEndedAtReasonCallsCount - - await waitForConfirmation { confirmation in - service.pushRegistry(pushRegistry, didReceiveIncomingPushWith: payload, for: .voIP) { - confirmation() - } - } - - #expect(callProvider.reportNewIncomingCallWithUpdateCompletionCallsCount == baselineNewIncomingCount + 1) - #expect(callProvider.reportCallWithEndedAtReasonCallsCount == baselineEndedCount + 1) - - let reportedCall = callProvider.reportNewIncomingCallWithUpdateCompletionReceivedArguments - let endedCall = callProvider.reportCallWithEndedAtReasonReceivedArguments - #expect(reportedCall?.uuid == endedCall?.uuid) - #expect(endedCall?.reason == expectedReason) - } -} - -private nonisolated class PKPushPayloadMock: PKPushPayload { - var dict: [AnyHashable: Any] = [:] - - override init() { - dict[ElementCallServiceNotificationKey.roomID.rawValue] = "!room:example.com" - dict[ElementCallServiceNotificationKey.roomDisplayName.rawValue] = "welcome" - dict[ElementCallServiceNotificationKey.rtcNotifyEventID.rawValue] = "$000" - dict[ElementCallServiceNotificationKey.expirationDate.rawValue] = Date(timeIntervalSince1970: 10) - } - - override var dictionaryPayload: [AnyHashable: Any] { - dict - } - - func updatingExpiration(_ from: Date, lifetime: TimeInterval) -> Self { - dict[ElementCallServiceNotificationKey.expirationDate.rawValue] = from.addingTimeInterval(lifetime) - return self - } - - func updateIsVoice(_ isVoice: Bool) -> Self { - 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 - } } diff --git a/UnitTests/Sources/ManualClockTests.swift b/UnitTests/Sources/ManualClockTests.swift index dab7b3a28..4ef109c56 100644 --- a/UnitTests/Sources/ManualClockTests.swift +++ b/UnitTests/Sources/ManualClockTests.swift @@ -53,6 +53,22 @@ final class ManualClockTests { } } + @Test + func earlyCancelSparesOtherSleep() async throws { + let sleeper = Task { try await clock.sleep(for: .seconds(10)) } + await clock.waitForScheduledSleep() + + // Cancelled before it starts, so it reaches the clock already cancelled. + let cancelledSleeper = Task { try await clock.sleep(for: .seconds(10)) } + cancelledSleeper.cancel() + await #expect(throws: CancellationError.self) { + try await cancelledSleeper.value + } + + clock.advance(by: .seconds(10)) + try await sleeper.value + } + @Test func sleepingUntilAPastDeadlineFinishesImmediately() async throws { clock.advance(by: .seconds(10)) diff --git a/UnitTests/Sources/NativeCallSystemTests.swift b/UnitTests/Sources/NativeCallSystemTests.swift new file mode 100644 index 000000000..9fabdc747 --- /dev/null +++ b/UnitTests/Sources/NativeCallSystemTests.swift @@ -0,0 +1,65 @@ +// +// Copyright 2026 Element Creations Ltd. +// +// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. +// Please see LICENSE files in the repository root for full details. +// + +import Combine +import ElementCall +@testable import ElementX +import Testing + +struct NativeCallSystemTests { + private let service = ElementCallServiceMock(.init()) + private let nativeCallEvents = PassthroughSubject() + private let system: NativeCallSystem + + init() { + service.nativeCallEventsPublisher = nativeCallEvents.eraseToAnyPublisher() + system = NativeCallSystem(service: service) + } + + @Test + func startCallSetsUpNativeSession() async { + await system.startCall(roomID: "!room:example.com", displayName: "welcome", isVideo: true) + + #expect(service.setupCallSessionRoomIDRoomDisplayNameIsVideoKindReceivedArguments?.kind == .native) + } + + @Test + func eventsReachCallStack() { + var events: [ElementCallSystemEvent] = [] + let cancellable = system.events.sink { events.append($0) } + defer { cancellable.cancel() } + + nativeCallEvents.send(.audioSessionActivated) + nativeCallEvents.send(.audioSessionDeactivated) + nativeCallEvents.send(.microphoneMuteChanged(isMuted: true)) + nativeCallEvents.send(.endCallRequested(roomID: "!room:example.com")) + + #expect(events == [.audioSessionActivated, + .audioSessionDeactivated, + .microphoneMuteChanged(isMuted: true), + .endCallRequested(roomID: "!room:example.com")]) + } + + @Test + func localEndTearsDownCall() { + system.endCall(roomID: "!room:example.com", reason: .local) + + #expect(service.tearDownCallSessionRoomIDReceivedRoomID == "!room:example.com") + #expect(!service.reportCallSessionEndedRoomIDReasonCalled) + } + + @Test(arguments: [(ElementCallEndReason.remoteEnded, CallEndReason.remoteEnded), + (.unanswered, .unanswered), + (.failed, .failed)]) + func otherEndIsReportedWithReason(reason: ElementCallEndReason, expectedReason: CallEndReason) { + system.endCall(roomID: "!room:example.com", reason: reason) + + #expect(service.reportCallSessionEndedRoomIDReasonReceivedArguments?.roomID == "!room:example.com") + #expect(service.reportCallSessionEndedRoomIDReasonReceivedArguments?.reason == expectedReason) + #expect(!service.tearDownCallSessionRoomIDCalled) + } +} diff --git a/UnitTests/Sources/TestUtilities/Extensions/ElementCallSystemEvent.swift b/UnitTests/Sources/TestUtilities/Extensions/ElementCallSystemEvent.swift new file mode 100644 index 000000000..1227707ab --- /dev/null +++ b/UnitTests/Sources/TestUtilities/Extensions/ElementCallSystemEvent.swift @@ -0,0 +1,23 @@ +// +// Copyright 2026 Element Creations Ltd. +// +// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. +// Please see LICENSE files in the repository root for full details. +// + +import ElementCall + +nonisolated extension ElementCallSystemEvent: @retroactive Equatable { + public static func == (lhs: ElementCallSystemEvent, rhs: ElementCallSystemEvent) -> Bool { + switch (lhs, rhs) { + case (.audioSessionActivated, .audioSessionActivated), (.audioSessionDeactivated, .audioSessionDeactivated): + true + case let (.microphoneMuteChanged(lhsIsMuted), .microphoneMuteChanged(rhsIsMuted)): + lhsIsMuted == rhsIsMuted + case let (.endCallRequested(lhsRoomID), .endCallRequested(rhsRoomID)): + lhsRoomID == rhsRoomID + default: + false + } + } +} diff --git a/UnitTests/Sources/TestUtilities/ManualClock.swift b/UnitTests/Sources/TestUtilities/ManualClock.swift index 0a5352d66..e4f0ab0fd 100644 --- a/UnitTests/Sources/TestUtilities/ManualClock.swift +++ b/UnitTests/Sources/TestUtilities/ManualClock.swift @@ -5,6 +5,7 @@ // Please see LICENSE files in the repository root for full details. // +import Foundation import Synchronization /// A clock whose sleeps only finish when the test advances it. @@ -26,6 +27,7 @@ final nonisolated class ManualClock: Clock { } private struct Sleep { + let id: UUID let deadline: Instant let continuation: CheckedContinuation } @@ -55,11 +57,13 @@ final nonisolated class ManualClock: Clock { /// cancelled, in which case this throws a `CancellationError`. Deadlines that have already /// passed return without suspending. `tolerance` is ignored. func sleep(until deadline: Instant, tolerance: Duration? = nil) async throws { + let id = UUID() + try await withTaskCancellationHandler { try Task.checkCancellation() try await withCheckedThrowingContinuation { continuation in - switch schedule(deadline: deadline, continuation: continuation) { + switch schedule(id: id, deadline: deadline, continuation: continuation) { case .elapsed: continuation.resume() case .scheduled(let duration, let observer): @@ -67,12 +71,13 @@ final nonisolated class ManualClock: Clock { // Cancellation that landed while scheduling found nothing to cancel. if Task.isCancelled { - cancelSleep() + cancelSleep(id: id) } } } } onCancel: { - cancelSleep() + // Runs straight away for a task that arrives cancelled, while another task's sleep may be pending. + cancelSleep(id: id) } } @@ -128,7 +133,7 @@ final nonisolated class ManualClock: Clock { /// Stores the sleep's continuation, handing the caller whatever needs resuming so that it /// happens outside of the lock. - private func schedule(deadline: Instant, continuation: CheckedContinuation) -> Scheduling { + private func schedule(id: UUID, deadline: Instant, continuation: CheckedContinuation) -> Scheduling { state.withLock { state in guard deadline > state.now else { return .elapsed @@ -136,7 +141,7 @@ final nonisolated class ManualClock: Clock { precondition(state.sleep == nil, "The clock only supports a single pending sleep.") - state.sleep = Sleep(deadline: deadline, continuation: continuation) + state.sleep = Sleep(id: id, deadline: deadline, continuation: continuation) let observer = state.sleepObserver state.sleepObserver = nil @@ -145,9 +150,12 @@ final nonisolated class ManualClock: Clock { } } - private func cancelSleep() { + private func cancelSleep(id: UUID) { let sleep = state.withLock { state -> Sleep? in - let sleep = state.sleep + guard let sleep = state.sleep, sleep.id == id else { + return nil + } + state.sleep = nil return sleep } diff --git a/UnitTests/Sources/UserSessionFlowCoordinatorTests.swift b/UnitTests/Sources/UserSessionFlowCoordinatorTests.swift index fb45ebdfb..7fa27d897 100644 --- a/UnitTests/Sources/UserSessionFlowCoordinatorTests.swift +++ b/UnitTests/Sources/UserSessionFlowCoordinatorTests.swift @@ -90,7 +90,7 @@ struct UserSessionFlowCoordinatorTests { func replacingTheSessionScreensEndsTheWebViewCall() async { // E.g. clearing the cache or signing out during a call: the call screen goes with the screens. await waitForConfirmation { confirmation in - elementCallService.setupCallSessionRoomIDRoomDisplayNameIsVideoClosure = { _, _, _ in confirmation() } + elementCallService.setupCallSessionRoomIDRoomDisplayNameIsVideoKindClosure = { _, _, _, _ in confirmation() } userSessionFlowCoordinator.handleAppRoute(.call(roomID: "1", isVoiceCall: false), animated: false) }