Files
bundesmessenger-ios/bwi/LeaveRoom/LeaveRoomHelper.swift
2025-08-27 12:15:03 +02:00

82 lines
2.6 KiB
Swift

//
/*
* Copyright (c) 2023 BWI GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
final class LeaveRoomHelper {
static func canLeaveRoom(_ session: MXSession, _ room: MXRoom) -> Bool {
let myUserId = session.myUserId
// None Admins can always leave the room
if !self.isAdmin(session.myUserId, room) {
return true
}
var canLeave = false
var hasInvites = false
// admins can only leave if there is at least one other admin
room.state { (state) in
if let members = state?.members.joinedMembers {
for user in members where user.userId != myUserId {
if self.isAdmin(user.userId, room) {
canLeave = true
break
}
}
}
if state?.membersCount.invited ?? 0 > 0 {
hasInvites = true
}
}
// A single admin can leave the room if he is the only member and there are no pending invites. User can leave DMs without a rule.
if !canLeave && self.isOnlyMember(room) && !hasInvites || room.isDirect {
canLeave = true
}
return canLeave
}
static private func isAdmin(_ userId: String, _ room: MXRoom) -> Bool {
var admin = false
room.state { (state) in
let powerLevels = state?.powerLevels
let userPowerLevel = state?.powerLevelOfUser(withUserID: userId)
let roomPowerLevel = RoomPowerLevelHelper.roomPowerLevel(from: userPowerLevel ?? RoomPowerLevel.user.rawValue)
if roomPowerLevel == RoomPowerLevel.admin {
admin = true
}
}
return admin
}
static func isOnlyMember(_ room: MXRoom) -> Bool {
var memberCount = 0
room.state { (state) in
if let members = state?.members.joinedMembers {
memberCount = members.count
}
}
return (memberCount == 1)
}
}