-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathCall.swift
More file actions
1758 lines (1611 loc) · 69.7 KB
/
Call.swift
File metadata and controls
1758 lines (1611 loc) · 69.7 KB
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright © 2025 Stream.io Inc. All rights reserved.
//
import AVFoundation
import Combine
import Foundation
import StreamWebRTC
/// Observable object that provides info about the call state, as well as methods for updating it.
public class Call: @unchecked Sendable, WSEventsSubscriber {
@Injected(\.streamVideo) var streamVideo
@Injected(\.callCache) var callCache
private lazy var stateMachine: StateMachine = .init(self)
@MainActor
public internal(set) var state = CallState()
/// The call id.
public let callId: String
/// The call type.
public let callType: String
/// The unique identifier of the call, formatted as `callType.name:callId`.
public var cId: String {
callCid(from: callId, callType: callType)
}
private let eventSubject: PassthroughSubject<WrappedEvent, Never> = .init()
public var eventPublisher: AnyPublisher<VideoEvent, Never> {
eventSubject
.compactMap {
switch $0 {
case let .coordinatorEvent(event):
return event
default:
return nil
}
}
.eraseToAnyPublisher()
}
/// Provides access to the microphone.
public let microphone: MicrophoneManager
/// Provides access to the camera.
public let camera: CameraManager
/// Provides access to the speaker.
public let speaker: SpeakerManager
/// Provides access to device's proximity
private lazy var proximity: ProximityManager = .init(
self,
activeCallPublisher: streamVideo.state.$activeCall.eraseToAnyPublisher()
)
/// Provides access to moderation.
public lazy var moderation = Moderation.Manager(self)
private let disposableBag = DisposableBag()
internal let callController: CallController
internal let coordinatorClient: DefaultAPIEndpoints
/// This adapter is used to manage closed captions for the
/// call.
private lazy var closedCaptionsAdapter = ClosedCaptionsAdapter(self)
@Atomic private var hasSubscribedToRequiredAdapters = false
internal init(
callType: String,
callId: String,
coordinatorClient: DefaultAPIEndpoints,
callController: CallController,
callSettings: CallSettings? = nil
) {
self.callId = callId
self.callType = callType
self.coordinatorClient = coordinatorClient
self.callController = callController
microphone = MicrophoneManager(
callController: callController,
initialStatus: callSettings?.audioOn == false ? .disabled : .enabled
)
camera = CameraManager(
callController: callController,
initialStatus: callSettings?.videoOn == false ? .disabled : .enabled,
initialDirection: .front
)
speaker = SpeakerManager(
callController: callController,
initialSpeakerStatus: callSettings?.speakerOn == false ? .disabled : .enabled,
initialAudioOutputStatus: callSettings?.audioOutputOn == false ? .disabled : .enabled
)
configure(callSettings: callSettings)
}
internal convenience init(
from response: CallStateResponseFields,
coordinatorClient: DefaultAPIEndpoints,
callController: CallController
) {
self.init(
callType: response.call.type,
callId: response.call.id,
coordinatorClient: coordinatorClient,
callController: callController
)
Task(disposableBag: disposableBag) { @MainActor [weak self] in
self?.state.update(from: response)
}
}
deinit {
log.debug("Call cID:\(cId) is deallocating...")
disposableBag.removeAll()
}
private func configure(callSettings: CallSettings?) {
/// If we received a non-nil initial callSettings, we updated them here.
if let callSettings {
Task(disposableBag: disposableBag) { @MainActor [weak self] in
self?.state.update(callSettings: callSettings)
}
}
_ = closedCaptionsAdapter
_ = moderation
_ = proximity
callController.call = self
speaker.call = self
// It's important to instantiate the stateMachine as soon as possible
// to ensure it's uniqueness.
_ = stateMachine
subscribeToOwnCapabilitiesChanges()
}
/// Joins the current call.
/// - Parameters:
/// - create: whether the call should be created if it doesn't exist.
/// - options: configuration options for the call.
/// - ring: whether the call should ring, `false` by default.
/// - notify: whether the participants should be notified about the call.
/// - callSettings: optional call settings.
/// - Throws: An error if the call could not be joined.
@discardableResult
public func join(
create: Bool = false,
options: CreateCallOptions? = nil,
ring: Bool = false,
notify: Bool = false,
callSettings: CallSettings? = nil
) async throws -> JoinCallResponse {
/// Determines the source from which the join action was initiated.
///
/// This block checks if the `joinSource` has already been set in the current
/// call state. If not, it assigns `.inApp` as the default join source,
/// indicating the call was joined from within the app UI. The resolved
/// `JoinSource` value is then used to record how the call was joined,
/// enabling analytics and behavioral branching based on entry point.
let joinSource = await {
if let joinSource = await state.joinSource {
return joinSource
} else {
return await Task { @MainActor in
state.joinSource = .inApp
return .inApp
}.value
}
}()
let result: Any? = stateMachine.withLock { currentStage, transitionHandler in
if
currentStage.id == .joined,
case let .joined(joinResponse) = currentStage.context.output {
return joinResponse
} else if
currentStage.id == .joining {
return stateMachine
.publisher
.tryMap { (stage) -> JoinCallResponse? in
switch stage.id {
case .joined:
guard
let stage = stage as? Call.StateMachine.Stage.JoinedStage
else {
throw ClientError()
}
switch stage.context.output {
case let .joined(response):
return response
default:
throw ClientError()
}
case .error:
guard
let stage = stage as? Call.StateMachine.Stage.ErrorStage
else {
throw ClientError()
}
throw stage.error
default:
return nil
}
}
.eraseToAnyPublisher()
} else {
let deliverySubject = CurrentValueSubject<JoinCallResponse?, Error>(nil)
transitionHandler(
.joining(
self,
input: .join(
.init(
create: create,
callSettings: callSettings,
options: options,
ring: ring,
notify: notify,
source: joinSource,
deliverySubject: deliverySubject
)
)
)
)
return deliverySubject.eraseToAnyPublisher()
}
}
if let joinResponse = result as? JoinCallResponse {
return joinResponse
} else if let publisher = result as? AnyPublisher<JoinCallResponse?, Error> {
let result = try await publisher
.compactMap { $0 }
.nextValue(timeout: CallConfiguration.timeout.join)
return result
} else {
throw ClientError("Call was unable to join call.")
}
}
/// Gets the call on the backend with the given parameters.
///
/// - Parameters:
/// - membersLimit: An optional integer specifying the maximum number of members allowed in the call.
/// - notify: A boolean value indicating whether members should be notified about the call.
/// - ring: A boolean value indicating whether to ring the call.
/// - Throws: An error if the call doesn't exist.
/// - Returns: The call's data.
public func get(
membersLimit: Int? = nil,
ring: Bool = false,
notify: Bool = false
) async throws -> GetCallResponse {
let response = try await coordinatorClient.getCall(
type: callType,
id: callId,
membersLimit: membersLimit,
ring: ring,
notify: notify,
video: nil
)
await state.update(from: response)
if ring {
Task(disposableBag: disposableBag) { @MainActor [weak self] in
self?.streamVideo.state.ringingCall = self
}
}
return response
}
/// Rings the call (sends call notification to members).
/// - Returns: The call's data.
@discardableResult
public func ring() async throws -> CallResponse {
let response = try await get(ring: true)
await state.update(from: response)
return response.call
}
/// Notifies the users of the call, by sending push notification.
/// - Returns: The call's data.
@discardableResult
public func notify() async throws -> CallResponse {
let response = try await get(notify: true)
await state.update(from: response)
return response.call
}
/// Creates a call with the specified parameters.
/// - Parameters:
/// - members: An optional array of `MemberRequest` objects to add to the call.
/// - memberIds: An optional array of member IDs to add to the call.
/// - custom: An optional dictionary of custom data to include in the call request.
/// - startsAt: An optional `Date` indicating when the call should start.
/// - team: An optional string representing the team for the call.
/// - ring: A boolean indicating whether to ring the call. Default is `false`.
/// - notify: A boolean indicating whether to send notifications. Default is `false`.
/// - maxDuration: An optional integer representing the maximum duration of the call in seconds.
/// - maxParticipants: An optional integer representing the maximum number of participants allowed in the call.
/// - backstage: An optional backstage request.
/// - video: A boolean indicating if the call will be video or only audio. Still requires appropriate
/// - transcription: An object to override the transcription Call settings from the dashboard.
/// setting of ``CallSettings`.`
/// - Returns: A `CallResponse` object representing the created call.
/// - Throws: An error if the call creation fails.
@discardableResult
public func create(
members: [MemberRequest]? = nil,
memberIds: [String]? = nil,
custom: [String: RawJSON]? = nil,
startsAt: Date? = nil,
team: String? = nil,
ring: Bool = false,
notify: Bool = false,
maxDuration: Int? = nil,
maxParticipants: Int? = nil,
backstage: BackstageSettingsRequest? = nil,
video: Bool? = nil,
transcription: TranscriptionSettingsRequest? = nil
) async throws -> CallResponse {
let membersFromMemberIds = memberIds?
.map { MemberRequest(userId: $0) } ?? []
var aggregatedMembers: [MemberRequest]? = (members ?? []) + membersFromMemberIds
if aggregatedMembers?.isEmpty == true {
aggregatedMembers = nil
}
var settingsOverride: CallSettingsRequest?
var limits: LimitsSettingsRequest?
if maxDuration != nil || maxParticipants != nil {
limits = .init(
maxDurationSeconds: maxDuration,
maxParticipants: maxParticipants
)
}
settingsOverride = CallSettingsRequest(
backstage: backstage,
limits: limits,
transcription: transcription
)
let request = GetOrCreateCallRequest(
data: CallRequest(
custom: custom,
members: aggregatedMembers,
settingsOverride: settingsOverride,
startsAt: startsAt,
team: team,
video: video
),
notify: notify,
ring: ring,
// This parameter is required for setting the video/audio in the
// CallKit VoIP notifications.
video: video
)
let response = try await coordinatorClient.getOrCreateCall(
type: callType,
id: callId,
getOrCreateCallRequest: request
)
await state.update(from: response)
if ring {
Task(disposableBag: disposableBag) { @MainActor [weak self] in
self?.streamVideo.state.ringingCall = self
}
}
return response.call
}
/// Initiates a ring action for the current call.
/// - Parameter request: The `RingCallRequest` containing ring configuration, such as member ids and whether it's a video call.
/// - Returns: A `RingCallResponse` with information about the ring operation.
/// - Throws: An error if the coordinator request fails or the call cannot be rung.
@discardableResult
public func ring(request: RingCallRequest) async throws -> RingCallResponse {
let response = try await coordinatorClient.ringCall(
type: callType,
id: callId,
ringCallRequest: request
)
return response
}
/// Updates an existing call with the specified parameters.
/// - Parameters:
/// - custom: An optional dictionary of custom data to include in the update request.
/// - settingsOverride: An optional `CallSettingsRequest` object to override the call settings.
/// - startsAt: An optional `Date` indicating when the call should start.
/// - Returns: An `UpdateCallResponse` object representing the updated call.
/// - Throws: An error if the call update fails.
@discardableResult
public func update(
custom: [String: RawJSON]? = nil,
settingsOverride: CallSettingsRequest? = nil,
startsAt: Date? = nil
) async throws -> UpdateCallResponse {
let request = UpdateCallRequest(
custom: custom,
settingsOverride: settingsOverride,
startsAt: startsAt
)
let response = try await coordinatorClient.updateCall(
type: callType,
id: callId,
updateCallRequest: request
)
await state.update(from: response)
return response
}
/// Accepts an incoming call.
@discardableResult
public func accept() async throws -> AcceptCallResponse {
let currentStage = stateMachine.currentStage
if
currentStage.id == .accepted,
case let .accepted(response) = currentStage.context.output {
return response
} else if
currentStage.id == .accepting,
case let .accepting(deliverySubject) = currentStage.context.input {
return try await deliverySubject.nextValue(timeout: CallConfiguration.timeout.accept)
} else {
let deliverySubject = PassthroughSubject<AcceptCallResponse, Error>()
stateMachine.transition(
.accepting(
self,
input: .accepting(deliverySubject: deliverySubject)
)
)
return try await deliverySubject.nextValue(timeout: CallConfiguration.timeout.accept)
}
}
/// Rejects a call with an optional reason.
/// - Parameters:
/// - reason: An optional `String` providing the reason for the rejection. Default is `nil`.
/// - Returns: A `RejectCallResponse` object indicating the result of the rejection.
/// - Throws: An error if the rejection fails.
@discardableResult
public func reject(reason: String? = nil) async throws -> RejectCallResponse {
let currentStage = stateMachine.currentStage
if
currentStage.id == .rejected,
case let .rejected(response) = currentStage.context.output {
return response
} else if
currentStage.id == .rejecting,
case let .rejecting(input) = currentStage.context.input {
return try await input
.deliverySubject
.nextValue(timeout: CallConfiguration.timeout.reject)
} else {
let deliverySubject = PassthroughSubject<RejectCallResponse, Error>()
stateMachine.transition(
.rejecting(
self,
input: .rejecting(.init(reason: reason, deliverySubject: deliverySubject))
)
)
return try await deliverySubject.nextValue(timeout: CallConfiguration.timeout.reject)
}
}
/// Adds the given user to the list of blocked users for the call.
/// - Parameter blockedUser: The user to add to the list of blocked users.
@discardableResult
public func block(user: User) async throws -> BlockUserResponse {
try await blockUser(with: user.id)
}
/// Removes the given user from the list of blocked users for the call.
/// - Parameter blockedUser: The user to remove from the list of blocked users.
@discardableResult
public func unblock(user: User) async throws -> UnblockUserResponse {
try await unblockUser(with: user.id)
}
/// Changes the track visibility for a participant (not visible if they go off-screen).
/// - Parameters:
/// - participant: the participant whose track visibility would be changed.
/// - isVisible: whether the track should be visible.
public func changeTrackVisibility(for participant: CallParticipant, isVisible: Bool) async {
await callController.changeTrackVisibility(for: participant, isVisible: isVisible)
}
@discardableResult
public func addMembers(members: [MemberRequest]) async throws -> UpdateCallMembersResponse {
try await updateCallMembers(
updateMembers: members
)
}
@discardableResult
public func updateMembers(members: [MemberRequest]) async throws -> UpdateCallMembersResponse {
try await updateCallMembers(
updateMembers: members
)
}
/// Adds members with the specified `ids` to the current call.
/// - Parameter ids: An array of `String` values representing the member IDs to add.
/// - Throws: An error if the members could not be added to the call.
@discardableResult
public func addMembers(ids: [String]) async throws -> UpdateCallMembersResponse {
try await updateCallMembers(
updateMembers: ids.map { MemberRequest(userId: $0) }
)
}
/// Remove members with the specified `ids` from the current call.
/// - Parameter ids: An array of `String` values representing the member IDs to remove.
/// - Throws: An error if the members could not be removed from the call.
@discardableResult
public func removeMembers(ids: [String]) async throws -> UpdateCallMembersResponse {
try await updateCallMembers(
removedIds: ids
)
}
/// Updates the track size for the provided participant.
/// - Parameters:
/// - trackSize: the size of the track.
/// - participant: the call participant.
public func updateTrackSize(_ trackSize: CGSize, for participant: CallParticipant) async {
await callController.updateTrackSize(trackSize, for: participant)
}
/// Sets a `VideoFilter` for the current call.
/// - Parameter videoFilter: Desired filter; pass `nil` to clear it.
public func setVideoFilter(_ videoFilter: VideoFilter?) {
moderation.setVideoFilter(videoFilter)
callController.setVideoFilter(videoFilter)
}
/// Sets an `AudioFilter` for the current call.
/// - Parameter audioFilter: Desired filter; pass `nil` to clear it.
public func setAudioFilter(_ audioFilter: AudioFilter?) {
streamVideo.videoConfig.audioProcessingModule.setAudioFilter(audioFilter)
}
/// Starts screensharing from the device.
/// - Parameters:
/// - type: The screensharing type (in-app or broadcasting).
/// - includeAudio: Whether to capture app audio during screensharing.
/// Only valid for `.inApp`; ignored otherwise.
public func startScreensharing(
type: ScreensharingType,
includeAudio: Bool = true
) async throws {
try await callController.startScreensharing(
type: type,
includeAudio: includeAudio
)
}
/// Stops screensharing from the current device.
public func stopScreensharing() async throws {
try await callController.stopScreensharing()
}
/// Publishes web socket events filtered by the provided type.
/// - Parameter event: Event type to observe.
/// - Returns: Publisher emitting instances of `WSEvent`.
public func eventPublisher<WSEvent: Event>(
for event: WSEvent.Type
) -> AnyPublisher<WSEvent, Never> {
eventPublisher
.compactMap { $0.rawValue as? WSEvent }
.eraseToAnyPublisher()
}
/// Subscribes to video events.
/// - Returns: `AsyncStream` of `VideoEvent`s.
public func subscribe() -> AsyncStream<VideoEvent> {
eventPublisher.eraseAsAsyncStream()
}
/// Subscribes to a particular web socket event.
/// - Parameter event: the type of the event you are subscribing to.
/// - Returns: `AsyncStream` of web socket events from the provided type.
public func subscribe<WSEvent: Event>(for event: WSEvent.Type) -> AsyncStream<WSEvent> {
eventPublisher(for: event).eraseAsAsyncStream()
}
/// Leave the current call.
public func leave() {
postNotification(with: CallNotification.callEnded, object: self)
disposableBag.removeAll()
callController.leave()
closedCaptionsAdapter.stop()
stateMachine.transition(.idle(.init(call: self)))
/// Upon `Call.leave` we remove the call from the cache. Any further actions that are required
/// to happen on the call object (e.g. rejoin) will need to fetch a new instance from `StreamVideo`
/// client.
callCache.remove(for: cId)
// Reset the activeAudioFilter
setAudioFilter(nil)
Task(disposableBag: disposableBag) { @MainActor [weak self] in
guard let self else {
return
}
if streamVideo.state.ringingCall?.cId == cId {
streamVideo.state.ringingCall = nil
}
if streamVideo.state.activeCall?.cId == cId {
streamVideo.state.activeCall = nil
}
}
}
/// Starts noise cancellation asynchronously.
/// - Throws: `ClientError.MissingPermissions` if the current user does not have the
/// capability to enable noise cancellation.
/// - Throws: An error if starting noise cancellation fails.
public func startNoiseCancellation() async throws {
guard await currentUserHasCapability(.enableNoiseCancellation) else {
throw ClientError.MissingPermissions()
}
try await callController.startNoiseCancellation(state.sessionId)
}
/// Stops noise cancellation asynchronously.
/// - Throws: An error if stopping noise cancellation fails.
public func stopNoiseCancellation() async throws {
try await callController.stopNoiseCancellation(state.sessionId)
}
// MARK: - Permissions
/// Checks if the current user can request permissions.
/// - Parameter permissions: The permissions to request.
/// - Returns: A Boolean value indicating if the current user can request the permissions.
@MainActor public func currentUserCanRequestPermissions(_ permissions: [Permission]) -> Bool {
guard let callSettings = state.settings else {
return false
}
for permission in permissions {
if permission.rawValue == Permission.sendAudio.rawValue
&& callSettings.audio.accessRequestEnabled == false {
return false
} else if permission.rawValue == Permission.sendVideo.rawValue
&& callSettings.video.accessRequestEnabled == false {
return false
} else if permission.rawValue == Permission.screenshare.rawValue
&& callSettings.screensharing.accessRequestEnabled == false {
return false
}
}
return true
}
/// Requests permissions for a call.
/// - Parameters:
/// - permissions: The permissions to request.
/// - Throws: A `ClientError.MissingPermissions` if the current user can't request the permissions.
@discardableResult
public func request(permissions: [Permission]) async throws -> RequestPermissionResponse {
if await state.isInitialized == false {
let response = try await get()
await state.update(from: response)
}
if await !currentUserCanRequestPermissions(permissions) {
throw ClientError.MissingPermissions()
}
let request = RequestPermissionRequest(
permissions: permissions.map(\.rawValue)
)
return try await coordinatorClient.requestPermission(
type: callType,
id: callId,
requestPermissionRequest: request
)
}
/// Checks if the current user has a certain call capability.
/// - Parameter capability: The capability to check.
/// - Returns: A Boolean value indicating if the current user has the call capability.
@MainActor public func currentUserHasCapability(_ capability: OwnCapability) -> Bool {
if !state.isInitialized {
log.warning("currentUserHasCapability called before the call was initialized using .get .create or .join")
}
return state.ownCapabilities.contains(capability)
}
/// Grants permissions to a user for a call.
/// - Parameters:
/// - permissions: The permissions to grant.
/// - userId: The ID of the user to grant permissions to.
/// - Throws: An error if the operation fails.
@discardableResult
public func grant(
permissions: [Permission],
for userId: String
) async throws -> UpdateUserPermissionsResponse {
try await updatePermissions(
for: userId,
granted: permissions.map(\.rawValue),
revoked: []
)
}
@discardableResult
public func grant(request: PermissionRequest) async throws -> UpdateUserPermissionsResponse {
let response = try await updatePermissions(
for: request.user.id,
granted: [request.permission],
revoked: []
)
Task(disposableBag: disposableBag) { @MainActor [weak self] in
guard let self else { return }
self.state.removePermissionRequest(request: request)
}
return response
}
/// Revokes permissions for a user in a call.
/// - Parameters:
/// - permissions: The list of permissions to revoke.
/// - userId: The ID of the user to revoke the permissions from.
/// - Throws: error if the permission update fails.
@discardableResult
public func revoke(
permissions: [Permission],
for userId: String
) async throws -> UpdateUserPermissionsResponse {
try await updatePermissions(
for: userId,
granted: [],
revoked: permissions.map(\.rawValue)
)
}
@discardableResult
public func mute(
userId: String,
audio: Bool = true,
video: Bool = true
) async throws -> MuteUsersResponse {
try await coordinatorClient.muteUsers(
type: callType,
id: callId,
muteUsersRequest: MuteUsersRequest(
audio: audio,
userIds: [userId],
video: video
)
)
}
@discardableResult
public func muteAllUsers(audio: Bool = true, video: Bool = true) async throws -> MuteUsersResponse {
try await coordinatorClient.muteUsers(
type: callType,
id: callId,
muteUsersRequest: MuteUsersRequest(
audio: audio,
muteAllUsers: true,
video: video
)
)
}
/// Ends a call.
/// - Throws: error if ending the call fails.
@discardableResult
public func end() async throws -> EndCallResponse {
try await coordinatorClient.endCall(type: callType, id: callId)
}
/// Blocks a user in a call.
/// - Parameters:
/// - userId: The ID of the user to block.
/// - Throws: error if blocking the user fails.
@discardableResult
public func blockUser(with userId: String) async throws -> BlockUserResponse {
let response = try await coordinatorClient.blockUser(
type: callType,
id: callId,
blockUserRequest: BlockUserRequest(userId: userId)
)
await state.blockUser(id: userId)
return response
}
/// Unblocks a user in a call.
/// - Parameters:
/// - userId: The ID of the user to unblock.
/// - Throws: error if unblocking the user fails.
@discardableResult
public func unblockUser(with userId: String) async throws -> UnblockUserResponse {
let response = try await coordinatorClient.unblockUser(
type: callType,
id: callId,
unblockUserRequest: UnblockUserRequest(userId: userId)
)
await state.unblockUser(id: userId)
return response
}
/// Starts a live call.
/// - Parameters:
/// - startsHls: whether hls streaming should be started.
/// - startRecording: whether recording should be started.
/// - startRtmpBroadcasts: whether RTMP broadcasting should be started.
/// - startTranscription: whether transcription should be started.
/// - Returns: `GoLiveResponse`.
@discardableResult
public func goLive(
startHls: Bool? = nil,
startRecording: Bool? = nil,
startRtmpBroadcasts: Bool? = nil,
startTranscription: Bool? = nil
) async throws -> GoLiveResponse {
let goLiveRequest = GoLiveRequest(
startHls: startHls,
startRecording: startRecording,
startRtmpBroadcasts: startRtmpBroadcasts,
startTranscription: startTranscription
)
return try await coordinatorClient.goLive(
type: callType,
id: callId,
goLiveRequest: goLiveRequest
)
}
/// Stops an ongoing live call.
@discardableResult
public func stopLive() async throws -> StopLiveResponse {
try await stopLive(request: .init())
}
public func stopLive(request: StopLiveRequest) async throws -> StopLiveResponse {
try await coordinatorClient.stopLive(
type: callType,
id: callId,
stopLiveRequest: request
)
}
// MARK: - Recording
/// Starts recording for the call.
@discardableResult
public func startRecording() async throws -> StartRecordingResponse {
let response = try await coordinatorClient.startRecording(
type: callType,
id: callId,
startRecordingRequest: StartRecordingRequest()
)
update(recordingState: .requested)
return response
}
/// Stops recording a call.
@discardableResult
public func stopRecording() async throws -> StopRecordingResponse {
try await coordinatorClient.stopRecording(type: callType, id: callId)
}
/// Lists recordings for the call.
public func listRecordings() async throws -> [CallRecording] {
let response = try await coordinatorClient.listRecordings(
type: callType,
id: callId
)
return response.recordings
}
// MARK: - Broadcasting
/// Starts HLS broadcasting of the call.
@discardableResult
public func startHLS() async throws -> StartHLSBroadcastingResponse {
try await coordinatorClient.startHLSBroadcasting(type: callType, id: callId)
}
/// Stops HLS broadcasting of the call.
@discardableResult
public func stopHLS() async throws -> StopHLSBroadcastingResponse {
try await coordinatorClient.stopHLSBroadcasting(type: callType, id: callId)
}
/// Starts RTMP broadcasting of the call.
/// - Parameter request: The request to start RTMP broadcasting.
/// - Returns: `StartRTMPBroadcastsResponse`.
/// - Throws: An error if starting RTMP broadcasting.
@discardableResult
public func startRTMPBroadcast(
request: StartRTMPBroadcastsRequest
) async throws -> StartRTMPBroadcastsResponse {
try await coordinatorClient.startRTMPBroadcasts(
type: callType,
id: callId,
startRTMPBroadcastsRequest: request
)
}
/// Stops RTMP broadcasting of the call.
/// - Parameter name: The name of the RTMP broadcast.
/// - Returns: `StopRTMPBroadcastsResponse`.
/// - Throws: An error if stopping RTMP broadcasting.
@discardableResult
public func stopRTMPBroadcasts(name: String) async throws -> StopRTMPBroadcastsResponse {
try await coordinatorClient.stopRTMPBroadcast(type: callType, id: callId, name: name)
}
// MARK: - Events
/// Sends a custom event to the call.
/// - Throws: An error if the sending fails.
@discardableResult
public func sendCustomEvent(_ data: [String: RawJSON]) async throws -> SendEventResponse {
try await coordinatorClient.sendCallEvent(
type: callType,
id: callId,
sendEventRequest: SendEventRequest(custom: data)
)
}
/// Sends a reaction to the call.
/// - Throws: An error if the sending fails.
@discardableResult
public func sendReaction(
type: String,
custom: [String: RawJSON]? = nil,
emojiCode: String? = nil
) async throws -> SendReactionResponse {
try await coordinatorClient.sendVideoReaction(
type: callType,
id: callId,
sendReactionRequest: SendReactionRequest(custom: custom, emojiCode: emojiCode, type: type)
)
}
// MARK: - Query members methods
internal func queryMembers(
filters: [String: RawJSON]? = nil, limit: Int? = nil, next: String? = nil, sort: [SortParamRequest]? = nil
) async throws -> QueryMembersResponse {
let request = QueryMembersRequest(
filterConditions: filters,
id: callId,
limit: limit,
next: next,
sort: sort,
type: callType
)
let response = try await coordinatorClient.queryCallMembers(queryMembersRequest: request)
await state.mergeMembers(response.members)
return response
}
/// Queries call members with the specified filters, sort options, and limit.
///
/// - Parameters:
/// - filters: An optional dictionary of filters.
/// - sort: An optional array of `SortParamRequest` that determines the sorting order of the results. Defaults to sorting by `created_at` in descending order.
/// - limit: The maximum number of members to return. Defaults to 25.
///
/// - Returns: A `QueryMembersResponse` containing the results of the query.
/// - Throws: An error if the query fails.
public func queryMembers(
filters: [String: RawJSON]? = nil,
sort: [SortParamRequest] = [SortParamRequest.descending("created_at")],
limit: Int = 25
) async throws -> QueryMembersResponse {
try await queryMembers(filters: filters, limit: limit, sort: sort)
}
/// Asynchronously queries members with pagination support, using filters, sort options, and limit.
///
/// - Parameters:
/// - filters: An optional dictionary of filters.
/// - sort: An optional array of `SortParamRequest` that determines the sorting order of the results.
/// - limit: The maximum number of members to return. Defaults to 25.
/// - next: A `String` representing the pagination token to fetch the next set of results.
///
/// - Returns: A `QueryMembersResponse` containing the results of the query.
/// - Throws: An error if the query fails.
public func queryMembers(
filters: [String: RawJSON]? = nil,
sort: [SortParamRequest]? = nil,
limit: Int = 25,
next: String
) async throws -> QueryMembersResponse {
try await queryMembers(filters: filters, limit: limit, next: next, sort: sort)
}
// MARK: - Pinning