@@ -95,13 +95,27 @@ public struct ChatRetentionPolicy {
9595 }
9696}
9797
98+ struct AdminRole : DittoDecodable {
99+ init ( value: [ String : Any ? ] ) {
100+ _id = value [ " _id " ] as? String
101+ email = value [ " email " ] as? String
102+ }
103+
104+ public var _id : String ?
105+ public var email : String ?
106+ }
107+
98108@MainActor
99109public class DittoChat : DittoSwiftChat , ObservableObject {
100110 @Published private( set) public var publicRoomsPublisher : AnyPublisher < [ Room ] , Never >
101111 public var retentionPolicy : ChatRetentionPolicy = . init( days: 30 )
102112 public var acceptLargeImages : Bool
103113 public var primaryColor : String ?
104- public var hasAdminPrivileges : Bool = false
114+ public var hasAdminPrivileges : Bool {
115+ return !roles. isEmpty
116+ }
117+ private var rolesCancellable : AnyCancellable ?
118+ private var roles : [ AdminRole ] = [ ]
105119
106120 private var localStore : LocalDataInterface
107121 internal var p2pStore : DittoDataInterface
@@ -118,14 +132,12 @@ public class DittoChat: DittoSwiftChat, ObservableObject {
118132 self . setCurrentUser ( withConfig: UserConfig ( id: userId) )
119133 }
120134 if let email = config. userEmail {
121- Task {
122- do {
123- self . hasAdminPrivileges = try await getAdminAccess (
124- email: email
125- )
126- } catch {
127- // TODO: Handle errors
128- }
135+ do {
136+ try setupRolesSubscription (
137+ email: email
138+ )
139+ } catch {
140+ // TODO: Handle errors
129141 }
130142 }
131143 }
@@ -144,11 +156,22 @@ public class DittoChat: DittoSwiftChat, ObservableObject {
144156 return room
145157 }
146158
147- func getAdminAccess ( email: String ) async throws -> Bool {
148- return try await p2pStore. ditto. store . execute (
159+ func setupRolesSubscription ( email: String ) throws {
160+ try p2pStore. ditto. sync . registerSubscription (
149161 query: " SELECT * FROM `roles` WHERE email = :email " ,
150162 arguments: [ " email " : email]
151- ) . items. count > 0
163+ )
164+
165+ rolesCancellable = p2pStore. ditto. store
166+ . observePublisher (
167+ query: " SELECT * FROM `roles` WHERE email = :email " ,
168+ mapTo: AdminRole . self
169+ )
170+ . catch { error in
171+ assertionFailure ( " ERROR with \( #function) " + error. localizedDescription)
172+ return Empty < [ AdminRole ] , Never > ( )
173+ }
174+ . assign ( to: \. roles, on: self )
152175 }
153176
154177 public func allUsersPublisher( ) -> AnyPublisher < [ ChatUser ] , Never > {
0 commit comments