session-ios/Session/Calls/Call Management/SessionCall.swift

267 lines
8.6 KiB
Swift
Raw Normal View History

2021-10-28 08:02:41 +02:00
import Foundation
import WebRTC
import SessionMessagingKit
2021-11-07 23:12:18 +01:00
import PromiseKit
2021-10-28 08:02:41 +02:00
2021-11-03 05:31:50 +01:00
public final class SessionCall: NSObject, WebRTCSessionDelegate {
2021-10-28 08:02:41 +02:00
// MARK: Metadata Properties
let uuid: UUID
let sessionID: String
let mode: Mode
let webRTCSession: WebRTCSession
2021-11-09 06:05:23 +01:00
let isOutgoing: Bool
2021-11-03 05:31:50 +01:00
var remoteSDP: RTCSessionDescription? = nil
2021-11-09 06:05:23 +01:00
var callMessageTimestamp: UInt64?
2021-11-03 05:31:50 +01:00
var isWaitingForRemoteSDP = false
2021-10-28 08:02:41 +02:00
var contactName: String {
let contact = Storage.shared.getContact(with: self.sessionID)
return contact?.displayName(for: Contact.Context.regular) ?? self.sessionID
}
var profilePicture: UIImage {
if let result = OWSProfileManager.shared().profileAvatar(forRecipientId: sessionID) {
return result
} else {
return Identicon.generatePlaceholderIcon(seed: sessionID, text: contactName, size: 300)
}
}
2021-11-03 05:31:50 +01:00
// MARK: Control
lazy public var videoCapturer: RTCVideoCapturer = {
return RTCCameraVideoCapturer(delegate: webRTCSession.localVideoSource)
}()
var isRemoteVideoEnabled = false {
didSet {
remoteVideoStateDidChange?(isRemoteVideoEnabled)
}
}
var isMuted = false {
willSet {
if newValue {
webRTCSession.mute()
} else {
webRTCSession.unmute()
}
}
}
var isVideoEnabled = false {
willSet {
if newValue {
webRTCSession.turnOnVideo()
} else {
webRTCSession.turnOffVideo()
}
}
}
2021-10-28 08:02:41 +02:00
// MARK: Mode
enum Mode {
case offer
2021-11-03 05:31:50 +01:00
case answer
2021-10-28 08:02:41 +02:00
}
2021-11-09 06:05:23 +01:00
// MARK: End call mode
enum EndCallMode {
case local
case remote
}
2021-10-28 08:02:41 +02:00
// MARK: Call State Properties
var connectingDate: Date? {
didSet {
stateDidChange?()
hasStartedConnectingDidChange?()
}
}
var connectedDate: Date? {
didSet {
stateDidChange?()
hasConnectedDidChange?()
}
}
var endDate: Date? {
didSet {
stateDidChange?()
hasEndedDidChange?()
}
}
// Not yet implemented
var isOnHold = false {
didSet {
stateDidChange?()
}
}
// MARK: State Change Callbacks
var stateDidChange: (() -> Void)?
var hasStartedConnectingDidChange: (() -> Void)?
var hasConnectedDidChange: (() -> Void)?
var hasEndedDidChange: (() -> Void)?
2021-11-03 05:31:50 +01:00
var remoteVideoStateDidChange: ((Bool) -> Void)?
2021-10-28 08:02:41 +02:00
// MARK: Derived Properties
var hasStartedConnecting: Bool {
get { return connectingDate != nil }
set { connectingDate = newValue ? Date() : nil }
}
var hasConnected: Bool {
get { return connectedDate != nil }
set { connectedDate = newValue ? Date() : nil }
}
var hasEnded: Bool {
get { return endDate != nil }
set { endDate = newValue ? Date() : nil }
}
var duration: TimeInterval {
guard let connectedDate = connectedDate else {
return 0
}
2021-11-09 06:05:23 +01:00
if let endDate = endDate {
return endDate.timeIntervalSince(connectedDate)
}
2021-10-28 08:02:41 +02:00
return Date().timeIntervalSince(connectedDate)
}
// MARK: Initialization
2021-11-09 06:05:23 +01:00
init(for sessionID: String, uuid: String, mode: Mode, outgoing: Bool = false) {
2021-10-28 08:02:41 +02:00
self.sessionID = sessionID
self.uuid = UUID(uuidString: uuid)!
self.mode = mode
self.webRTCSession = WebRTCSession.current ?? WebRTCSession(for: sessionID, with: uuid)
2021-11-09 06:05:23 +01:00
self.isOutgoing = outgoing
2021-11-08 05:09:45 +01:00
WebRTCSession.current = self.webRTCSession
2021-10-28 08:02:41 +02:00
super.init()
2021-11-03 05:31:50 +01:00
self.webRTCSession.delegate = self
2021-11-09 01:53:38 +01:00
if AppEnvironment.shared.callManager.currentCall == nil {
AppEnvironment.shared.callManager.currentCall = self
} else {
SNLog("[Calls] A call is ongoing.")
}
2021-10-28 08:02:41 +02:00
}
2021-11-03 05:31:50 +01:00
func reportIncomingCallIfNeeded(completion: @escaping (Error?) -> Void) {
guard case .answer = mode else { return }
2021-10-28 08:02:41 +02:00
AppEnvironment.shared.callManager.reportIncomingCall(self, callerName: contactName) { error in
2021-11-03 05:31:50 +01:00
completion(error)
}
}
func didReceiveRemoteSDP(sdp: RTCSessionDescription) {
guard remoteSDP == nil else { return }
remoteSDP = sdp
if isWaitingForRemoteSDP {
webRTCSession.handleRemoteSDP(sdp, from: sessionID) // This sends an answer message internally
isWaitingForRemoteSDP = false
2021-10-28 08:02:41 +02:00
}
}
// MARK: Actions
2021-11-09 01:53:38 +01:00
func startSessionCall() {
2021-10-28 08:02:41 +02:00
guard case .offer = mode else { return }
2021-11-07 23:12:18 +01:00
var promise: Promise<Void>!
Storage.write(with: { transaction in
promise = self.webRTCSession.sendPreOffer(to: self.sessionID, using: transaction)
}, completion: { [weak self] in
let _ = promise.done {
Storage.shared.write { transaction in
2021-11-09 06:05:23 +01:00
self?.webRTCSession.sendOffer(to: self!.sessionID, using: transaction as! YapDatabaseReadWriteTransaction).done { timestamp in
2021-11-07 23:12:18 +01:00
self?.hasStartedConnecting = true
2021-11-09 06:05:23 +01:00
self?.callMessageTimestamp = timestamp
2021-11-07 23:12:18 +01:00
}.retainUntilComplete()
}
}
})
2021-10-28 08:02:41 +02:00
}
2021-11-09 01:53:38 +01:00
func answerSessionCall() {
2021-11-03 05:31:50 +01:00
guard case .answer = mode else { return }
2021-10-28 08:02:41 +02:00
hasStartedConnecting = true
2021-11-03 05:31:50 +01:00
if let sdp = remoteSDP {
webRTCSession.handleRemoteSDP(sdp, from: sessionID) // This sends an answer message internally
} else {
isWaitingForRemoteSDP = true
}
2021-10-28 08:02:41 +02:00
}
func endSessionCall() {
guard !hasEnded else { return }
Storage.write { transaction in
self.webRTCSession.endCall(with: self.sessionID, using: transaction)
}
hasEnded = true
}
2021-11-03 05:31:50 +01:00
2021-11-09 06:05:23 +01:00
// MARK: Update call message
func updateCallMessage(mode: EndCallMode) {
guard let callMessageTimestamp = callMessageTimestamp else { return }
Storage.write { transaction in
let tsMessage: TSMessage?
if self.isOutgoing {
tsMessage = TSOutgoingMessage.find(withTimestamp: callMessageTimestamp)
} else {
tsMessage = TSIncomingMessage.find(withAuthorId: self.sessionID, timestamp: callMessageTimestamp, transaction: transaction)
}
if let messageToUpdate = tsMessage {
var shouldMarkAsRead = false
let newMessageBody: String
if self.duration > 0 {
let durationString = NSString.formatDurationSeconds(UInt32(self.duration), useShortFormat: true)
newMessageBody = "\(self.isOutgoing ? NSLocalizedString("call_outgoing", comment: "") : NSLocalizedString("call_incoming", comment: "")): \(durationString)"
shouldMarkAsRead = true
} else {
switch mode {
case .local:
newMessageBody = self.isOutgoing ? NSLocalizedString("call_cancelled", comment: "") : NSLocalizedString("call_rejected", comment: "")
shouldMarkAsRead = true
case .remote:
newMessageBody = self.isOutgoing ? NSLocalizedString("call_rejected", comment: "") : NSLocalizedString("call_missing", comment: "")
}
}
messageToUpdate.updateCall(withNewBody: newMessageBody, transaction: transaction)
if let incomingMessage = tsMessage as? TSIncomingMessage, shouldMarkAsRead {
incomingMessage.markAsReadNow(withSendReadReceipt: false, transaction: transaction)
}
}
}
}
2021-11-03 05:31:50 +01:00
// MARK: Renderer
func attachRemoteVideoRenderer(_ renderer: RTCVideoRenderer) {
webRTCSession.attachRemoteRenderer(renderer)
}
2021-11-09 06:05:23 +01:00
func removeRemoteVideoRenderer(_ renderer: RTCVideoRenderer) {
webRTCSession.removeRemoteRenderer(renderer)
}
2021-11-03 05:31:50 +01:00
func attachLocalVideoRenderer(_ renderer: RTCVideoRenderer) {
webRTCSession.attachLocalRenderer(renderer)
}
// MARK: Delegate
public func webRTCIsConnected() {
self.hasConnected = true
}
public func isRemoteVideoDidChange(isEnabled: Bool) {
isRemoteVideoEnabled = isEnabled
}
public func dataChannelDidOpen() {
// Send initial video status
if (isVideoEnabled) {
webRTCSession.turnOnVideo()
} else {
webRTCSession.turnOffVideo()
}
}
2021-10-28 08:02:41 +02:00
}