-
Notifications
You must be signed in to change notification settings - Fork 13
/
RNAzureCommunicationUICalling.swift
363 lines (319 loc) · 17.2 KB
/
RNAzureCommunicationUICalling.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
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import AzureCommunicationUICalling
import AzureCommunicationCalling
import AzureCommunicationCommon
import UIKit
import SwiftUI
@objc(RNAzureCommunicationUICalling)
class RNAzureCommunicationUICalling: RCTEventEmitter {
enum RNEvents: String, CaseIterable {
case getToken
}
private var tokenRefresherHandler: TokenRefreshHandler?
private var callComposite: CallComposite?
private var headerViewData: CallScreenHeaderViewData?
override static func requiresMainQueueSetup() -> Bool {
return false
}
override func supportedEvents() -> [String]! {
return RNEvents.allCases.map({ $0.rawValue })
}
@objc func tokenRefresher(_ token: String) {
self.tokenRefresherHandler?(token, nil)
}
@objc func getSupportedLocales(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
let localeStrings = SupportedLocale.values.map { $0.identifier }
resolve(localeStrings)
}
@objc func getDebugInfo(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
let callHistoryRecords = NSMutableArray()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if callComposite == nil {
callComposite = CallComposite()
}
callComposite?.debugInfo.callHistoryRecords.forEach {
let callIDs = NSMutableArray()
$0.callIds.forEach { callIDs.add($0) }
let record = NSMutableDictionary()
record.setValue(dateFormatter.string(from: $0.callStartedOn), forKey: "callStartedOn")
record.setValue(callIDs, forKey: "callIds")
callHistoryRecords.add(record)
}
let result: NSDictionary = NSMutableDictionary()
result.setValue(callHistoryRecords, forKey: "callHistoryRecords")
resolve(result)
}
@objc func dismiss() {
guard let callComposite = callComposite else {
return
}
callComposite.dismiss()
}
@objc func startCallComposite(_ localOptions: NSDictionary,
localAvatar: AnyObject?,
remoteOptions: NSDictionary,
remoteAvatar: AnyObject?,
localizationOptions: NSDictionary,
orientationOptions: NSDictionary?,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let localOptionsDict = localOptions as? [String: Any],
let remoteOptionsDict = remoteOptions as? [String: Any],
let localizationOptionsDict = localizationOptions as? [String: Any],
let orientationOptionDict = orientationOptions as? [String: Any] else {
return
}
// required options
guard let tokenInput = remoteOptionsDict["token"] as? String,
let meetingInput = remoteOptionsDict["meeting"] as? String else {
reject(RNCallCompositeConnectionError.invalidInput.getErrorCode(),
"Token and Meeting info cannot be empty",
RNCallCompositeConnectionError.invalidInput)
return
}
DispatchQueue.main.async {
self._startCallComposite(displayName: localOptionsDict["displayName"] as? String,
tokenInput: tokenInput,
meetingInput: meetingInput,
localAvatar: localAvatar,
title: localOptionsDict["title"] as? String,
subtitle: localOptionsDict["subtitle"] as? String,
languageCode: localizationOptionsDict["locale"] as? String ?? "en",
isRightToLeft: localizationOptionsDict["locale"] as? Bool ?? false,
disableLeaveCallConfirmation: localOptionsDict["disableLeaveCallConfirmation"] as? Bool ?? false,
remoteAvatar: remoteAvatar,
setupOrientation: orientationOptionDict["setupOrientation"] as? String,
callOrientation: orientationOptionDict["callOrientation"] as? String,
resolver: resolve,
rejecter: reject)
}
}
private func _startCallComposite(displayName: String?,
tokenInput: String,
meetingInput: String,
localAvatar: AnyObject?,
title: String?,
subtitle: String?,
languageCode: String,
isRightToLeft: Bool,
disableLeaveCallConfirmation: Bool,
remoteAvatar: AnyObject?,
setupOrientation: String?,
callOrientation: String?,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
var localizationConfig: LocalizationOptions?
let layoutDirection: LayoutDirection = isRightToLeft ? .rightToLeft : .leftToRight
let locale = Locale(identifier: languageCode.isEmpty ? "en" : languageCode)
localizationConfig = LocalizationOptions(locale: locale,
layoutDirection: layoutDirection)
var callScreenControlBarOptions: CallScreenControlBarOptions?
var callScreenOptions: CallScreenOptions?
var mode: LeaveCallConfirmationMode = disableLeaveCallConfirmation ? LeaveCallConfirmationMode.alwaysDisabled : LeaveCallConfirmationMode.alwaysEnabled
callScreenControlBarOptions = CallScreenControlBarOptions(leaveCallConfirmationMode: mode)
headerViewData = CallScreenHeaderViewData(title: "Custom title",
subtitle: "Custom subtitle")
callScreenOptions = CallScreenOptions(controlBarOptions: callScreenControlBarOptions,
headerViewData: headerViewData)
let callCompositeOptions: CallCompositeOptions
callCompositeOptions = CallCompositeOptions(localization: localizationConfig,
setupScreenOrientation: OrientationOptions.portrait,
callingScreenOrientation: OrientationOptions.allButUpsideDown,
callScreenOptions: callScreenOptions,
displayName: displayName)
if let communicationTokenCredential = try? getTokenCredential(tokenInput: tokenInput) {
callComposite = CallComposite(credential: communicationTokenCredential, withOptions: callCompositeOptions)
} else {
reject(RNCallCompositeConnectionError.invalidToken.getErrorCode(),
"Token is invalid",
RNCallCompositeConnectionError.invalidToken)
}
guard let callComposite = callComposite else {
return
}
callComposite.events.onError = onError(resolve, reject)
let onRemoteParticipantJoinedHandler: ([CommunicationIdentifier]) -> Void = { [weak callComposite] communicationIds in
guard let callComposite = callComposite else {
return
}
self.onRemoteParticipantJoined(resolve, reject)(callComposite, communicationIds, remoteAvatar)
}
let onRemoteParticipantLeftHandler: ([CommunicationIdentifier]) -> Void = { [weak callComposite] communicationIds in
guard let callComposite = callComposite else {
return
}
self.onRemoteParticipantLeft(resolve, reject)(callComposite, communicationIds)
}
callComposite.events.onRemoteParticipantJoined = onRemoteParticipantJoinedHandler
callComposite.events.onRemoteParticipantLeft = onRemoteParticipantLeftHandler
callComposite.events.onDismissed = { dismissedEvent in
print("ReactNativeDemoView::getEventsHandler::onDismissed \(dismissedEvent)")
}
callComposite.events.onCallStateChanged = { [weak callComposite] callState in
print("ReactNativeDemoView::getEventsHandler::onCallStateChanged \(callState)")
guard let callComposite = callComposite else {
return
}
print("ReactNativeDemoView::getEventsHandler::onCallStateChanged \(callComposite.callState)")
}
var localOptions: LocalOptions? = nil
var participantViewData: ParticipantViewData? = nil
var setupViewData: SetupScreenViewData? = nil
if let localAvatar = localAvatar {
let avatar = RCTConvert.uiImage(localAvatar)
participantViewData = ParticipantViewData(avatar: avatar, displayName: displayName)
}
if let title = title {
setupViewData = SetupScreenViewData(title: title, subtitle: subtitle)
}
localOptions = LocalOptions(participantViewData: participantViewData, setupScreenViewData: setupViewData)
if isRoomsCall(meetingInput: meetingInput) {
callComposite.launch(locator: .roomCall(roomId: meetingInput), localOptions: localOptions)
} else if let url = URL(string: meetingInput),
UIApplication.shared.canOpenURL(url as URL) {
callComposite.launch(locator: .teamsMeeting(teamsLink: meetingInput), localOptions: localOptions)
} else if let uuid = UUID(uuidString: meetingInput) {
// If the input is a valid UUID
callComposite.launch(locator: .groupCall(groupId: uuid), localOptions: localOptions)
} else {
let ids: [String] = meetingInput.split(separator: ",").map {
String($0).trimmingCharacters(in: .whitespacesAndNewlines)
}
let communicationIdentifiers: [CommunicationIdentifier] =
ids.map { createCommunicationIdentifier(fromRawId: $0) }
callComposite.launch(participants: communicationIdentifiers, localOptions: localOptions)
}
resolve(nil)
}
private func getTokenCredential(tokenInput: String) throws -> CommunicationTokenCredential {
if let url = URL(string: tokenInput),
UIApplication.shared.canOpenURL(url as URL) {
let communicationTokenRefreshOptions = CommunicationTokenRefreshOptions(initialToken: nil,
refreshProactively: true,
tokenRefresher: getCommunicationToken(tokenUrl: url))
if let communicationTokenCredential = try? CommunicationTokenCredential(withOptions: communicationTokenRefreshOptions) {
return communicationTokenCredential
} else {
throw RNCallCompositeConnectionError.invalidToken
}
} else {
if let communicationTokenCredential = try? CommunicationTokenCredential(token: tokenInput) {
return communicationTokenCredential
} else {
throw RNCallCompositeConnectionError.invalidToken
}
}
}
private func isRoomsCall(meetingInput: String) -> Bool {
for ch in meetingInput {
if !(ch >= "0" && ch <= "9") {
return false
}
}
return true
}
private func getCommunicationToken(tokenUrl: URL) -> TokenRefresher {
return { [weak self] completionHandler in
self?.tokenRefresherHandler = completionHandler
self?.sendEvent(withName: RNEvents.getToken.rawValue,
body: ["url": tokenUrl.absoluteString])
}
}
func onError(_ resolve: @escaping RCTPromiseResolveBlock,
_ reject: @escaping RCTPromiseRejectBlock) -> ((CallCompositeError) -> Void) {
return { (error: CallCompositeError) -> Void in
print("ReactNativeDemoView::getEventsHandler::onError \(error)")
print("ReactNativeDemoView error.code \(error.code)")
resolve(error.error?.localizedDescription ?? "Unknown error")
}
}
func onRemoteParticipantJoined(_ resolve: @escaping RCTPromiseResolveBlock,
_ reject: @escaping RCTPromiseRejectBlock) -> ((CallComposite, [CommunicationIdentifier], AnyObject?) -> Void) {
return { (callComposite: CallComposite, identifiers: [CommunicationIdentifier], remoteAvatar: AnyObject?) -> Void in
print("ReactNativeDemoView::getEventsHandler::onRemoteParticipantJoined \(identifiers)")
if self.headerViewData != nil && identifiers.count >= 1 {
self.headerViewData?.title = "Custom title updated with participant \(identifiers.count)"
self.headerViewData?.subtitle = "Custom subtitle updated with participant \(identifiers.count)"
}
guard let remoteAvatar = remoteAvatar, let remoteAvatarImage = RCTConvert.uiImage(remoteAvatar) else {
return
}
RNCallCompositeRemoteParticipantAvatarHelper.onRemoteParticipantJoined(to: callComposite,
identifiers: identifiers,
remoteAvatar: remoteAvatarImage)
}
}
func onRemoteParticipantLeft(_ resolve: @escaping RCTPromiseResolveBlock,
_ reject: @escaping RCTPromiseRejectBlock) -> ((CallComposite, [CommunicationIdentifier]) -> Void) {
return { (callComposite: CallComposite, identifiers: [CommunicationIdentifier]) -> Void in
print("ReactNativeDemoView::getEventsHandler::onRemoteParticipantLeft \(identifiers)")
if self.headerViewData != nil && identifiers.count == 0 {
self.headerViewData?.title = "Custom title updated"
self.headerViewData?.subtitle = "Custom subtitle updated"
}
}
}
}
enum RNCallCompositeConnectionError: Error {
case invalidToken
case invalidInput
func getErrorCode() -> String {
switch self {
case .invalidToken:
return CallCompositeErrorCode.tokenExpired
case .invalidInput:
return CallCompositeErrorCode.callJoin
}
}
}
struct RNCallCompositeRemoteParticipantAvatarHelper {
private static func getRemoteParticipantId(_ identifier: CommunicationIdentifier) -> String? {
switch identifier {
case is CommunicationUserIdentifier:
return (identifier as? CommunicationUserIdentifier)?.identifier
case is UnknownIdentifier:
return (identifier as? UnknownIdentifier)?.identifier
case is PhoneNumberIdentifier:
return (identifier as? PhoneNumberIdentifier)?.phoneNumber
case is MicrosoftTeamsUserIdentifier:
return (identifier as? MicrosoftTeamsUserIdentifier)?.userId
default:
return nil
}
}
static func onRemoteParticipantJoined(to callComposite: CallComposite,
identifiers: [CommunicationIdentifier],
remoteAvatar: UIImage? = nil) {
let avatars = ["cat", "fox", "koala", "monkey", "mouse", "octopus"]
for identifier in identifiers {
let id = getRemoteParticipantId(identifier)
let nameIdValue = id != nil ? "\(id?.suffix(4) ?? "")" : ""
var avatarImage: UIImage?
var selectedAvatarName = ""
if let lastSymbol = id?.last {
let index = Int((lastSymbol.asciiValue ?? 0 ) % 6)
selectedAvatarName = avatars[index]
avatarImage = UIImage(named: selectedAvatarName)
}
let displayName = selectedAvatarName.isEmpty ? nameIdValue : "\(selectedAvatarName) \(nameIdValue)"
let participantViewData = ParticipantViewData(avatar: remoteAvatar ?? avatarImage,
displayName: displayName)
callComposite.set(remoteParticipantViewData: participantViewData,
for: identifier) { result in
switch result {
case .success:
print("::::RNCallCompositeRemoteParticipantAvatarHelper::onRemoteParticipantJoined::success")
break
case .failure(let error):
print("::::RNCallCompositeRemoteParticipantAvatarHelper::onRemoteParticipantJoined::failure \(error)")
}
}
}
}
}