mirror of
https://github.com/Novaloop-AG/element-x-ios.git
synced 2026-10-31 16:24:11 +00:00
a520d94760
* Enable Swift 6.2 with default main actor isolation for the app target Turn on SWIFT_VERSION 6.2, SWIFT_APPROACHABLE_CONCURRENCY and SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor for the ElementX target, matching the NSE and Share Extension (which already use 6.2 without the main actor default). # Conflicts: # ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved * Update the code generation templates for Swift 6 Emit nonisolated/@unchecked Sendable mocks and nonisolated string enums, and mark async mock methods @concurrent so they keep suspending like the real implementations (otherwise intermediate states are unobservable in tests). Includes the regenerated mocks and strings. # Conflicts: # ElementX/Sources/Mocks/Generated/GeneratedMocks.swift * Make the data layer and services nonisolated and Sendable Annotate the value-type models, Rust SDK proxy wrappers, timeline item graph, settings, logging and NSE-shared types as nonisolated, and conform the service protocols to Sendable so their existentials can cross isolation boundaries. These types run off the main actor and no longer inherit the target's default main actor isolation. * Adopt the new isolation across call sites, mocks and signatures Update call sites, closure signatures and mock configuration helpers to match the nonisolated/Sendable data layer, including the main actor isolated mock inits and the @Sendable filter on recentlyVisitedRooms. ^ Conflicts: ^ ElementX/Sources/Services/SecureBackup/SecureBackupController.swift * Remove redundant @MainActor annotations With the app target defaulting to main actor isolation, the explicit @MainActor on view models, coordinators, views and their protocols is no longer required. * Fix concurrency hotspots surfaced by the migration Resolve the room summary main-thread deadlock by moving diff processing onto AsyncStreams, add the SDKListener.onMainActor FIFO bridge for SDK callbacks, hop KVO/timer/UIKit callbacks to the main actor via assumeIsolated, add isolated deinits, and apply the few justified nonisolated(unsafe) escapes for queue-confined Apple APIs. * Fix the unit tests for Swift 6 concurrency Hop the waitForConfirmation body onto the caller's actor (Swift Testing runs confirmation closures off-actor), and adjust the affected suites and async signatures. * offload diffs on concurrent threads instead of main actor * make room info protocols sendable * use a task group for fetching data so that everything runs concurrently in the TextRoomTimelineView when getting the preview. * use the generic onMainActor implementation, which already makes a stream and send the continuation on the main actor. * small pr comments issues being addressed * update enterprise * Update StaticCode to 1.1.0 and specify the required Swift isolation. * fix ElementCallServiceTests * update enterprise * re-generate mocks * update enterprise * enterprise new code conformed to swift 6 --------- Co-authored-by: Doug <douglase@element.io>
207 lines
8.3 KiB
Swift
207 lines
8.3 KiB
Swift
//
|
|
// Copyright 2025 Element Creations Ltd.
|
|
// Copyright 2022-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 Combine
|
|
import MatrixRustSDK
|
|
import SwiftUI
|
|
|
|
typealias UserProfileScreenViewModelType = StateStoreViewModelV2<UserProfileScreenViewState, UserProfileScreenViewAction>
|
|
|
|
class UserProfileScreenViewModel: UserProfileScreenViewModelType, UserProfileScreenViewModelProtocol {
|
|
private let userSession: UserSessionProtocol
|
|
private let userIndicatorController: UserIndicatorControllerProtocol
|
|
private let analytics: AnalyticsServiceProtocol
|
|
private let appSettings: AppSettings
|
|
|
|
private var actionsSubject: PassthroughSubject<UserProfileScreenViewModelAction, Never> = .init()
|
|
var actionsPublisher: AnyPublisher<UserProfileScreenViewModelAction, Never> {
|
|
actionsSubject.eraseToAnyPublisher()
|
|
}
|
|
|
|
init(userID: String,
|
|
isPresentedModally: Bool,
|
|
userSession: UserSessionProtocol,
|
|
userIndicatorController: UserIndicatorControllerProtocol,
|
|
analytics: AnalyticsServiceProtocol,
|
|
appSettings: AppSettings) {
|
|
self.userSession = userSession
|
|
self.userIndicatorController = userIndicatorController
|
|
self.analytics = analytics
|
|
self.appSettings = appSettings
|
|
|
|
let initialViewState = UserProfileScreenViewState(userID: userID,
|
|
isOwnUser: userID == userSession.clientProxy.userID,
|
|
isPresentedModally: isPresentedModally,
|
|
bindings: .init())
|
|
|
|
super.init(initialViewState: initialViewState, mediaProvider: userSession.mediaProvider)
|
|
|
|
showLoadingIndicator(allowsInteraction: true)
|
|
Task {
|
|
await loadProfile()
|
|
hideLoadingIndicator()
|
|
}
|
|
}
|
|
|
|
// MARK: - Public
|
|
|
|
func stop() {
|
|
// Work around QLPreviewController dismissal issues, see the InteractiveQuickLookModifier.
|
|
state.bindings.mediaPreviewItem = nil
|
|
|
|
hideLoadingIndicator()
|
|
}
|
|
|
|
override func process(viewAction: UserProfileScreenViewAction) {
|
|
switch viewAction {
|
|
case .displayAvatar(let url):
|
|
Task { await displayFullScreenAvatar(url) }
|
|
case .openDirectChat:
|
|
openDirectChat()
|
|
case .createDirectChat:
|
|
Task { await createDirectChat() }
|
|
case .startCall(let roomID, let isVoiceCall):
|
|
Task { await startCall(roomID: roomID, isVoiceCall: isVoiceCall) }
|
|
case .dismiss:
|
|
actionsSubject.send(.dismiss)
|
|
}
|
|
}
|
|
|
|
// MARK: - Private
|
|
|
|
// The proxies aren't Sendable, fetch through these helpers so that
|
|
// they never leave the main actor when running calls in parallel.
|
|
|
|
private func fetchProfile() async -> Result<UserProfileProxy, ClientProxyError> {
|
|
await userSession.clientProxy.profile(for: state.userID)
|
|
}
|
|
|
|
private func fetchUserIdentity() async -> Result<UserIdentityProxyProtocol?, ClientProxyError> {
|
|
await userSession.clientProxy.userIdentity(for: state.userID, fallBackToServer: true)
|
|
}
|
|
|
|
private func loadProfile() async {
|
|
async let profileResult = fetchProfile()
|
|
async let identityResult = fetchUserIdentity()
|
|
|
|
switch await profileResult {
|
|
case .success(let userProfile):
|
|
state.userProfile = userProfile
|
|
state.permalink = (try? matrixToUserPermalink(userId: state.userID)).flatMap(URL.init(string:))
|
|
|
|
switch userSession.clientProxy.directRoomForUserID(userProfile.userID) {
|
|
case .success(let roomID):
|
|
state.dmRoomID = roomID
|
|
case .failure:
|
|
break
|
|
}
|
|
case .failure(let error):
|
|
state.bindings.alertInfo = .init(id: .unknown)
|
|
MXLog.error("Failed to find user profile: \(error)")
|
|
}
|
|
|
|
if case let .success(.some(identity)) = await identityResult {
|
|
state.isIdentityKnown = true
|
|
state.isVerified = identity.verificationState == .verified
|
|
} else {
|
|
state.isIdentityKnown = false
|
|
MXLog.error("Failed to find the user's identity.")
|
|
}
|
|
}
|
|
|
|
private func displayFullScreenAvatar(_ url: URL) async {
|
|
guard let userProfile = state.userProfile else { fatalError() }
|
|
|
|
showLoadingIndicator(allowsInteraction: false)
|
|
defer { hideLoadingIndicator() }
|
|
|
|
// We don't actually know the mime type here, assume it's an image.
|
|
if let mediaSource = try? MediaSourceProxy(url: url, mimeType: "image/jpeg"),
|
|
case let .success(file) = await userSession.mediaProvider.loadFileFromSource(mediaSource) {
|
|
state.bindings.mediaPreviewItem = MediaPreviewItem(file: file, title: userProfile.displayName)
|
|
}
|
|
}
|
|
|
|
private func openDirectChat() {
|
|
guard let userProfile = state.userProfile else { fatalError() }
|
|
|
|
showLoadingIndicator(allowsInteraction: false)
|
|
defer { hideLoadingIndicator() }
|
|
|
|
switch userSession.clientProxy.directRoomForUserID(userProfile.userID) {
|
|
case .success(let roomID):
|
|
if let roomID {
|
|
actionsSubject.send(.openDirectChat(roomID: roomID))
|
|
} else {
|
|
Task {
|
|
let isUnknown = if case let .success(identity) = await userSession.clientProxy.userIdentity(for: userProfile.userID, fallBackToServer: false) {
|
|
identity == nil
|
|
} else {
|
|
true
|
|
}
|
|
state.bindings.inviteConfirmationUser = .init(user: userProfile, isUnknown: isUnknown)
|
|
}
|
|
}
|
|
case .failure:
|
|
state.bindings.alertInfo = .init(id: .failedOpeningDirectChat)
|
|
}
|
|
}
|
|
|
|
private func createDirectChat() async {
|
|
guard let userProfile = state.userProfile else { fatalError() }
|
|
|
|
showLoadingIndicator(allowsInteraction: false)
|
|
defer { hideLoadingIndicator() }
|
|
|
|
switch await userSession.clientProxy.createDirectRoom(with: userProfile.userID, expectedRoomName: userProfile.displayName) {
|
|
case .success(let roomID):
|
|
analytics.trackCreatedRoom(isDM: true)
|
|
actionsSubject.send(.openDirectChat(roomID: roomID))
|
|
case .failure:
|
|
state.bindings.alertInfo = .init(id: .failedOpeningDirectChat)
|
|
}
|
|
}
|
|
|
|
private func startCall(roomID: String, isVoiceCall: Bool) async {
|
|
guard case let .joined(roomProxy) = await userSession.clientProxy.roomForIdentifier(roomID) else {
|
|
showErrorIndicator()
|
|
return
|
|
}
|
|
actionsSubject.send(.startCall(roomProxy: roomProxy, isVoiceCall: isVoiceCall))
|
|
}
|
|
|
|
// MARK: User Indicators
|
|
|
|
private var loadingIndicatorIdentifier: String {
|
|
"\(Self.self)-Loading"
|
|
}
|
|
|
|
private var statusIndicatorIdentifier: String {
|
|
"\(Self.self)-Status"
|
|
}
|
|
|
|
private func showLoadingIndicator(allowsInteraction: Bool) {
|
|
userIndicatorController.submitIndicator(UserIndicator(id: loadingIndicatorIdentifier,
|
|
type: .modal(progress: .indeterminate, interactiveDismissDisabled: false, allowsInteraction: allowsInteraction),
|
|
title: L10n.commonLoading,
|
|
persistent: true),
|
|
delay: .milliseconds(100))
|
|
}
|
|
|
|
private func hideLoadingIndicator() {
|
|
userIndicatorController.retractIndicatorWithId(loadingIndicatorIdentifier)
|
|
}
|
|
|
|
private func showErrorIndicator() {
|
|
userIndicatorController.submitIndicator(UserIndicator(id: statusIndicatorIdentifier,
|
|
type: .toast,
|
|
title: L10n.errorUnknown,
|
|
icon: \.close))
|
|
}
|
|
}
|