-
Notifications
You must be signed in to change notification settings - Fork 2
/
ProviderDelegate.swift
361 lines (317 loc) · 16.5 KB
/
ProviderDelegate.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
/*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import CallKit
import UIKit
import linphonesw
import AVFoundation
import os
@objc public class CallInfo: NSObject {
var callId: String = ""
var toAddr: Address?
var isOutgoing = false
var sasEnabled = false
var connected = false
var reason: Reason = Reason.None
var phoneNumber: String?
var displayName: String?
var videoEnabled = false
var isConference = false
static func newIncomingCallInfo(callId: String) -> CallInfo {
let callInfo = CallInfo()
callInfo.callId = callId
return callInfo
}
static func newOutgoingCallInfo(addr: Address, isSas: Bool, displayName: String, isVideo: Bool, isConference:Bool) -> CallInfo {
let callInfo = CallInfo()
callInfo.isOutgoing = true
callInfo.sasEnabled = isSas
callInfo.toAddr = addr
callInfo.displayName = displayName
callInfo.videoEnabled = isVideo
callInfo.isConference = isConference
return callInfo
}
}
/*
* A delegate to support callkit.
*/
public class ProviderDelegate: NSObject {
static var shared = ProviderDelegate()
let provider: CXProvider
var uuids: [String : UUID] = [:]
var callInfos: [UUID : CallInfo] = [:]
var logger: Logger? = nil
override init() {
provider = CXProvider(configuration: ProviderDelegate.providerConfiguration)
super.init()
provider.setDelegate(self, queue: nil)
}
static var providerConfiguration: CXProviderConfiguration {
get {
let providerConfiguration = CXProviderConfiguration(localizedName: Bundle.main.infoDictionary!["CFBundleName"] as! String)
// providerConfiguration.ringtoneSound = ConfigManager.instance().lpConfigBoolForKey(key: "use_device_ringtone") ? nil : "notes_of_the_optimistic.caf"
providerConfiguration.supportsVideo = true
providerConfiguration.iconTemplateImageData = UIImage(named: "callkit_logo")?.pngData()
providerConfiguration.supportedHandleTypes = [.generic, .phoneNumber, .emailAddress]
providerConfiguration.maximumCallsPerCallGroup = 10
providerConfiguration.maximumCallGroups = 10
//not show app's calls in tel's history
//providerConfiguration.includesCallsInRecents = YES;
return providerConfiguration
}
}
@objc static func resetSharedProviderConfiguration() {
shared.provider.configuration = ProviderDelegate.providerConfiguration
}
func reportIncomingCall(call:Call?, uuid: UUID, handle: String, hasVideo: Bool, phoneNumber: String, displayName: String?) {
let update = CXCallUpdate()
update.hasVideo = hasVideo
if let displayName = displayName {
update.remoteHandle = CXHandle(type: .generic, value: handle)
update.localizedCallerName = displayName
} else {
update.remoteHandle = CXHandle(type: .phoneNumber, value: phoneNumber)
update.hasVideo = hasVideo
}
let callInfo = callInfos[uuid]
let callId = callInfo?.callId
logger?.message("[LinphoneProviderDelegate] CallKit: report new incoming call with call-id: [\(String(describing: callId))] and UUID: [\(uuid.description)]")
//CallManager.instance().setHeldOtherCalls(exceptCallid: callId ?? "")
provider.reportNewIncomingCall(with: uuid, update: update) { error in
if error == nil {
if CallManager.instance().endCallkit {
let call = CallManager.instance().lc?.getCallByCallid(callId: callId!)
if (call?.state == .PushIncomingReceived) {
try? call?.terminate()
}
}
} else {
self.logger?.error("[LinphoneProviderDelegate] CallKit: cannot complete incoming call with call-id: [\(String(describing: callId))] and UUID: [\(uuid.description)] from [\(handle)] caused by [\(error!.localizedDescription)]")
let code = (error as NSError?)?.code
switch code {
case CXErrorCodeIncomingCallError.filteredByDoNotDisturb.rawValue:
callInfo?.reason = Reason.Busy // This answer is only for this device. Using Reason.DoNotDisturb will make all other end point stop ringing.
case CXErrorCodeIncomingCallError.filteredByBlockList.rawValue:
callInfo?.reason = Reason.DoNotDisturb
default:
callInfo?.reason = Reason.Unknown
}
self.callInfos.updateValue(callInfo!, forKey: uuid)
try? call?.decline(reason: callInfo!.reason)
}
}
}
func updateCall(uuid: UUID, handle: String, hasVideo: Bool = false, displayName: String?) {
guard let displayName = displayName else {
return
}
let update = CXCallUpdate()
update.remoteHandle = CXHandle(type:.generic, value:handle)
update.localizedCallerName = displayName
update.hasVideo = hasVideo
provider.reportCall(with: uuid, updated: update)
}
func reportOutgoingCallStartedConnecting(uuid:UUID) {
provider.reportOutgoingCall(with: uuid, startedConnectingAt: nil)
}
func reportOutgoingCallConnected(uuid:UUID) {
provider.reportOutgoingCall(with: uuid, connectedAt: nil)
}
func endCall(uuid: UUID) {
provider.reportCall(with: uuid, endedAt: .init(), reason: .failed)
}
func endCallNotExist(uuid: UUID, timeout: DispatchTime) {
DispatchQueue.main.asyncAfter(deadline: timeout) {
let callId = CallManager.instance().providerDelegate.callInfos[uuid]?.callId
if (callId == nil) {
// callkit already ended
return
}
let call = CallManager.instance().callByCallId(callId: callId)
if (call == nil) {
self.logger?.message("[LinphoneProviderDelegate] CallKit: terminate call with call-id: \(String(describing: callId)) and UUID: \(uuid) which does not exist.")
CallManager.instance().providerDelegate.endCall(uuid: uuid)
}
}
}
}
// MARK: - CXProviderDelegate
extension ProviderDelegate: CXProviderDelegate {
public func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
let uuid = action.callUUID
let callId = callInfos[uuid]?.callId
// remove call infos first, otherwise CXEndCallAction will be called more than onece
if (callId != nil) {
uuids.removeValue(forKey: callId!)
}
callInfos.removeValue(forKey: uuid)
let call = CallManager.instance().callByCallId(callId: callId)
if let call = call {
CallManager.instance().terminateCall(call: call.getCobject);
logger?.message("[LinphoneProviderDelegate] CallKit: Call ended with call-id: \(String(describing: callId)) an UUID: \(uuid.description).")
}
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
let uuid = action.callUUID
let callInfo = callInfos[uuid]
let callId = callInfo?.callId
logger?.message("[LinphoneProviderDelegate] CallKit: answer call with call-id: \(String(describing: callId)) and UUID: \(uuid.description).")
let call1 = CallManager.instance().callByCallId(callId: callId)
let call2 = CallManager.instance().callByNumber(caller: callInfo?.phoneNumber)
guard let call = (call1 != nil ? call1 : call2) else {
logger?.message("[LinphoneProviderDelegate] CallKit: Cannot find call with call-id: \(String(describing: callId)) and UUID: \(uuid.description).")
action.fail()
return
}
if (UIApplication.shared.applicationState != .active) {
CallManager.instance().backgroundContextCall = call
CallManager.instance().backgroundContextCameraIsEnabled = call.params?.videoEnabled == true || call.callLog?.wasConference() == true
call.cameraEnabled = false // Disable camera while app is not on foreground
}
CallManager.instance().callkitAudioSessionActivated = false
CallManager.instance().lc?.configureAudioSession()
CallManager.instance().acceptCall(call: call, hasVideo: call.params?.videoEnabled ?? false)
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {
let uuid = action.callUUID
let callId = callInfos[uuid]?.callId
let call = CallManager.instance().callByCallId(callId: callId)
if (call == nil) {
logger?.error("[LinphoneProviderDelegate] CXSetHeldCallAction: no call !")
action.fail()
return
}
do {
if (CallManager.instance().lc?.isInConference ?? false && action.isOnHold) {
try CallManager.instance().lc?.leaveConference()
logger?.debug("[LinphoneProviderDelegate] CallKit: call-id: [\(String(describing: callId))] leaving conference")
NotificationCenter.default.post(name: Notification.Name("LinphoneCallUpdate"), object: self)
action.fulfill()
}else{
let state = action.isOnHold ? "Paused" : "Resumed"
logger?.debug("[LinphoneProviderDelegate] CallKit: Call with call-id: [\(String(describing: callId))] and UUID: [\(uuid)] paused status changed to: [\(state)]")
if (action.isOnHold) {
CallManager.instance().speakerBeforePause = CallManager.instance().isSpeakerEnabled()
try call!.pause()
// fullfill() the action now to indicate to Callkit that this call is no longer active, even if the
// SIP transaction is not completed yet. At this stage, the media streams are off.
// If callkit is not aware that the pause action is completed, it will terminate this call if we
// attempt to resume another one.
action.fulfill()
} else {
if (CallManager.instance().lc?.conference != nil && CallManager.instance().lc?.callsNb ?? 0 > 1) {
try CallManager.instance().lc?.enterConference()
action.fulfill()
NotificationCenter.default.post(name: Notification.Name("LinphoneCallUpdate"), object: self)
} else {
try call!.resume()
// We'll notify callkit that the action is fulfilled when receiving the 200Ok, which is the point
// where we actually start the media streams.
CallManager.instance().actionToFulFill = action;
// HORRIBLE HACK HERE - PLEASE APPLE FIX THIS !!
// When resuming a SIP call after a native call has ended remotely, didActivate: audioSession
// is never called.
// It looks like in this case, it is implicit.
// As a result we have to notify the Core that the AudioSession is active.
// The SpeakerBox demo application written by Apple exhibits this behavior.
// https://developer.apple.com/documentation/callkit/making_and_receiving_voip_calls_with_callkit
// We can clearly see there that startAudio() is called immediately in the CXSetHeldCallAction
// handler, while it is called from didActivate: audioSession otherwise.
// Callkit's design is not consistent, or its documentation imcomplete, wich is somewhat disapointing.
//
logger?.debug("[LinphoneProviderDelegate] Assuming AudioSession is active when executing a CXSetHeldCallAction with isOnHold=false.")
CallManager.instance().activateAudioIfNeeded(activate: true)
}
}
}
} catch {
logger?.error("[LinphoneProviderDelegate] CallKit: Call set held (paused or resumed) \(uuid) failed because \(error)")
action.fail()
}
}
public func provider(_ provider: CXProvider, perform action: CXStartCallAction) {
do {
let uuid = action.callUUID
let callInfo = callInfos[uuid]
// We don't need to update display name
// let update = CXCallUpdate()
// update.remoteHandle = action.handle
// update.localizedCallerName = callInfo?.displayName
// self.provider.reportCall(with: action.callUUID, updated: update)
let addr = callInfo?.toAddr
if (addr == nil) {
logger?.error("[LinphoneProviderDelegate] CallKit: can not call a null address!")
action.fail()
}
CallManager.instance().lc?.configureAudioSession()
try CallManager.instance().doCall(addr: addr!, isSas: callInfo?.sasEnabled ?? false, isVideo: callInfo?.videoEnabled ?? false, isConference: callInfo?.isConference ?? false)
} catch {
logger?.error("[LinphoneProviderDelegate] CallKit: Call started failed because \(error)")
action.fail()
}
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXSetGroupCallAction) {
logger?.message("[LinphoneProviderDelegate] CallKit: Call grouped callUUid : \(action.callUUID) with callUUID: \(String(describing: action.callUUIDToGroupWith)).")
CallManager.instance().addAllToLocalConference()
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {
let uuid = action.callUUID
let callId = callInfos[uuid]?.callId
logger?.message("[LinphoneProviderDelegate] CallKit: Call muted with call-id: \(String(describing: callId)) an UUID: \(uuid.description).")
CallManager.instance().lc!.micEnabled = !CallManager.instance().lc!.micEnabled
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXPlayDTMFCallAction) {
let uuid = action.callUUID
let callId = callInfos[uuid]?.callId
logger?.message("[LinphoneProviderDelegate] CallKit: Call send dtmf with call-id: \(String(describing: callId)) an UUID: \(uuid.description).")
let call = CallManager.instance().callByCallId(callId: callId)
if (call != nil) {
let digit = (action.digits.cString(using: String.Encoding.utf8)?[0])!
do {
try call!.sendDtmf(dtmf: digit)
} catch {
logger?.error("[LinphoneProviderDelegate] CallKit: Call send dtmf \(uuid) failed because \(error)")
}
}
action.fulfill()
}
public func provider(_ provider: CXProvider, timedOutPerforming action: CXAction) {
let uuid = action.uuid
let callId = callInfos[uuid]?.callId
logger?.message("[LinphoneProviderDelegate] CallKit: Call time out with call-id: \(String(describing: callId)) an UUID: \(uuid.description).")
action.fulfill()
}
public func providerDidReset(_ provider: CXProvider) {
logger?.message("[LinphoneProviderDelegate] CallKit: did reset.")
}
public func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
logger?.message("[LinphoneProviderDelegate] CallKit: audio session activated.")
CallManager.instance().activateAudioIfNeeded(activate: true)
}
public func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
logger?.message("[LinphoneProviderDelegate] CallKit: audio session deactivated.")
CallManager.instance().activateAudioIfNeeded(activate: false)
}
}