-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathCallViewModel.swift
More file actions
1233 lines (1124 loc) · 45.9 KB
/
CallViewModel.swift
File metadata and controls
1233 lines (1124 loc) · 45.9 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 © 2026 Stream.io Inc. All rights reserved.
//
import Combine
import StreamVideo
import StreamWebRTC
import SwiftUI
// View model that provides methods for views that present a call.
@MainActor
open class CallViewModel: ObservableObject {
@Injected(\.streamVideo) var streamVideo
@Injected(\.pictureInPictureAdapter) var pictureInPictureAdapter
@Injected(\.callAudioRecorder) var audioRecorder
@Injected(\.applicationStateAdapter) var applicationStateAdapter
/// Provides access to the current call.
@Published public private(set) var call: Call? {
didSet {
guard call?.cId != oldValue?.cId else { return }
pictureInPictureAdapter.call = call
lastLayoutChange = Date()
participantUpdates = call?.state.$participantsMap
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] participants in
self?.callParticipants = participants
})
blockedUserUpdates = call?.state.$blockedUserIds
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] blockedUserIds in
self?.blockedUsers = blockedUserIds.map { User(id: $0) }
})
recordingUpdates = call?.state.$recordingState
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] newState in
self?.recordingState = newState
})
reconnectionUpdates = call?.state.$reconnectionStatus
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] reconnectionStatus in
guard let self else { return }
switch reconnectionStatus {
case .reconnecting where callingState != .reconnecting:
setCallingState(.reconnecting)
default:
if callingState != .inCall, callingState != .outgoing {
setCallingState(.inCall)
}
}
})
screenSharingUpdates = call?.state.$screenSharingSession
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] screenSharingSession in
if screenSharingSession?.participant.id != self?.lastScreenSharingParticipant?.id {
self?.lastLayoutChange = Date()
}
self?.lastScreenSharingParticipant = screenSharingSession?.participant
})
callSettingsUpdates = call?
.state
.$callSettings
.receive(on: DispatchQueue.main)
.assign(to: \.callSettings, onWeak: self)
// We only update the outgoingCallMembers if they are empty (which
// means that the call was created externally)
outgoingCallMembersUpdates = call?
.state
.$members
.filter { [weak self] _ in
self?.outgoingCallMembers.isEmpty == true
&& self?.callingState == .outgoing
}
.receive(on: RunLoop.main)
.assign(to: \.outgoingCallMembers, onWeak: self)
}
}
/// Tracks the current state of a call. It should be used to show different UI in your views.
@Published public var callingState: CallingState = .idle {
didSet {
// When we join a call and then ring, we need to disable the speaker.
// If the dashboard settings have the speaker on, we need to enable it
// again when we transition into a call.
if let temporaryCallSettings, oldValue == .outgoing && callingState == .inCall {
if temporaryCallSettings.speakerOn {
Task {
do {
try await call?.speaker.enableSpeakerPhone()
} catch {
log.error("Error enabling the speaker: \(error.localizedDescription)")
}
}
}
self.temporaryCallSettings = nil
}
handleRingingEvents()
}
}
/// Optional, has a value if there was an error. You can use it to display more detailed error messages to the users.
public var error: Error? {
didSet {
errorAlertShown = error != nil
if let error = error as? APIError {
toast = Toast(style: .error, message: error.message)
} else if let error {
toast = Toast(style: .error, message: error.localizedDescription)
} else {
toast = nil
}
}
}
/// Controls the display of toast messages.
@Published public var toast: Toast?
/// If the `error` property has a value, it's true. You can use it to control the visibility of an alert presented to the user.
@Published public var errorAlertShown = false
/// Whether the list of participants is shown during the call.
@Published public var participantsShown = false
/// Whether the list of participants is shown during the call.
@Published public var moreControlsShown = false
/// List of the outgoing call members.
@Published public var outgoingCallMembers = [Member]()
/// Dictionary of the call participants.
@Published public private(set) var callParticipants = [String: CallParticipant]() {
didSet {
updateCallStateIfNeeded()
}
}
/// Contains info about a participant event. It's reset to nil after 2 seconds.
@Published public var participantEvent: ParticipantEvent?
/// Provides information about the current call settings, such as the camera position and whether there's an audio and video turned on.
@Published public internal(set) var callSettings: CallSettings {
didSet {
localCallSettingsChange = true
}
}
/// Whether the call is in minimized mode.
@Published public var isMinimized = false
/// `false` by default. It becomes `true` when the current user's local video is shown as a primary view.
@Published public var localVideoPrimary = false
/// Whether the UI elements, such as the call controls should be hidden (for example while screensharing).
@Published public var hideUIElements = false
/// A list of the blocked users in the call.
@Published public var blockedUsers = [User]()
/// The current recording state of the call.
@Published public var recordingState: RecordingState = .noRecording
/// The participants layout.
@Published public private(set) var participantsLayout: ParticipantsLayout {
didSet {
if participantsLayout != oldValue {
lastLayoutChange = Date()
}
}
}
/// A flag controlling whether picture-in-picture should be enabled for the call. Default value is `true`.
@Published public var isPictureInPictureEnabled = true
/// Returns the local participant of the call.
public var localParticipant: CallParticipant? {
call?.state.localParticipant
}
/// Returns the noiseCancellationFilter if available.
public var noiseCancellationAudioFilter: AudioFilter? { streamVideo.videoConfig.noiseCancellationFilter }
private var participantUpdates: AnyCancellable?
private var blockedUserUpdates: AnyCancellable?
private var reconnectionUpdates: AnyCancellable?
private var recordingUpdates: AnyCancellable?
private var screenSharingUpdates: AnyCancellable?
private var callSettingsUpdates: AnyCancellable?
private var outgoingCallMembersUpdates: AnyCancellable?
private var applicationLifecycleUpdates: AnyCancellable?
private var ringingCancellable: AnyCancellable?
private var lastScreenSharingParticipant: CallParticipant?
private var lastLayoutChange = Date()
private var enteringCallTask: Task<Void, Never>?
private var participantsSortComparators = defaultSortPreset
private let callEventsHandler = CallEventsHandler()
private let disposableBag = DisposableBag()
private lazy var participantEventResetAdapter = ParticipantEventResetAdapter(self)
/// The variable is `true` if CallSettings have been set on the CallViewModel instance (directly or indirectly).
/// The variable will be reset to `false` when `leaveCall` will be invoked.
private(set) var localCallSettingsChange = false
private var hasAcceptedCall = false
private var skipCallStateUpdates = false
private var temporaryCallSettings: CallSettings?
public var participants: [CallParticipant] {
let updateParticipants = call?.state.participants ?? []
return updateParticipants.filter {
// In Grid layout with less than 3 participants the local user
// will be presented on the floating video track view. For this
// reason we filter out the participant to avoid showing them twice.
if
participantsLayout == .grid,
updateParticipants.count <= 3,
(call?.state.screenSharingSession == nil || call?.state.isCurrentUserScreensharing == true) {
return $0.id != call?.state.sessionId
} else {
return true
}
}
}
private var automaticLayoutHandling = true
/// The policy to whenever call events occur in order to decide if the current user should remain
/// in the call or not. Default value is the no operation policy `DefaultParticipantAutoLeavePolicy`,
public var participantAutoLeavePolicy: ParticipantAutoLeavePolicy = DefaultParticipantAutoLeavePolicy() {
didSet {
var oldValue = oldValue
oldValue.onPolicyTriggered = nil
participantAutoLeavePolicy.onPolicyTriggered = { [weak self] in self?.participantAutoLeavePolicyTriggered() }
}
}
public init(
participantsLayout: ParticipantsLayout = .grid,
callSettings: CallSettings? = nil
) {
self.participantsLayout = participantsLayout
self.callSettings = callSettings ?? .default
localCallSettingsChange = callSettings != nil
subscribeToCallEvents()
subscribeToApplicationLifecycleEvents()
// As we are setting the value on init, the `didSet` won't trigger, thus
// we are firing it manually.
// For any subsequent changes, `didSet` will trigger as expected.
participantAutoLeavePolicy.onPolicyTriggered = { [weak self] in self?.participantAutoLeavePolicyTriggered() }
_ = participantEventResetAdapter
}
deinit {
enteringCallTask?.cancel()
disposableBag.removeAll()
}
/// Toggles the state of the camera (visible vs non-visible).
public func toggleCameraEnabled() {
guard let call = call else {
callSettings = callSettings.withUpdatedVideoState(!callSettings.videoOn)
return
}
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
try await call.camera.toggle()
localCallSettingsChange = true
} catch {
log.error("Error toggling camera", error: error)
}
}
}
/// Toggles the state of the microphone (muted vs unmuted).
public func toggleMicrophoneEnabled() {
guard let call = call else {
callSettings = callSettings.withUpdatedAudioState(!callSettings.audioOn)
return
}
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
try await call.microphone.toggle()
localCallSettingsChange = true
} catch {
log.error("Error toggling microphone", error: error)
}
}
}
/// Toggles the camera position (front vs back).
public func toggleCameraPosition() {
guard let call = call, callSettings.videoOn else {
self.callSettings = callSettings.withUpdatedCameraPosition(callSettings.cameraPosition.next())
return
}
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
try await call.camera.flip()
localCallSettingsChange = true
} catch {
log.error("Error toggling camera position", error: error)
}
}
}
/// Enables or disables the audio output.
public func toggleAudioOutput() {
guard let call = call else {
callSettings = callSettings.withUpdatedAudioOutputState(!callSettings.audioOutputOn)
return
}
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
if callSettings.audioOutputOn {
try await call.speaker.disableAudioOutput()
} else {
try await call.speaker.enableAudioOutput()
}
localCallSettingsChange = true
} catch {
log.error("Error toggling audio output", error: error)
}
}
}
/// Enables or disables the speaker.
public func toggleSpeaker() {
guard let call = call else {
callSettings = callSettings.withUpdatedSpeakerState(!callSettings.speakerOn)
return
}
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
try await call.speaker.toggleSpeakerPhone()
localCallSettingsChange = true
} catch {
log.error("Error toggling speaker", error: error)
}
}
}
/// Starts a call with the provided info.
/// - Parameters:
/// - callType: the type of the call.
/// - callId: the id of the call.
/// - members: list of members that are part of the call.
/// - ring: whether the call should ring.
/// - 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.
/// - startsAt: An optional date when the call starts.
/// - backstage: An optional request for setting up backstage.
/// - video: A boolean indicating if the call will be video or only audio. Still requires appropriate
/// setting of ``CallSettings`.`
public func startCall(
callType: String,
callId: String,
members: [Member],
team: String? = nil,
ring: Bool = false,
maxDuration: Int? = nil,
maxParticipants: Int? = nil,
startsAt: Date? = nil,
backstage: BackstageSettingsRequest? = nil,
customData: [String: RawJSON]? = nil,
video: Bool? = nil
) {
outgoingCallMembers = members
setCallingState(ring ? .outgoing : .joining)
let membersRequest: [MemberRequest]? = members.isEmpty
? nil
: members.map(\.toMemberRequest)
if !ring {
enterCall(
callType: callType,
callId: callId,
members: membersRequest ?? [],
team: team,
ring: ring,
maxDuration: maxDuration,
maxParticipants: maxParticipants,
startsAt: startsAt,
backstage: backstage,
customData: customData
)
} else {
/// If no CallSettings have been provided, we skip passing the default ones, in order to
/// respect any dashboard changes.
let callSettings = localCallSettingsChange ? callSettings : nil
let call = streamVideo.call(
callType: callType,
callId: callId,
callSettings: callSettings
)
self.call = call
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
let callData = try await call.create(
members: membersRequest,
custom: customData,
team: team,
ring: ring,
maxDuration: maxDuration,
maxParticipants: maxParticipants,
video: video
)
let timeoutSeconds = TimeInterval(
callData.settings.ring.autoCancelTimeoutMs / 1000
)
startTimer(timeout: timeoutSeconds)
} catch {
self.error = error
setCallingState(.idle)
self.call = nil
}
}
}
}
/// Joins an existing call with the provided info.
/// - Parameters:
/// - callType: the type of the call.
/// - callId: the id of the call.
public func joinCall(
callType: String,
callId: String,
customData: [String: RawJSON]? = nil
) {
setCallingState(.joining)
enterCall(
callType: callType,
callId: callId,
members: [],
customData: customData
)
}
/// Joins a call and then rings the specified members.
/// - Parameters:
/// - callType: The type of the call to join (for example, "default").
/// - callId: The unique identifier of the call.
/// - members: The members who should be rung for this call.
/// - team: An optional team identifier to associate with the call.
/// - maxDuration: The maximum duration of the call in seconds.
/// - maxParticipants: The maximum number of participants allowed in the call.
/// - startsAt: An optional scheduled start time for the call.
/// - customData: Optional custom payload to associate with the call on creation.
/// - video: Optional flag indicating whether the ring should suggest a video call.
public func joinAndRingCall(
callType: String,
callId: String,
members: [Member],
team: String? = nil,
maxDuration: Int? = nil,
maxParticipants: Int? = nil,
startsAt: Date? = nil,
customData: [String: RawJSON]? = nil,
video: Bool? = nil
) {
outgoingCallMembers = members
skipCallStateUpdates = true
setCallingState(.outgoing)
let membersRequest: [MemberRequest]? = members.isEmpty
? nil
: members.map(\.toMemberRequest)
if enteringCallTask != nil || callingState == .inCall {
return
}
enteringCallTask = Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
log.debug("Starting call")
let call = call ?? streamVideo.call(
callType: callType,
callId: callId,
callSettings: callSettings
)
var settingsRequest: CallSettingsRequest?
var limits: LimitsSettingsRequest?
if maxDuration != nil || maxParticipants != nil {
limits = .init(maxDurationSeconds: maxDuration, maxParticipants: maxParticipants)
}
settingsRequest = .init(limits: limits)
let options = CreateCallOptions(
members: membersRequest,
custom: customData,
settings: settingsRequest,
startsAt: startsAt,
team: team
)
let settings = localCallSettingsChange ? callSettings : nil
call.updateParticipantsSorting(with: participantsSortComparators)
let joinResponse = try await call.join(
create: true,
options: options,
ring: false,
callSettings: settings
)
temporaryCallSettings = call.state.callSettings
try? await call.speaker.disableSpeakerPhone()
try await call.ring(
request: .init(membersIds: members.map(\.id).filter { $0 != self.streamVideo.user.id }, video: video)
)
let autoCancelTimeoutMs = call.state.settings?.ring.autoCancelTimeoutMs
?? joinResponse.call.settings.ring.autoCancelTimeoutMs
let timeoutSeconds = TimeInterval(autoCancelTimeoutMs) / 1000
startTimer(timeout: timeoutSeconds)
save(call: call)
enteringCallTask = nil
hasAcceptedCall = false
} catch {
hasAcceptedCall = false
log.error("Error starting a call", error: error)
self.error = error
setCallingState(.idle)
audioRecorder.stopRecording()
enteringCallTask = nil
}
}
}
/// Enters into a lobby before joining a call.
/// - Parameters:
/// - callType: the type of the call.
/// - callId: the id of the call.
/// - members: list of members that are part of the call.
public func enterLobby(
callType: String,
callId: String,
members: [Member]
) {
let lobbyInfo = LobbyInfo(callId: callId, callType: callType, participants: members)
setCallingState(.lobby(lobbyInfo))
if !localCallSettingsChange {
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
let call = streamVideo.call(callType: callType, callId: callId)
let info = try await call.get()
self.callSettings = .init(info.call.settings)
} catch {
log.error(error)
}
}
}
}
/// Accepts the call with the provided call id and type.
/// - Parameters:
/// - callType: the type of the call.
/// - callId: the id of the call.
public func acceptCall(
callType: String,
callId: String,
customData: [String: RawJSON]? = nil
) {
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
let call = streamVideo.call(callType: callType, callId: callId)
do {
hasAcceptedCall = true
try await call.accept()
// Mirror `joinCall` so the incoming UI is dismissed before
// `enterCall` finishes the async join flow.
await MainActor.run { self.setCallingState(.joining) }
enterCall(
call: call,
callType: callType,
callId: callId,
members: [],
customData: customData
)
} catch {
hasAcceptedCall = false
self.error = error
setCallingState(.idle)
self.call = nil
}
}
}
/// Rejects the call with the provided call id and type.
/// - Parameters:
/// - callType: the type of the call.
/// - callId: the id of the call.
public func rejectCall(
callType: String,
callId: String
) {
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
let call = streamVideo.call(callType: callType, callId: callId)
let rejectionReason = await streamVideo
.rejectionReasonProvider
.reason(for: call.cId, ringTimeout: false)
log.debug(
"""
Rejecting with reason: \(rejectionReason ?? "nil")
call:\(call.callId)
callType: \(call.callType)
ringTimeout: \(false)
"""
)
_ = try? await call.reject(reason: rejectionReason)
setCallingState(.idle)
}
}
/// 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) {
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
await call?.changeTrackVisibility(for: participant, isVisible: isVisible)
}
}
/// 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) {
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
log.debug("Updating track size for participant \(participant.name) to \(trackSize)")
await call?.updateTrackSize(trackSize, for: participant)
}
}
/// Starts screensharing for the current call.
/// - 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) {
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
await disablePictureInPictureIfRequired(type)
try await call?.startScreensharing(type: type, includeAudio: includeAudio)
} catch {
log.error(error)
}
}
}
public func stopScreensharing() {
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
try await call?.stopScreensharing()
} catch {
log.error(error)
}
}
}
/// Hangs up from the active call.
public func hangUp() {
handleCallHangUp(ringTimeout: false)
}
/// Sets a video filter for the current call.
/// - Parameter videoFilter: the video filter to be set.
public func setVideoFilter(_ videoFilter: VideoFilter?) {
call?.setVideoFilter(videoFilter)
}
/// Updates the participants layout.
/// - Parameter participantsLayout: the new participants layout.
public func update(participantsLayout: ParticipantsLayout) {
automaticLayoutHandling = false
self.participantsLayout = participantsLayout
}
public func setActiveCall(
_ call: Call?,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line
) {
log.debug(
"Will setActiveCall to cID:\(call?.cId ?? "-")",
functionName: function,
fileName: file,
lineNumber: line
)
if let call, (callingState != .inCall || self.call?.cId != call.cId) {
if !skipCallStateUpdates {
setCallingState(.inCall)
}
self.call = call
} else if call == nil, callingState != .idle {
setCallingState(.idle)
Task { @MainActor in
self.call = nil
}
}
}
/// Updates the participants sorting.
/// - Parameter participantsSortComparators: the new sort comparators.
public func update(participantsSortComparators: [StreamSortComparator<CallParticipant>]) {
self.participantsSortComparators = participantsSortComparators
}
// MARK: - private
func setCallingState(
_ newValue: CallingState,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line
) {
guard callingState != newValue else {
return
}
log.debug(
"CallingState will be updated \(callingState) → \(newValue)",
functionName: function,
fileName: file,
lineNumber: line
)
guard !Thread.isMainThread else {
callingState = newValue
return
}
Task { @MainActor in
setCallingState(
newValue,
file: file,
function: function,
line: line
)
}
}
/// Leaves the current call.
private func leaveCall() {
log.debug("Leaving call")
enteringCallTask?.cancel()
enteringCallTask = nil
participantUpdates?.cancel()
participantUpdates = nil
blockedUserUpdates?.cancel()
blockedUserUpdates = nil
automaticLayoutHandling = true
reconnectionUpdates?.cancel()
reconnectionUpdates = nil
screenSharingUpdates?.cancel()
screenSharingUpdates = nil
recordingUpdates?.cancel()
recordingUpdates = nil
skipCallStateUpdates = false
temporaryCallSettings = nil
lastScreenSharingParticipant = nil
call?.leave()
pictureInPictureAdapter.call = nil
pictureInPictureAdapter.sourceView = nil
call = nil
callParticipants = [:]
outgoingCallMembers = []
setCallingState(.idle)
isMinimized = false
localVideoPrimary = false
hasAcceptedCall = false
audioRecorder.stopRecording()
// Reset the CallSettings so that the next Call will be joined
// with either new overrides or the values provided from the API.
callSettings = .default
localCallSettingsChange = false
}
private func enterCall(
call: Call? = nil,
callType: String,
callId: String,
members: [MemberRequest],
team: String? = nil,
ring: Bool = false,
maxDuration: Int? = nil,
maxParticipants: Int? = nil,
startsAt: Date? = nil,
backstage: BackstageSettingsRequest? = nil,
customData: [String: RawJSON]? = nil
) {
if enteringCallTask != nil || callingState == .inCall {
return
}
enteringCallTask = Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
log.debug("Starting call")
let call = call ?? streamVideo.call(
callType: callType,
callId: callId,
callSettings: callSettings
)
var settingsRequest: CallSettingsRequest?
var limits: LimitsSettingsRequest?
if maxDuration != nil || maxParticipants != nil {
limits = .init(maxDurationSeconds: maxDuration, maxParticipants: maxParticipants)
}
settingsRequest = .init(backstage: backstage, limits: limits)
let options = CreateCallOptions(
members: members,
custom: customData,
settings: settingsRequest,
startsAt: startsAt,
team: team
)
let settings = localCallSettingsChange ? callSettings : nil
call.updateParticipantsSorting(with: participantsSortComparators)
try await call.join(
create: true,
options: options,
ring: ring,
callSettings: settings
)
save(call: call)
enteringCallTask = nil
hasAcceptedCall = false
} catch {
hasAcceptedCall = false
log.error("Error starting a call", error: error)
self.error = error
setCallingState(.idle)
audioRecorder.stopRecording()
enteringCallTask = nil
}
}
}
private func save(call: Call) {
guard enteringCallTask != nil else {
call.leave()
self.call = nil
return
}
setActiveCall(call)
log.debug("Started call")
}
private func handleRingingEvents() {
if callingState != .outgoing {
ringingCancellable?.cancel()
ringingCancellable = nil
}
}
private func startTimer(timeout: TimeInterval) {
ringingCancellable = Foundation
.Timer
.publish(every: timeout, on: .main, in: .default)
.autoconnect()
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
guard let self = self else { return }
log.debug("Detected ringing timeout, hanging up...")
handleCallHangUp(ringTimeout: true)
}
}
private func handleCallHangUp(ringTimeout: Bool = false) {
if skipCallStateUpdates {
skipCallStateUpdates = false
}
guard
let call,
callingState == .outgoing
else {
leaveCall()
return
}
Task(disposableBag: disposableBag, priority: .userInitiated) { [weak self] in
guard let self else { return }
do {
let rejectionReason = await streamVideo
.rejectionReasonProvider
.reason(for: call.cId, ringTimeout: ringTimeout)
log.debug(
"""
Rejecting with reason: \(rejectionReason ?? "nil")
call:\(call.callId)
callType: \(call.callType)
ringTimeout: \(ringTimeout)
"""
)
try await call.reject(reason: rejectionReason)
} catch {
log.error(error)
}
leaveCall()
}
}
private func subscribeToCallEvents() {
streamVideo
.eventPublisher()
.receive(on: DispatchQueue.main) // Required because CallViewModel is isolated on MainActor
.sink { [weak self] event in
guard let self else { return }
if let callEvent = callEventsHandler.checkForCallEvents(from: event) {
switch callEvent {
case let .incoming(incomingCall):
let currentUserId = streamVideo.user.id
Task { @MainActor [weak self] in
if incomingCall.caller.id != currentUserId {
let isAppActive = UIApplication.shared.applicationState == .active
// TODO: implement holding a call.
if self?.callingState == .idle && isAppActive {
self?.setCallingState(.incoming(incomingCall))
/// We start the ringing timer, so we can cancel when the timeout
/// is over.
self?.startTimer(timeout: incomingCall.timeout)
}
}
}
case .accepted:
handleAcceptedEvent(callEvent)
case .rejected:
handleRejectedEvent(callEvent)
case .ended:
handleEndedEvent(callEvent)
case let .userBlocked(callEventInfo):
if
callEventInfo.user?.id == streamVideo.user.id,
callEventInfo.callCid == call?.cId {
leaveCall()
}
case .userUnblocked:
break
case .sessionStarted:
break
}
} else if
let participantEvent = callEventsHandler.checkForParticipantEvents(from: event),
participantEvent.callCid == call?.cId {
guard participants.count < 25 else {
log.debug("Skipping participant events for big calls")
return
}
Task(disposableBag: disposableBag, priority: .userInitiated) { @MainActor [weak self] in
self?.participantEvent = participantEvent
}
}
}
.store(in: disposableBag)
}
private func handleAcceptedEvent(_ callEvent: CallEvent) {
guard case let .accepted(event) = callEvent else {
return
}
switch callingState {
case let .incoming(incomingCall):
guard
event.callCid == callCid(from: incomingCall.id, callType: incomingCall.type),
event.user?.id == streamVideo.user.id,
hasAcceptedCall == false
else {
break
}
/// If the call that was accepted is the incoming call we are presenting, then we reject
/// and set the activeCall to the current one in order to reset the callingState to
/// inCall or idle.
Task {
log