diff --git a/ElementX.xcodeproj/project.pbxproj b/ElementX.xcodeproj/project.pbxproj index 931fb4183..2281b7812 100644 --- a/ElementX.xcodeproj/project.pbxproj +++ b/ElementX.xcodeproj/project.pbxproj @@ -207,6 +207,7 @@ 1C9BB74711E5F24C77B7FED0 /* RoomMembersListScreenCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AEA0B743847CFA5B3C38EE4 /* RoomMembersListScreenCoordinator.swift */; }; 1CA094038D4D036A6F0A1314 /* VoiceMessageTrashButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABF84AA68B2B7584D9275769 /* VoiceMessageTrashButton.swift */; }; 1CA6E1843E1B3680544EB584 /* GalleryRoomTimelineItemContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35A5AB4E2E5CA98F99BFC552 /* GalleryRoomTimelineItemContent.swift */; }; + 1CD98CDEBF33A4AD2FCA3A5B /* SDKRoomFeeds.swift in Sources */ = {isa = PBXBuildFile; fileRef = A135DE31BA694AF72FEB4EDC /* SDKRoomFeeds.swift */; }; 1CF975943A3048FCF3723D46 /* preview_avatar_user.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 94A561C542596126DAE211AD /* preview_avatar_user.jpg */; }; 1D2D713A5A269072D103AE37 /* CLLocationManagerProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA46D6DD4B4AB17E1D45092E /* CLLocationManagerProtocol.swift */; }; 1D5DC685CED904386C89B7DA /* NSRegularExpresion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95BAC0F6C9644336E9567EE6 /* NSRegularExpresion.swift */; }; @@ -524,6 +525,7 @@ 4FFDC274824F7CC0BBDF581E /* BugReportScreenModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51C2BCE0BC1FC69C1B36E688 /* BugReportScreenModels.swift */; }; 50381244BA280451771BE3ED /* PINTextFieldTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF13BFD415CA84B1272E94F8 /* PINTextFieldTests.swift */; }; 5038E69A5E6A89DE1A345E04 /* ShouldScrollOnKeyboardDidShow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 832397B5C3D00A4BF52C5F0B /* ShouldScrollOnKeyboardDidShow.swift */; }; + 503B97AB3D6FD7463D39DC63 /* SDKMatrixBackend.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53B93EB7ECD9DB7C3AC580CC /* SDKMatrixBackend.swift */; }; 5044C78B1B49328F5BB1FEB8 /* NotificationItemProxyProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DDB7A9BB466C56614BB589D /* NotificationItemProxyProtocol.swift */; }; 50539366B408780B232C1910 /* EstimatedWaveformView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD0FF64B0E6470F66F42E182 /* EstimatedWaveformView.swift */; }; 5100F53E6884A15F9BA07CC3 /* AttributedStringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37CA26F55123E36B50DB0B3A /* AttributedStringTests.swift */; }; @@ -1428,6 +1430,7 @@ DA6E57CB533213D438001A31 /* ClientFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 996AF8CF3FCF19B62F005C57 /* ClientFactory.swift */; }; DA7E867F5EAFF8E20B2EE3B6 /* SecureBackupScreenModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B3D16709ADD4F4BCC710B1E /* SecureBackupScreenModels.swift */; }; DA8AE352C8FFCD47327811CA /* LeaveSpaceModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 822B5573BDF52CF220BF9A17 /* LeaveSpaceModels.swift */; }; + DAD9BD3474218AFFBA09DCB6 /* SDKMappings.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD081A2F18228153CA989B11 /* SDKMappings.swift */; }; DAF63A9CF9932CA8F6830F11 /* ShareExtensionModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCAC01A97A43BE07B9E94E43 /* ShareExtensionModels.swift */; }; DB01FDD050A43B72C5425549 /* CreateRoomScreenViewModelProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AC5E094DFE18C3AB7619D34 /* CreateRoomScreenViewModelProtocol.swift */; }; DB079D1929B5A5F52D207C83 /* RoomDetailsScreenModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 466C71A0FED9BFF287613C82 /* RoomDetailsScreenModels.swift */; }; @@ -1538,6 +1541,7 @@ 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 */; }; + EBC581C6777E3419EA3BB1E7 /* SDKMappingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1E6D75B5D2EE9121F02EC9C /* SDKMappingsTests.swift */; }; EBE13FAB4E29738AC41BD3E5 /* InfoPlistReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A580295A56B55A856CC4084 /* InfoPlistReader.swift */; }; EC09E502A21E4EAA8B367AB8 /* ReportContentScreenViewModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30EA681527A8FE65E4C8E9A9 /* ReportContentScreenViewModelTests.swift */; }; EC1A0E85CEE50BF0C64EEFA5 /* LabsScreenViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4D9DF4F2DF3507F99B5B97B /* LabsScreenViewModel.swift */; }; @@ -2333,6 +2337,7 @@ 53482ECA4B6633961EC224F5 /* ScrollViewAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScrollViewAdapter.swift; sourceTree = ""; }; 5351EBD7A0B9610548E4B7B2 /* EncryptedRoomTimelineItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EncryptedRoomTimelineItem.swift; sourceTree = ""; }; 536E72DCBEEC4A1FE66CFDCE /* target.yml */ = {isa = PBXFileReference; lastKnownFileType = text.yaml; path = target.yml; sourceTree = ""; }; + 53B93EB7ECD9DB7C3AC580CC /* SDKMatrixBackend.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SDKMatrixBackend.swift; sourceTree = ""; }; 53C65A839BC897F6C236E8A5 /* TimelineInteractionHandlerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimelineInteractionHandlerTests.swift; sourceTree = ""; }; 53D4EE9E5F3E5BF651869242 /* NativeCallStackTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeCallStackTests.swift; sourceTree = ""; }; 53F41CEAAE2BB4E74CDC2278 /* TimelineMediaPreviewViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimelineMediaPreviewViewModel.swift; sourceTree = ""; }; @@ -2795,6 +2800,7 @@ A11D53EE8E666C25F97B4369 /* AppSettingsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppSettingsTests.swift; sourceTree = ""; }; A12D3B1BCF920880CA8BBB6B /* UserIndicatorControllerProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserIndicatorControllerProtocol.swift; sourceTree = ""; }; A130A2251A15A7AACC84FD37 /* RoomPollsHistoryScreenViewModelProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomPollsHistoryScreenViewModelProtocol.swift; sourceTree = ""; }; + A135DE31BA694AF72FEB4EDC /* SDKRoomFeeds.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SDKRoomFeeds.swift; sourceTree = ""; }; A14FD296A75F5F5637EDC365 /* RoomThreadListScreenCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomThreadListScreenCoordinator.swift; sourceTree = ""; }; A16CD2C62CB7DB78A4238485 /* ReportContentScreenCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportContentScreenCoordinator.swift; sourceTree = ""; }; A16D0F226B1819D017531647 /* BlockedUsersScreenCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlockedUsersScreenCoordinator.swift; sourceTree = ""; }; @@ -3165,6 +3171,7 @@ DCAC01A97A43BE07B9E94E43 /* ShareExtensionModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareExtensionModels.swift; sourceTree = ""; }; DCDAB580109C09A6AA97AF7E /* PollFormScreenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PollFormScreenTests.swift; sourceTree = ""; }; DCF239C619971FDE48132550 /* SecureBackupLogoutConfirmationScreenModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureBackupLogoutConfirmationScreenModels.swift; sourceTree = ""; }; + DD081A2F18228153CA989B11 /* SDKMappings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SDKMappings.swift; sourceTree = ""; }; DD297970D7A0F8BAF870F010 /* SpacesScreenModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacesScreenModels.swift; sourceTree = ""; }; DD3C65634A34467CB407A061 /* target.yml */ = {isa = PBXFileReference; lastKnownFileType = text.yaml; path = target.yml; sourceTree = ""; }; DD955A0380C287C418F1A74D /* PhotoLibraryManagerMock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhotoLibraryManagerMock.swift; sourceTree = ""; }; @@ -3301,6 +3308,7 @@ F17EFA1D3D09FC2F9C5E1CB2 /* MediaProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MediaProvider.swift; sourceTree = ""; }; F1B0FC6A77FDFDE2BFE49E13 /* MediaUploadQualitySettingsScreenCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MediaUploadQualitySettingsScreenCoordinator.swift; sourceTree = ""; }; F1B8500C152BC59445647DA8 /* UnsupportedRoomTimelineItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnsupportedRoomTimelineItem.swift; sourceTree = ""; }; + F1E6D75B5D2EE9121F02EC9C /* SDKMappingsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SDKMappingsTests.swift; sourceTree = ""; }; F276F31C1AEC19E52B951B62 /* SendInviteConfirmationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SendInviteConfirmationView.swift; sourceTree = ""; }; F288457CD4C821DF48C1B6EE /* NativeCallRoomContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeCallRoomContext.swift; sourceTree = ""; }; F2B94F1B0B5D9D42B15AA6E8 /* ChatsTabFlowCoordinatorStateMachine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatsTabFlowCoordinatorStateMachine.swift; sourceTree = ""; }; @@ -4291,6 +4299,7 @@ 956F0BFAC003151CECBBFE45 /* NativeCallStack.swift */, 02A84AEC7D5644B3F83B5333 /* NativeCallStyle.swift */, C3C2316BADD6C1119C1FA229 /* NativeCallSystem.swift */, + 4E71D9C65C9DDA02D6B603F8 /* Matrix */, ); path = NativeCall; sourceTree = ""; @@ -4864,6 +4873,16 @@ path = ClassicApp; sourceTree = ""; }; + 4E71D9C65C9DDA02D6B603F8 /* Matrix */ = { + isa = PBXGroup; + children = ( + DD081A2F18228153CA989B11 /* SDKMappings.swift */, + 53B93EB7ECD9DB7C3AC580CC /* SDKMatrixBackend.swift */, + A135DE31BA694AF72FEB4EDC /* SDKRoomFeeds.swift */, + ); + path = Matrix; + sourceTree = ""; + }; 4EC4EBBC4F6885775F198875 /* Sources */ = { isa = PBXGroup; children = ( @@ -5462,6 +5481,7 @@ F46E441BA50705E6CEC89FE0 /* RoomSummaryProviderTests.swift */, 046C0D3F53B0B5EF0A1F5BEA /* RoomSummaryTests.swift */, B7728AA8046D460145EAC740 /* RoomTests.swift */, + F1E6D75B5D2EE9121F02EC9C /* SDKMappingsTests.swift */, 5413213B56FB76C1071E2BFB /* SearchScreenViewModelTests.swift */, 848F69921527D31CAACB93AF /* SecureBackupLogoutConfirmationScreenViewModelTests.swift */, 0315C328FF40F84276364E66 /* SecurityAndPrivacyScreenViewModelTests.swift */, @@ -8653,6 +8673,7 @@ 6AB306367E56A6F6DFA0E2FF /* RoomSummaryProviderTests.swift in Sources */, 15913A5B07118C1268A840E4 /* RoomSummaryTests.swift in Sources */, 62811275F1ED9EA55638838E /* RoomTests.swift in Sources */, + EBC581C6777E3419EA3BB1E7 /* SDKMappingsTests.swift in Sources */, D69CCEC785E6C819551B402F /* SearchScreenViewModelTests.swift in Sources */, EB87DF90CF6F8D5D12404C6E /* SecureBackupLogoutConfirmationScreenViewModelTests.swift in Sources */, CB9FB2BEF313072C705AC9B5 /* SecurityAndPrivacyScreenViewModelTests.swift in Sources */, @@ -9637,6 +9658,9 @@ B2F8E01ABA1BA30265B4ECBE /* RoundedCornerShape.swift in Sources */, 82434593648CB74121F1A821 /* RowDivider.swift in Sources */, 3F55721B5C08E8D9F1295592 /* SDKListener.swift in Sources */, + DAD9BD3474218AFFBA09DCB6 /* SDKMappings.swift in Sources */, + 503B97AB3D6FD7463D39DC63 /* SDKMatrixBackend.swift in Sources */, + 1CD98CDEBF33A4AD2FCA3A5B /* SDKRoomFeeds.swift in Sources */, 88CBF1595E39CE697928DE48 /* SFNumberedListView.swift in Sources */, 74998B11397D89DD6C24AE33 /* ScanStateMediaEventsTimelineViews.swift in Sources */, FB595EC9C00AB32F39034055 /* SceneDelegate.swift in Sources */, @@ -11115,7 +11139,7 @@ repositoryURL = "https://github.com/element-hq/element-call-ios"; requirement = { kind = exactVersion; - version = "0.1.0-rc.11"; + version = "0.1.0-rc.13"; }; }; 395DE6AE429B7ACC7C7FE31D /* XCRemoteSwiftPackageReference "KZFileWatchers" */ = { diff --git a/ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index f7d96cac9..a291c0cd5 100644 --- a/ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "f99db7401bc7af2ca673ef115aba55ebf7c2a2853096963e2b6b0899b7b70542", + "originHash" : "1964864908944417b4a35a1c63d86d9c5801ed33b9ccea55fb0e6aa645bdc917", "pins" : [ { "identity" : "compound-design-tokens", @@ -60,8 +60,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/element-hq/element-call-ios", "state" : { - "revision" : "d77b4ee326582083cabe53ffbd872a751c3cb989", - "version" : "0.1.0-rc.11" + "revision" : "8e9ae6edc68667e1951d2b8ac8c83841e7f08447", + "version" : "0.1.0-rc.13" } }, { @@ -185,8 +185,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/element-hq/matrix-rust-rtc", "state" : { - "revision" : "c7a81b6742dc5e571b90b05f5109677384efb933", - "version" : "0.5.0-rc.5" + "revision" : "de417a84c566932192c011d9931403b304b9156b", + "version" : "0.5.0-rc.8" } }, { diff --git a/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift b/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift index 6125f79b8..360c8e0dc 100644 --- a/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift +++ b/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift @@ -2591,32 +2591,32 @@ nonisolated class ClientProxyMock: ClientProxyProtocol, @unchecked Sendable { } nonisolated(unsafe) var underlyingLiveLocationOwnInfoUpdatesPublisher: AnyPublisher! - //MARK: - makeNativeCallTransport + //MARK: - makeNativeCallBackend - private let makeNativeCallTransportCallsCountLock = NSLock() - private nonisolated(unsafe) var makeNativeCallTransportUnderlyingCallsCount = 0 - var makeNativeCallTransportCallsCount: Int { - get { makeNativeCallTransportCallsCountLock.withLock { makeNativeCallTransportUnderlyingCallsCount } } - set { makeNativeCallTransportCallsCountLock.withLock { makeNativeCallTransportUnderlyingCallsCount = newValue } } + private let makeNativeCallBackendCallsCountLock = NSLock() + private nonisolated(unsafe) var makeNativeCallBackendUnderlyingCallsCount = 0 + var makeNativeCallBackendCallsCount: Int { + get { makeNativeCallBackendCallsCountLock.withLock { makeNativeCallBackendUnderlyingCallsCount } } + set { makeNativeCallBackendCallsCountLock.withLock { makeNativeCallBackendUnderlyingCallsCount = newValue } } } - var makeNativeCallTransportCalled: Bool { - return makeNativeCallTransportCallsCount > 0 + var makeNativeCallBackendCalled: Bool { + return makeNativeCallBackendCallsCount > 0 } - private let makeNativeCallTransportReturnValueLock = NSLock() - private nonisolated(unsafe) var makeNativeCallTransportUnderlyingReturnValue: ElementCallMatrixTransportProtocol? - var makeNativeCallTransportReturnValue: ElementCallMatrixTransportProtocol? { - get { makeNativeCallTransportReturnValueLock.withLock { makeNativeCallTransportUnderlyingReturnValue } } - set { makeNativeCallTransportReturnValueLock.withLock { makeNativeCallTransportUnderlyingReturnValue = newValue } } + private let makeNativeCallBackendReturnValueLock = NSLock() + private nonisolated(unsafe) var makeNativeCallBackendUnderlyingReturnValue: any ElementCallMatrixBackendProtocol? + var makeNativeCallBackendReturnValue: any ElementCallMatrixBackendProtocol? { + get { makeNativeCallBackendReturnValueLock.withLock { makeNativeCallBackendUnderlyingReturnValue } } + set { makeNativeCallBackendReturnValueLock.withLock { makeNativeCallBackendUnderlyingReturnValue = newValue } } } - nonisolated(unsafe) var makeNativeCallTransportClosure: (() -> ElementCallMatrixTransportProtocol?)? + nonisolated(unsafe) var makeNativeCallBackendClosure: (() -> any ElementCallMatrixBackendProtocol?)? - func makeNativeCallTransport() -> ElementCallMatrixTransportProtocol? { - makeNativeCallTransportCallsCountLock.withLock { makeNativeCallTransportUnderlyingCallsCount += 1 } - if let makeNativeCallTransportClosure = makeNativeCallTransportClosure { - return makeNativeCallTransportClosure() + func makeNativeCallBackend() -> any ElementCallMatrixBackendProtocol? { + makeNativeCallBackendCallsCountLock.withLock { makeNativeCallBackendUnderlyingCallsCount += 1 } + if let makeNativeCallBackendClosure = makeNativeCallBackendClosure { + return makeNativeCallBackendClosure() } else { - return makeNativeCallTransportReturnValue + return makeNativeCallBackendReturnValue } } //MARK: - isOnlyDeviceLeft diff --git a/ElementX/Sources/Services/Client/ClientProxy.swift b/ElementX/Sources/Services/Client/ClientProxy.swift index dc6e03fab..6ea5411a7 100644 --- a/ElementX/Sources/Services/Client/ClientProxy.swift +++ b/ElementX/Sources/Services/Client/ClientProxy.swift @@ -319,8 +319,8 @@ class ClientProxy: ClientProxyProtocol { } } - func makeNativeCallTransport() -> ElementCallMatrixTransportProtocol? { - (client as? Client).flatMap { ElementCallSDKTransport(client: $0) } + func makeNativeCallBackend() -> (any ElementCallMatrixBackendProtocol)? { + (client as? Client).flatMap { SDKMatrixBackend(client: $0, logger: NativeCallStack.Logger()) } } var isLoginWithQRCodeSupported: Bool { diff --git a/ElementX/Sources/Services/Client/ClientProxyProtocol.swift b/ElementX/Sources/Services/Client/ClientProxyProtocol.swift index 4fe9ac341..2e94f6a89 100644 --- a/ElementX/Sources/Services/Client/ClientProxyProtocol.swift +++ b/ElementX/Sources/Services/Client/ClientProxyProtocol.swift @@ -174,8 +174,8 @@ protocol ClientProxyProtocol: AnyObject { var isReportRoomSupported: Bool { get async } var isLiveKitRTCSupported: Bool { get async } - /// Builds a Matrix transport for the call package, `nil` when not backed by a real SDK client. - func makeNativeCallTransport() -> ElementCallMatrixTransportProtocol? + /// Builds the call package's Matrix backend, `nil` when not backed by a real SDK client. + func makeNativeCallBackend() -> (any ElementCallMatrixBackendProtocol)? var isLoginWithQRCodeSupported: Bool { get async } diff --git a/ElementX/Sources/Services/ElementCall/ElementCallManager.swift b/ElementX/Sources/Services/ElementCall/ElementCallManager.swift index fcb6d912e..d3b540ccc 100644 --- a/ElementX/Sources/Services/ElementCall/ElementCallManager.swift +++ b/ElementX/Sources/Services/ElementCall/ElementCallManager.swift @@ -9,6 +9,7 @@ import AVFoundation import CallKit import Combine +import ElementCall import Foundation import PushKit import UIKit @@ -404,8 +405,8 @@ final class ElementCallManager: NSObject, ElementCallManagerProtocol, PKPushRegi } func provider(_ provider: CXProvider, perform action: CXStartCallAction) { - // The native controller configured the audio session already; CallKit activates it and - // reports back through `didActivate`. + // CallKit activates the session and reports back through `didActivate`. + configureNativeCallAudioSession() action.fulfill() callProvider.reportOutgoingCall(with: action.callUUID, startedConnectingAt: nil) } @@ -436,6 +437,7 @@ final class ElementCallManager: NSObject, ElementCallManagerProtocol, PKPushRegi // https://stackoverflow.com/questions/71483732/webrtc-running-from-wkwebview-avaudiosession-development-roadblock // First fullfill the action + configureNativeCallAudioSession() action.fulfill() if appSettings.nativeCallEnabled { @@ -514,6 +516,18 @@ final class ElementCallManager: NSObject, ElementCallManagerProtocol, PKPushRegi // MARK: - Private + /// Must run before a CallKit action is fulfilled: the system activates the session with whatever + /// category it has then, and an answered call reaches the controller only after that. + private func configureNativeCallAudioSession() { + guard appSettings.nativeCallEnabled else { return } + + do { + try CallAudioSessionConfigurator.configure() + } catch { + MXLog.error("Failed configuring the call audio session with error: \(error)") + } + } + /// 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 { diff --git a/ElementX/Sources/Services/ElementCall/ElementCallService.swift b/ElementX/Sources/Services/ElementCall/ElementCallService.swift index db7665dae..f86258790 100644 --- a/ElementX/Sources/Services/ElementCall/ElementCallService.swift +++ b/ElementX/Sources/Services/ElementCall/ElementCallService.swift @@ -194,8 +194,8 @@ final class ElementCallService: ElementCallServiceProtocol { guard nativeCallStack == nil else { return } - guard let transport = clientProxy.makeNativeCallTransport() else { - MXLog.error("Cannot start the native call stack without a transport") + guard let backend = clientProxy.makeNativeCallBackend() else { + MXLog.error("Cannot start the native call stack without a Matrix backend") return } @@ -211,7 +211,7 @@ final class ElementCallService: ElementCallServiceProtocol { // surface. Screen sharing stays off until the broadcast extension that makes it work lands. let options = ElementCallOptions(isDeveloperModeEnabled: appSettings.developerOptionsEnabled) - let stack = NativeCallStack(transport: transport, + let stack = NativeCallStack(backend: backend, system: NativeCallSystem(service: self), options: options, style: style) diff --git a/ElementX/Sources/Services/NativeCall/Matrix/SDKMappings.swift b/ElementX/Sources/Services/NativeCall/Matrix/SDKMappings.swift new file mode 100644 index 000000000..4f1a0080f --- /dev/null +++ b/ElementX/Sources/Services/NativeCall/Matrix/SDKMappings.swift @@ -0,0 +1,200 @@ +// +// 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 +import Foundation +import MatrixRustSDK + +/// What ``SDKMatrixBackend`` turns SDK values into, kept apart from the listeners so every mapping can +/// be tested without a client. +nonisolated enum SDKMappings { + // MARK: Events + + /// Under the subscribed type rather than the event's own: the SDK hands it back as ruma's enum, + /// whose custom variant has no readable string. Ruma treats `m.call.member` and + /// `org.matrix.msc3401.call.member` as one type, which is harmless because the room-state dialect + /// subscribes to one spelling only. Stripped state (an invited room) has no event ID or timestamp + /// and is dropped. State is never encrypted. + static func event(_ event: RoomStateEvent, subscribedAs eventType: String) -> ElementCallMatrixEvent? { + guard let eventID = event.eventId, let timestamp = event.timestamp else { return nil } + return ElementCallMatrixEvent(eventID: eventID, + sender: event.sender, + eventType: eventType, + stateKey: event.stateKey, + originServerTimestamp: date(milliseconds: timestamp), + contentJSON: event.contentJson, + encryption: encryption(nil)) + } + + /// As for state, under the subscribed type. + static func event(_ event: RoomMessageLikeEvent, subscribedAs eventType: String) -> ElementCallMatrixEvent { + ElementCallMatrixEvent(eventID: event.eventId, + sender: event.sender, + eventType: eventType, + originServerTimestamp: date(milliseconds: event.timestamp), + contentJSON: event.contentJson, + encryption: encryption(event.encryptionInfo)) + } + + /// A sticky event carries the whole event as JSON, and its type on the wire, which for an unstable + /// type may differ from the key's. Nil when it is malformed. + static func event(_ event: StickyEvent) -> ElementCallMatrixEvent? { + guard let object = jsonObject(event.eventJson), + let content = object["content"] as? [String: Any], + let timestamp = (object["origin_server_ts"] as? NSNumber)?.uint64Value, + let contentData = try? JSONSerialization.data(withJSONObject: content), + let contentJSON = String(data: contentData, encoding: .utf8) else { + return nil + } + return ElementCallMatrixEvent(eventID: event.eventId, + sender: event.key.sender, + eventType: object["type"] as? String ?? event.key.eventType, + originServerTimestamp: date(milliseconds: timestamp), + contentJSON: contentJSON, + encryption: encryption(event.encryptionInfo)) + } + + /// Room version 11 moved `redacts` into the content, and the SDK hands over the content only, so a + /// redaction in an older room is missed. + static func redactedEventID(fromContent contentJSON: String) -> String? { + jsonObject(contentJSON)?["redacts"] as? String + } + + // MARK: Encryption and trust + + /// How the SDK says an event arrived; no encryption info is cleartext. + /// + /// Whether to vouch for the sender is the client's threat model, and the SDK has already applied + /// it: an event or to-device message whose sender fails the client's + /// `DecryptionSettings.senderDeviceTrustRequirement` is never delivered. Of what remains, the + /// sender is confirmed unless its shield is red. + static func encryption(_ info: EventEncryptionInfo?) -> ElementCallEventEncryption { + guard let info else { return .cleartext } + let isRed = if case .red = info.shieldState { + true + } else { + false + } + return .encrypted(senderDeviceID: info.senderDeviceId, isSenderConfirmed: !isRed) + } + + /// Nil while the client does not know, never a guess. + static func isEncrypted(_ state: EncryptionState) -> Bool? { + switch state { + case .encrypted: true + case .notEncrypted: false + case .unknown: nil + } + } + + // MARK: Members + + /// Whether a freshly read, sorted membership is worth delivering. Compared whole, never by count. + /// An empty list is never delivered: we are in the room, so it is the store not having loaded the + /// members yet, and the core would ignore a set without us. + static func shouldDeliver(_ members: [String], lastDelivered: [String]?) -> Bool { + !members.isEmpty && members != lastDelivered + } + + // MARK: To-device + + /// The claimed sender is unauthenticated; an encrypted message's attested one is what counts. + static func toDeviceMessage(_ message: ToDeviceMessage) -> ElementCallToDeviceMessage { + ElementCallToDeviceMessage(sender: message.encryptionInfo?.senderId ?? message.senderId, + eventType: message.eventType, + contentJSON: message.content, + encryption: encryption(message.encryptionInfo)) + } + + /// The recipients the SDK could not serve, from its user ID → device IDs: the core re-sends only to + /// those. + static func undelivered(_ recipients: [ElementCallDevice], failures: [String: [String]]) -> [ElementCallDevice: String] { + let failed = recipients.filter { failures[$0.userID]?.contains($0.deviceID) ?? false } + return Dictionary(failed.map { ($0, "The message could not be delivered to this device") }) { first, _ in first } + } + + // MARK: Transports and failures + + /// The MSC4143 `rtc_transports` array the core parses, rebuilt from the SDK's typed transports. + static func transportsJSON(_ transports: [RtcTransport]) -> String { + let objects: [[String: Any]] = transports.map { transport in + switch transport { + case .liveKit(let serviceURL): + return ["type": "livekit", "livekit_service_url": serviceURL] + case .custom(let type, let data): + var fields = jsonObject(data) ?? [:] + fields["type"] = type + return fields + } + } + guard let data = try? JSONSerialization.data(withJSONObject: objects, options: .sortedKeys) else { return "[]" } + return String(data: data, encoding: .utf8) ?? "[]" + } + + /// A failure as the core classifies it, which it does on the Matrix error code. The bindings do not + /// carry the HTTP status. The server's retry-after is passed on so the core waits that long + /// rather than its own backoff step, though the SDK has usually spent it already, retrying a + /// rate limit itself before the call returns. + static func backendError(_ error: any Error) -> ElementCallMatrixBackendError { + switch error { + case let error as ElementCallMatrixBackendError: + error + case ClientError.MatrixApi(.limitExceeded(let retryAfter), let code, let message, _): + ElementCallMatrixBackendError(errorCode: code, retryAfter: retryAfter.map { .milliseconds($0) }, reason: message) + case ClientError.MatrixApi(_, let code, let message, _): + ElementCallMatrixBackendError(errorCode: code, reason: message) + default: + ElementCallMatrixBackendError(reason: "\(error)") + } + } + + private static func date(milliseconds: UInt64) -> Date { + Date(timeIntervalSince1970: Double(milliseconds) / 1000) + } + + private static func jsonObject(_ json: String) -> [String: Any]? { + guard let data = json.data(using: .utf8) else { return nil } + return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + } +} + +/// The live sticky events, by key, in the order they arrived. +nonisolated struct SDKStickyEventSet { + private var keys = [StickyKey]() + private var events = [StickyKey: ElementCallMatrixEvent]() + + mutating func apply(_ update: StickyEventsUpdate) -> [ElementCallMatrixEvent] { + switch update { + case .reset(let live): + keys.removeAll() + events.removeAll() + live.forEach { put($0) } + case .changes(let added, let updated, let removed): + added.forEach { put($0) } + updated.forEach { put($0) } + removed.forEach { remove($0.key) } + } + return keys.compactMap { events[$0] } + } + + /// A malformed event takes its key's place away rather than leaving the one it replaced live. + private mutating func put(_ event: StickyEvent) { + guard let mappedEvent = SDKMappings.event(event) else { + remove(event.key) + return + } + if events.updateValue(mappedEvent, forKey: event.key) == nil { + keys.append(event.key) + } + } + + private mutating func remove(_ key: StickyKey) { + if events.removeValue(forKey: key) != nil { + keys.removeAll { $0 == key } + } + } +} diff --git a/ElementX/Sources/Services/NativeCall/Matrix/SDKMatrixBackend.swift b/ElementX/Sources/Services/NativeCall/Matrix/SDKMatrixBackend.swift new file mode 100644 index 000000000..31aa19a60 --- /dev/null +++ b/ElementX/Sources/Services/NativeCall/Matrix/SDKMatrixBackend.swift @@ -0,0 +1,210 @@ +// +// 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 +import Foundation +import MatrixRustSDK + +/// The call's Matrix backend over a Rust SDK `Client`, for a host that has an SDK client to hand to +/// `ElementCallController`. The reference a host copies, so the package carries no SDK dependency and +/// never holds back a host's SDK bump. The example itself has no client and runs on fakes, so this is +/// compiled and its mappings are unit-tested, but it is never run here. +/// +/// One per Matrix session, alive between calls. The core calls it from its own threads, and the SDK +/// calls the listeners below from its own; the core's sinks only post to a channel, so events are +/// delivered straight from the SDK's callbacks, with nothing buffered in between. +/// +/// Every type in these files is marked `nonisolated` although this target does not need it: a host +/// whose default isolation is the main actor, as Element X's is, must be able to copy them unchanged. +final nonisolated class SDKMatrixBackend: ElementCallMatrixBackendProtocol { + static let redactionEventType = "m.room.redaction" + /// The core retries a failed send itself, within its own budget, so the SDK must not retry underneath it. + static let noRetry = RequestConfigOverride(retryLimit: 0, timeout: nil) + + let userID: String + let deviceID: String + + private let client: Client + private let logger: (any ElementCallLoggingProtocol)? + + init?(client: Client, logger: (any ElementCallLoggingProtocol)? = nil) { + guard let userID = try? client.userId(), let deviceID = try? client.deviceId() else { + logger?.log(.error, "no user or device ID, cannot serve a call") + return nil + } + self.client = client + self.userID = userID + self.deviceID = deviceID + self.logger = logger + } + + // MARK: - Sends + + func sendStickyEvent(roomID: String, eventType: String, contentJSON: String, duration: Duration) async throws(ElementCallMatrixBackendError) -> String { + try await send("sendStickyEvent(\(eventType))") { + try await room(roomID).sendStickyRaw(eventType: eventType, + content: contentJSON, + durationMs: UInt64(duration / .milliseconds(1)), + requestConfigOverride: Self.noRetry) + } + } + + /// The bindings have no delayed events (matrix-rust-sdk#6973), so this answers as a homeserver + /// without MSC4140: the core joins without a dead man's switch, never asks again this session, and + /// shortens the membership's lifetime instead. + func sendDelayedStateEvent(roomID: String, eventType: String, stateKey: String, contentJSON: String, delay: Duration) async throws(ElementCallMatrixBackendError) -> String { + throw Self.delayedEventsNotSupported + } + + func sendDelayedStickyEvent(roomID: String, eventType: String, contentJSON: String, stickyDuration: Duration, delay: Duration) async throws(ElementCallMatrixBackendError) -> String { + throw Self.delayedEventsNotSupported + } + + // Never called: no delayed event was ever scheduled. + func restartDelayedEvent(roomID: String, delayID: String) async throws(ElementCallMatrixBackendError) { + throw Self.delayedEventsNotSupported + } + + func cancelDelayedEvent(roomID: String, delayID: String) async throws(ElementCallMatrixBackendError) { + throw Self.delayedEventsNotSupported + } + + func sendStateEvent(roomID: String, eventType: String, stateKey: String, contentJSON: String) async throws(ElementCallMatrixBackendError) -> String { + try await send("sendStateEvent(\(eventType))") { + try await room(roomID).sendStateEventRaw(eventType: eventType, stateKey: stateKey, content: contentJSON, requestConfigOverride: Self.noRetry) + } + } + + func sendRoomEvent(roomID: String, eventType: String, contentJSON: String) async throws(ElementCallMatrixBackendError) -> String { + try await send("sendRoomEvent(\(eventType))") { + try await room(roomID).sendRaw(eventType: eventType, content: contentJSON, requestConfigOverride: Self.noRetry) + } + } + + func redactEvent(roomID: String, eventID: String, reason: String?) async throws(ElementCallMatrixBackendError) { + try await send("redactEvent") { + try await room(roomID).redact(eventId: eventID, reason: reason) + } + } + + /// Media keys never go out in the clear, and every undelivered recipient is reported: one reported + /// as delivered is never re-sent to, so a failure reported as a success leaves a member keyless. + func sendToDeviceMessage(eventType: String, contentJSON: String, to recipients: [ElementCallDevice]) async throws(ElementCallMatrixBackendError) -> [ElementCallDevice: String] { + try await send("sendToDeviceMessage(\(eventType) to \(recipients.map { "\($0.userID)/\($0.deviceID)" }))") { + let devices = Dictionary(grouping: recipients, by: \.userID).mapValues { $0.map(\.deviceID) } + let failures = try await client.sendEncryptedToDeviceMessage(eventType: eventType, recipients: devices, content: contentJSON).failures + if !failures.isEmpty { + logger?.log(.warning, "to-device \(eventType) not delivered to \(failures)") + } + return SDKMappings.undelivered(recipients, failures: failures) + } + } + + // MARK: - Reads + + /// Each subject on its own listener, so one that fails ends only itself. The room handle is held + /// by the listeners until the core cancels. + func subscribeToRoom(roomID: String, subjects: ElementCallRoomSubjects, sink: ElementCallRoomSink) throws(ElementCallMatrixBackendError) -> ElementCallBackendSubscription { + let room = try room(roomID) + logger?.log(.info, "subscribing \(roomID) to state \(subjects.stateEventTypes), timeline \(subjects.timelineEventTypes)") + + var handles = [TaskHandle]() + handles.append(room.subscribeToStickyEvents(listener: SDKStickyEventsListener(sink: sink))) + // The SDK answers at once from the store, an empty set included, which is the first delivery + // the core waits on. Only the state the sync asks for is stored, which is why the call keeps + // to the room-state format: `m.rtc.slot` is not in sliding sync's `required_state`, so the + // store reads every room as slotless. + for eventType in subjects.stateEventTypes { + handles.append(room.subscribeToStateEvents(eventType: stateEventTypeFromString(s: eventType), + listener: SDKStateEventsListener { events in + sink.deliverStateEvents(events.compactMap { SDKMappings.event($0, subscribedAs: eventType) }, ofType: eventType) + })) + } + for eventType in subjects.timelineEventTypes where eventType != Self.redactionEventType { + handles.append(room.subscribeToMessageLikeEvents(eventType: messageLikeEventTypeFromString(s: eventType), + listener: SDKMessageLikeEventsListener { event in + sink.deliverTimelineEvents([SDKMappings.event(event, subscribedAs: eventType)]) + })) + } + handles.append(room.subscribeToMessageLikeEvents(eventType: messageLikeEventTypeFromString(s: Self.redactionEventType), + listener: SDKMessageLikeEventsListener { event in + if let redacted = SDKMappings.redactedEventID(fromContent: event.contentJson) { + sink.deliverRedaction(ofEventID: redacted) + } + })) + + let roomInfo = SDKRoomInfoFeed(room: room, logger: logger) + let tasks = [Task { await roomInfo.deliverEncryption(into: sink) }, + Task { await roomInfo.deliverJoinedMembers(into: sink) }] + + let allHandles = handles + [roomInfo.handle] + return ElementCallBackendSubscription { + allHandles.forEach { $0.cancel() } + tasks.forEach { $0.cancel() } + } + } + + func subscribeToDeviceMessages(eventTypes: [String], sink: ElementCallToDeviceSink) throws(ElementCallMatrixBackendError) -> ElementCallBackendSubscription { + logger?.log(.info, "subscribing to to-device \(eventTypes)") + let handle = client.subscribeToCustomToDeviceMessages(eventTypes: eventTypes, listener: SDKToDeviceListener { message in + sink.deliver(SDKMappings.toDeviceMessage(message)) + }) + return ElementCallBackendSubscription { handle.cancel() } + } + + /// The SDK's relations come back as typed content, with neither raw JSON nor encryption info, so + /// a hand raised before we joined shows only once it changes. None rather than a failure, which + /// is how the core asks a backend that cannot serve them to say so. + func relations(roomID: String, eventID: String, relationshipType: String, eventType: String) async throws(ElementCallMatrixBackendError) -> [ElementCallMatrixEvent] { + [] + } + + func openIDToken() async throws(ElementCallMatrixBackendError) -> ElementCallOpenIDToken { + try await send("openIDToken") { + let token = try await client.requestOpenidToken() + return ElementCallOpenIDToken(accessToken: token.accessToken, + tokenType: token.tokenType, + matrixServerName: token.matrixServerName, + expiresIn: .seconds(token.expiresInSeconds)) + } + } + + /// The SDK falls back to the well-known when the homeserver lacks the MSC4143 endpoint; neither + /// answering is none. + func rtcTransportsJSON() async throws(ElementCallMatrixBackendError) -> String { + try await send("rtcTransportsJSON") { + try await SDKMappings.transportsJSON(client.discoverRtcTransports() ?? []) + } + } + + // MARK: - Private + + private static let delayedEventsNotSupported = ElementCallMatrixBackendError(errorCode: "M_UNRECOGNIZED", + reason: "Delayed events are not exposed by the SDK bindings") + + /// Taken per send rather than kept: a handle is cheap, and one held across calls outlives the + /// room if we leave it. + private func room(_ roomID: String) throws(ElementCallMatrixBackendError) -> Room { + guard let room = try? client.getRoom(roomId: roomID) else { + // Final, and no Matrix code says so: inventing one would be a lie about the homeserver. + throw ElementCallMatrixBackendError(isPermanent: true, reason: "Not a joined room: \(roomID)") + } + return room + } + + /// Logged on entry, and failing as the core reads failures: which refusals retire a feature for + /// the session is the core's decision, made from the error code and status, never ours. + private func send(_ description: String, _ body: () async throws -> T) async throws(ElementCallMatrixBackendError) -> T { + logger?.log(.info, "backend: \(description)") + do { + return try await body() + } catch { + logger?.log(.warning, "backend: \(description) failed: \(error)") + throw SDKMappings.backendError(error) + } + } +} diff --git a/ElementX/Sources/Services/NativeCall/Matrix/SDKRoomFeeds.swift b/ElementX/Sources/Services/NativeCall/Matrix/SDKRoomFeeds.swift new file mode 100644 index 000000000..a80388118 --- /dev/null +++ b/ElementX/Sources/Services/NativeCall/Matrix/SDKRoomFeeds.swift @@ -0,0 +1,157 @@ +// +// 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 +import Foundation +import MatrixRustSDK +import Synchronization + +// The SDK's listener protocols, each over a closure, so a subscription can say what it delivers where +// it subscribes. + +final nonisolated class SDKStateEventsListener: RoomStateEventsListener { + private let onUpdate: @Sendable ([RoomStateEvent]) -> Void + + init(onUpdate: @escaping @Sendable ([RoomStateEvent]) -> Void) { + self.onUpdate = onUpdate + } + + func onUpdate(events: [RoomStateEvent]) { + onUpdate(events) + } +} + +final nonisolated class SDKMessageLikeEventsListener: RoomMessageLikeEventsListener { + private let onEvent: @Sendable (RoomMessageLikeEvent) -> Void + + init(onEvent: @escaping @Sendable (RoomMessageLikeEvent) -> Void) { + self.onEvent = onEvent + } + + func onEvent(event: RoomMessageLikeEvent) { + onEvent(event) + } +} + +final nonisolated class SDKToDeviceListener: ToDeviceMessageListener { + private let onMessage: @Sendable (ToDeviceMessage) -> Void + + init(onMessage: @escaping @Sendable (ToDeviceMessage) -> Void) { + self.onMessage = onMessage + } + + func onMessage(message: ToDeviceMessage) { + onMessage(message) + } +} + +/// Folds the SDK's resets and changes into the whole set, which is what the core wants. The first +/// update is the current set, an empty one included. +final nonisolated class SDKStickyEventsListener: StickyEventsListener { + private let sink: ElementCallRoomSink + private let set = Mutex(SDKStickyEventSet()) + + init(sink: ElementCallRoomSink) { + self.sink = sink + } + + func onUpdate(update: StickyEventsUpdate) { + sink.deliverStickyEvents(set.withLock { $0.apply(update) }) + } +} + +/// The room's encryption and joined members, both read off the room info, which is what changes when +/// either does. One info subscription for the two, each subject following it in its own task. +final nonisolated class SDKRoomInfoFeed: Sendable { + let handle: TaskHandle + + private let room: Room + private let logger: (any ElementCallLoggingProtocol)? + private let encryptionUpdates: AsyncStream + private let memberUpdates: AsyncStream + + init(room: Room, logger: (any ElementCallLoggingProtocol)?) { + self.room = room + self.logger = logger + let (encryptionUpdates, encryption) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + let (memberUpdates, members) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + self.encryptionUpdates = encryptionUpdates + self.memberUpdates = memberUpdates + handle = room.subscribeToRoomInfoUpdates(listener: SDKRoomInfoListener { + encryption.yield() + members.yield() + }) + } + + /// Asked of the homeserver when the store does not know yet, and never answered with a guess: the + /// core treats cleartext membership as valid in an unencrypted room, so an unknown state delivers + /// nothing, which keeps the call from joining rather than letting it join an encrypted room + /// believing it is not. + func deliverEncryption(into sink: ElementCallRoomSink) async { + var lastDelivered: Bool? + func deliver(_ state: EncryptionState) { + guard let isEncrypted = SDKMappings.isEncrypted(state), isEncrypted != lastDelivered else { return } + lastDelivered = isEncrypted + sink.deliverEncryption(isEncrypted: isEncrypted) + } + + do { + try await deliver(room.latestEncryptionState()) + } catch { + logger?.log(.warning, "could not fetch the encryption state of \(room.id()): \(error)") + deliver(room.encryptionState()) + } + for await _ in encryptionUpdates { + deliver(room.encryptionState()) + } + } + + /// Re-read on every room info update rather than when the joined count moves: one person leaving + /// as another joins keeps the count while the membership differs, and the core would carry on + /// encrypting media for whoever left. + func deliverJoinedMembers(into sink: ElementCallRoomSink) async { + var lastDelivered: [String]? + func deliver() async { + guard let members = await joinedMembers(), SDKMappings.shouldDeliver(members, lastDelivered: lastDelivered) else { return } + lastDelivered = members + sink.deliverJoinedMembers(members) + } + + await deliver() + for await _ in memberUpdates { + await deliver() + } + } + + /// `members()` rather than `membersNoSync()`: it fetches from the homeserver the first time, which + /// a room we are joined to but have never opened needs, and reads the store after that. + private func joinedMembers() async -> [String]? { + do { + let iterator = try await room.members() + var joined = [String]() + while let chunk = iterator.nextChunk(chunkSize: 100) { + joined.append(contentsOf: chunk.filter { $0.membership == .join }.map(\.userId)) + } + return joined.sorted() + } catch { + logger?.log(.warning, "cannot load the members of \(room.id()): \(error)") + return nil + } + } +} + +private final nonisolated class SDKRoomInfoListener: RoomInfoListener { + private let onUpdate: @Sendable () -> Void + + init(onUpdate: @escaping @Sendable () -> Void) { + self.onUpdate = onUpdate + } + + func call(roomInfo: RoomInfo) { + onUpdate() + } +} diff --git a/ElementX/Sources/Services/NativeCall/NativeCallStack.swift b/ElementX/Sources/Services/NativeCall/NativeCallStack.swift index 3d92b86ad..ad10b87e1 100644 --- a/ElementX/Sources/Services/NativeCall/NativeCallStack.swift +++ b/ElementX/Sources/Services/NativeCall/NativeCallStack.swift @@ -18,9 +18,7 @@ import Foundation @MainActor final class NativeCallStack { /// The call itself, for the screen that is built from it. Everything else asks this type. - var controller: ElementCallController { - stack.controller - } + let controller: ElementCallController var actions: AnyPublisher { actionsSubject.eraseToAnyPublisher() @@ -29,24 +27,23 @@ final class NativeCallStack { /// Prefix for native call related logs nonisolated static let logPrefix = "[NativeCall]" - private let stack: ElementCallStack private let actionsSubject = PassthroughSubject() private var cancellables = Set() /// A call requested while another one was still running, started once that one has ended. private var pendingCallRequest: (roomProxy: JoinedRoomProxyProtocol, isVoiceCall: Bool)? - init(transport: any ElementCallMatrixTransportProtocol, + init(backend: any ElementCallMatrixBackendProtocol, system: any ElementCallSystemProvidingProtocol, options: ElementCallOptions, style: ElementCallStyle) { - stack = ElementCallStack(transport: transport, - system: system, - options: options, - style: style, - logger: Logger()) + controller = ElementCallController(backend: backend, + system: system, + options: options, + style: style, + logger: Logger()) - stack.controller.actions + controller.actions .receive(on: DispatchQueue.main) .sink { [weak self] action in self?.handle(action) @@ -135,8 +132,8 @@ final class NativeCallStack { } /// Sends the call package's log lines to `MXLog`, keeping the package's own file and line so - /// entries point at its source rather than at here. - private struct Logger: ElementCallLoggingProtocol { + /// entries point at its source rather than at here. Shared with the Matrix backend. + struct Logger: ElementCallLoggingProtocol { func log(_ record: ElementCallLogRecord) { let message = "\(NativeCallStack.logPrefix) \(record.message)" switch record.level { diff --git a/ElementX/Sources/Services/NativeCall/NativeCallStyle.swift b/ElementX/Sources/Services/NativeCall/NativeCallStyle.swift index 4cae514a0..9e24b4ce3 100644 --- a/ElementX/Sources/Services/NativeCall/NativeCallStyle.swift +++ b/ElementX/Sources/Services/NativeCall/NativeCallStyle.swift @@ -117,6 +117,11 @@ struct NativeCallIcons: ElementCallIconRenderingProtocol { case .userProfile: \.userProfileSolid case .overflow: \.overflowHorizontal case .collapse: \.collapse + case .info: \.infoSolid + case .chevronRight: \.chevronRight + case .error: \.errorSolid + case .spinner: \.spinner + case .keyOff: \.keyOffSolid } } diff --git a/UnitTests/Sources/ElementCallServiceTests.swift b/UnitTests/Sources/ElementCallServiceTests.swift index 89ccdc308..5279baac3 100644 --- a/UnitTests/Sources/ElementCallServiceTests.swift +++ b/UnitTests/Sources/ElementCallServiceTests.swift @@ -304,7 +304,7 @@ final class ElementCallServiceTests { /// service only keeps a weak reference, as the app owns the session. private func nativeUserSession() -> UserSessionMock { let clientProxy = ClientProxyMock(.init()) - clientProxy.makeNativeCallTransportReturnValue = ElementCallFakeTransport() + clientProxy.makeNativeCallBackendReturnValue = ElementCallFakeMatrixBackend() let session = UserSessionMock(.init(clientProxy: clientProxy)) nativeSession = session return session diff --git a/UnitTests/Sources/NativeCallStackTests.swift b/UnitTests/Sources/NativeCallStackTests.swift index 7d9824723..6e68dca11 100644 --- a/UnitTests/Sources/NativeCallStackTests.swift +++ b/UnitTests/Sources/NativeCallStackTests.swift @@ -17,7 +17,7 @@ final class NativeCallStackTests { private var cancellables = Set() init() { - stack = NativeCallStack(transport: ElementCallFakeTransport(), + stack = NativeCallStack(backend: ElementCallFakeMatrixBackend(), system: ElementCallFakeSystem(), options: ElementCallOptions(), style: .stock) @@ -46,7 +46,7 @@ final class NativeCallStackTests { stack.stop() - let joining = NativeCallStack(transport: ElementCallFakeTransport(), + let joining = NativeCallStack(backend: ElementCallFakeMatrixBackend(), system: ElementCallFakeSystem(), options: ElementCallOptions(), style: .stock) diff --git a/UnitTests/Sources/SDKMappingsTests.swift b/UnitTests/Sources/SDKMappingsTests.swift new file mode 100644 index 000000000..208f8e5f4 --- /dev/null +++ b/UnitTests/Sources/SDKMappingsTests.swift @@ -0,0 +1,231 @@ +// +// 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 +@testable import ElementX +import Foundation +import MatrixRustSDK +import Testing + +struct SDKMappingsTests { + // MARK: Events + + @Test + func stateIsReportedUnderTheSubscribedSpelling() throws { + let event = RoomStateEvent(eventType: stateEventTypeFromString(s: "org.matrix.msc3401.call.member"), + stateKey: "_@bob:example.org_DEV", + sender: "@bob:example.org", + contentJson: #"{"application":"m.call"}"#, + eventId: "$member", + timestamp: 1234) + + let mappedEvent = try #require(SDKMappings.event(event, subscribedAs: "m.call.member")) + + #expect(mappedEvent.eventType == "m.call.member") + #expect(mappedEvent.eventID == "$member") + #expect(mappedEvent.stateKey == "_@bob:example.org_DEV") + #expect(mappedEvent.originServerTimestamp == Date(timeIntervalSince1970: 1.234)) + #expect(mappedEvent.contentJSON == #"{"application":"m.call"}"#) + #expect(mappedEvent.encryption == .cleartext) + } + + @Test + func strippedStateIsDropped() { + let event = RoomStateEvent(eventType: stateEventTypeFromString(s: "m.call.member"), + stateKey: "", + sender: "@bob:example.org", + contentJson: "{}", + eventId: nil, + timestamp: nil) + + #expect(SDKMappings.event(event, subscribedAs: "m.call.member") == nil) + } + + @Test + func messageLikeEventsCarryTheirEncryption() { + let event = RoomMessageLikeEvent(eventType: messageLikeEventTypeFromString(s: "m.reaction"), + eventId: "$hand", + sender: "@bob:example.org", + timestamp: 99, + contentJson: "{}", + encryptionInfo: encryptionInfo(senderID: "@bob:example.org", shield: .none)) + + let mappedEvent = SDKMappings.event(event, subscribedAs: "m.reaction") + + #expect(mappedEvent.eventType == "m.reaction") + #expect(mappedEvent.stateKey == nil) + #expect(mappedEvent.encryption == .encrypted(senderDeviceID: "BOBDEVICE", isSenderConfirmed: true)) + } + + @Test + func redactsIsReadFromTheContent() { + #expect(SDKMappings.redactedEventID(fromContent: #"{"redacts":"$hand","reason":"lowered"}"#) == "$hand") + // Before room version 11 `redacts` sat beside the content, which the SDK does not hand over. + #expect(SDKMappings.redactedEventID(fromContent: #"{"reason":"lowered"}"#) == nil) + #expect(SDKMappings.redactedEventID(fromContent: "not json") == nil) + } + + // MARK: Trust + + @Test + func aSenderIsConfirmedUnlessItsShieldIsRed() { + #expect(SDKMappings.encryption(encryptionInfo(senderID: "@bob:example.org", shield: .none)) == .encrypted(senderDeviceID: "BOBDEVICE", isSenderConfirmed: true)) + #expect(SDKMappings.encryption(encryptionInfo(senderID: "@bob:example.org", shield: .grey(code: .authenticityNotGuaranteed))) == .encrypted(senderDeviceID: "BOBDEVICE", isSenderConfirmed: true)) + #expect(SDKMappings.encryption(encryptionInfo(senderID: "@bob:example.org", shield: .red(code: .unknownDevice))) == .encrypted(senderDeviceID: "BOBDEVICE", isSenderConfirmed: false)) + } + + @Test + func noEncryptionInfoIsCleartext() { + #expect(SDKMappings.encryption(nil) == .cleartext) + } + + @Test + func anUnknownEncryptionStateIsNeverAGuess() { + #expect(SDKMappings.isEncrypted(.encrypted) == true) + #expect(SDKMappings.isEncrypted(.notEncrypted) == false) + #expect(SDKMappings.isEncrypted(.unknown) == nil) + } + + // MARK: Members + + @Test + func membersAreComparedWholeAndNeverDeliveredEmpty() { + #expect(SDKMappings.shouldDeliver(["@a:x", "@b:x"], lastDelivered: nil)) + #expect(!SDKMappings.shouldDeliver(["@a:x", "@b:x"], lastDelivered: ["@a:x", "@b:x"])) + // One leaving as another joins keeps the count. + #expect(SDKMappings.shouldDeliver(["@a:x", "@c:x"], lastDelivered: ["@a:x", "@b:x"])) + #expect(!SDKMappings.shouldDeliver([], lastDelivered: nil)) + } + + // MARK: To-device + + @Test + func anEncryptedMessageComesFromItsAttestedSender() { + let message = ToDeviceMessage(eventType: "io.element.call.encryption_keys", + senderId: "@mallory:example.org", + content: "{}", + encryptionInfo: encryptionInfo(senderID: "@bob:example.org", shield: .none)) + + let mappedMessage = SDKMappings.toDeviceMessage(message) + + #expect(mappedMessage.sender == "@bob:example.org") + #expect(mappedMessage.encryption == .encrypted(senderDeviceID: "BOBDEVICE", isSenderConfirmed: true)) + } + + @Test + func aCleartextMessageKeepsItsClaimedSender() { + let message = ToDeviceMessage(eventType: "io.element.call.encryption_keys", senderId: "@bob:example.org", content: "{}", encryptionInfo: nil) + + let mappedMessage = SDKMappings.toDeviceMessage(message) + + #expect(mappedMessage.sender == "@bob:example.org") + #expect(mappedMessage.encryption == .cleartext) + } + + @Test + func onlyTheFailedRecipientsAreUndelivered() { + let recipients = [ElementCallDevice(userID: "@bob:x", deviceID: "B1"), + ElementCallDevice(userID: "@bob:x", deviceID: "B2"), + ElementCallDevice(userID: "@carol:x", deviceID: "C1")] + + let undelivered = SDKMappings.undelivered(recipients, failures: ["@bob:x": ["B2"]]) + + #expect(Set(undelivered.keys) == [ElementCallDevice(userID: "@bob:x", deviceID: "B2")]) + } + + // MARK: Transports and failures + + @Test + func transportsAreRebuiltAsTheMSC4143Array() throws { + let json = SDKMappings.transportsJSON([.liveKit(serviceUrl: "https://sfu.example.org"), + .custom(transportType: "other", data: #"{"url":"https://other.example.org"}"#)]) + + let array = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: String]]) + #expect(array == [["type": "livekit", "livekit_service_url": "https://sfu.example.org"], + ["type": "other", "url": "https://other.example.org"]]) + #expect(SDKMappings.transportsJSON([]) == "[]") + } + + @Test + func aHomeserverRefusalKeepsItsErrorCode() { + let error = SDKMappings.backendError(ClientError.MatrixApi(kind: .forbidden, code: "M_FORBIDDEN", msg: "no", details: nil)) + + #expect(error.errorCode == "M_FORBIDDEN") + #expect(error.statusCode == nil) + #expect(error.retryAfter == nil) + // The core classifies on the code; the mark is only for a final failure with none. + #expect(!error.isPermanent) + } + + @Test + func aRateLimitCarriesTheServersDelay() { + let error = SDKMappings.backendError(ClientError.MatrixApi(kind: .limitExceeded(retryAfterMs: 7000), code: "M_LIMIT_EXCEEDED", msg: "slow down", details: nil)) + + #expect(error.errorCode == "M_LIMIT_EXCEEDED") + #expect(error.retryAfter == .seconds(7)) + #expect(!error.isPermanent) + } + + @Test + func aFailureWithNoCodeIsLeftForTheCoreToRetry() { + struct Offline: Error { } + + let error = SDKMappings.backendError(Offline()) + + #expect(error.errorCode == nil) + #expect(error.retryAfter == nil) + #expect(!error.isPermanent) + } + + // MARK: Sticky events + + @Test + func stickyUpdatesFoldIntoTheWholeSet() { + var set = SDKStickyEventSet() + let alice = stickyEvent(sender: "@alice:x", id: "$a1") + let bob = stickyEvent(sender: "@bob:x", id: "$b1") + + #expect(set.apply(.reset(events: [])).isEmpty) + #expect(set.apply(.reset(events: [alice, bob])).map(\.eventID) == ["$a1", "$b1"]) + + let aliceAgain = stickyEvent(sender: "@alice:x", id: "$a2") + #expect(set.apply(.changes(added: [], updated: [aliceAgain], removed: [])).map(\.eventID) == ["$a2", "$b1"]) + + let removal = StickyEventRemoval(key: bob.key, reason: .expired) + #expect(set.apply(.changes(added: [], updated: [], removed: [removal])).map(\.eventID) == ["$a2"]) + } + + @Test + func aStickyEventIsReportedWithItsWireTypeAndContent() throws { + let mappedEvent = try #require(SDKMappings.event(stickyEvent(sender: "@alice:x", id: "$a1"))) + + #expect(mappedEvent.eventType == "org.matrix.msc4143.rtc.member") + #expect(mappedEvent.sender == "@alice:x") + #expect(mappedEvent.originServerTimestamp == Date(timeIntervalSince1970: 0.042)) + #expect(mappedEvent.contentJSON == #"{"slot_id":"m.call#ROOM"}"#) + } + + // MARK: - Fixtures + + private func encryptionInfo(senderID: String, shield: ShieldState) -> EventEncryptionInfo { + EventEncryptionInfo(senderId: senderID, + senderDeviceId: "BOBDEVICE", + senderCurve25519Key: nil, + sessionId: nil, + shieldState: shield, + shieldStateStrict: shield) + } + + private func stickyEvent(sender: String, id: String) -> StickyEvent { + let json = #"{"type":"org.matrix.msc4143.rtc.member","origin_server_ts":42,"content":{"slot_id":"m.call#ROOM"}}"# + return StickyEvent(key: StickyKey(sender: sender, eventType: "m.rtc.member", stickyKey: "\(sender)_DEV"), + eventId: id, + expiresAtMs: 0, + eventJson: json, + encryptionInfo: nil) + } +} diff --git a/project.yml b/project.yml index 019fdf0e5..22d54fcf3 100644 --- a/project.yml +++ b/project.yml @@ -90,7 +90,7 @@ packages: exactVersion: 0.28.1-rc.1 ElementCall: url: https://github.com/element-hq/element-call-ios # Native implementation - exactVersion: 0.1.0-rc.11 + exactVersion: 0.1.0-rc.13 # path: ../element-call-ios Emojibase: url: https://github.com/matrix-org/emojibase-bindings