Files
element-x-ios/ElementX/Sources/Screens/RoomMemberListScreen/RoomMembersListScreenViewModel.swift
T
Mauro a520d94760 Swift 6 Migration (#5733)
* 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>
2026-06-18 17:55:31 +02:00

244 lines
11 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 SwiftUI
typealias RoomMembersListScreenViewModelType = StateStoreViewModel<RoomMembersListScreenViewState, RoomMembersListScreenViewAction>
class RoomMembersListScreenViewModel: RoomMembersListScreenViewModelType, RoomMembersListScreenViewModelProtocol {
private let userSession: UserSessionProtocol
private let roomProxy: JoinedRoomProxyProtocol
private let userIndicatorController: UserIndicatorControllerProtocol
private let analytics: AnalyticsServiceProtocol
private var members: [RoomMemberProxyProtocol] = []
private var currentUserProxy: RoomMemberProxyProtocol?
private var actionsSubject: PassthroughSubject<RoomMembersListScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<RoomMembersListScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(initialMode: RoomMembersListScreenMode = .members,
userSession: UserSessionProtocol,
roomProxy: JoinedRoomProxyProtocol,
userIndicatorController: UserIndicatorControllerProtocol,
analytics: AnalyticsServiceProtocol) {
self.userSession = userSession
self.roomProxy = roomProxy
self.userIndicatorController = userIndicatorController
self.analytics = analytics
super.init(initialViewState: .init(joinedMembersCount: roomProxy.infoPublisher.value.joinedMembersCount,
bindings: .init(mode: initialMode)),
mediaProvider: userSession.mediaProvider)
setupMembers()
}
// MARK: - Public
override func process(viewAction: RoomMembersListScreenViewAction) {
switch viewAction {
case .selectMember(let member):
selectMember(member)
case .invite:
actionsSubject.send(.invite)
}
}
func stop() {
hideLoadingIndicator(Self.setupMembersLoadingIndicatorIdentifier)
hideLoadingIndicator(Self.updateStateLoadingIndicatorIdentifier)
}
// MARK: - Members
private func setupMembers() {
Task {
showLoadingIndicator(Self.setupMembersLoadingIndicatorIdentifier)
await roomProxy.updateMembers()
hideLoadingIndicator(Self.setupMembersLoadingIndicatorIdentifier)
}
roomProxy.membersPublisher
.combineLatest(roomProxy.identityStatusChangesPublisher)
.filter { !$0.0.isEmpty }
.receive(on: DispatchQueue.main)
.sink { [weak self] members, _ in
self?.updateState(members: members)
}
.store(in: &cancellables)
roomProxy.timeline.timelineItemProvider.membershipChangePublisher.sink { [roomProxy] _ in
Task { await roomProxy.updateMembers() }
}
.store(in: &cancellables)
roomProxy.infoPublisher
.map(\.powerLevels)
.removeDuplicates { $0?.userPowerLevels == $1?.userPowerLevels }
.sink { [weak self] _ in
Task { await self?.roomProxy.updateMembers() }
}
.store(in: &cancellables)
}
private func updateState(members: [RoomMemberProxyProtocol]) {
Task {
showLoadingIndicator(Self.updateStateLoadingIndicatorIdentifier)
defer {
hideLoadingIndicator(Self.updateStateLoadingIndicatorIdentifier)
}
let members = members.sorted()
let roomMembersDetails = await buildMembersDetails(members: members)
self.members = members
self.currentUserProxy = members.first { $0.userID == roomProxy.ownUserID }
var newBindings = state.bindings
if roomMembersDetails.bannedMembers.count == 0 {
newBindings.mode = .members
}
self.state = .init(joinedMembersCount: roomProxy.infoPublisher.value.joinedMembersCount,
joinedMembers: roomMembersDetails.joinedMembers,
invitedMembers: roomMembersDetails.invitedMembers,
bannedMembers: roomMembersDetails.bannedMembers,
bindings: newBindings)
if let powerLevels = roomProxy.infoPublisher.value.powerLevels {
self.state.canInviteUsers = powerLevels.canOwnUserInvite()
self.state.canKickUsers = powerLevels.canOwnUserKick()
self.state.canBanUsers = powerLevels.canOwnUserBan()
}
}
}
private func buildMembersDetails(members: [RoomMemberProxyProtocol]) async -> RoomMembersDetails {
// We don't care about identity statuses on non-encrypted rooms
let isEncrypted = roomProxy.infoPublisher.value.isEncrypted
return await Task.detached { [weak self] in
// accessing RoomMember's properties is very slow. We need to do it in a background thread.
var invitedMembers: [RoomMemberListScreenEntry] = .init()
var joinedMembers: [RoomMemberListScreenEntry] = .init()
var bannedMembers: [RoomMemberListScreenEntry] = .init()
for member in members {
var verificationState: UserIdentityVerificationState = .notVerified
if isEncrypted, let fetchedState = await self?.userIdentityVerificationState(for: member.userID) {
verificationState = fetchedState
}
switch member.membership {
case .invite:
invitedMembers.append(.init(member: .init(withProxy: member), verificationState: verificationState))
case .join:
joinedMembers.append(.init(member: .init(withProxy: member), verificationState: verificationState))
case .ban:
bannedMembers.append(.init(member: .init(withProxy: member), verificationState: verificationState))
default:
continue
}
}
return .init(invitedMembers: invitedMembers,
joinedMembers: joinedMembers,
bannedMembers: bannedMembers.sorted { $0.member.id.localizedStandardCompare($1.member.id) == .orderedAscending }) // Re-sort ignoring display name.
}
.value
}
/// The client proxy isn't Sendable, fetch identities through this helper so
/// that it never leaves the main actor.
private func userIdentityVerificationState(for userID: String) async -> UserIdentityVerificationState? {
guard case let .success(userIdentity) = await userSession.clientProxy.userIdentity(for: userID, fallBackToServer: false) else {
return nil
}
return userIdentity?.verificationState
}
private func selectMember(_ member: RoomMemberDetails) {
guard currentUserProxy?.userID != member.id else {
showMemberDetails(member)
return
}
let manageMemberViewModel = ManageRoomMemberSheetViewModel(memberDetails: .memberDetails(roomMember: member),
permissions: .init(canKick: state.canKickUsers,
canBan: state.canBanUsers,
ownPowerLevel: currentUserProxy?.powerLevel ?? .init(value: 0)),
roomProxy: roomProxy,
userIndicatorController: userIndicatorController,
analyticsService: analytics,
mediaProvider: userSession.mediaProvider)
manageMemberViewModel.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .dismiss(let shouldShowDetails):
state.bindings.manageMemeberViewModel = nil
if shouldShowDetails {
showMemberDetails(member)
}
}
}
.store(in: &cancellables)
state.bindings.manageMemeberViewModel = manageMemberViewModel
}
private func showMemberDetails(_ member: RoomMemberDetails) {
guard let member = members.first(where: { $0.userID == member.id }) else {
MXLog.error("Selected member \(member.id) not found")
return
}
actionsSubject.send(.selectMember(member))
}
// MARK: - Indicators
private static let setupMembersLoadingIndicatorIdentifier = "\(RoomMembersListScreenViewModel.self)-SetupMembers"
private static let updateStateLoadingIndicatorIdentifier = "\(RoomMembersListScreenViewModel.self)-UpdateState"
private func showLoadingIndicator(_ identifier: String) {
userIndicatorController.submitIndicator(UserIndicator(id: identifier,
type: .modal(progress: .indeterminate, interactiveDismissDisabled: false, allowsInteraction: true),
title: L10n.commonLoading,
persistent: true),
delay: .milliseconds(200))
}
private func hideLoadingIndicator(_ identifier: String) {
userIndicatorController.retractIndicatorWithId(identifier)
}
private func showManageMemberIndicator(title: String) {
userIndicatorController.submitIndicator(UserIndicator(id: title,
type: .toast(progress: .indeterminate),
title: title,
persistent: true))
}
private func hideManageMemberIndicator(title: String) {
userIndicatorController.retractIndicatorWithId(title)
}
private func showManageMemberFailure(title: String) {
userIndicatorController.retractIndicatorWithId(title)
userIndicatorController.submitIndicator(UserIndicator(title: L10n.commonFailed, icon: \.close))
}
}
private nonisolated struct RoomMembersDetails {
var invitedMembers: [RoomMemberListScreenEntry]
var joinedMembers: [RoomMemberListScreenEntry]
var bannedMembers: [RoomMemberListScreenEntry]
}