-
Notifications
You must be signed in to change notification settings - Fork 0
/
WhiteBoardViewModel.swift
489 lines (402 loc) · 18.5 KB
/
WhiteBoardViewModel.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//
// WhiteBoardViewModel.swift
// APIExample_RTM2x
//
// Created by BBC on 2024/4/24.
//
import Foundation
import AgoraRtmKit
import SwiftUI
class WhiteBoardViewModel: NSObject, ObservableObject {
var agoraRtmKit: AgoraRtmClientKit? = nil
@AppStorage("userID") var userID: String = ""
@Published var token: String = ""
@Published var users: [AgoraRtmUserState] = []
@Published var isLoggedIn: Bool = false
@Published var connectionState: AgoraRtmClientConnectionState = .disconnected
@Published var mainChannel = "WhiteBoardRootChannel" // to publish and receive poll questions/answers
@Published var tokenRTC: String = ""
var agoraStreamChannel: AgoraRtmStreamChannel? = nil
// For Channel Channel, Key for new Drawing
let NewDrawingType = "newDrawing"
// For Stream Channel, Keys for update and deleting drawing
let UpdateDrawingTopic = "UpdateDrawing"
let DeleteDrawingTopic = "DeleteDrawing"
let DeleteAllDrawingTopic = "DeleteAllDrawing"
// For Storage, Keys for storing metadata
let StorageDrawingKey = "storageDrawingKey"
@Published var drawings: [Drawing] = [Drawing]()
// // MARK: TESTING
// @Published var fails: Int = 0
@MainActor
func loginRTM() async throws {
do {
if userID.isEmpty {
throw customError.emptyUIDLoginError
}
// Initialize RTM instance
if agoraRtmKit == nil {
let config = AgoraRtmClientConfig(appId: Configurations.agora_AppID , userId: userID)
agoraRtmKit = try AgoraRtmClientKit(config, delegate: self)
}
// Login to RTM server
// Use AppID to login if app certificate is NOT enabled for project
if let (response, error) = await agoraRtmKit?.login(token.isEmpty ? Configurations.agora_AppID : token) {
if error == nil{
isLoggedIn = true
}else{
print("Bac's code loginRTM login result = \(String(describing: response?.description)) | error \(String(describing: error))")
await agoraRtmKit?.logout()
throw error ?? customError.loginRTMError
}
} else {
// Handle any cases where login fails or error is present
print("Bac's code loginRTM login result = \(userID)")
}
}catch {
print("Bac's Some other error occurred: \(error.localizedDescription)")
throw error
}
}
// Logout RTM server
func logoutRTM(){
agoraRtmKit?.logout()
agoraRtmKit?.destroy()
isLoggedIn = false
}
// Join Stream Channel
func createAndJoinStreamChannel() async{
do {
agoraStreamChannel = try agoraRtmKit?.createStreamChannel(mainChannel)
let joinOption = AgoraRtmJoinChannelOption()
joinOption.features = [.presence]
joinOption.token = tokenRTC
if let (response, error) = await agoraStreamChannel?.join(joinOption) {
if error == nil {
// Join successful
print("Bac's createAndJoinStreamChannel success \(String(describing: response))")
}else {
// Join failed
print("Bac's createAndJoinStreamChannel failed \(String(describing: error)) \(error?.reason ?? "")")
}
}
} catch {
print("Bac's createAndJoinStreamChannel error \(error)")
}
}
// Subscribe to Message Channel to publish large data (> 1KB)
func subscribeChannel() async -> Bool {
let subOptions: AgoraRtmSubscribeOptions = AgoraRtmSubscribeOptions()
subOptions.features = [.message]
if let (_, error) = await agoraRtmKit?.subscribe(channelName: mainChannel, option: subOptions){
if error == nil {
return true
}
return false
}
return false
}
// Publish New Drawing with Channel Message (bc new Drawing can be larger than 1KB)
func publishNewDrawing(drawing: Drawing) async -> Bool{
let pubOptions = AgoraRtmPublishOptions()
pubOptions.customType = NewDrawingType
pubOptions.channelType = .message
if let newDrawingString = convertObjectToJsonString(object: drawing){
if let (_, error) = await agoraRtmKit?.publish(channelName: mainChannel, message: newDrawingString, option: pubOptions) {
if error == nil {
// Publish successful, save drawing to Agora Storage
return true
}else {
// fails += 1
return false
}
}
}
return false
}
// Publish new drawing points
func publishDrawingUpdate(newPoint: DrawingPoint) async -> Bool{
if let newDrawingPointString = convertObjectToJsonString(object: newPoint){
if let (_, error) = await agoraStreamChannel?.publishTopicMessage(topic: UpdateDrawingTopic, message: newDrawingPointString, option: nil) {
if error == nil {
// Publish successful
return true
}else {
// fails += 1
print("Bac's publishToTopic failed topic \(UpdateDrawingTopic) error \(String(describing: error))")
return false
}
}
return false
}
return false
}
// Publish delete single drawing
func publishDeleteDrawing(drawingID: UUID) async -> Bool {
if let (_, error) = await agoraStreamChannel?.publishTopicMessage(topic: DeleteDrawingTopic, message: drawingID.uuidString, option: nil) {
if error == nil {
// Publish successful
let _ = await saveDrawingsToStorage() // Resave current savings to cloud
return true
}else {
// Publish failed
// fails += 1
return false
}
}
return false
}
// Publish delete ALL drawings
@MainActor
func publishDeleteAllDrawing() async -> Bool {
if let (_, _) = await agoraStreamChannel?.publishTopicMessage(topic: DeleteAllDrawingTopic, message: "yes", option: nil) {
Task {
await MainActor.run {
drawings.removeAll()
}
let _ = await deleteAllDrawingsFromStorage() // Delete All drawings from storage
}
// if error == nil {
// print("Bac's publishDeleteDrawing Success")
// Task {
// await MainActor.run {
// drawings.removeAll()
// }
// let _ = await deleteAllDrawingsFromStorage() // Delete All drawings from storage
// }
// return true
// }else {
// print("Bac's publishDeleteDrawing failed topic \(DeleteDrawingTopic) error \(String(describing: error))")
//
// return false
// }
}
return false
}
// Pre-join some topics
func preJoinSubTopics() async {
for topic in [UpdateDrawingTopic, DeleteDrawingTopic, DeleteAllDrawingTopic] {
// Join as publisher first, if success then subscribe
let _ = await JoinAndSubTopic(topic: topic)
}
}
// Join a single topic as publisher
func joinOneTopic(topic: String) async -> Bool{
// Set publishing options
let publishTopicOptions = AgoraRtmJoinTopicOption()
publishTopicOptions.priority = .high
publishTopicOptions.qos = .ordered
if let (_, error) = await agoraStreamChannel?.joinTopic(topic, option: publishTopicOptions) {
if error == nil {
// Join success
print("Bac's joinOneTopics \(topic) success")
return true
}else {
// Join failed
print("Bac's joinOneTopics \(topic) failed \(error?.code ?? 0) \(error?.reason ?? "")")
return false
}
}
return false
}
// Subscribe to a single topic to receive topic messages
func subscribeOneTopic(topic: String) async -> Bool{
// Set subscribing options
let subscribeTopicOptions = AgoraRtmTopicOption()
subscribeTopicOptions.users = users.map(\.userId) // get the list of usersID
// Subscribe to topic
if let (response, error) = await agoraStreamChannel?.subscribeTopic(topic, option: subscribeTopicOptions) {
if error == nil {
// Subscribe success
print("Bac's subscribe \(topic) success")
print("Bac's subscribed Success users \(String(describing: response?.succeedUsers)) AND Failed \(String(describing: response?.failedUsers)) ")
return true
}else {
// Subscribe failed
print("Bac's subscribe failed \(error?.code ?? 0) \(error?.reason ?? "")")
return false
}
}
return false
}
// Join and subscribe a topic
func JoinAndSubTopic(topic: String) async -> Bool{
let resultA = await joinOneTopic(topic: topic)
let resultB = resultA ? await subscribeOneTopic(topic: topic) : false
return resultB // only return true if join and sub is successful
}
// Resubscribe when a new user joins
func reSubscribeNewUsers() async {
// Set subscribing options
let subscribeTopicOptions = AgoraRtmTopicOption()
subscribeTopicOptions.users = users.map(\.userId) // get the list of usersID
for topic in [UpdateDrawingTopic, DeleteDrawingTopic, DeleteAllDrawingTopic] {
if let (_, error) = await agoraStreamChannel?.subscribeTopic(topic, option: subscribeTopicOptions) {
if error == nil {
// Subscribe success
}else {
// Subscribe failed
print("Bac's subscribeTopics failed \(error?.code ?? 0) \(error?.reason ?? "")")
}
}
}
}
@MainActor
func publishToTopic(topic: String, message: String) async -> Bool {
if let (_, error) = await agoraStreamChannel?.publishTopicMessage(topic: topic, message: message, option: nil) {
if error == nil {
// Publish successful
}else {
print("Bac's publishToTopic failed topic \(topic) message \(message) error \(String(describing: error))")
return false
}
}
return false
}
// Storage Methods
func saveDrawingsToStorage() async -> Bool {
guard let metaData: AgoraRtmMetadata = agoraRtmKit?.getStorage()?.createMetadata() else { return false }
guard let drawingsString = convertObjectToJsonString(object: drawings) else {
print("Bac's saveDrawingsToStorage failed to convertObjectoString")
return false}
print("Bac's saveDrawingsToStorage success \(drawingsString)")
let metaDataItem: AgoraRtmMetadataItem = AgoraRtmMetadataItem()
metaDataItem.key = StorageDrawingKey
metaDataItem.value = drawingsString
metaData.setMetadataItem(metaDataItem)
if let (_, error) = await agoraRtmKit?.getStorage()?.setChannelMetadata(channelName: mainChannel, channelType: .message, data: metaData, options: AgoraRtmMetadataOptions(), lock: nil) {
if error == nil {
print("Bac's saveDrawingsToStorage saving success")
return true
}else {
// fails += 1
print("Bac's saveDrawingsToStorage saving failed")
return false
}
}
return false
}
func getDrawingsFromStorage() async -> Bool {
if let (response, error) = await agoraRtmKit?.getStorage()?.getChannelMetadata(channelName: mainChannel, channelType: .message) {
if error == nil {
// Get Successful, do here
print("Bac's getDrawingsFromStorage success error")
guard let drawingsString = response?.data?.getItems().first(where: {$0.key == StorageDrawingKey})?.value else {return false}
print("Bac's getDrawingsFromStorage drawingsString \(drawingsString)")
let newDrawings = convertJsonStringToObject(jsonString: drawingsString, objectType: [Drawing].self) ?? []
Task {
await MainActor.run {
drawings = newDrawings
}
}
return true
}else {
print("Bac's getDrawingsFromStorage failed error \(String(describing: error))")
return false
}
}
return false
}
func deleteAllDrawingsFromStorage() async -> Bool {
guard let metaData: AgoraRtmMetadata = agoraRtmKit?.getStorage()?.createMetadata() else { return false }
if let (_, error) = await agoraRtmKit?.getStorage()?.removeChannelMetadata(channelName: mainChannel, channelType: .message, data: metaData, options: nil, lock: nil) {
if error == nil {
// Delete Successful
return true
}else {
// Delete failed
return false
}
}
return false
}
}
extension WhiteBoardViewModel: AgoraRtmClientDelegate {
// Receive message event notifications in subscribed message channels and subscribed topics.
func rtmKit(_ rtmKit: AgoraRtmClientKit, didReceiveMessageEvent event: AgoraRtmMessageEvent) {
// print("Bac's didReceiveMessageEvent msg = \(event.message.stringData ?? "Empty") from \(event.publisher) Topic \(String(describing: event.channelTopic))")
switch event.channelType {
case .message:
print("Bac's didReceiveMessageEvent new drawing \(event.message.stringData ?? "Empty")")
if event.customType == NewDrawingType {
// Received new drawing,
if let jsonString = event.message.stringData, let newDrawing = convertJsonStringToObject(jsonString: jsonString, objectType: Drawing.self) {
print("Bac's didReceiveMessageEvent new drawing is \(jsonString)")
drawings.append(newDrawing)
}
}
break
case .stream:
switch event.channelTopic {
case UpdateDrawingTopic:
if let jsonString = event.message.stringData, let newDrawingPoint = convertJsonStringToObject(jsonString: jsonString, objectType: DrawingPoint.self) {
print("Bac's didReceiveMessageEvent new drawing point is \(jsonString)")
if let index = drawings.firstIndex(where: {$0.id == newDrawingPoint.id}) {
print("Bac's didReceiveMessageEvent UID FOUND")
drawings[index].points.append(newDrawingPoint.point)
}else {
print("Bac's didReceiveMessageEvent UID NOT FOUND")
}
}
break
case DeleteDrawingTopic:
print("Bac's code DeleteDrawingTopic \(event.message.stringData ?? "")")
if let convertedUUID = UUID(uuidString: event.message.stringData ?? "") {
if let index = drawings.firstIndex(where: {$0.id == convertedUUID}) {
print("Bac's code DeleteDrawingTopic reached inside")
drawings.remove(at: index)
}
}
break
case DeleteAllDrawingTopic:
Task {
await MainActor.run {
drawings.removeAll()
}
}
break;
default:
break
}
break
case .user:
break
case .none:
break
@unknown default:
print("Bac's didReceiveMessageEvent channelType is unknown")
}
}
// Receive presence event notifications in subscribed message channels and joined stream channels.
func rtmKit(_ rtmKit: AgoraRtmClientKit, didReceivePresenceEvent event: AgoraRtmPresenceEvent) {
print("Bac's didReceivePresenceEvent channelType \(event.channelType) publisher \(String(describing: event.publisher)) channel \(event.channelName) type \(event.type) ")
if event.type == .remoteLeaveChannel || event.type == .remoteConnectionTimeout {
// Remove user from list
if let userIndex = users.firstIndex(where: {$0.userId == event.publisher}) {
users.remove(at: userIndex)
}
}else if event.type == .remoteJoinChannel && event.publisher != nil {
// Add user to list if it doesn't exist
if !users.contains(where: {$0.userId == event.publisher}) && event.publisher != nil {
let userState = AgoraRtmUserState()
userState.userId = event.publisher!
userState.states = event.states
users.append(userState)
}
// StreamChannel - Resubscribe for new users
Task {
await reSubscribeNewUsers()
}
}else if event.type == .snapshot {
print("Bac's didReceivePresenceEvent snapshot")
users = event.snapshot
}else if event.type == .remoteStateChanged {
print("Bac's didReceivePresenceEvent remoteStateChanged")
}
}
// Triggers when connection changes
func rtmKit(_ kit: AgoraRtmClientKit, channel channelName: String, connectionChangedToState state: AgoraRtmClientConnectionState, reason: AgoraRtmClientConnectionChangeReason) {
print("Bac's connectionChangedToState \(state) reason \(reason.rawValue)")
connectionState = connectionState
}
}