-
Notifications
You must be signed in to change notification settings - Fork 1
/
StorageView.swift
313 lines (269 loc) · 10.4 KB
/
StorageView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
//
// GettingStartedView.swift
// Example-App
//
// Created by Max Cobb on 01/08/2023.
//
import SwiftUI
import AgoraRtm
public class StorageSignalingManager: SignalingManager, RtmClientDelegate {
/// Log into Signaling with a token, and subscribe to a message channel.
/// - Parameters:
/// - channel: Channel name to subscribe to.
/// - token: token to be used for login authentication.
override func subscribe(to channel: String) async throws -> RtmCommonResponse {
try await self.signalingEngine.subscribe(
toChannel: channel, features: .metadata
)
}
@Published public var selectedUser: RtmMetadata?
@Published var localMetadata: RtmMetadata?
@Published var remoteUsers: [String: [String: String]] = [:]
public func setUserMetadata(to localData: [String: String]) async throws {
guard let storage = signalingEngine.storage,
let userMetadata = signalingEngine.storage?.createMetadata()
else { return }
self.localMetadata = userMetadata
localData.forEach { item in
userMetadata.setMetadataItem(
RtmMetadataItem(key: item.key, value: item.value, revision: -1)
)
}
_ = try await storage.setMetadata(
forUser: self.userId, data: userMetadata,
options: RtmMetadataOptions(recordTs: true, recordUserId: true)
)
}
public func updateUserInfo(with updates: [String: String]) async throws {
guard let localMetadata else { return }
for metadataItem in localMetadata.metadataItems
where updates.keys.contains(metadataItem.key) {
metadataItem.value = updates[metadataItem.key]!
}
_ = try await signalingEngine.storage?.setMetadata(
forUser: self.userId, data: localMetadata,
options: RtmMetadataOptions(recordTs: true, recordUserId: true)
)
}
func getMetadata(for user: String) async throws -> RtmGetMetadataResponse {
try await signalingEngine.storage!.getMetadata(forUser: user)
}
func subscribeToMetadata(for user: String) async {
do {
try await signalingEngine.storage?.subscribeToMetadata(forUser: user)
} catch {
// could not subscribe to metadata
}
}
func updateMetadata(for user: String, data: [String: String]) async {
guard let storage = signalingEngine.storage,
let metadata = storage.createMetadata()
else { return }
for item in data {
metadata.setMetadataItem(
RtmMetadataItem(key: item.key, value: item.value)
)
}
do {
try await signalingEngine.storage?.updateMetadata(forUser: user, data: metadata)
} catch {
// could not update metadata
}
}
func setMetadata(
forChannel channel: String,
metaItem: (key: String, value: String), revision: Int64 = -1,
lock: String? = nil
) async throws {
// If we have a lock string, try to acquire it
if let lock {
try await signalingEngine.lock?.acquireLock(
named: lock, fromChannel: .messageChannel(channel)
)
}
// Ensure we can create metadata
guard let metadata = signalingEngine.storage?.createMetadata() else { return }
// Set the metadata item
metadata.setMetadataItem(RtmMetadataItem(
key: metaItem.key, value: metaItem.value, revision: revision
))
try await signalingEngine.storage?.setMetadata(
forChannel: .messageChannel(channel),
data: metadata, lock: lock
)
// If we have a lock string, release it.
if let lock {
try await signalingEngine.lock?.releaseLock(
named: lock, fromChannel: .messageChannel(channel)
)
}
await self.updateLabel(to: "success")
}
func setMetadata(forUser user: String, items: [String: String]) {
guard let storage = signalingEngine.storage,
let metadata = storage.createMetadata()
else { return }
for item in items {
metadata.setMetadataItem(
RtmMetadataItem(key: item.key, value: item.value)
)
}
storage.setMetadata(forUser: user, data: metadata)
}
func getMetadata(forChannel channel: String) async throws -> RtmGetMetadataResponse {
try await signalingEngine.storage!.getMetadata(
forChannel: .messageChannel(channel)
)
}
public func removeUserInfo(for keys: [String]) async throws {
guard let removeMetadata = signalingEngine.storage?
.createMetadata() else { return }
keys.forEach { key in
removeMetadata.setMetadataItem(.init(key: key, value: ""))
}
_ = try await signalingEngine.storage?.removeMetadata(
forUser: self.userId, data: removeMetadata
)
}
public func rtmKit(_ rtmClient: RtmClientKit, didReceiveStorageEvent event: RtmStorageEvent) {
switch (event.eventType, event.storageType) {
case (.set, .user), (.update, .user), (.snapshot, .user):
// user metadata set, updated, or a snapshot has been given
print("user update")
case (.set, .channel), (.update, .channel), (.snapshot, .channel):
// channel metadata set, updated, or a snapshot has been given
print("channel update")
default: break
}
}
}
extension StorageSignalingManager {
func setLock(lockName: String, channel: String, ttl: Int32) async throws {
try await signalingEngine.lock?.setLock(
named: lockName,
forChannel: .messageChannel(channel),
ttl: ttl
)
}
func acquireLock(lockName: String, channel: String, retry: Bool) async -> RtmCommonResponse? {
try? await signalingEngine.lock?.acquireLock(
named: lockName,
fromChannel: .messageChannel(channel),
retry: retry
)
}
func releaseLock(lockName: String, channel: String, retry: Bool) {
signalingEngine.lock?.releaseLock(
named: lockName, fromChannel: .messageChannel(channel)
)
}
func removeLock(lockName: String, channel: String) {
signalingEngine.lock?.removeLock(
named: lockName, fromChannel: .messageChannel(channel)
)
}
func getLocks(inChannel channel: String) async throws -> RtmGetLocksResponse? {
try await signalingEngine.lock?.getLocks(forChannel: .messageChannel(channel))
}
}
extension StorageSignalingManager {
// MARK: Handle Errors
/// Handle different error cases, and fetch a new token if appropriate.
/// - Parameters:
/// - error: Error thrown by logging in or subscribing to a channel.
/// - channel: Channel to which a subscription was attempted.
func handleLoginSubError(error: RtmErrorInfo, channel: String) async {
switch error.errorCode {
case .loginNoServerResources, .loginTimeout, .loginRejected, .loginAborted:
await self.updateLabel(to: "could not log in, check your app ID and token")
case .channelSubscribeFailed, .channelSubscribeTimeout, .channelNotSubscribed:
await self.updateLabel(to: "could not subscribe to channel")
case .invalidToken:
if label == nil, let token = try? await self.fetchToken(
from: DocsAppConfig.shared.tokenUrl,
username: DocsAppConfig.shared.uid
) {
await self.updateLabel(to: "fetching token")
await self.loginAndSub(to: channel, with: token)
}
default:
await self.updateLabel(to: """
failed: \(error.operation)
reason: \(error.reason)
""")
}
}
}
// MARK: - UI
struct StorageView: View {
@ObservedObject var signalingManager: StorageSignalingManager
let channelId: String
@State private var isSheetPresented: Bool = false
var body: some View {
ZStack {
if self.signalingManager.remoteUsers.isEmpty {
Text("None").padding()
} else {
List(signalingManager.remoteUsers.keys.sorted(), id: \.self) { key in
Button(action: {
Task {try await self.didSelectUser(key)}
}, label: {
Text(key)
})
}.sheet(isPresented: $isSheetPresented) {
if let selectedUser = signalingManager.selectedUser {
DictionaryView(data: selectedUser)
}
}
}
}.onAppear {
await signalingManager.loginAndSub(to: self.channelId, with: DocsAppConfig.shared.token)
try? await signalingManager.setUserMetadata(to: ["joinedAt": Date.now.description])
}.onDisappear {
try? await signalingManager.destroy()
}
}
// MARK: - Helpers and Setup
func didSelectUser(_ user: String) async throws {
guard let storage = self.signalingManager.signalingEngine.storage,
let data = try await storage.getMetadata(forUser: user).data
else { return }
DispatchQueue.main.async {
self.signalingManager.selectedUser = data
self.isSheetPresented = true
}
}
init(channelId: String, userId: String) {
DocsAppConfig.shared.channel = channelId
DocsAppConfig.shared.uid = userId
self.channelId = channelId
self.signalingManager = StorageSignalingManager(
appId: DocsAppConfig.shared.appId, userId: userId
)
}
static var docPath: String = "storage"
static var docTitle: String = "Store channel and user data"
}
private struct DictionaryView: View {
@State var data: RtmMetadata
var body: some View {
Group {
if data.metadataItems.isEmpty {
Text("No data")
} else {
List(data.metadataItems, id: \.key) { item in
Text("\(item.key): \(item.value)")
}
}
}.navigationTitle("User Details")
}
}
// MARK: - Previews
struct StorageView_Previews: PreviewProvider {
static var previews: some View {
GettingStartedView(
channelId: DocsAppConfig.shared.channel,
userId: DocsAppConfig.shared.uid
)
}
}