mirror of https://github.com/oxen-io/session-ios
WIP: WebRTC calling
* Ensure NotificationsManager has dependencies Otherwise it's easy to mess up the order of the required dependencies. * move AccountManager into Environment, it's heavy to construct // FREEBIEpull/1/head
parent
f01c5a1985
commit
647b2b37e9
@ -0,0 +1,30 @@
|
||||
Apart from the general `BUILDING.md` there are certain things that have
|
||||
to be done by Signal-iOS maintainers.
|
||||
|
||||
For transperancy and bus factor, they are outlined here.
|
||||
|
||||
## Dependencies
|
||||
|
||||
Keeping cocoapods based dependencies is easy enough.
|
||||
|
||||
`pod update`
|
||||
|
||||
### WebRTC
|
||||
|
||||
We don't currently have an automated build (cocoapod/carthage) setup for
|
||||
the WebRTC.framework. Instead, read the WebRTC upstream source and build
|
||||
setup instructions here:
|
||||
|
||||
https://webrtc.org/native-code/ios/
|
||||
|
||||
Once you have your build environment set up and the WebRTC source downloaded:
|
||||
|
||||
cd webrtc
|
||||
# build a fat framework
|
||||
src/webrtc/build/ios/build_ios_libs.sh
|
||||
# Put it in our frameworks search path
|
||||
mv src/webrtc/ios_libs_out/WebRTC.framework ../Signal-iOS/Carthage/Builds
|
||||
|
||||
## Translations
|
||||
|
||||
Read more about translations in [TRANSLATIONS.md](signal/translations/TRANSLATIONS.md)
|
@ -0,0 +1,5 @@
|
||||
line_length: 200
|
||||
disabled_rules:
|
||||
- file_length
|
||||
- todo
|
||||
|
@ -0,0 +1,34 @@
|
||||
// Created by Michael Kirk on 12/28/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc(OWSCallNotificationsAdapter)
|
||||
class CallNotificationsAdapter: NSObject {
|
||||
|
||||
let TAG = "[CallNotificationsAdapter]"
|
||||
let adaptee: OWSCallNotificationsAdaptee
|
||||
|
||||
override init() {
|
||||
// TODO We can't mix UINotification (NotificationManager) with the UNNotifications
|
||||
// Because registering message categories in one, clobbers the notifications in the other.
|
||||
// We have to first port *all* the existing UINotifications to UNNotifications
|
||||
// which is a good thing to do, but in trying to limit the scope of changes that's been
|
||||
// left out for now.
|
||||
// if #available(iOS 10.0, *) {
|
||||
// adaptee = UserNotificationsAdaptee()
|
||||
// } else {
|
||||
adaptee = NotificationsManager()
|
||||
// }
|
||||
}
|
||||
|
||||
func presentIncomingCall(_ call: SignalCall, callerName: String) {
|
||||
Logger.debug("\(TAG) in \(#function)")
|
||||
adaptee.presentIncomingCall(call, callerName: callerName)
|
||||
}
|
||||
|
||||
func presentMissedCall(_ call: SignalCall, callerName: String) {
|
||||
Logger.debug("\(TAG) in \(#function)")
|
||||
adaptee.presentMissedCall(call, callerName: callerName)
|
||||
}
|
||||
}
|
@ -0,0 +1,117 @@
|
||||
// Created by Michael Kirk on 12/23/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
/**
|
||||
* TODO This is currently unused code. I started implenting new notifications as UserNotifications rather than the deprecated
|
||||
* LocalNotifications before I realized we can't mix and match. Registering notifications for one clobbers the other.
|
||||
* So, for now iOS10 continues to use LocalNotifications until we can port all the NotificationsManager stuff here.
|
||||
*/
|
||||
import Foundation
|
||||
import UserNotifications
|
||||
|
||||
@available(iOS 10.0, *)
|
||||
struct AppNotifications {
|
||||
enum Category {
|
||||
case missedCall
|
||||
|
||||
// Don't forget to update this! We use it to register categories.
|
||||
static let allValues = [ missedCall ]
|
||||
}
|
||||
|
||||
enum Action {
|
||||
case callBack
|
||||
}
|
||||
|
||||
static var allCategories: Set<UNNotificationCategory> {
|
||||
let categories = Category.allValues.map { category($0) }
|
||||
return Set(categories)
|
||||
}
|
||||
|
||||
static func category(_ type: Category) -> UNNotificationCategory {
|
||||
switch type {
|
||||
case .missedCall:
|
||||
return UNNotificationCategory(identifier: "org.whispersystems.signal.AppNotifications.Category.missedCall",
|
||||
actions: [ action(.callBack) ],
|
||||
intentIdentifiers: [],
|
||||
options: [])
|
||||
}
|
||||
}
|
||||
|
||||
static func action(_ type: Action) -> UNNotificationAction {
|
||||
switch type {
|
||||
case .callBack:
|
||||
return UNNotificationAction(identifier: "org.whispersystems.signal.AppNotifications.Action.callBack",
|
||||
title: Strings.Calls.callBackButtonTitle,
|
||||
options: .authenticationRequired)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(iOS 10.0, *)
|
||||
class UserNotificationsAdaptee: NSObject, OWSCallNotificationsAdaptee, UNUserNotificationCenterDelegate {
|
||||
let TAG = "[UserNotificationsAdaptee]"
|
||||
|
||||
private let center: UNUserNotificationCenter
|
||||
|
||||
var previewType: NotificationType {
|
||||
return Environment.getCurrent().preferences.notificationPreviewType()
|
||||
}
|
||||
|
||||
override init() {
|
||||
self.center = UNUserNotificationCenter.current()
|
||||
super.init()
|
||||
|
||||
center.delegate = self
|
||||
|
||||
// FIXME TODO only do this after user has registered.
|
||||
// maybe the PushManager needs a reference to the NotificationsAdapter.
|
||||
requestAuthorization()
|
||||
|
||||
center.setNotificationCategories(AppNotifications.allCategories)
|
||||
}
|
||||
|
||||
func requestAuthorization() {
|
||||
center.requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in
|
||||
if granted {
|
||||
Logger.debug("\(self.TAG) \(#function) succeeded.")
|
||||
} else if error != nil {
|
||||
Logger.error("\(self.TAG) \(#function) failed with error: \(error!)")
|
||||
} else {
|
||||
Logger.error("\(self.TAG) \(#function) failed without error.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - OWSCallNotificationsAdaptee
|
||||
|
||||
public func presentIncomingCall(_ call: SignalCall, callerName: String) {
|
||||
Logger.debug("\(TAG) \(#function) is no-op, because it's handled with callkit.")
|
||||
// TODO since CallKit doesn't currently work on the simulator,
|
||||
// we could implement UNNotifications for simulator testing.
|
||||
}
|
||||
|
||||
public func presentMissedCall(_ call: SignalCall, callerName: String) {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
|
||||
let content = UNMutableNotificationContent()
|
||||
// TODO group by thread identifier
|
||||
// content.threadIdentifier = threadId
|
||||
|
||||
let notificationBody = { () -> String in
|
||||
switch previewType {
|
||||
case .noNameNoPreview:
|
||||
return Strings.Calls.missedCallNotificationBody
|
||||
case .nameNoPreview, .namePreview:
|
||||
let format = Strings.Calls.missedCallNotificationBodyWithCallerName
|
||||
return String(format: format, callerName)
|
||||
}}()
|
||||
|
||||
content.body = notificationBody
|
||||
content.sound = UNNotificationSound.default()
|
||||
content.categoryIdentifier = AppNotifications.category(.missedCall).identifier
|
||||
|
||||
let request = UNNotificationRequest.init(identifier: call.localId.uuidString, content: content, trigger: nil)
|
||||
|
||||
center.add(request)
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
// Created by Michael Kirk on 12/29/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc class Strings: NSObject {
|
||||
@objc class Calls: NSObject {
|
||||
static let callBackButtonTitle = NSLocalizedString("CALLBACK_BUTTON_TITLE", comment: "notification action")
|
||||
static let missedCallNotificationBody = NSLocalizedString("MISSED_CALL", comment: "notification title")
|
||||
static let missedCallNotificationBodyWithCallerName = NSLocalizedString("MSGVIEW_MISSED_CALL", comment: "notification title. Embeds {{Caller's Name}}")
|
||||
}
|
||||
}
|
@ -0,0 +1,929 @@
|
||||
// Created by Michael Kirk on 11/11/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
import PromiseKit
|
||||
import WebRTC
|
||||
|
||||
/**
|
||||
* ## Call Setup (Signaling) Flow
|
||||
*
|
||||
* ## Key
|
||||
* - SS: Message sent via Signal Service
|
||||
* - DC: Message sent via WebRTC Data Channel
|
||||
*
|
||||
* | Caller | Callee |
|
||||
* +----------------------------+-------------------------+
|
||||
* handleOutgoingCall --[SS.CallOffer]-->
|
||||
* and start storing ICE updates
|
||||
*
|
||||
* Received call offer
|
||||
* Send call answer
|
||||
* <--[SS.CallAnswer]--
|
||||
* Start sending ICE updates immediately
|
||||
* <--[SS.ICEUpdates]--
|
||||
*
|
||||
* Received CallAnswer,
|
||||
* so send any stored ice updates
|
||||
* --[SS.ICEUpdates]-->
|
||||
*
|
||||
* Once compatible ICE updates have been exchanged...
|
||||
* (ICE Connected)
|
||||
*
|
||||
* Show remote ringing UI
|
||||
* Connect to offered Data Channel
|
||||
* Show incoming call UI.
|
||||
*
|
||||
* Answers Call
|
||||
* send connected message
|
||||
* <--[DC.ConnectedMesage]--
|
||||
* Received connected message
|
||||
* Show Call is connected.
|
||||
*/
|
||||
|
||||
enum CallError: Error {
|
||||
case providerReset
|
||||
case assertionError(description: String)
|
||||
case disconnected
|
||||
case externalError(underlyingError: Error)
|
||||
case timeout(description: String)
|
||||
}
|
||||
|
||||
// FIXME TODO do we need to timeout?
|
||||
fileprivate let timeoutSeconds = 60
|
||||
|
||||
@objc class CallService: NSObject, RTCDataChannelDelegate, RTCPeerConnectionDelegate {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
let TAG = "[CallService]"
|
||||
|
||||
// MARK: Dependencies
|
||||
|
||||
let accountManager: AccountManager
|
||||
let messageSender: MessageSender
|
||||
var callUIAdapter: CallUIAdapter!
|
||||
|
||||
// MARK: Class
|
||||
|
||||
static let fallbackIceServer = RTCIceServer(urlStrings: ["stun:stun1.l.google.com:19302"])
|
||||
|
||||
// Synchronize call signaling on the callSignalingQueue to make sure any appropriate requisite state is set.
|
||||
static let signalingQueue = DispatchQueue(label: "CallServiceSignalingQueue")
|
||||
|
||||
// MARK: Ivars
|
||||
|
||||
var peerConnectionClient: PeerConnectionClient?
|
||||
// TODO move thread into SignalCall? Or refactor messageSender to take SignalRecipient
|
||||
var thread: TSContactThread?
|
||||
var call: SignalCall?
|
||||
var sendIceUpdatesImmediately = true
|
||||
var pendingIceUpdateMessages = [OWSCallIceUpdateMessage]()
|
||||
var incomingCallPromise: Promise<Void>?
|
||||
|
||||
// Used to coordinate promises across delegate methods
|
||||
var fulfillCallConnectedPromise: (()->())?
|
||||
|
||||
required init(accountManager: AccountManager, contactsManager: OWSContactsManager, messageSender: MessageSender, notificationsAdapter: CallNotificationsAdapter) {
|
||||
self.accountManager = accountManager
|
||||
self.messageSender = messageSender
|
||||
|
||||
super.init()
|
||||
|
||||
self.callUIAdapter = CallUIAdapter(callService: self, contactsManager: contactsManager, notificationsAdapter: notificationsAdapter)
|
||||
}
|
||||
|
||||
// MARK: - Class Methods
|
||||
|
||||
// MARK: Notifications
|
||||
|
||||
// Wrapping these class constants in a method to make it accessible to objc
|
||||
class func callServiceActiveCallNotificationName() -> String {
|
||||
return "CallServiceActiveCallNotification"
|
||||
}
|
||||
|
||||
// MARK: - Service Actions
|
||||
|
||||
// Unless otherwise documented, these `handleXXX` methods expect to be called on the SignalingQueue to coordinate
|
||||
// state across calls.
|
||||
|
||||
/**
|
||||
* Initiate an outgoing call.
|
||||
*/
|
||||
public func handleOutgoingCall(_ call: SignalCall) -> Promise<Void> {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
self.call = call
|
||||
|
||||
let thread = TSContactThread.getOrCreateThread(contactId: call.remotePhoneNumber)
|
||||
self.thread = thread
|
||||
|
||||
sendIceUpdatesImmediately = false
|
||||
pendingIceUpdateMessages = []
|
||||
|
||||
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(), withCallNumber: call.remotePhoneNumber, callType: RPRecentCallTypeOutgoing, in: thread)
|
||||
callRecord.save()
|
||||
|
||||
guard self.peerConnectionClient == nil else {
|
||||
let errorDescription = "\(TAG) peerconnection was unexpectedly already set."
|
||||
Logger.error(errorDescription)
|
||||
call.state = .localFailure
|
||||
return Promise(error: CallError.assertionError(description: errorDescription))
|
||||
}
|
||||
|
||||
return getIceServers().then(on: CallService.signalingQueue) { iceServers -> Promise<HardenedRTCSessionDescription> in
|
||||
Logger.debug("\(self.TAG) got ice servers:\(iceServers)")
|
||||
let peerConnectionClient = PeerConnectionClient(iceServers: iceServers, peerConnectionDelegate: self)
|
||||
self.peerConnectionClient = peerConnectionClient
|
||||
|
||||
// When calling, it's our responsibility to create the DataChannel. Receivers will not have to do this explicitly.
|
||||
self.peerConnectionClient!.createSignalingDataChannel(delegate: self)
|
||||
|
||||
return self.peerConnectionClient!.createOffer()
|
||||
}.then(on: CallService.signalingQueue) { (sessionDescription: HardenedRTCSessionDescription) -> Promise<Void> in
|
||||
return self.peerConnectionClient!.setLocalSessionDescription(sessionDescription).then(on: CallService.signalingQueue) {
|
||||
let offerMessage = OWSCallOfferMessage(callId: call.signalingId, sessionDescription: sessionDescription.sdp)
|
||||
let callMessage = OWSOutgoingCallMessage(thread: thread, offerMessage: offerMessage)
|
||||
return self.sendMessage(callMessage)
|
||||
}
|
||||
}.catch(on: CallService.signalingQueue) { error in
|
||||
Logger.error("\(self.TAG) placing call failed with error: \(error)")
|
||||
|
||||
if let callError = error as? CallError {
|
||||
self.handleFailedCall(error: callError)
|
||||
} else {
|
||||
let externalError = CallError.externalError(underlyingError: error)
|
||||
self.handleFailedCall(error: externalError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by the call initiator after receiving a CallAnswer from the callee.
|
||||
*/
|
||||
public func handleReceivedAnswer(thread: TSContactThread, callId: UInt64, sessionDescription: String) {
|
||||
Logger.debug("\(TAG) received call answer for call: \(callId) thread: \(thread)")
|
||||
assertOnSignalingQueue()
|
||||
|
||||
guard let call = self.call else {
|
||||
handleFailedCall(error: .assertionError(description:"call was unexpectedly nil in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
guard call.signalingId == callId else {
|
||||
let description: String = "received answer for call: \(callId) but current call has id: \(call.signalingId)"
|
||||
handleFailedCall(error: .assertionError(description: description))
|
||||
return
|
||||
}
|
||||
|
||||
// Now that we know the recipient trusts our identity, we no longer need to enqueue ICE updates.
|
||||
self.sendIceUpdatesImmediately = true
|
||||
|
||||
if pendingIceUpdateMessages.count > 0 {
|
||||
let callMessage = OWSOutgoingCallMessage(thread: thread, iceUpdateMessages: pendingIceUpdateMessages)
|
||||
_ = sendMessage(callMessage).catch { error in
|
||||
Logger.error("\(self.TAG) failed to send ice updates in \(#function) with error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
guard let peerConnectionClient = self.peerConnectionClient else {
|
||||
handleFailedCall(error: CallError.assertionError(description: "peerConnectionClient was unexpectedly nil in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
let sessionDescription = RTCSessionDescription(type: .answer, sdp: sessionDescription)
|
||||
_ = peerConnectionClient.setRemoteSessionDescription(sessionDescription).then {
|
||||
Logger.debug("\(self.TAG) successfully set remote description")
|
||||
}.catch(on: CallService.signalingQueue) { error in
|
||||
if let callError = error as? CallError {
|
||||
self.handleFailedCall(error: callError)
|
||||
} else {
|
||||
let externalError = CallError.externalError(underlyingError: error)
|
||||
self.handleFailedCall(error: externalError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handleLocalBusyCall(_ call: SignalCall, thread: TSContactThread) {
|
||||
Logger.debug("\(TAG) \(#function) for call: \(call) thread: \(thread)")
|
||||
assertOnSignalingQueue()
|
||||
|
||||
let busyMessage = OWSCallBusyMessage(callId: call.signalingId)
|
||||
let callMessage = OWSOutgoingCallMessage(thread: thread, busyMessage: busyMessage)
|
||||
_ = sendMessage(callMessage)
|
||||
|
||||
handleMissedCall(call, thread: thread)
|
||||
}
|
||||
|
||||
public func handleMissedCall(_ call: SignalCall, thread: TSContactThread) {
|
||||
// Insert missed call record
|
||||
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(),
|
||||
withCallNumber: thread.contactIdentifier(),
|
||||
callType: RPRecentCallTypeMissed,
|
||||
in: thread)
|
||||
callRecord.save()
|
||||
|
||||
self.callUIAdapter.reportMissedCall(call)
|
||||
}
|
||||
|
||||
public func handleRemoteBusy(thread: TSContactThread) {
|
||||
Logger.debug("\(TAG) \(#function) for thread: \(thread)")
|
||||
assertOnSignalingQueue()
|
||||
|
||||
guard let call = self.call else {
|
||||
handleFailedCall(error: .assertionError(description: "call unexpectedly nil in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
call.state = .remoteBusy
|
||||
terminateCall()
|
||||
}
|
||||
|
||||
private func isBusy() -> Bool {
|
||||
// TODO CallManager adapter?
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Received an incoming call offer. We still have to complete setting up the Signaling channel before we notify
|
||||
* the user of an incoming call.
|
||||
*/
|
||||
public func handleReceivedOffer(thread: TSContactThread, callId: UInt64, sessionDescription callerSessionDescription: String) {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
Logger.verbose("\(TAG) receivedCallOffer for thread:\(thread)")
|
||||
let newCall = SignalCall.incomingCall(localId: UUID(), remotePhoneNumber: thread.contactIdentifier(), signalingId: callId)
|
||||
|
||||
guard call == nil else {
|
||||
// TODO on iOS10+ we can use CallKit to swap calls rather than just returning busy immediately.
|
||||
Logger.verbose("\(TAG) receivedCallOffer for thread: \(thread) but we're already in call: \(call)")
|
||||
|
||||
handleLocalBusyCall(newCall, thread: thread)
|
||||
return
|
||||
}
|
||||
|
||||
self.thread = thread
|
||||
call = newCall
|
||||
|
||||
let backgroundTask = UIApplication.shared.beginBackgroundTask {
|
||||
let timeout = CallError.timeout(description: "background task time ran out before call connected.")
|
||||
CallService.signalingQueue.async {
|
||||
self.handleFailedCall(error: timeout)
|
||||
}
|
||||
}
|
||||
|
||||
incomingCallPromise = firstly {
|
||||
return getIceServers()
|
||||
}.then(on: CallService.signalingQueue) { (iceServers: [RTCIceServer]) -> Promise<HardenedRTCSessionDescription> in
|
||||
// FIXME for first time call recipients I think we'll see mic/camera permission requests here,
|
||||
// even though, from the users perspective, no incoming call is yet visible.
|
||||
self.peerConnectionClient = PeerConnectionClient(iceServers: iceServers, peerConnectionDelegate: self)
|
||||
|
||||
let offerSessionDescription = RTCSessionDescription(type: .offer, sdp: callerSessionDescription)
|
||||
let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)
|
||||
|
||||
// Find a sessionDescription compatible with my constraints and the remote sessionDescription
|
||||
return self.peerConnectionClient!.negotiateSessionDescription(remoteDescription: offerSessionDescription, constraints: constraints)
|
||||
}.then(on: CallService.signalingQueue) { (negotiatedSessionDescription: HardenedRTCSessionDescription) in
|
||||
// TODO? WebRtcCallService.this.lockManager.updatePhoneState(LockManager.PhoneState.PROCESSING);
|
||||
Logger.debug("\(self.TAG) set the remote description")
|
||||
|
||||
let answerMessage = OWSCallAnswerMessage(callId: newCall.signalingId, sessionDescription: negotiatedSessionDescription.sdp)
|
||||
let callAnswerMessage = OWSOutgoingCallMessage(thread: thread, answerMessage: answerMessage)
|
||||
|
||||
return self.sendMessage(callAnswerMessage)
|
||||
}.then(on: CallService.signalingQueue) {
|
||||
Logger.debug("\(self.TAG) successfully sent callAnswerMessage")
|
||||
|
||||
let (promise, fulfill, _) = Promise<Void>.pending()
|
||||
|
||||
let timeout: Promise<Void> = after(interval: TimeInterval(timeoutSeconds)).then { () -> Void in
|
||||
// rejecting a promise by throwing is safely a no-op if the promise has already been fulfilled
|
||||
throw CallError.timeout(description: "timed out waiting for call to connect")
|
||||
}
|
||||
|
||||
// This will be fulfilled (potentially) by the RTCDataChannel delegate method
|
||||
self.fulfillCallConnectedPromise = fulfill
|
||||
|
||||
return race(promise, timeout)
|
||||
}.catch(on: CallService.signalingQueue) { error in
|
||||
if let callError = error as? CallError {
|
||||
self.handleFailedCall(error: callError)
|
||||
} else {
|
||||
let externalError = CallError.externalError(underlyingError: error)
|
||||
self.handleFailedCall(error: externalError)
|
||||
}
|
||||
}.always {
|
||||
Logger.debug("\(self.TAG) ending background task awaiting inbound call connection")
|
||||
UIApplication.shared.endBackgroundTask(backgroundTask)
|
||||
}
|
||||
}
|
||||
|
||||
public func handleCallBack(recipientId: String) {
|
||||
// TODO #function is called from objc, how to access swift defiend dispatch queue (OS_dispatch_queue)
|
||||
//assertOnSignalingQueue()
|
||||
|
||||
guard self.call == nil else {
|
||||
Logger.error("\(TAG) unexpectedly found an existing call when trying to call back: \(recipientId)")
|
||||
return
|
||||
}
|
||||
|
||||
// Because we may not be on signalingQueue (because this method is called from Objc which doesn't have
|
||||
// access to signalingQueue (that I can find). FIXME?
|
||||
type(of: self).signalingQueue.async {
|
||||
let call = self.callUIAdapter.startOutgoingCall(handle: recipientId)
|
||||
self.callUIAdapter.showCall(call)
|
||||
}
|
||||
}
|
||||
|
||||
public func handleRemoteAddedIceCandidate(thread: TSContactThread, callId: UInt64, sdp: String, lineIndex: Int32, mid: String) {
|
||||
assertOnSignalingQueue()
|
||||
Logger.debug("\(TAG) called \(#function)")
|
||||
|
||||
guard self.thread != nil else {
|
||||
handleFailedCall(error: .assertionError(description: "ignoring remote ice update for thread: \(thread.uniqueId) since there is no current thread. TODO: Signaling messages out of order?"))
|
||||
return
|
||||
}
|
||||
|
||||
guard thread.contactIdentifier() == self.thread!.contactIdentifier() else {
|
||||
handleFailedCall(error: .assertionError(description: "ignoring remote ice update for thread: \(thread.uniqueId) since the current call is for thread: \(self.thread!.uniqueId)"))
|
||||
return
|
||||
}
|
||||
|
||||
guard let call = self.call else {
|
||||
handleFailedCall(error: .assertionError(description: "ignoring remote ice update for callId: \(callId), since there is no current call."))
|
||||
return
|
||||
}
|
||||
|
||||
guard call.signalingId == callId else {
|
||||
handleFailedCall(error: .assertionError(description: "ignoring remote ice update for call: \(callId) since the current call is: \(call.signalingId)"))
|
||||
return
|
||||
}
|
||||
|
||||
guard let peerConnectionClient = self.peerConnectionClient else {
|
||||
handleFailedCall(error: .assertionError(description: "ignoring remote ice update for thread: \(thread) since the current call hasn't initialized it's peerConnectionClient"))
|
||||
return
|
||||
}
|
||||
|
||||
peerConnectionClient.addIceCandidate(RTCIceCandidate(sdp: sdp, sdpMLineIndex: lineIndex, sdpMid: mid))
|
||||
}
|
||||
|
||||
private func handleLocalAddedIceCandidate(_ iceCandidate: RTCIceCandidate) {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
guard let call = self.call else {
|
||||
handleFailedCall(error: .assertionError(description: "ignoring local ice candidate, since there is no current call."))
|
||||
return
|
||||
}
|
||||
|
||||
guard call.state != .idle else {
|
||||
handleFailedCall(error: .assertionError(description: "ignoring local ice candidate, since call is now idle."))
|
||||
return
|
||||
}
|
||||
|
||||
guard let thread = self.thread else {
|
||||
handleFailedCall(error: .assertionError(description: "ignoring local ice candidate, because there was no current TSContactThread."))
|
||||
return
|
||||
}
|
||||
|
||||
let iceUpdateMessage = OWSCallIceUpdateMessage(callId: call.signalingId, sdp: iceCandidate.sdp, sdpMLineIndex: iceCandidate.sdpMLineIndex, sdpMid: iceCandidate.sdpMid)
|
||||
|
||||
if self.sendIceUpdatesImmediately {
|
||||
let callMessage = OWSOutgoingCallMessage(thread: thread, iceUpdateMessage: iceUpdateMessage)
|
||||
_ = sendMessage(callMessage)
|
||||
} else {
|
||||
// For outgoing messages, we wait to send ice updates until we're sure client received our call message.
|
||||
// e.g. if the client has blocked our message due to an identity change, we'd otherwise
|
||||
// bombard them with a bunch *more* undecipherable messages.
|
||||
Logger.debug("\(TAG) enqueuing iceUpdate until we receive call answer")
|
||||
self.pendingIceUpdateMessages.append(iceUpdateMessage)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private func handleIceConnected() {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
Logger.debug("\(TAG) in \(#function)")
|
||||
|
||||
guard let call = self.call else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) ignoring \(#function) since there is no current call."))
|
||||
return
|
||||
}
|
||||
|
||||
guard let thread = self.thread else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) ignoring \(#function) since there is no current thread."))
|
||||
return
|
||||
}
|
||||
|
||||
guard let peerConnectionClient = self.peerConnectionClient else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) ignoring \(#function) since there is no current peerConnectionClient."))
|
||||
return
|
||||
}
|
||||
|
||||
switch call.state {
|
||||
case .dialing:
|
||||
call.state = .remoteRinging
|
||||
case .answering:
|
||||
call.state = .localRinging
|
||||
self.callUIAdapter.reportIncomingCall(call, thread: thread, audioManager: peerConnectionClient)
|
||||
self.fulfillCallConnectedPromise?()
|
||||
case .remoteRinging:
|
||||
Logger.info("\(TAG) call alreading ringing. Ignoring \(#function)")
|
||||
default:
|
||||
Logger.debug("\(TAG) unexpected call state for \(#function): \(call.state)")
|
||||
}
|
||||
}
|
||||
|
||||
public func handleRemoteHangup(thread: TSContactThread) {
|
||||
Logger.debug("\(TAG) in \(#function)")
|
||||
assertOnSignalingQueue()
|
||||
|
||||
guard thread.contactIdentifier() == self.thread?.contactIdentifier() else {
|
||||
// This can safely be ignored.
|
||||
// We don't want to fail the current call because an old call was slow to send us the hangup message.
|
||||
Logger.warn("\(TAG) ignoring hangup for thread:\(thread) which is not the current thread: \(self.thread)")
|
||||
return
|
||||
}
|
||||
|
||||
guard let call = self.call else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) call was unexpectedly nil in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
switch call.state {
|
||||
case .idle, .dialing, .answering, .localRinging, .localFailure, .remoteBusy, .remoteRinging:
|
||||
handleMissedCall(call, thread: thread)
|
||||
case .connected, .localHangup, .remoteHangup:
|
||||
Logger.info("\(TAG) call is finished.")
|
||||
}
|
||||
|
||||
call.state = .remoteHangup
|
||||
// Notify UI
|
||||
callUIAdapter.endCall(call)
|
||||
|
||||
// self.call is nil'd in `terminateCall`, so it's important we update it's state *before* calling `terminateCall`
|
||||
terminateCall()
|
||||
}
|
||||
|
||||
public func handleAnswerCall(localId: UUID) {
|
||||
// TODO #function is called from objc, how to access swift defiend dispatch queue (OS_dispatch_queue)
|
||||
//assertOnSignalingQueue()
|
||||
|
||||
guard let call = self.call else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) call was unexpectedly nil in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
guard call.localId == localId else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) callLocalId:\(localId) doesn't match current calls: \(call.localId)"))
|
||||
return
|
||||
}
|
||||
|
||||
// Because we may not be on signalingQueue (because this method is called from Objc which doesn't have
|
||||
// access to signalingQueue (that I can find). FIXME?
|
||||
type(of: self).signalingQueue.async {
|
||||
self.handleAnswerCall(call)
|
||||
}
|
||||
}
|
||||
|
||||
public func handleAnswerCall(_ call: SignalCall) {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
Logger.debug("\(TAG) in \(#function)")
|
||||
|
||||
guard self.call != nil else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) ignoring \(#function) since there is no current call"))
|
||||
return
|
||||
}
|
||||
|
||||
guard call == self.call! else {
|
||||
// This could conceivably happen if the other party of an old call was slow to send us their answer
|
||||
// and we've subsequently engaged in another call. Don't kill the current call, but just ignore it.
|
||||
Logger.warn("\(TAG) ignoring \(#function) for call other than current call")
|
||||
return
|
||||
}
|
||||
|
||||
guard let thread = self.thread else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) ignoring \(#function) for call other than current call"))
|
||||
return
|
||||
}
|
||||
|
||||
guard let peerConnectionClient = self.peerConnectionClient else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) missing peerconnection client in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(), withCallNumber: call.remotePhoneNumber, callType: RPRecentCallTypeIncoming, in: thread)
|
||||
callRecord.save()
|
||||
|
||||
callUIAdapter.answerCall(call)
|
||||
|
||||
let message = DataChannelMessage.forConnected(callId: call.signalingId)
|
||||
if peerConnectionClient.sendDataChannelMessage(data: message.asData()) {
|
||||
Logger.debug("\(TAG) sendDataChannelMessage returned true")
|
||||
} else {
|
||||
Logger.warn("\(TAG) sendDataChannelMessage returned false")
|
||||
}
|
||||
|
||||
handleConnectedCall(call)
|
||||
}
|
||||
|
||||
func handleConnectedCall(_ call: SignalCall) {
|
||||
Logger.debug("\(TAG) in \(#function)")
|
||||
assertOnSignalingQueue()
|
||||
|
||||
guard let peerConnectionClient = self.peerConnectionClient else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) peerConnectionClient unexpectedly nil in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
call.state = .connected
|
||||
|
||||
// We don't risk transmitting any media until the remote client has admitted to being connected.
|
||||
peerConnectionClient.setAudioEnabled(enabled: true)
|
||||
peerConnectionClient.setVideoEnabled(enabled: call.hasVideo)
|
||||
}
|
||||
|
||||
public func handleDeclineCall(localId: UUID) {
|
||||
// #function is called from objc, how to access swift defiend dispatch queue (OS_dispatch_queue)
|
||||
//assertOnSignalingQueue()
|
||||
|
||||
guard let call = self.call else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) call was unexpectedly nil in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
guard call.localId == localId else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) callLocalId:\(localId) doesn't match current calls: \(call.localId)"))
|
||||
return
|
||||
}
|
||||
|
||||
// Because we may not be on signalingQueue (because this method is called from Objc which doesn't have
|
||||
// access to signalingQueue (that I can find). FIXME?
|
||||
type(of: self).signalingQueue.async {
|
||||
self.handleDeclineCall(call)
|
||||
}
|
||||
}
|
||||
|
||||
public func handleDeclineCall(_ call: SignalCall) {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
Logger.info("\(TAG) in \(#function)")
|
||||
|
||||
// Currently we just handle this as a hangup. But we could offer more descriptive action. e.g. DataChannel message
|
||||
handleLocalHungupCall(call)
|
||||
}
|
||||
|
||||
func handleLocalHungupCall(_ call: SignalCall) {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
guard self.call != nil else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) ignoring \(#function) since there is no current call"))
|
||||
return
|
||||
}
|
||||
|
||||
guard call == self.call! else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) ignoring \(#function) for call other than current call"))
|
||||
return
|
||||
}
|
||||
|
||||
guard let peerConnectionClient = self.peerConnectionClient else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) missing peerconnection client in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
guard let thread = self.thread else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) missing thread in \(#function)"))
|
||||
return
|
||||
}
|
||||
|
||||
call.state = .localHangup
|
||||
|
||||
// TODO something like this lifted from Signal-Android.
|
||||
// this.accountManager.cancelInFlightRequests();
|
||||
// this.messageSender.cancelInFlightRequests();
|
||||
|
||||
// If the call is connected, we can send the hangup via the data channel.
|
||||
let message = DataChannelMessage.forHangup(callId: call.signalingId)
|
||||
if peerConnectionClient.sendDataChannelMessage(data: message.asData()) {
|
||||
Logger.debug("\(TAG) sendDataChannelMessage returned true")
|
||||
} else {
|
||||
Logger.warn("\(TAG) sendDataChannelMessage returned false")
|
||||
}
|
||||
|
||||
// If the call hasn't started yet, we don't have a data channel to communicate the hang up. Use Signal Service Message.
|
||||
let hangupMessage = OWSCallHangupMessage(callId: call.signalingId)
|
||||
let callMessage = OWSOutgoingCallMessage(thread: thread, hangupMessage: hangupMessage)
|
||||
_ = sendMessage(callMessage).then(on: CallService.signalingQueue) {
|
||||
Logger.debug("\(self.TAG) successfully sent hangup call message to \(thread)")
|
||||
}.catch(on: CallService.signalingQueue) { error in
|
||||
Logger.error("\(self.TAG) failed to send hangup call message to \(thread) with error: \(error)")
|
||||
}
|
||||
|
||||
terminateCall()
|
||||
}
|
||||
|
||||
func handleToggledMute(isMuted: Bool) {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
guard let peerConnectionClient = self.peerConnectionClient else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) peerConnectionClient unexpectedly nil in \(#function)"))
|
||||
return
|
||||
}
|
||||
peerConnectionClient.setAudioEnabled(enabled: !isMuted)
|
||||
}
|
||||
|
||||
private func handleDataChannelMessage(_ message: OWSWebRTCProtosData) {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
guard let call = self.call else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) received data message, but there is no current call. Ignoring."))
|
||||
return
|
||||
}
|
||||
|
||||
if message.hasConnected() {
|
||||
Logger.debug("\(TAG) remote participant sent Connected via data channel")
|
||||
|
||||
let connected = message.connected!
|
||||
|
||||
guard connected.id == call.signalingId else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) received connected message for call with id:\(connected.id) but current call has id:\(call.signalingId)"))
|
||||
return
|
||||
}
|
||||
|
||||
handleConnectedCall(call)
|
||||
|
||||
} else if message.hasHangup() {
|
||||
Logger.debug("\(TAG) remote participant sent Hangup via data channel")
|
||||
|
||||
let hangup = message.hangup!
|
||||
|
||||
guard hangup.id == call.signalingId else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) received hangup message for call with id:\(hangup.id) but current call has id:\(call.signalingId)"))
|
||||
return
|
||||
}
|
||||
|
||||
guard let thread = self.thread else {
|
||||
handleFailedCall(error: .assertionError(description:"\(TAG) current contact thread is unexpectedly nil when receiving hangup DataChannelMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
handleRemoteHangup(thread: thread)
|
||||
} else if message.hasVideoStreamingStatus() {
|
||||
Logger.debug("\(TAG) remote participant sent VideoStreamingStatus via data channel")
|
||||
|
||||
// TODO: translate from java
|
||||
// Intent intent = new Intent(this, WebRtcCallService.class);
|
||||
// intent.setAction(ACTION_REMOTE_VIDEO_MUTE);
|
||||
// intent.putExtra(EXTRA_CALL_ID, dataMessage.getVideoStreamingStatus().getId());
|
||||
// intent.putExtra(EXTRA_MUTE, !dataMessage.getVideoStreamingStatus().getEnabled());
|
||||
// startService(intent);
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Helpers
|
||||
|
||||
private func assertOnSignalingQueue() {
|
||||
if #available(iOS 10.0, *) {
|
||||
dispatchPrecondition(condition: .onQueue(type(of: self).signalingQueue))
|
||||
} else {
|
||||
// Skipping check on <iOS10, since syntax is different and it's just a development convenience.
|
||||
}
|
||||
}
|
||||
|
||||
private func getIceServers() -> Promise<[RTCIceServer]> {
|
||||
|
||||
return firstly {
|
||||
return accountManager.getTurnServerInfo()
|
||||
}.then(on: CallService.signalingQueue) { turnServerInfo -> [RTCIceServer] in
|
||||
Logger.debug("\(self.TAG) got turn server urls: \(turnServerInfo.urls)")
|
||||
|
||||
return turnServerInfo.urls.map { url in
|
||||
if url.hasPrefix("turn") {
|
||||
// only pass credentials for "turn:" servers.
|
||||
return RTCIceServer(urlStrings: [url], username: turnServerInfo.username, credential: turnServerInfo.password)
|
||||
} else {
|
||||
return RTCIceServer(urlStrings: [url])
|
||||
}
|
||||
} + [CallService.fallbackIceServer]
|
||||
}
|
||||
}
|
||||
|
||||
private func sendMessage(_ message: OWSOutgoingCallMessage) -> Promise<Void> {
|
||||
return Promise { fulfill, reject in
|
||||
self.messageSender.send(message, success: fulfill, failure: reject)
|
||||
}
|
||||
}
|
||||
|
||||
public func handleFailedCall(error: CallError) {
|
||||
assertOnSignalingQueue()
|
||||
Logger.error("\(TAG) call failed with error: \(error)")
|
||||
|
||||
// It's essential to set call.state before terminateCall, because terminateCall nils self.call
|
||||
call?.error = error
|
||||
call?.state = .localFailure
|
||||
|
||||
terminateCall()
|
||||
}
|
||||
|
||||
private func terminateCall() {
|
||||
assertOnSignalingQueue()
|
||||
|
||||
// lockManager.updatePhoneState(LockManager.PhoneState.PROCESSING);
|
||||
// NotificationBarManager.setCallEnded(this);
|
||||
//
|
||||
// incomingRinger.stop();
|
||||
// outgoingRinger.stop();
|
||||
// outgoingRinger.playDisconnected();
|
||||
//
|
||||
// if (peerConnection != null) {
|
||||
// peerConnection.dispose();
|
||||
// peerConnection = null;
|
||||
// }
|
||||
//
|
||||
// if (eglBase != null && localRenderer != null && remoteRenderer != null) {
|
||||
// localRenderer.release();
|
||||
// remoteRenderer.release();
|
||||
// eglBase.release();
|
||||
// }
|
||||
//
|
||||
// shutdownAudio();
|
||||
//
|
||||
// this.callState = CallState.STATE_IDLE;
|
||||
// this.recipient = null;
|
||||
// this.callId = null;
|
||||
// this.audioEnabled = false;
|
||||
// this.videoEnabled = false;
|
||||
// this.pendingIceUpdates = null;
|
||||
// lockManager.updatePhoneState(LockManager.PhoneState.IDLE);
|
||||
|
||||
peerConnectionClient?.terminate()
|
||||
peerConnectionClient = nil
|
||||
call = nil
|
||||
thread = nil
|
||||
incomingCallPromise = nil
|
||||
sendIceUpdatesImmediately = true
|
||||
pendingIceUpdateMessages = []
|
||||
}
|
||||
|
||||
// MARK: - RTCDataChannelDelegate
|
||||
|
||||
/** The data channel state changed. */
|
||||
public func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) {
|
||||
Logger.debug("\(TAG) dataChannelDidChangeState: \(dataChannel)")
|
||||
// SignalingQueue.dispatch.async {}
|
||||
}
|
||||
|
||||
/** The data channel successfully received a data buffer. */
|
||||
public func dataChannel(_ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer) {
|
||||
Logger.debug("\(TAG) dataChannel didReceiveMessageWith buffer:\(buffer)")
|
||||
|
||||
guard let dataChannelMessage = OWSWebRTCProtosData.parse(from:buffer.data) else {
|
||||
// TODO can't proto parsings throw an exception? Is it just being lost in the Objc->Swift?
|
||||
Logger.error("\(TAG) failed to parse dataProto")
|
||||
return
|
||||
}
|
||||
|
||||
CallService.signalingQueue.async {
|
||||
self.handleDataChannelMessage(dataChannelMessage)
|
||||
}
|
||||
}
|
||||
|
||||
/** The data channel's |bufferedAmount| changed. */
|
||||
public func dataChannel(_ dataChannel: RTCDataChannel, didChangeBufferedAmount amount: UInt64) {
|
||||
Logger.debug("\(TAG) didChangeBufferedAmount: \(amount)")
|
||||
}
|
||||
|
||||
// MARK: - RTCPeerConnectionDelegate
|
||||
|
||||
/** Called when the SignalingState changed. */
|
||||
public func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {
|
||||
Logger.debug("\(TAG) didChange signalingState:\(stateChanged.debugDescription)")
|
||||
}
|
||||
|
||||
/** Called when media is received on a new stream from remote peer. */
|
||||
public func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {
|
||||
Logger.debug("\(TAG) didAdd stream:\(stream)")
|
||||
}
|
||||
|
||||
/** Called when a remote peer closes a stream. */
|
||||
public func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {
|
||||
Logger.debug("\(TAG) didRemove Stream:\(stream)")
|
||||
}
|
||||
|
||||
/** Called when negotiation is needed, for example ICE has restarted. */
|
||||
public func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {
|
||||
Logger.debug("\(TAG) shouldNegotiate")
|
||||
}
|
||||
|
||||
/** Called any time the IceConnectionState changes. */
|
||||
public func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {
|
||||
Logger.debug("\(TAG) didChange IceConnectionState:\(newState.debugDescription)")
|
||||
|
||||
CallService.signalingQueue.async {
|
||||
switch newState {
|
||||
case .connected, .completed:
|
||||
self.handleIceConnected()
|
||||
case .failed:
|
||||
Logger.warn("\(self.TAG) RTCIceConnection failed.")
|
||||
guard let thread = self.thread else {
|
||||
Logger.error("\(self.TAG) refusing to hangup for failed IceConnection because there is no current thread")
|
||||
return
|
||||
}
|
||||
self.handleFailedCall(error: CallError.disconnected)
|
||||
default:
|
||||
Logger.debug("\(self.TAG) ignoring change IceConnectionState:\(newState.debugDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Called any time the IceGatheringState changes. */
|
||||
public func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {
|
||||
Logger.debug("\(TAG) didChange IceGatheringState:\(newState.debugDescription)")
|
||||
}
|
||||
|
||||
/** New ice candidate has been found. */
|
||||
public func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {
|
||||
Logger.debug("\(TAG) didGenerate IceCandidate:\(candidate.sdp)")
|
||||
CallService.signalingQueue.async {
|
||||
self.handleLocalAddedIceCandidate(candidate)
|
||||
}
|
||||
}
|
||||
|
||||
/** Called when a group of local Ice candidates have been removed. */
|
||||
public func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {
|
||||
Logger.debug("\(TAG) didRemove IceCandidates:\(candidates)")
|
||||
}
|
||||
|
||||
/** New data channel has been opened. */
|
||||
public func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {
|
||||
Logger.debug("\(TAG) didOpen dataChannel:\(dataChannel)")
|
||||
CallService.signalingQueue.async {
|
||||
guard let peerConnectionClient = self.peerConnectionClient else {
|
||||
Logger.error("\(self.TAG) surprised to find nil peerConnectionClient in \(#function)")
|
||||
return
|
||||
}
|
||||
|
||||
Logger.debug("\(self.TAG) set dataChannel")
|
||||
peerConnectionClient.dataChannel = dataChannel
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mark: Pretty Print Objc enums.
|
||||
|
||||
fileprivate extension RTCSignalingState {
|
||||
var debugDescription: String {
|
||||
switch self {
|
||||
case .stable:
|
||||
return "stable"
|
||||
case .haveLocalOffer:
|
||||
return "haveLocalOffer"
|
||||
case .haveLocalPrAnswer:
|
||||
return "haveLocalPrAnswer"
|
||||
case .haveRemoteOffer:
|
||||
return "haveRemoteOffer"
|
||||
case .haveRemotePrAnswer:
|
||||
return "haveRemotePrAnswer"
|
||||
case .closed:
|
||||
return "closed"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate extension RTCIceGatheringState {
|
||||
var debugDescription: String {
|
||||
switch self {
|
||||
case .new:
|
||||
return "new"
|
||||
case .gathering:
|
||||
return "gathering"
|
||||
case .complete:
|
||||
return "complete"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate extension RTCIceConnectionState {
|
||||
var debugDescription: String {
|
||||
switch self {
|
||||
case .new:
|
||||
return "new"
|
||||
case .checking:
|
||||
return "checking"
|
||||
case .connected:
|
||||
return "connected"
|
||||
case .completed:
|
||||
return "completed"
|
||||
case .failed:
|
||||
return "failed"
|
||||
case .disconnected:
|
||||
return "disconnected"
|
||||
case .closed:
|
||||
return "closed"
|
||||
case .count:
|
||||
return "count"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,113 @@
|
||||
// Created by Michael Kirk on 12/8/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
|
||||
class DataChannelMessage {
|
||||
|
||||
private let connected: Connected?
|
||||
private let hangup: Hangup?
|
||||
private let videoStreamingStatus: VideoStreamingStatus?
|
||||
|
||||
private class Connected {
|
||||
let callId: UInt64
|
||||
|
||||
init(callId: UInt64) {
|
||||
self.callId = callId
|
||||
}
|
||||
|
||||
func asProtobuf() -> OWSWebRTCProtosConnected {
|
||||
let builder = OWSWebRTCProtosConnectedBuilder()
|
||||
builder.setId(callId)
|
||||
return builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
private class Hangup {
|
||||
let callId: UInt64
|
||||
|
||||
init(callId: UInt64) {
|
||||
self.callId = callId
|
||||
}
|
||||
|
||||
func asProtobuf() -> OWSWebRTCProtosHangup {
|
||||
let builder = OWSWebRTCProtosHangupBuilder()
|
||||
builder.setId(callId)
|
||||
return builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
private class VideoStreamingStatus {
|
||||
private let callId: UInt64
|
||||
private let enabled: Bool
|
||||
|
||||
init(callId: UInt64, enabled: Bool) {
|
||||
self.callId = callId
|
||||
self.enabled = enabled
|
||||
}
|
||||
|
||||
func asProtobuf() -> OWSWebRTCProtosVideoStreamingStatus {
|
||||
let builder = OWSWebRTCProtosVideoStreamingStatusBuilder()
|
||||
builder.setId(callId)
|
||||
builder.setEnabled(enabled)
|
||||
return builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Init
|
||||
|
||||
private init(connected: Connected) {
|
||||
self.connected = connected
|
||||
self.hangup = nil
|
||||
self.videoStreamingStatus = nil
|
||||
}
|
||||
|
||||
private init(hangup: Hangup) {
|
||||
self.connected = nil
|
||||
self.hangup = hangup
|
||||
self.videoStreamingStatus = nil
|
||||
}
|
||||
|
||||
private init(videoStreamingStatus: VideoStreamingStatus) {
|
||||
self.connected = nil
|
||||
self.hangup = nil
|
||||
self.videoStreamingStatus = videoStreamingStatus
|
||||
}
|
||||
|
||||
// MARK: Factory
|
||||
|
||||
class func forConnected(callId: UInt64) -> DataChannelMessage {
|
||||
return DataChannelMessage(connected:Connected(callId: callId))
|
||||
}
|
||||
|
||||
class func forHangup(callId: UInt64) -> DataChannelMessage {
|
||||
return DataChannelMessage(hangup: Hangup(callId: callId))
|
||||
}
|
||||
|
||||
class func forVideoStreamingStatus(callId: UInt64, enabled: Bool) -> DataChannelMessage {
|
||||
return DataChannelMessage(videoStreamingStatus: VideoStreamingStatus(callId: callId, enabled: enabled))
|
||||
}
|
||||
|
||||
// MARK: Serialization
|
||||
|
||||
func asProtobuf() -> PBGeneratedMessage {
|
||||
let builder = OWSWebRTCProtosDataBuilder()
|
||||
if connected != nil {
|
||||
builder.setConnected(connected!.asProtobuf())
|
||||
}
|
||||
|
||||
if hangup != nil {
|
||||
builder.setHangup(hangup!.asProtobuf())
|
||||
}
|
||||
|
||||
if videoStreamingStatus != nil {
|
||||
builder.setVideoStreamingStatus(videoStreamingStatus!.asProtobuf())
|
||||
}
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
func asData() -> Data {
|
||||
return self.asProtobuf().data()
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
// Created by Michael Kirk on 1/3/17.
|
||||
// Copyright © 2017 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
* Manage call related UI in a pre-CallKit world.
|
||||
*/
|
||||
class NonCallKitCallUIAdaptee: CallUIAdaptee {
|
||||
|
||||
let TAG = "[NonCallKitCallUIAdaptee]"
|
||||
|
||||
let notificationsAdapter: CallNotificationsAdapter
|
||||
let callService: CallService
|
||||
|
||||
required init(callService: CallService, notificationsAdapter: CallNotificationsAdapter) {
|
||||
self.callService = callService
|
||||
self.notificationsAdapter = notificationsAdapter
|
||||
}
|
||||
|
||||
public func startOutgoingCall(_ call: SignalCall) {
|
||||
CallService.signalingQueue.async {
|
||||
_ = self.callService.handleOutgoingCall(call).then {
|
||||
Logger.debug("\(self.TAG) handleOutgoingCall succeeded")
|
||||
}.catch { error in
|
||||
Logger.error("\(self.TAG) handleOutgoingCall failed with error: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func reportIncomingCall(_ call: SignalCall, callerName: String, audioManager: SignalCallAudioManager) {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
|
||||
// present Call View controller
|
||||
let callNotificationName = CallService.callServiceActiveCallNotificationName()
|
||||
NotificationCenter.default.post(name: NSNotification.Name(rawValue: callNotificationName), object: call)
|
||||
|
||||
// present lock screen notification
|
||||
if UIApplication.shared.applicationState == .active {
|
||||
Logger.debug("\(TAG) skipping notification since app is already active.")
|
||||
} else {
|
||||
notificationsAdapter.presentIncomingCall(call, callerName: callerName)
|
||||
}
|
||||
}
|
||||
|
||||
public func reportMissedCall(_ call: SignalCall, callerName: String) {
|
||||
notificationsAdapter.presentMissedCall(call, callerName: callerName)
|
||||
}
|
||||
|
||||
public func answerCall(_ call: SignalCall) {
|
||||
// NO-OP
|
||||
}
|
||||
|
||||
public func declineCall(_ call: SignalCall) {
|
||||
CallService.signalingQueue.async {
|
||||
self.callService.handleDeclineCall(call)
|
||||
}
|
||||
}
|
||||
|
||||
public func endCall(_ call: SignalCall) {
|
||||
CallService.signalingQueue.async {
|
||||
self.callService.handleLocalHungupCall(call)
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,305 @@
|
||||
// Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
|
||||
#import <ProtocolBuffers/ProtocolBuffers.h>
|
||||
|
||||
// @@protoc_insertion_point(imports)
|
||||
|
||||
@class OWSWebRTCProtosConnected;
|
||||
@class OWSWebRTCProtosConnectedBuilder;
|
||||
@class OWSWebRTCProtosData;
|
||||
@class OWSWebRTCProtosDataBuilder;
|
||||
@class OWSWebRTCProtosHangup;
|
||||
@class OWSWebRTCProtosHangupBuilder;
|
||||
@class OWSWebRTCProtosVideoStreamingStatus;
|
||||
@class OWSWebRTCProtosVideoStreamingStatusBuilder;
|
||||
@class ObjectiveCFileOptions;
|
||||
@class ObjectiveCFileOptionsBuilder;
|
||||
@class PBDescriptorProto;
|
||||
@class PBDescriptorProtoBuilder;
|
||||
@class PBDescriptorProtoExtensionRange;
|
||||
@class PBDescriptorProtoExtensionRangeBuilder;
|
||||
@class PBEnumDescriptorProto;
|
||||
@class PBEnumDescriptorProtoBuilder;
|
||||
@class PBEnumOptions;
|
||||
@class PBEnumOptionsBuilder;
|
||||
@class PBEnumValueDescriptorProto;
|
||||
@class PBEnumValueDescriptorProtoBuilder;
|
||||
@class PBEnumValueOptions;
|
||||
@class PBEnumValueOptionsBuilder;
|
||||
@class PBFieldDescriptorProto;
|
||||
@class PBFieldDescriptorProtoBuilder;
|
||||
@class PBFieldOptions;
|
||||
@class PBFieldOptionsBuilder;
|
||||
@class PBFileDescriptorProto;
|
||||
@class PBFileDescriptorProtoBuilder;
|
||||
@class PBFileDescriptorSet;
|
||||
@class PBFileDescriptorSetBuilder;
|
||||
@class PBFileOptions;
|
||||
@class PBFileOptionsBuilder;
|
||||
@class PBMessageOptions;
|
||||
@class PBMessageOptionsBuilder;
|
||||
@class PBMethodDescriptorProto;
|
||||
@class PBMethodDescriptorProtoBuilder;
|
||||
@class PBMethodOptions;
|
||||
@class PBMethodOptionsBuilder;
|
||||
@class PBOneofDescriptorProto;
|
||||
@class PBOneofDescriptorProtoBuilder;
|
||||
@class PBServiceDescriptorProto;
|
||||
@class PBServiceDescriptorProtoBuilder;
|
||||
@class PBServiceOptions;
|
||||
@class PBServiceOptionsBuilder;
|
||||
@class PBSourceCodeInfo;
|
||||
@class PBSourceCodeInfoBuilder;
|
||||
@class PBSourceCodeInfoLocation;
|
||||
@class PBSourceCodeInfoLocationBuilder;
|
||||
@class PBUninterpretedOption;
|
||||
@class PBUninterpretedOptionBuilder;
|
||||
@class PBUninterpretedOptionNamePart;
|
||||
@class PBUninterpretedOptionNamePartBuilder;
|
||||
|
||||
|
||||
|
||||
@interface OWSWebRTCProtosOwswebRtcdataProtosRoot : NSObject {
|
||||
}
|
||||
+ (PBExtensionRegistry*) extensionRegistry;
|
||||
+ (void) registerAllExtensions:(PBMutableExtensionRegistry*) registry;
|
||||
@end
|
||||
|
||||
#define Connected_id @"id"
|
||||
@interface OWSWebRTCProtosConnected : PBGeneratedMessage<GeneratedMessageProtocol> {
|
||||
@private
|
||||
BOOL hasId_:1;
|
||||
UInt64 id;
|
||||
}
|
||||
- (BOOL) hasId;
|
||||
@property (readonly) UInt64 id;
|
||||
|
||||
+ (instancetype) defaultInstance;
|
||||
- (instancetype) defaultInstance;
|
||||
|
||||
- (BOOL) isInitialized;
|
||||
- (void) writeToCodedOutputStream:(PBCodedOutputStream*) output;
|
||||
- (OWSWebRTCProtosConnectedBuilder*) builder;
|
||||
+ (OWSWebRTCProtosConnectedBuilder*) builder;
|
||||
+ (OWSWebRTCProtosConnectedBuilder*) builderWithPrototype:(OWSWebRTCProtosConnected*) prototype;
|
||||
- (OWSWebRTCProtosConnectedBuilder*) toBuilder;
|
||||
|
||||
+ (OWSWebRTCProtosConnected*) parseFromData:(NSData*) data;
|
||||
+ (OWSWebRTCProtosConnected*) parseFromData:(NSData*) data extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
+ (OWSWebRTCProtosConnected*) parseFromInputStream:(NSInputStream*) input;
|
||||
+ (OWSWebRTCProtosConnected*) parseFromInputStream:(NSInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
+ (OWSWebRTCProtosConnected*) parseFromCodedInputStream:(PBCodedInputStream*) input;
|
||||
+ (OWSWebRTCProtosConnected*) parseFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
@end
|
||||
|
||||
@interface OWSWebRTCProtosConnectedBuilder : PBGeneratedMessageBuilder {
|
||||
@private
|
||||
OWSWebRTCProtosConnected* resultConnected;
|
||||
}
|
||||
|
||||
- (OWSWebRTCProtosConnected*) defaultInstance;
|
||||
|
||||
- (OWSWebRTCProtosConnectedBuilder*) clear;
|
||||
- (OWSWebRTCProtosConnectedBuilder*) clone;
|
||||
|
||||
- (OWSWebRTCProtosConnected*) build;
|
||||
- (OWSWebRTCProtosConnected*) buildPartial;
|
||||
|
||||
- (OWSWebRTCProtosConnectedBuilder*) mergeFrom:(OWSWebRTCProtosConnected*) other;
|
||||
- (OWSWebRTCProtosConnectedBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input;
|
||||
- (OWSWebRTCProtosConnectedBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
|
||||
- (BOOL) hasId;
|
||||
- (UInt64) id;
|
||||
- (OWSWebRTCProtosConnectedBuilder*) setId:(UInt64) value;
|
||||
- (OWSWebRTCProtosConnectedBuilder*) clearId;
|
||||
@end
|
||||
|
||||
#define Hangup_id @"id"
|
||||
@interface OWSWebRTCProtosHangup : PBGeneratedMessage<GeneratedMessageProtocol> {
|
||||
@private
|
||||
BOOL hasId_:1;
|
||||
UInt64 id;
|
||||
}
|
||||
- (BOOL) hasId;
|
||||
@property (readonly) UInt64 id;
|
||||
|
||||
+ (instancetype) defaultInstance;
|
||||
- (instancetype) defaultInstance;
|
||||
|
||||
- (BOOL) isInitialized;
|
||||
- (void) writeToCodedOutputStream:(PBCodedOutputStream*) output;
|
||||
- (OWSWebRTCProtosHangupBuilder*) builder;
|
||||
+ (OWSWebRTCProtosHangupBuilder*) builder;
|
||||
+ (OWSWebRTCProtosHangupBuilder*) builderWithPrototype:(OWSWebRTCProtosHangup*) prototype;
|
||||
- (OWSWebRTCProtosHangupBuilder*) toBuilder;
|
||||
|
||||
+ (OWSWebRTCProtosHangup*) parseFromData:(NSData*) data;
|
||||
+ (OWSWebRTCProtosHangup*) parseFromData:(NSData*) data extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
+ (OWSWebRTCProtosHangup*) parseFromInputStream:(NSInputStream*) input;
|
||||
+ (OWSWebRTCProtosHangup*) parseFromInputStream:(NSInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
+ (OWSWebRTCProtosHangup*) parseFromCodedInputStream:(PBCodedInputStream*) input;
|
||||
+ (OWSWebRTCProtosHangup*) parseFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
@end
|
||||
|
||||
@interface OWSWebRTCProtosHangupBuilder : PBGeneratedMessageBuilder {
|
||||
@private
|
||||
OWSWebRTCProtosHangup* resultHangup;
|
||||
}
|
||||
|
||||
- (OWSWebRTCProtosHangup*) defaultInstance;
|
||||
|
||||
- (OWSWebRTCProtosHangupBuilder*) clear;
|
||||
- (OWSWebRTCProtosHangupBuilder*) clone;
|
||||
|
||||
- (OWSWebRTCProtosHangup*) build;
|
||||
- (OWSWebRTCProtosHangup*) buildPartial;
|
||||
|
||||
- (OWSWebRTCProtosHangupBuilder*) mergeFrom:(OWSWebRTCProtosHangup*) other;
|
||||
- (OWSWebRTCProtosHangupBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input;
|
||||
- (OWSWebRTCProtosHangupBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
|
||||
- (BOOL) hasId;
|
||||
- (UInt64) id;
|
||||
- (OWSWebRTCProtosHangupBuilder*) setId:(UInt64) value;
|
||||
- (OWSWebRTCProtosHangupBuilder*) clearId;
|
||||
@end
|
||||
|
||||
#define VideoStreamingStatus_id @"id"
|
||||
#define VideoStreamingStatus_enabled @"enabled"
|
||||
@interface OWSWebRTCProtosVideoStreamingStatus : PBGeneratedMessage<GeneratedMessageProtocol> {
|
||||
@private
|
||||
BOOL hasEnabled_:1;
|
||||
BOOL hasId_:1;
|
||||
BOOL enabled_:1;
|
||||
UInt64 id;
|
||||
}
|
||||
- (BOOL) hasId;
|
||||
- (BOOL) hasEnabled;
|
||||
@property (readonly) UInt64 id;
|
||||
- (BOOL) enabled;
|
||||
|
||||
+ (instancetype) defaultInstance;
|
||||
- (instancetype) defaultInstance;
|
||||
|
||||
- (BOOL) isInitialized;
|
||||
- (void) writeToCodedOutputStream:(PBCodedOutputStream*) output;
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) builder;
|
||||
+ (OWSWebRTCProtosVideoStreamingStatusBuilder*) builder;
|
||||
+ (OWSWebRTCProtosVideoStreamingStatusBuilder*) builderWithPrototype:(OWSWebRTCProtosVideoStreamingStatus*) prototype;
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) toBuilder;
|
||||
|
||||
+ (OWSWebRTCProtosVideoStreamingStatus*) parseFromData:(NSData*) data;
|
||||
+ (OWSWebRTCProtosVideoStreamingStatus*) parseFromData:(NSData*) data extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
+ (OWSWebRTCProtosVideoStreamingStatus*) parseFromInputStream:(NSInputStream*) input;
|
||||
+ (OWSWebRTCProtosVideoStreamingStatus*) parseFromInputStream:(NSInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
+ (OWSWebRTCProtosVideoStreamingStatus*) parseFromCodedInputStream:(PBCodedInputStream*) input;
|
||||
+ (OWSWebRTCProtosVideoStreamingStatus*) parseFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
@end
|
||||
|
||||
@interface OWSWebRTCProtosVideoStreamingStatusBuilder : PBGeneratedMessageBuilder {
|
||||
@private
|
||||
OWSWebRTCProtosVideoStreamingStatus* resultVideoStreamingStatus;
|
||||
}
|
||||
|
||||
- (OWSWebRTCProtosVideoStreamingStatus*) defaultInstance;
|
||||
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) clear;
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) clone;
|
||||
|
||||
- (OWSWebRTCProtosVideoStreamingStatus*) build;
|
||||
- (OWSWebRTCProtosVideoStreamingStatus*) buildPartial;
|
||||
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) mergeFrom:(OWSWebRTCProtosVideoStreamingStatus*) other;
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input;
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
|
||||
- (BOOL) hasId;
|
||||
- (UInt64) id;
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) setId:(UInt64) value;
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) clearId;
|
||||
|
||||
- (BOOL) hasEnabled;
|
||||
- (BOOL) enabled;
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) setEnabled:(BOOL) value;
|
||||
- (OWSWebRTCProtosVideoStreamingStatusBuilder*) clearEnabled;
|
||||
@end
|
||||
|
||||
#define Data_connected @"connected"
|
||||
#define Data_hangup @"hangup"
|
||||
#define Data_videoStreamingStatus @"videoStreamingStatus"
|
||||
@interface OWSWebRTCProtosData : PBGeneratedMessage<GeneratedMessageProtocol> {
|
||||
@private
|
||||
BOOL hasConnected_:1;
|
||||
BOOL hasHangup_:1;
|
||||
BOOL hasVideoStreamingStatus_:1;
|
||||
OWSWebRTCProtosConnected* connected;
|
||||
OWSWebRTCProtosHangup* hangup;
|
||||
OWSWebRTCProtosVideoStreamingStatus* videoStreamingStatus;
|
||||
}
|
||||
- (BOOL) hasConnected;
|
||||
- (BOOL) hasHangup;
|
||||
- (BOOL) hasVideoStreamingStatus;
|
||||
@property (readonly, strong) OWSWebRTCProtosConnected* connected;
|
||||
@property (readonly, strong) OWSWebRTCProtosHangup* hangup;
|
||||
@property (readonly, strong) OWSWebRTCProtosVideoStreamingStatus* videoStreamingStatus;
|
||||
|
||||
+ (instancetype) defaultInstance;
|
||||
- (instancetype) defaultInstance;
|
||||
|
||||
- (BOOL) isInitialized;
|
||||
- (void) writeToCodedOutputStream:(PBCodedOutputStream*) output;
|
||||
- (OWSWebRTCProtosDataBuilder*) builder;
|
||||
+ (OWSWebRTCProtosDataBuilder*) builder;
|
||||
+ (OWSWebRTCProtosDataBuilder*) builderWithPrototype:(OWSWebRTCProtosData*) prototype;
|
||||
- (OWSWebRTCProtosDataBuilder*) toBuilder;
|
||||
|
||||
+ (OWSWebRTCProtosData*) parseFromData:(NSData*) data;
|
||||
+ (OWSWebRTCProtosData*) parseFromData:(NSData*) data extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
+ (OWSWebRTCProtosData*) parseFromInputStream:(NSInputStream*) input;
|
||||
+ (OWSWebRTCProtosData*) parseFromInputStream:(NSInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
+ (OWSWebRTCProtosData*) parseFromCodedInputStream:(PBCodedInputStream*) input;
|
||||
+ (OWSWebRTCProtosData*) parseFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
@end
|
||||
|
||||
@interface OWSWebRTCProtosDataBuilder : PBGeneratedMessageBuilder {
|
||||
@private
|
||||
OWSWebRTCProtosData* resultData;
|
||||
}
|
||||
|
||||
- (OWSWebRTCProtosData*) defaultInstance;
|
||||
|
||||
- (OWSWebRTCProtosDataBuilder*) clear;
|
||||
- (OWSWebRTCProtosDataBuilder*) clone;
|
||||
|
||||
- (OWSWebRTCProtosData*) build;
|
||||
- (OWSWebRTCProtosData*) buildPartial;
|
||||
|
||||
- (OWSWebRTCProtosDataBuilder*) mergeFrom:(OWSWebRTCProtosData*) other;
|
||||
- (OWSWebRTCProtosDataBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input;
|
||||
- (OWSWebRTCProtosDataBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
|
||||
|
||||
- (BOOL) hasConnected;
|
||||
- (OWSWebRTCProtosConnected*) connected;
|
||||
- (OWSWebRTCProtosDataBuilder*) setConnected:(OWSWebRTCProtosConnected*) value;
|
||||
- (OWSWebRTCProtosDataBuilder*) setConnectedBuilder:(OWSWebRTCProtosConnectedBuilder*) builderForValue;
|
||||
- (OWSWebRTCProtosDataBuilder*) mergeConnected:(OWSWebRTCProtosConnected*) value;
|
||||
- (OWSWebRTCProtosDataBuilder*) clearConnected;
|
||||
|
||||
- (BOOL) hasHangup;
|
||||
- (OWSWebRTCProtosHangup*) hangup;
|
||||
- (OWSWebRTCProtosDataBuilder*) setHangup:(OWSWebRTCProtosHangup*) value;
|
||||
- (OWSWebRTCProtosDataBuilder*) setHangupBuilder:(OWSWebRTCProtosHangupBuilder*) builderForValue;
|
||||
- (OWSWebRTCProtosDataBuilder*) mergeHangup:(OWSWebRTCProtosHangup*) value;
|
||||
- (OWSWebRTCProtosDataBuilder*) clearHangup;
|
||||
|
||||
- (BOOL) hasVideoStreamingStatus;
|
||||
- (OWSWebRTCProtosVideoStreamingStatus*) videoStreamingStatus;
|
||||
- (OWSWebRTCProtosDataBuilder*) setVideoStreamingStatus:(OWSWebRTCProtosVideoStreamingStatus*) value;
|
||||
- (OWSWebRTCProtosDataBuilder*) setVideoStreamingStatusBuilder:(OWSWebRTCProtosVideoStreamingStatusBuilder*) builderForValue;
|
||||
- (OWSWebRTCProtosDataBuilder*) mergeVideoStreamingStatus:(OWSWebRTCProtosVideoStreamingStatus*) value;
|
||||
- (OWSWebRTCProtosDataBuilder*) clearVideoStreamingStatus;
|
||||
@end
|
||||
|
||||
|
||||
// @@protoc_insertion_point(global_scope)
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,313 @@
|
||||
// Created by Michael Kirk on 11/29/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
import PromiseKit
|
||||
import WebRTC
|
||||
|
||||
let kAudioTrackType = kRTCMediaStreamTrackKindAudio
|
||||
let kVideoTrackType = kRTCMediaStreamTrackKindVideo
|
||||
|
||||
class PeerConnectionClient: NSObject, SignalCallAudioManager {
|
||||
|
||||
let TAG = "[PeerConnectionClient]"
|
||||
enum Identifiers: String {
|
||||
case mediaStream = "ARDAMS",
|
||||
videoTrack = "ARDAMSv0",
|
||||
audioTrack = "ARDAMSa0",
|
||||
dataChannelSignaling = "signaling"
|
||||
}
|
||||
|
||||
// Connection
|
||||
|
||||
private let peerConnection: RTCPeerConnection
|
||||
private let iceServers: [RTCIceServer]
|
||||
private let connectionConstraints: RTCMediaConstraints
|
||||
private let configuration: RTCConfiguration
|
||||
private let factory = RTCPeerConnectionFactory()
|
||||
|
||||
// DataChannel
|
||||
|
||||
// peerConnection expects to be the final owner of dataChannel. Otherwise, a crash when peerConnection deallocs
|
||||
// `dataChannel` is public because on incoming calls, we don't explicitly create the channel, rather `CallService`
|
||||
// assigns it when the channel is discovered due to the caller having created it.
|
||||
public var dataChannel: RTCDataChannel?
|
||||
|
||||
// Audio
|
||||
|
||||
private var audioSender: RTCRtpSender?
|
||||
private var audioTrack: RTCAudioTrack?
|
||||
private var audioConstraints: RTCMediaConstraints
|
||||
|
||||
// Video
|
||||
|
||||
private var videoSender: RTCRtpSender?
|
||||
private var videoTrack: RTCVideoTrack?
|
||||
private var cameraConstraints: RTCMediaConstraints
|
||||
|
||||
init(iceServers: [RTCIceServer], peerConnectionDelegate: RTCPeerConnectionDelegate) {
|
||||
self.iceServers = iceServers
|
||||
|
||||
configuration = RTCConfiguration()
|
||||
configuration.iceServers = iceServers
|
||||
configuration.bundlePolicy = .maxBundle
|
||||
configuration.rtcpMuxPolicy = .require
|
||||
|
||||
let connectionConstraintsDict = ["DtlsSrtpKeyAgreement": "true"]
|
||||
connectionConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: connectionConstraintsDict)
|
||||
peerConnection = factory.peerConnection(with: configuration,
|
||||
constraints: connectionConstraints,
|
||||
delegate: peerConnectionDelegate)
|
||||
|
||||
audioConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints:nil)
|
||||
cameraConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)
|
||||
super.init()
|
||||
|
||||
createAudioSender()
|
||||
createVideoSender()
|
||||
}
|
||||
|
||||
// MARK: - Media Streams
|
||||
|
||||
public func createSignalingDataChannel(delegate: RTCDataChannelDelegate) {
|
||||
let dataChannel = peerConnection.dataChannel(forLabel: Identifiers.dataChannelSignaling.rawValue,
|
||||
configuration: RTCDataChannelConfiguration())
|
||||
dataChannel.delegate = delegate
|
||||
|
||||
self.dataChannel = dataChannel
|
||||
}
|
||||
|
||||
// MARK: Video
|
||||
|
||||
fileprivate func createVideoSender() {
|
||||
guard !Platform.isSimulator else {
|
||||
Logger.warn("\(TAG) Refusing to create local video track on simulator.")
|
||||
return
|
||||
}
|
||||
|
||||
let videoSource = factory.avFoundationVideoSource(with: cameraConstraints)
|
||||
let videoTrack = factory.videoTrack(with: videoSource, trackId: Identifiers.videoTrack.rawValue)
|
||||
self.videoTrack = videoTrack
|
||||
|
||||
// Disable by default until call is connected.
|
||||
// FIXME - do we require mic permissions at this point?
|
||||
// if so maybe it would be better to not even add the track until the call is connected
|
||||
// instead of creating it and disabling it.
|
||||
videoTrack.isEnabled = false
|
||||
|
||||
// Occasionally seeing this crash on the next line, after a *second* call:
|
||||
// -[__NSCFNumber length]: unrecognized selector sent to instance 0x1562c610
|
||||
// Seems like either videoKind or videoStreamId (both of which are Strings) is being GC'd prematurely.
|
||||
// Not sure why, but assigned the value to local vars above in hopes of avoiding it.
|
||||
// let videoKind = kRTCMediaStreamTrackKindVideo
|
||||
|
||||
let videoSender = peerConnection.sender(withKind: kVideoTrackType, streamId: Identifiers.mediaStream.rawValue)
|
||||
videoSender.track = videoTrack
|
||||
self.videoSender = videoSender
|
||||
}
|
||||
|
||||
public func setVideoEnabled(enabled: Bool) {
|
||||
guard let videoTrack = self.videoTrack else {
|
||||
let action = enabled ? "enable" : "disable"
|
||||
Logger.error("\(TAG)) trying to \(action) videoTack which doesn't exist")
|
||||
return
|
||||
}
|
||||
|
||||
videoTrack.isEnabled = enabled
|
||||
}
|
||||
|
||||
// MARK: Audio
|
||||
|
||||
fileprivate func createAudioSender() {
|
||||
let audioSource = factory.audioSource(with: self.audioConstraints)
|
||||
|
||||
let audioTrack = factory.audioTrack(with: audioSource, trackId: Identifiers.audioTrack.rawValue)
|
||||
self.audioTrack = audioTrack
|
||||
|
||||
// Disable by default until call is connected.
|
||||
// FIXME - do we require mic permissions at this point?
|
||||
// if so maybe it would be better to not even add the track until the call is connected
|
||||
// instead of creating it and disabling it.
|
||||
audioTrack.isEnabled = false
|
||||
|
||||
let audioSender = peerConnection.sender(withKind: kAudioTrackType, streamId: Identifiers.mediaStream.rawValue)
|
||||
audioSender.track = audioTrack
|
||||
self.audioSender = audioSender
|
||||
}
|
||||
|
||||
public func setAudioEnabled(enabled: Bool) {
|
||||
guard let audioTrack = self.audioTrack else {
|
||||
let action = enabled ? "enable" : "disable"
|
||||
Logger.error("\(TAG) trying to \(action) audioTrack which doesn't exist.")
|
||||
return
|
||||
}
|
||||
|
||||
audioTrack.isEnabled = enabled
|
||||
}
|
||||
|
||||
// MARK: - Session negotiation
|
||||
|
||||
var defaultOfferConstraints: RTCMediaConstraints {
|
||||
let mandatoryConstraints = [
|
||||
"OfferToReceiveAudio": "true",
|
||||
"OfferToReceiveVideo" : "true"
|
||||
]
|
||||
return RTCMediaConstraints(mandatoryConstraints:mandatoryConstraints, optionalConstraints:nil)
|
||||
}
|
||||
|
||||
func createOffer() -> Promise<HardenedRTCSessionDescription> {
|
||||
return Promise { fulfill, reject in
|
||||
peerConnection.offer(for: self.defaultOfferConstraints, completionHandler: { (sdp: RTCSessionDescription?, error: Error?) in
|
||||
guard error == nil else {
|
||||
reject(error!)
|
||||
return
|
||||
}
|
||||
|
||||
guard let sessionDescription = sdp else {
|
||||
Logger.error("\(self.TAG) No session description was obtained, even though there was no error reported.")
|
||||
let error = OWSErrorMakeUnableToProcessServerResponseError()
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
|
||||
fulfill(HardenedRTCSessionDescription(rtcSessionDescription: sessionDescription))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func setLocalSessionDescription(_ sessionDescription: HardenedRTCSessionDescription) -> Promise<Void> {
|
||||
return PromiseKit.wrap {
|
||||
Logger.verbose("\(self.TAG) setting local session description: \(sessionDescription)")
|
||||
peerConnection.setLocalDescription(sessionDescription.rtcSessionDescription, completionHandler: $0)
|
||||
}
|
||||
}
|
||||
|
||||
func negotiateSessionDescription(remoteDescription: RTCSessionDescription, constraints: RTCMediaConstraints) -> Promise<HardenedRTCSessionDescription> {
|
||||
return firstly {
|
||||
return self.setRemoteSessionDescription(remoteDescription)
|
||||
}.then {
|
||||
return self.negotiateAnswerSessionDescription(constraints: constraints)
|
||||
}
|
||||
}
|
||||
|
||||
func setRemoteSessionDescription(_ sessionDescription: RTCSessionDescription) -> Promise<Void> {
|
||||
return PromiseKit.wrap {
|
||||
Logger.verbose("\(self.TAG) setting remote description: \(sessionDescription)")
|
||||
peerConnection.setRemoteDescription(sessionDescription, completionHandler: $0)
|
||||
}
|
||||
}
|
||||
|
||||
func negotiateAnswerSessionDescription(constraints: RTCMediaConstraints) -> Promise<HardenedRTCSessionDescription> {
|
||||
return Promise { fulfill, reject in
|
||||
Logger.debug("\(self.TAG) negotiating answer session.")
|
||||
|
||||
peerConnection.answer(for: constraints, completionHandler: { (sdp: RTCSessionDescription?, error: Error?) in
|
||||
guard error == nil else {
|
||||
reject(error!)
|
||||
return
|
||||
}
|
||||
|
||||
guard let sessionDescription = sdp else {
|
||||
Logger.error("\(self.TAG) unexpected empty session description, even though no error was reported.")
|
||||
let error = OWSErrorMakeUnableToProcessServerResponseError()
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
|
||||
let hardenedSessionDescription = HardenedRTCSessionDescription(rtcSessionDescription: sessionDescription)
|
||||
|
||||
self.setLocalSessionDescription(hardenedSessionDescription).then {
|
||||
fulfill(hardenedSessionDescription)
|
||||
}.catch { error in
|
||||
reject(error)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func addIceCandidate(_ candidate: RTCIceCandidate) {
|
||||
Logger.debug("\(TAG) adding candidate")
|
||||
self.peerConnection.add(candidate)
|
||||
}
|
||||
|
||||
func terminate() {
|
||||
// Some notes on preventing crashes while disposing of peerConnection for video calls
|
||||
// from: https://groups.google.com/forum/#!searchin/discuss-webrtc/objc$20crash$20dealloc%7Csort:relevance/discuss-webrtc/7D-vk5yLjn8/rBW2D6EW4GYJ
|
||||
// The sequence to make it work appears to be
|
||||
//
|
||||
// [capturer stop]; // I had to add this as a method to RTCVideoCapturer
|
||||
// [localRenderer stop];
|
||||
// [remoteRenderer stop];
|
||||
// [peerConnection close];
|
||||
|
||||
// audioTrack is a strong property because we need access to it to mute/unmute, but I was seeing it
|
||||
// become nil when it was only a weak property. So we retain it and manually nil the reference here, because
|
||||
// we are likely to crash if we retain any peer connection properties when the peerconnection is released
|
||||
audioTrack = nil
|
||||
videoTrack = nil
|
||||
dataChannel = nil
|
||||
audioSender = nil
|
||||
videoSender = nil
|
||||
|
||||
peerConnection.close()
|
||||
}
|
||||
|
||||
// MARK: Data Channel
|
||||
|
||||
func sendDataChannelMessage(data: Data) -> Bool {
|
||||
guard let dataChannel = self.dataChannel else {
|
||||
Logger.error("\(TAG) in \(#function) ignoring sending \(data) for nil dataChannel")
|
||||
return false
|
||||
}
|
||||
|
||||
let buffer = RTCDataBuffer(data: data, isBinary: false)
|
||||
return dataChannel.sendData(buffer)
|
||||
}
|
||||
|
||||
// MARK: CallAudioManager
|
||||
|
||||
internal func configureAudioSession() {
|
||||
Logger.warn("TODO: \(#function)")
|
||||
}
|
||||
|
||||
internal func stopAudio() {
|
||||
Logger.warn("TODO: \(#function)")
|
||||
}
|
||||
|
||||
internal func startAudio() {
|
||||
guard let audioSender = self.audioSender else {
|
||||
Logger.error("\(TAG) ignoring \(#function) because audioSender was nil")
|
||||
return
|
||||
}
|
||||
|
||||
Logger.warn("TODO: \(#function)")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restrict an RTCSessionDescription to more secure parameters
|
||||
*/
|
||||
class HardenedRTCSessionDescription {
|
||||
let rtcSessionDescription: RTCSessionDescription
|
||||
var sdp: String { return rtcSessionDescription.sdp }
|
||||
|
||||
init(rtcSessionDescription: RTCSessionDescription) {
|
||||
self.rtcSessionDescription = HardenedRTCSessionDescription.harden(rtcSessionDescription: rtcSessionDescription)
|
||||
}
|
||||
|
||||
/**
|
||||
* Set some more secure parameters for the session description
|
||||
*/
|
||||
class func harden(rtcSessionDescription: RTCSessionDescription) -> RTCSessionDescription {
|
||||
var description = rtcSessionDescription.sdp
|
||||
|
||||
// Enforce Constant bit rate.
|
||||
description = description.replacingOccurrences(of: "(a=fmtp:111 ((?!cbr=).)*)\r?\n", with: "$1;cbr=1\r\n")
|
||||
|
||||
// Strip plaintext audio-level details
|
||||
// https://tools.ietf.org/html/rfc6464
|
||||
description = description.replacingOccurrences(of: ".+urn:ietf:params:rtp-hdrext:ssrc-audio-level.*\r?\n", with: "")
|
||||
|
||||
return RTCSessionDescription.init(type: rtcSessionDescription.type, sdp: description)
|
||||
}
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
// Created by Michael Kirk on 12/7/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
|
||||
enum CallState: String {
|
||||
case idle
|
||||
case dialing
|
||||
case answering
|
||||
case remoteRinging
|
||||
case localRinging
|
||||
case connected
|
||||
case localFailure // terminal
|
||||
case localHangup // terminal
|
||||
case remoteHangup // terminal
|
||||
case remoteBusy // terminal
|
||||
}
|
||||
|
||||
/**
|
||||
* Data model for a WebRTC backed voice/video call.
|
||||
*/
|
||||
@objc class SignalCall: NSObject {
|
||||
|
||||
let TAG = "[SignalCall]"
|
||||
|
||||
var state: CallState {
|
||||
didSet {
|
||||
Logger.debug("\(TAG) state changed: \(oldValue) -> \(state)")
|
||||
stateDidChange?(state)
|
||||
}
|
||||
}
|
||||
|
||||
let signalingId: UInt64
|
||||
let remotePhoneNumber: String
|
||||
let localId: UUID
|
||||
var hasVideo = false
|
||||
var error: CallError?
|
||||
|
||||
var stateDidChange: ((_ newState: CallState) -> Void)?
|
||||
|
||||
init(localId: UUID, signalingId: UInt64, state: CallState, remotePhoneNumber: String) {
|
||||
self.localId = localId
|
||||
self.signalingId = signalingId
|
||||
self.state = state
|
||||
self.remotePhoneNumber = remotePhoneNumber
|
||||
}
|
||||
|
||||
class func outgoingCall(localId: UUID, remotePhoneNumber: String) -> SignalCall {
|
||||
return SignalCall(localId: localId, signalingId: UInt64.ows_random(), state: .dialing, remotePhoneNumber: remotePhoneNumber)
|
||||
}
|
||||
|
||||
class func incomingCall(localId: UUID, remotePhoneNumber: String, signalingId: UInt64) -> SignalCall {
|
||||
return SignalCall(localId: localId, signalingId: signalingId, state: .answering, remotePhoneNumber: remotePhoneNumber)
|
||||
}
|
||||
|
||||
// MARK: Equatable
|
||||
static func == (lhs: SignalCall, rhs: SignalCall) -> Bool {
|
||||
return lhs.localId == rhs.localId
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fileprivate extension UInt64 {
|
||||
static func ows_random() -> UInt64 {
|
||||
var random: UInt64 = 0
|
||||
arc4random_buf(&random, MemoryLayout.size(ofValue: random))
|
||||
return random
|
||||
}
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
// Created by Michael Kirk on 12/13/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import UIKit
|
||||
import CallKit
|
||||
|
||||
/**
|
||||
* Based on SpeakerboxCallManager, from the Apple CallKit Example app. Though, it's responsibilities are mostly mirrored (and delegated from) CallUIAdapter?
|
||||
* TODO: Would it simplify things to merge this into CallKitCallUIAdaptee?
|
||||
*/
|
||||
@available(iOS 10.0, *)
|
||||
final class CallKitCallManager: NSObject {
|
||||
|
||||
let callController = CXCallController()
|
||||
|
||||
// MARK: Actions
|
||||
|
||||
func startCall(_ call: SignalCall) {
|
||||
let handle = CXHandle(type: .phoneNumber, value: call.remotePhoneNumber)
|
||||
let startCallAction = CXStartCallAction(call: call.localId, handle: handle)
|
||||
|
||||
startCallAction.isVideo = call.hasVideo
|
||||
|
||||
let transaction = CXTransaction()
|
||||
transaction.addAction(startCallAction)
|
||||
|
||||
requestTransaction(transaction)
|
||||
}
|
||||
|
||||
func end(call: SignalCall) {
|
||||
let endCallAction = CXEndCallAction(call: call.localId)
|
||||
let transaction = CXTransaction()
|
||||
transaction.addAction(endCallAction)
|
||||
|
||||
requestTransaction(transaction)
|
||||
}
|
||||
|
||||
func setHeld(call: SignalCall, onHold: Bool) {
|
||||
let setHeldCallAction = CXSetHeldCallAction(call: call.localId, onHold: onHold)
|
||||
let transaction = CXTransaction()
|
||||
transaction.addAction(setHeldCallAction)
|
||||
|
||||
requestTransaction(transaction)
|
||||
}
|
||||
|
||||
private func requestTransaction(_ transaction: CXTransaction) {
|
||||
callController.request(transaction) { error in
|
||||
if let error = error {
|
||||
print("Error requesting transaction: \(error)")
|
||||
} else {
|
||||
print("Requested transaction successfully")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Call Management
|
||||
|
||||
private(set) var calls = [SignalCall]()
|
||||
|
||||
func callWithLocalId(_ localId: UUID) -> SignalCall? {
|
||||
guard let index = calls.index(where: { $0.localId == localId }) else {
|
||||
return nil
|
||||
}
|
||||
return calls[index]
|
||||
}
|
||||
|
||||
func addCall(_ call: SignalCall) {
|
||||
calls.append(call)
|
||||
}
|
||||
|
||||
func removeCall(_ call: SignalCall) {
|
||||
calls.removeFirst(where: { $0 === call })
|
||||
}
|
||||
|
||||
func removeAllCalls() {
|
||||
calls.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fileprivate extension Array {
|
||||
|
||||
mutating func removeFirst(where predicate: (Element) throws -> Bool) rethrows {
|
||||
guard let index = try index(where: predicate) else {
|
||||
return
|
||||
}
|
||||
|
||||
remove(at: index)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
// Created by Michael Kirk on 1/3/17.
|
||||
// Copyright © 2017 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
|
||||
@available(iOS 10.0, *)
|
||||
class CallKitCallUIAdaptee: CallUIAdaptee {
|
||||
|
||||
let TAG = "[CallKitCallUIAdaptee]"
|
||||
let providerDelegate: CallKitProviderDelegate
|
||||
let callManager: CallKitCallManager
|
||||
let notificationsAdapter: CallNotificationsAdapter
|
||||
|
||||
init(callService: CallService, notificationsAdapter: CallNotificationsAdapter) {
|
||||
self.callManager = CallKitCallManager()
|
||||
self.providerDelegate = CallKitProviderDelegate(callManager: callManager, callService: callService)
|
||||
self.notificationsAdapter = notificationsAdapter
|
||||
}
|
||||
|
||||
public func startOutgoingCall(_ call: SignalCall) {
|
||||
// Add the new outgoing call to the app's list of calls.
|
||||
// So we can find it in the provider delegate callbacks.
|
||||
self.callManager.addCall(call)
|
||||
providerDelegate.callManager.startCall(call)
|
||||
}
|
||||
|
||||
public func reportIncomingCall(_ call: SignalCall, callerName: String, audioManager: SignalCallAudioManager) {
|
||||
// FIXME weird to pass the audio manager in here.
|
||||
// Crux is, the peerconnectionclient is what controls the audio channel.
|
||||
// But a peerconnectionclient is per call.
|
||||
// While this providerDelegate is an app singleton.
|
||||
providerDelegate.audioManager = audioManager
|
||||
|
||||
providerDelegate.reportIncomingCall(call) { error in
|
||||
if error == nil {
|
||||
Logger.debug("\(self.TAG) successfully reported incoming call.")
|
||||
} else {
|
||||
Logger.error("\(self.TAG) providerDelegate.reportIncomingCall failed with error: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func reportMissedCall(_ call: SignalCall, callerName: String) {
|
||||
notificationsAdapter.presentMissedCall(call, callerName: callerName)
|
||||
}
|
||||
|
||||
func answerCall(_ call: SignalCall) {
|
||||
showCall(call)
|
||||
}
|
||||
|
||||
public func declineCall(_ call: SignalCall) {
|
||||
callManager.end(call: call)
|
||||
}
|
||||
|
||||
func endCall(_ call: SignalCall) {
|
||||
callManager.end(call: call)
|
||||
}
|
||||
}
|
@ -0,0 +1,259 @@
|
||||
// Created by Michael Kirk on 12/23/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
import UIKit
|
||||
import CallKit
|
||||
import AVFoundation
|
||||
|
||||
@available(iOS 10.0, *)
|
||||
final class CallKitProviderDelegate: NSObject, CXProviderDelegate {
|
||||
|
||||
let TAG = "[CallKitProviderDelegate]"
|
||||
let callManager: CallKitCallManager
|
||||
let callService: CallService
|
||||
private let provider: CXProvider
|
||||
|
||||
// FIXME - I might be thinking about this the wrong way.
|
||||
// It seems like the provider delegate wants to stop/start the audio recording
|
||||
// process, but the ProviderDelegate is an app singleton
|
||||
// and the audio recording process is currently controlled (I think) by
|
||||
// the PeerConnectionClient instance, which is one per call (NOT a singleton).
|
||||
// It seems like a mess to reconcile this difference in cardinality. But... here we are.
|
||||
var audioManager: SignalCallAudioManager?
|
||||
|
||||
init(callManager: CallKitCallManager, callService: CallService) {
|
||||
self.callService = callService
|
||||
self.callManager = callManager
|
||||
provider = CXProvider(configuration: type(of: self).providerConfiguration)
|
||||
|
||||
super.init()
|
||||
|
||||
provider.setDelegate(self, queue: nil)
|
||||
}
|
||||
|
||||
/// The app's provider configuration, representing its CallKit capabilities
|
||||
static var providerConfiguration: CXProviderConfiguration {
|
||||
let localizedName = NSLocalizedString("APPLICATION_NAME", comment: "Name of application")
|
||||
let providerConfiguration = CXProviderConfiguration(localizedName: localizedName)
|
||||
|
||||
providerConfiguration.supportsVideo = true
|
||||
|
||||
providerConfiguration.maximumCallsPerCallGroup = 1
|
||||
|
||||
providerConfiguration.supportedHandleTypes = [.phoneNumber]
|
||||
|
||||
if let iconMaskImage = UIImage(named: "IconMask") {
|
||||
providerConfiguration.iconTemplateImageData = UIImagePNGRepresentation(iconMaskImage)
|
||||
}
|
||||
|
||||
providerConfiguration.ringtoneSound = "r.caf"
|
||||
|
||||
return providerConfiguration
|
||||
}
|
||||
|
||||
/// Use CXProvider to report the incoming call to the system
|
||||
func reportIncomingCall(_ call: SignalCall, completion: ((NSError?) -> Void)? = nil) {
|
||||
// Construct a CXCallUpdate describing the incoming call, including the caller.
|
||||
let update = CXCallUpdate()
|
||||
update.remoteHandle = CXHandle(type: .phoneNumber, value: call.remotePhoneNumber)
|
||||
update.hasVideo = call.hasVideo
|
||||
|
||||
// Report the incoming call to the system
|
||||
provider.reportNewIncomingCall(with: call.localId, update: update) { error in
|
||||
/*
|
||||
Only add incoming call to the app's list of calls if the call was allowed (i.e. there was no error)
|
||||
since calls may be "denied" for various legitimate reasons. See CXErrorCodeIncomingCallError.
|
||||
*/
|
||||
if error == nil {
|
||||
self.callManager.addCall(call)
|
||||
}
|
||||
|
||||
completion?(error as? NSError)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: CXProviderDelegate
|
||||
|
||||
func providerDidReset(_ provider: CXProvider) {
|
||||
Logger.debug("\(TAG) in \(#function)")
|
||||
|
||||
stopAudio()
|
||||
|
||||
/*
|
||||
End any ongoing calls if the provider resets, and remove them from the app's list of calls,
|
||||
since they are no longer valid.
|
||||
*/
|
||||
// This is a little goofy because CallKit assumes multiple calls (maybe some are held, or group calls?)
|
||||
// but CallService currently just has one call at a time.
|
||||
for call in callManager.calls {
|
||||
callService.handleFailedCall(error: .providerReset)
|
||||
}
|
||||
|
||||
// Remove all calls from the app's list of calls.
|
||||
callManager.removeAllCalls()
|
||||
}
|
||||
|
||||
func provider(_ provider: CXProvider, perform action: CXStartCallAction) {
|
||||
Logger.debug("\(TAG) in \(#function) CXStartCallAction")
|
||||
|
||||
/*
|
||||
Configure the audio session, but do not start call audio here, since it must be done once
|
||||
the audio session has been activated by the system after having its priority elevated.
|
||||
*/
|
||||
configureAudioSession()
|
||||
|
||||
// TODO does this work when `action.handle.value` is not in e164 format, e.g. if called via intent?
|
||||
guard let call = callManager.callWithLocalId(action.callUUID) else {
|
||||
Logger.error("\(TAG) unable to find call in \(#function)")
|
||||
return
|
||||
}
|
||||
|
||||
CallService.signalingQueue.async {
|
||||
self.callService.handleOutgoingCall(call).then {
|
||||
action.fulfill()
|
||||
}.catch { error in
|
||||
self.callManager.removeCall(call)
|
||||
action.fail()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO FIXME
|
||||
// /*
|
||||
// Set callback blocks for significant events in the call's lifecycle, so that the CXProvider may be updated
|
||||
// to reflect the updated state.
|
||||
// */
|
||||
// call.hasStartedConnectingDidChange = { [weak self] in
|
||||
// self?.provider.reportOutgoingCall(with: call.uuid, startedConnectingAt: call.connectingDate)
|
||||
// }
|
||||
// call.hasConnectedDidChange = { [weak self] in
|
||||
// self?.provider.reportOutgoingCall(with: call.uuid, connectedAt: call.connectDate)
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
|
||||
Logger.debug("\(TAG) Received \(#function) CXAnswerCallAction")
|
||||
// Retrieve the SpeakerboxCall instance corresponding to the action's call UUID
|
||||
guard let call = callManager.callWithLocalId(action.callUUID) else {
|
||||
action.fail()
|
||||
return
|
||||
}
|
||||
|
||||
// Original Speakerbox implementation
|
||||
// /*
|
||||
// Configure the audio session, but do not start call audio here, since it must be done once
|
||||
// the audio session has been activated by the system after having its priority elevated.
|
||||
// */
|
||||
// configureAudioSession()
|
||||
//
|
||||
// // Trigger the call to be answered via the underlying network service.
|
||||
// call.answerSpeakerboxCall()
|
||||
|
||||
// Synchronous to ensure work is done before call is displayed as "answered"
|
||||
CallService.signalingQueue.sync {
|
||||
self.callService.handleAnswerCall(call)
|
||||
}
|
||||
|
||||
// Signal to the system that the action has been successfully performed.
|
||||
action.fulfill()
|
||||
}
|
||||
|
||||
func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
|
||||
Logger.debug("\(TAG) Received \(#function) CXEndCallAction")
|
||||
guard let call = callManager.callWithLocalId(action.callUUID) else {
|
||||
action.fail()
|
||||
return
|
||||
}
|
||||
|
||||
// Original Speakerbox implementation
|
||||
// // Stop call audio whenever ending the call.
|
||||
// stopAudio()
|
||||
// // Trigger the call to be ended via the underlying network service.
|
||||
// call.endSpeakerboxCall()
|
||||
|
||||
// Synchronous to ensure call is terminated before call is displayed as "ended"
|
||||
CallService.signalingQueue.sync {
|
||||
self.callService.handleLocalHungupCall(call)
|
||||
}
|
||||
|
||||
// Signal to the system that the action has been successfully performed.
|
||||
action.fulfill()
|
||||
|
||||
// Remove the ended call from the app's list of calls.
|
||||
callManager.removeCall(call)
|
||||
}
|
||||
|
||||
func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {
|
||||
Logger.debug("\(TAG) Received \(#function) CXSetHeldCallAction")
|
||||
guard let call = callManager.callWithLocalId(action.callUUID) else {
|
||||
action.fail()
|
||||
return
|
||||
}
|
||||
Logger.warn("TODO, set held call: \(call)")
|
||||
|
||||
// TODO FIXME
|
||||
// // Update the SpeakerboxCall's underlying hold state.
|
||||
// call.isOnHold = action.isOnHold
|
||||
//
|
||||
// // Stop or start audio in response to holding or unholding the call.
|
||||
// if call.isOnHold {
|
||||
// stopAudio()
|
||||
// } else {
|
||||
// startAudio()
|
||||
// }
|
||||
|
||||
// Signal to the system that the action has been successfully performed.
|
||||
action.fulfill()
|
||||
}
|
||||
|
||||
func provider(_ provider: CXProvider, timedOutPerforming action: CXAction) {
|
||||
Logger.debug("\(TAG) Timed out \(#function)")
|
||||
|
||||
// React to the action timeout if necessary, such as showing an error UI.
|
||||
}
|
||||
|
||||
func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
|
||||
Logger.debug("\(TAG) Received \(#function)")
|
||||
|
||||
startAudio()
|
||||
}
|
||||
|
||||
func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
|
||||
Logger.debug("\(TAG) Received \(#function)")
|
||||
|
||||
/*
|
||||
Restart any non-call related audio now that the app's audio session has been
|
||||
de-activated after having its priority restored to normal.
|
||||
*/
|
||||
}
|
||||
|
||||
// MARK: - Audio
|
||||
|
||||
func startAudio() {
|
||||
guard let audioManager = self.audioManager else {
|
||||
Logger.error("\(TAG) audioManager was unexpectedly nil while tryign to start audio")
|
||||
return
|
||||
}
|
||||
|
||||
audioManager.startAudio()
|
||||
}
|
||||
|
||||
func stopAudio() {
|
||||
guard let audioManager = self.audioManager else {
|
||||
Logger.error("\(TAG) audioManager was unexpectedly nil while tryign to stop audio")
|
||||
return
|
||||
}
|
||||
|
||||
audioManager.stopAudio()
|
||||
}
|
||||
|
||||
func configureAudioSession() {
|
||||
guard let audioManager = self.audioManager else {
|
||||
Logger.error("\(TAG) audioManager was unexpectedly nil while trying to: \(#function)")
|
||||
return
|
||||
}
|
||||
|
||||
audioManager.configureAudioSession()
|
||||
}
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
// Created by Michael Kirk on 12/18/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
|
||||
struct TurnServerInfo {
|
||||
|
||||
let TAG = "[TurnServerInfo]"
|
||||
let password: String
|
||||
let username: String
|
||||
let urls: [String]
|
||||
|
||||
init?(attributes: [String: AnyObject]) {
|
||||
if let passwordAttribute = (attributes["password"] as? String) {
|
||||
password = passwordAttribute
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if let usernameAttribute = attributes["username"] as? String {
|
||||
username = usernameAttribute
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if let urlsAttribute = attributes["urls"] as? [String] {
|
||||
urls = urlsAttribute
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,119 @@
|
||||
// Created by Michael Kirk on 12/13/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
import PromiseKit
|
||||
import CallKit
|
||||
|
||||
protocol CallUIAdaptee {
|
||||
func startOutgoingCall(_ call: SignalCall)
|
||||
func reportIncomingCall(_ call: SignalCall, callerName: String, audioManager: SignalCallAudioManager)
|
||||
func reportMissedCall(_ call: SignalCall, callerName: String)
|
||||
func answerCall(_ call: SignalCall)
|
||||
func declineCall(_ call: SignalCall)
|
||||
func endCall(_ call: SignalCall)
|
||||
}
|
||||
|
||||
extension CallUIAdaptee {
|
||||
public func showCall(_ call: SignalCall) {
|
||||
let callNotificationName = CallService.callServiceActiveCallNotificationName()
|
||||
NotificationCenter.default.post(name: NSNotification.Name(rawValue: callNotificationName), object: call)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the user of call related activities.
|
||||
* Driven by either a CallKit or System notifications adaptee
|
||||
*/
|
||||
class CallUIAdapter {
|
||||
|
||||
let TAG = "[CallUIAdapter]"
|
||||
private let adaptee: CallUIAdaptee
|
||||
private let contactsManager: OWSContactsManager
|
||||
|
||||
required init(callService: CallService, contactsManager: OWSContactsManager, notificationsAdapter: CallNotificationsAdapter) {
|
||||
self.contactsManager = contactsManager
|
||||
if Platform.isSimulator {
|
||||
// Callkit doesn't seem entirely supported in simulator.
|
||||
// e.g. you can't receive calls in the call screen.
|
||||
// So we use the non-call kit call UI.
|
||||
Logger.info("\(TAG) choosing non-callkit adaptee for simulator.")
|
||||
adaptee = NonCallKitCallUIAdaptee(callService: callService, notificationsAdapter: notificationsAdapter)
|
||||
} else if #available(iOS 10.0, *) {
|
||||
Logger.info("\(TAG) choosing callkit adaptee for iOS10+")
|
||||
adaptee = CallKitCallUIAdaptee(callService: callService, notificationsAdapter: notificationsAdapter)
|
||||
} else {
|
||||
Logger.info("\(TAG) choosing non-callkit adaptee for older iOS")
|
||||
adaptee = NonCallKitCallUIAdaptee(callService: callService, notificationsAdapter: notificationsAdapter)
|
||||
}
|
||||
}
|
||||
|
||||
public func reportIncomingCall(_ call: SignalCall, thread: TSContactThread, audioManager: SignalCallAudioManager) {
|
||||
let callerName = self.contactsManager.displayName(forPhoneIdentifier: call.remotePhoneNumber)
|
||||
adaptee.reportIncomingCall(call, callerName: callerName, audioManager: audioManager)
|
||||
}
|
||||
|
||||
public func reportMissedCall(_ call: SignalCall) {
|
||||
let callerName = self.contactsManager.displayName(forPhoneIdentifier: call.remotePhoneNumber)
|
||||
adaptee.reportMissedCall(call, callerName: callerName)
|
||||
}
|
||||
|
||||
public func startOutgoingCall(handle: String) -> SignalCall {
|
||||
let call = SignalCall.outgoingCall(localId: UUID(), remotePhoneNumber: handle)
|
||||
adaptee.startOutgoingCall(call)
|
||||
return call
|
||||
}
|
||||
|
||||
public func answerCall(_ call: SignalCall) {
|
||||
adaptee.answerCall(call)
|
||||
}
|
||||
|
||||
public func declineCall(_ call: SignalCall) {
|
||||
adaptee.declineCall(call)
|
||||
}
|
||||
|
||||
public func endCall(_ call: SignalCall) {
|
||||
adaptee.endCall(call)
|
||||
}
|
||||
|
||||
public func showCall(_ call: SignalCall) {
|
||||
adaptee.showCall(call)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* FIXME TODO I actually don't yet understand the role of these CallAudioManager methods as
|
||||
* called in the speakerbox example. Are they redundant with what the RTC setup
|
||||
* already does for us?
|
||||
*
|
||||
* Here's the AVSessionConfig for the ARDRTC Example app, which maybe belongs
|
||||
* in the coonfigureAudio session. and maybe the adding audio tracks is sufficient for startAudio's implenetation?
|
||||
*
|
||||
*
|
||||
187 RTCAudioSessionConfiguration *configuration =
|
||||
188 [[RTCAudioSessionConfiguration alloc] init];
|
||||
189 configuration.category = AVAudioSessionCategoryAmbient;
|
||||
190 configuration.categoryOptions = AVAudioSessionCategoryOptionDuckOthers;
|
||||
191 configuration.mode = AVAudioSessionModeDefault;
|
||||
192
|
||||
193 RTCAudioSession *session = [RTCAudioSession sharedInstance];
|
||||
194 [session lockForConfiguration];
|
||||
195 BOOL hasSucceeded = NO;
|
||||
196 NSError *error = nil;
|
||||
197 if (session.isActive) {
|
||||
198 hasSucceeded = [session setConfiguration:configuration error:&error];
|
||||
199 } else {
|
||||
200 hasSucceeded = [session setConfiguration:configuration
|
||||
201 active:YES
|
||||
202 error:&error];
|
||||
203 }
|
||||
204 if (!hasSucceeded) {
|
||||
205 RTCLogError(@"Error setting configuration: %@", error.localizedDescription);
|
||||
206 }
|
||||
207 [session unlockForConfiguration];
|
||||
*/
|
||||
protocol SignalCallAudioManager {
|
||||
func startAudio()
|
||||
func stopAudio()
|
||||
func configureAudioSession()
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
// Created by Michael Kirk on 12/28/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SignalCall;
|
||||
|
||||
@protocol OWSCallNotificationsAdaptee <NSObject>
|
||||
|
||||
- (void)presentIncomingCall:(SignalCall *)call callerName:(NSString *)callerName;
|
||||
|
||||
- (void)presentMissedCall:(SignalCall *)call callerName:(NSString *)callerName;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
@ -0,0 +1,81 @@
|
||||
// Created by Michael Kirk on 12/4/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
|
||||
@objc(OWSWebRTCCallMessageHandler)
|
||||
class WebRTCCallMessageHandler: NSObject, OWSCallMessageHandler {
|
||||
|
||||
// MARK - Properties
|
||||
|
||||
let TAG = "[WebRTCCallMessageHandler]"
|
||||
|
||||
// MARK: Dependencies
|
||||
|
||||
let accountManager: AccountManager
|
||||
let callService: CallService
|
||||
let messageSender: MessageSender
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
required init(accountManager: AccountManager, callService: CallService, messageSender: MessageSender) {
|
||||
self.accountManager = accountManager
|
||||
self.callService = callService
|
||||
self.messageSender = messageSender
|
||||
}
|
||||
|
||||
// MARK: - Call Handlers
|
||||
|
||||
public func receivedOffer(_ offer: OWSSignalServiceProtosCallMessageOffer, from callerId: String) {
|
||||
Logger.verbose("\(TAG) handling offer from caller:\(callerId)")
|
||||
|
||||
let thread = TSContactThread.getOrCreateThread(contactId: callerId)
|
||||
CallService.signalingQueue.async {
|
||||
_ = self.callService.handleReceivedOffer(thread: thread, callId: offer.id, sessionDescription: offer.sessionDescription)
|
||||
}
|
||||
}
|
||||
|
||||
public func receivedAnswer(_ answer: OWSSignalServiceProtosCallMessageAnswer, from callerId: String) {
|
||||
Logger.verbose("\(TAG) handling answer from caller:\(callerId)")
|
||||
|
||||
let thread = TSContactThread.getOrCreateThread(contactId: callerId)
|
||||
CallService.signalingQueue.async {
|
||||
self.callService.handleReceivedAnswer(thread: thread, callId: answer.id, sessionDescription: answer.sessionDescription)
|
||||
}
|
||||
}
|
||||
|
||||
public func receivedIceUpdate(_ iceUpdate: OWSSignalServiceProtosCallMessageIceUpdate, from callerId: String) {
|
||||
Logger.verbose("\(TAG) handling iceUpdates from caller:\(callerId)")
|
||||
|
||||
let thread = TSContactThread.getOrCreateThread(contactId: callerId)
|
||||
|
||||
// Discrepency between our protobuf's sdpMlineIndex, which is unsigned,
|
||||
// while the RTC iOS API requires a signed int.
|
||||
let lineIndex = Int32(iceUpdate.sdpMlineIndex)
|
||||
|
||||
CallService.signalingQueue.async {
|
||||
self.callService.handleRemoteAddedIceCandidate(thread: thread, callId: iceUpdate.id, sdp: iceUpdate.sdp, lineIndex: lineIndex, mid: iceUpdate.sdpMid)
|
||||
}
|
||||
}
|
||||
|
||||
public func receivedHangup(_ hangup: OWSSignalServiceProtosCallMessageHangup, from callerId: String) {
|
||||
Logger.verbose("\(TAG) handling 'hangup' from caller:\(callerId)")
|
||||
|
||||
let thread = TSContactThread.getOrCreateThread(contactId: callerId)
|
||||
|
||||
CallService.signalingQueue.async {
|
||||
self.callService.handleRemoteHangup(thread: thread)
|
||||
}
|
||||
}
|
||||
|
||||
public func receivedBusy(_ busy: OWSSignalServiceProtosCallMessageBusy, from callerId: String) {
|
||||
Logger.verbose("\(TAG) handling 'busy' from caller:\(callerId)")
|
||||
|
||||
let thread = TSContactThread.getOrCreateThread(contactId: callerId)
|
||||
|
||||
CallService.signalingQueue.async {
|
||||
self.callService.handleRemoteBusy(thread: thread)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,18 +1,23 @@
|
||||
//
|
||||
// NotificationsManager.h
|
||||
// Signal
|
||||
//
|
||||
// Created by Frederic Jacobs on 22/12/15.
|
||||
// Copyright © 2015 Open Whisper Systems. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "OWSCallNotificationsAdaptee.h"
|
||||
#import <SignalServiceKit/NotificationsProtocol.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class TSCall;
|
||||
@class TSContactThread;
|
||||
@class OWSContactsManager;
|
||||
@class SignalCall;
|
||||
@class PropertyListPreferences;
|
||||
|
||||
@interface NotificationsManager : NSObject <NotificationsProtocol, OWSCallNotificationsAdaptee>
|
||||
|
||||
@interface NotificationsManager : NSObject <NotificationsProtocol>
|
||||
#pragma mark - RedPhone Call Notifications
|
||||
|
||||
- (void)notifyUserForCall:(TSCall *)call inThread:(TSThread *)thread;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
@ -0,0 +1,14 @@
|
||||
// Created by Michael Kirk on 12/23/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
|
||||
struct Platform {
|
||||
static let isSimulator: Bool = {
|
||||
var isSim = false
|
||||
#if arch(i386) || arch(x86_64)
|
||||
isSim = true
|
||||
#endif
|
||||
return isSim
|
||||
}()
|
||||
}
|
@ -0,0 +1,321 @@
|
||||
// Created by Michael Kirk on 11/10/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import Foundation
|
||||
import WebRTC
|
||||
import PromiseKit
|
||||
|
||||
@objc class CallAudioService: NSObject {
|
||||
private let TAG = "[CallAudioService]"
|
||||
private var vibrateTimer: Timer?
|
||||
private let audioManager = AppAudioManager.sharedInstance()
|
||||
|
||||
// Mark: Vibration config
|
||||
private let vibrateRepeatDuration = 1.6
|
||||
|
||||
// Our ring buzz is a pair of vibrations.
|
||||
// `pulseDuration` is the small pause between the two vibrations in the pair.
|
||||
private let pulseDuration = 0.2
|
||||
|
||||
public var isSpeakerphoneEnabled = false {
|
||||
didSet {
|
||||
handleUpdatedSpeakerphone()
|
||||
}
|
||||
}
|
||||
|
||||
public func handleState(_ state: CallState) {
|
||||
switch state {
|
||||
case .idle: handleIdle()
|
||||
case .dialing: handleDialing()
|
||||
case .answering: handleAnswering()
|
||||
case .remoteRinging: handleRemoteRinging()
|
||||
case .localRinging: handleLocalRinging()
|
||||
case .connected: handleConnected()
|
||||
case .localFailure: handleLocalFailure()
|
||||
case .localHangup: handleLocalHangup()
|
||||
case .remoteHangup: handleRemoteHangup()
|
||||
case .remoteBusy: handleBusy()
|
||||
}
|
||||
}
|
||||
|
||||
private func handleIdle() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
}
|
||||
|
||||
private func handleDialing() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
}
|
||||
|
||||
private func handleAnswering() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
stopRinging()
|
||||
}
|
||||
|
||||
private func handleRemoteRinging() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
}
|
||||
|
||||
private func handleLocalRinging() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
|
||||
audioManager.setAudioEnabled(true)
|
||||
audioManager.handleInboundRing()
|
||||
vibrateTimer = Timer.scheduledTimer(timeInterval: vibrateRepeatDuration, target: self, selector: #selector(vibrate), userInfo: nil, repeats: true)
|
||||
}
|
||||
|
||||
private func handleConnected() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
stopRinging()
|
||||
}
|
||||
|
||||
private func handleLocalFailure() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
stopRinging()
|
||||
}
|
||||
|
||||
private func handleLocalHangup() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
stopRinging()
|
||||
}
|
||||
|
||||
private func handleRemoteHangup() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
stopRinging()
|
||||
}
|
||||
|
||||
private func handleBusy() {
|
||||
Logger.debug("\(TAG) \(#function)")
|
||||
stopRinging()
|
||||
}
|
||||
|
||||
private func handleUpdatedSpeakerphone() {
|
||||
audioManager.toggleSpeakerPhone(isEnabled: isSpeakerphoneEnabled)
|
||||
}
|
||||
|
||||
// MARK: Helpers
|
||||
|
||||
private func stopRinging() {
|
||||
// Disables external speaker used for ringing, unless user enables speakerphone.
|
||||
audioManager.setDefaultAudioProfile()
|
||||
audioManager.cancelAllAudio()
|
||||
|
||||
vibrateTimer?.invalidate()
|
||||
vibrateTimer = nil
|
||||
}
|
||||
|
||||
public func vibrate() {
|
||||
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
|
||||
DispatchQueue.default.asyncAfter(deadline: DispatchTime.now() + pulseDuration) {
|
||||
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc(OWSCallViewController)
|
||||
class CallViewController: UIViewController {
|
||||
|
||||
enum CallDirection {
|
||||
case unspecified, outgoing, incoming
|
||||
}
|
||||
|
||||
let TAG = "[CallViewController]"
|
||||
|
||||
// Dependencies
|
||||
let callService: CallService
|
||||
let callUIAdapter: CallUIAdapter
|
||||
let contactsManager: OWSContactsManager
|
||||
let audioService: CallAudioService
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
var peerConnectionClient: PeerConnectionClient?
|
||||
var callDirection: CallDirection = .unspecified
|
||||
var thread: TSContactThread!
|
||||
var call: SignalCall!
|
||||
|
||||
@IBOutlet weak var contactNameLabel: UILabel!
|
||||
@IBOutlet weak var contactAvatarView: AvatarImageView!
|
||||
@IBOutlet weak var callStatusLabel: UILabel!
|
||||
|
||||
// MARK: Outgoing or Accepted Call Controls
|
||||
|
||||
@IBOutlet weak var callControls: UIView!
|
||||
@IBOutlet weak var muteButton: UIButton!
|
||||
@IBOutlet weak var speakerPhoneButton: UIButton!
|
||||
|
||||
// MARK: Incoming Call Controls
|
||||
|
||||
@IBOutlet weak var incomingCallControls: UIView!
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
required init?(coder aDecoder: NSCoder) {
|
||||
contactsManager = Environment.getCurrent().contactsManager
|
||||
callService = Environment.getCurrent().callService
|
||||
callUIAdapter = callService.callUIAdapter
|
||||
audioService = CallAudioService()
|
||||
super.init(coder: aDecoder)
|
||||
}
|
||||
|
||||
required init() {
|
||||
contactsManager = Environment.getCurrent().contactsManager
|
||||
callService = Environment.getCurrent().callService
|
||||
callUIAdapter = callService.callUIAdapter
|
||||
audioService = CallAudioService()
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
|
||||
guard let thread = self.thread else {
|
||||
Logger.error("\(TAG) tried to show call call without specifying thread.")
|
||||
showCallFailed(error: OWSErrorMakeAssertionError())
|
||||
return
|
||||
}
|
||||
|
||||
contactNameLabel.text = contactsManager.displayName(forPhoneIdentifier: thread.contactIdentifier())
|
||||
contactAvatarView.image = OWSAvatarBuilder.buildImage(for: thread, contactsManager: contactsManager)
|
||||
|
||||
switch callDirection {
|
||||
case .unspecified:
|
||||
Logger.error("\(TAG) must set call direction before call starts.")
|
||||
showCallFailed(error: OWSErrorMakeAssertionError())
|
||||
case .outgoing:
|
||||
self.call = self.callUIAdapter.startOutgoingCall(handle: thread.contactIdentifier())
|
||||
case .incoming:
|
||||
Logger.error("\(TAG) handling Incoming call")
|
||||
// No-op, since call service is already set up at this point, the result of which was presenting this viewController.
|
||||
}
|
||||
|
||||
call.stateDidChange = callStateDidChange
|
||||
callStateDidChange(call.state)
|
||||
}
|
||||
|
||||
// objc accessible way to set our swift enum.
|
||||
func setOutgoingCallDirection() {
|
||||
callDirection = .outgoing
|
||||
}
|
||||
|
||||
// objc accessible way to set our swift enum.
|
||||
func setIncomingCallDirection() {
|
||||
callDirection = .incoming
|
||||
}
|
||||
|
||||
func showCallFailed(error: Error) {
|
||||
// TODO Show something in UI.
|
||||
Logger.error("\(TAG) call failed with error: \(error)")
|
||||
}
|
||||
|
||||
func localizedTextForCallState(_ callState: CallState) -> String {
|
||||
switch callState {
|
||||
case .idle, .remoteHangup, .localHangup:
|
||||
return NSLocalizedString("IN_CALL_TERMINATED", comment: "Call setup status label")
|
||||
case .dialing:
|
||||
return NSLocalizedString("IN_CALL_CONNECTING", comment: "Call setup status label")
|
||||
case .remoteRinging, .localRinging:
|
||||
return NSLocalizedString("IN_CALL_RINGING", comment: "Call setup status label")
|
||||
case .answering:
|
||||
return NSLocalizedString("IN_CALL_SECURING", comment: "Call setup status label")
|
||||
case .connected:
|
||||
return NSLocalizedString("IN_CALL_TALKING", comment: "Call setup status label")
|
||||
case .remoteBusy:
|
||||
return NSLocalizedString("END_CALL_RESPONDER_IS_BUSY", comment: "Call setup status label")
|
||||
case .localFailure:
|
||||
return NSLocalizedString("END_CALL_UNCATEGORIZED_FAILURE", comment: "Call setup status label")
|
||||
}
|
||||
}
|
||||
|
||||
func updateCallUI(callState: CallState) {
|
||||
let textForState = localizedTextForCallState(callState)
|
||||
Logger.info("\(TAG) new call status: \(callState) aka \"\(textForState)\"")
|
||||
|
||||
self.callStatusLabel.text = textForState
|
||||
|
||||
// Show Incoming vs. (Outgoing || Accepted) call controls
|
||||
callControls.isHidden = callState == .localRinging
|
||||
incomingCallControls.isHidden = callState != .localRinging
|
||||
|
||||
// Dismiss Handling
|
||||
switch callState {
|
||||
case .remoteHangup, .remoteBusy, .localFailure:
|
||||
Logger.debug("\(TAG) dismissing after delay because new state is \(textForState)")
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
|
||||
self.dismiss(animated: true)
|
||||
}
|
||||
case .localHangup:
|
||||
Logger.debug("\(TAG) dismissing immediately from local hangup")
|
||||
self.dismiss(animated: true)
|
||||
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
func callStateDidChange(_ newState: CallState) {
|
||||
DispatchQueue.main.async {
|
||||
self.updateCallUI(callState: newState)
|
||||
}
|
||||
self.audioService.handleState(newState)
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends a connected call. Do not confuse with `didPressDeclineCall`.
|
||||
*/
|
||||
@IBAction func didPressHangup(sender: UIButton) {
|
||||
Logger.info("\(TAG) called \(#function)")
|
||||
if let call = self.call {
|
||||
callUIAdapter.endCall(call)
|
||||
} else {
|
||||
Logger.warn("\(TAG) hung up, but call was unexpectedly nil")
|
||||
}
|
||||
|
||||
self.dismiss(animated: true)
|
||||
}
|
||||
|
||||
@IBAction func didPressMute(sender muteButton: UIButton) {
|
||||
Logger.info("\(TAG) called \(#function)")
|
||||
muteButton.isSelected = !muteButton.isSelected
|
||||
CallService.signalingQueue.async {
|
||||
self.callService.handleToggledMute(isMuted: muteButton.isSelected)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func didPressSpeakerphone(sender speakerphoneButton: UIButton) {
|
||||
Logger.info("\(TAG) called \(#function)")
|
||||
speakerphoneButton.isSelected = !speakerphoneButton.isSelected
|
||||
audioService.isSpeakerphoneEnabled = speakerphoneButton.isSelected
|
||||
}
|
||||
|
||||
@IBAction func didPressAnswerCall(sender: UIButton) {
|
||||
Logger.info("\(TAG) called \(#function)")
|
||||
|
||||
guard let call = self.call else {
|
||||
Logger.error("\(TAG) call was unexpectedly nil. Terminating call.")
|
||||
self.callStatusLabel.text = NSLocalizedString("END_CALL_UNCATEGORIZED_FAILURE", comment: "Call setup status label")
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
|
||||
self.dismiss(animated: true)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
CallService.signalingQueue.async {
|
||||
self.callService.handleAnswerCall(call)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Denies an incoming not-yet-connected call, Do not confuse with `didPressHangup`.
|
||||
*/
|
||||
@IBAction func didPressDeclineCall(sender: UIButton) {
|
||||
Logger.info("\(TAG) called \(#function)")
|
||||
|
||||
if let call = self.call {
|
||||
callUIAdapter.declineCall(call)
|
||||
} else {
|
||||
Logger.warn("\(TAG) denied call, but call was unexpectedly nil")
|
||||
}
|
||||
|
||||
self.dismiss(animated: true)
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
// Created by Michael Kirk on 12/11/16.
|
||||
// Copyright © 2016 Open Whisper Systems. All rights reserved.
|
||||
|
||||
import UIKit
|
||||
|
||||
@IBDesignable
|
||||
class AvatarImageView: UIImageView {
|
||||
|
||||
override func layoutSubviews() {
|
||||
self.layer.masksToBounds = true
|
||||
self.layer.cornerRadius = self.frame.size.width / 2
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
# Assumes you've installed protobuf-objc
|
||||
# see: https://github.com/alexeyxo/protobuf-objc
|
||||
|
||||
PROTOC=protoc \
|
||||
--plugin=/usr/local/bin/proto-gen-objc \
|
||||
--proto_path="${HOME}/src/WhisperSystems/protobuf-objc/src/compiler/" \
|
||||
--proto_path="${HOME}/src/WhisperSystems/protobuf-objc/src/compiler/google/protobuf/" \
|
||||
--proto_path='./'
|
||||
|
||||
all: webrtc_data_proto
|
||||
|
||||
webrtc_data_proto: OWSWebRTCDataProtos.proto
|
||||
$(PROTOC) --objc_out=../Signal/src/call/ \
|
||||
OWSWebRTCDataProtos.proto
|
||||
|
@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Copyright (C) 2014-2016 Open Whisper Systems
|
||||
*
|
||||
* Licensed according to the LICENSE file in this repository.
|
||||
*/
|
||||
|
||||
package signal;
|
||||
|
||||
option java_package = "org.thoughtcrime.securesms.webrtc";
|
||||
option java_outer_classname = "WebRtcDataProtos";
|
||||
|
||||
// These options require the objc protobuf tools and may need to be commented
|
||||
// out if using them for a different platform.
|
||||
import "objectivec-descriptor.proto";
|
||||
option (google.protobuf.objectivec_file_options).class_prefix = "OWSWebRTCProtos";
|
||||
|
||||
message Connected
|
||||
{
|
||||
optional uint64 id = 1;
|
||||
}
|
||||
|
||||
message Hangup
|
||||
{
|
||||
optional uint64 id = 1;
|
||||
}
|
||||
|
||||
message VideoStreamingStatus
|
||||
{
|
||||
optional uint64 id = 1;
|
||||
optional bool enabled = 2;
|
||||
}
|
||||
|
||||
message Data
|
||||
{
|
||||
|
||||
optional Connected connected = 1;
|
||||
optional Hangup hangup = 2;
|
||||
optional VideoStreamingStatus videoStreamingStatus = 3;
|
||||
}
|
Loading…
Reference in New Issue