// /* * 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 // 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 } } } } // A single admin can leave the room if he is the only member if !canLeave && self.isOnlyMember(room) { 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 = powerLevels?.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) } }