CallsService.swift 13.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*
 *  Copyright (C) 2017 Savoir-faire Linux Inc.
 *
 *  Author: Silbino Gonçalves Matado <silbino.gmatado@savoirfairelinux.com>
 *  Author: Kateryna Kostiuk <kateryna.kostiuk@savoirfairelinux.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
 */

import RxSwift
import SwiftyBeaver
import Contacts

enum CallServiceError: Error {
    case acceptCallFailed
    case refuseCallFailed
    case hangUpCallFailed
    case holdCallFailed
    case unholdCallFailed
    case placeCallFailed
}

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
35 36 37 38 39 40 41 42 43
enum MediaType: String, CustomStringConvertible {
    case audio = "MEDIA_TYPE_AUDIO"
    case video = "MEDIA_TYPE_VIDEO"

    var description: String {
        return self.rawValue
    }
}

44 45 46 47 48
struct Base64VCard {
    var data: [Int: String] //The key is the number of vCard part
    var partsReceived: Int
}

49 50 51 52 53 54 55
class CallsService: CallsAdapterDelegate {

    fileprivate let disposeBag = DisposeBag()
    fileprivate let callsAdapter: CallsAdapter
    fileprivate let log = SwiftyBeaver.self

    fileprivate var calls = [String: CallModel]()
56 57 58

    fileprivate var base64VCards = [Int: Base64VCard]() //The key is the vCard id
    fileprivate let ringVCardMIMEType = "x-ring/ring.profile.vcard;"
59 60

    let currentCall = ReplaySubject<CallModel>.create(bufferSize: 1)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
61
    let newCall = Variable<CallModel>(CallModel(withCallId: "", callDetails: [:]))
62 63 64 65
    //let receivedVCard = PublishSubject<Profile>()
    let dbManager = DBManager(profileHepler: ProfileDataHelper(), conversationHelper: ConversationDataHelper(), interactionHepler: InteractionDataHelper())
    fileprivate let responseStream = PublishSubject<ServiceEvent>()
    var sharedResponseStream: Observable<ServiceEvent>
66 67 68

    init(withCallsAdapter callsAdapter: CallsAdapter) {
        self.callsAdapter = callsAdapter
69 70
        self.responseStream.disposed(by: disposeBag)
        self.sharedResponseStream = responseStream.share()
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        CallsAdapter.delegate = self
    }

    func accept(callId: String) -> Completable {
        return Completable.create(subscribe: { completable in
            let success = self.callsAdapter.acceptCall(withId: callId)
            if success {
                completable(.completed)
            } else {
                completable(.error(CallServiceError.acceptCallFailed))
            }
            return Disposables.create { }
        })
    }

    func refuse(callId: String) -> Completable {
        return Completable.create(subscribe: { completable in
            let success = self.callsAdapter.refuseCall(withId: callId)
            if success {
                completable(.completed)
            } else {
                completable(.error(CallServiceError.refuseCallFailed))
            }
            return Disposables.create { }
        })
    }

    func hangUp(callId: String) -> Completable {
        return Completable.create(subscribe: { completable in
            let success = self.callsAdapter.hangUpCall(withId: callId)
            if success {
                completable(.completed)
            } else {
                completable(.error(CallServiceError.hangUpCallFailed))
            }
            return Disposables.create { }
        })
    }

    func hold(callId: String) -> Completable {
        return Completable.create(subscribe: { completable in
            let success = self.callsAdapter.holdCall(withId: callId)
            if success {
                completable(.completed)
            } else {
                completable(.error(CallServiceError.holdCallFailed))
            }
            return Disposables.create { }
        })
    }

    func unhold(callId: String) -> Completable {
        return Completable.create(subscribe: { completable in
            let success = self.callsAdapter.unholdCall(withId: callId)
            if success {
                completable(.completed)
            } else {
                completable(.error(CallServiceError.unholdCallFailed))
            }
            return Disposables.create { }
        })
    }

134 135 136 137
    func placeCall(withAccount account: AccountModel,
                   toRingId ringId: String,
                   userName: String,
                   isAudioOnly: Bool = false) -> Single<CallModel> {
138 139

        //Create and emit the call
140 141 142 143
        var callDetails = [String: String]()
        callDetails[CallDetailKey.callTypeKey.rawValue] = String(describing: CallType.outgoing)
        callDetails[CallDetailKey.displayNameKey.rawValue] = userName
        callDetails[CallDetailKey.accountIdKey.rawValue] = account.id
144
        callDetails[CallDetailKey.audioOnlyKey.rawValue] = isAudioOnly.toString()
145
        let call = CallModel(withCallId: ringId, callDetails: callDetails)
146
        call.state = .connecting
147
        return Single<CallModel>.create(subscribe: { [unowned self] single in
148
            if let callId = self.callsAdapter.placeCall(withAccountId: account.id,
149 150
                                                        toRingId: "ring:\(ringId)",
                                                        details: callDetails),
151 152 153 154 155 156 157 158 159 160 161 162 163
                let callDictionary = self.callsAdapter.callDetails(withCallId: callId) {
                call.update(withDictionary: callDictionary)
                call.callId = callId
                self.currentCall.onNext(call)
                self.calls[callId] = call
                single(.success(call))
            } else {
                single(.error(CallServiceError.placeCallFailed))
            }
            return Disposables.create { }
        })
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    func muteAudio(call callId: String, mute: Bool) {
        self.callsAdapter
            .muteMedia(callId,
                       mediaType: String(describing: MediaType.audio),
                       muted: mute)
    }

    func muteVideo(call callId: String, mute: Bool) {
        self.callsAdapter
            .muteMedia(callId,
                       mediaType: String(describing: MediaType.video),
                       muted: mute)
    }

    func sendVCard(callID: String, accountID: String) {
        if accountID.isEmpty || callID.isEmpty {
            return
        }
        VCardUtils.loadVCard(named: VCardFiles.myProfile.rawValue,
                             inFolder: VCardFolders.profile.rawValue)
            .subscribe(onSuccess: { [unowned self] card in
                VCardUtils.sendVCard(card: card,
                                     callID: callID,
                                     accountID: accountID,
                                     sender: self)
            }).disposed(by: disposeBag)
    }

    func sendChunk(callID: String, message: [String: String], accountId: String) {
        self.callsAdapter.sendTextMessage(withCallID: callID,
                                          message: message,
                                          accountId: accountId,
                                          sMixed: true)
    }

199 200 201 202 203 204 205 206 207 208
    // MARK: CallsAdapterDelegate

    func didChangeCallState(withCallId callId: String, state: String, stateCode: NSInteger) {

        if let callDictionary = self.callsAdapter.callDetails(withCallId: callId) {

            //Add or update new call
            var call = self.calls[callId]
            if call == nil {
                call = CallModel(withCallId: callId, callDetails: callDictionary)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
209
                self.calls[callId] = call
210 211 212 213 214 215 216
            } else {
                call?.update(withDictionary: callDictionary)
            }

            //Update the call
            call?.state = CallState(rawValue: state)!

217 218 219 220 221 222 223
            //send vCard
            if (call?.state == .ringing && call?.callType == .outgoing) ||
                (call?.state == .current && call?.callType == .incoming) {
                let accountID = call?.accountId
                self.sendVCard(callID: callId, accountID: accountID!)
            }

224 225 226 227 228 229 230 231 232 233 234
            //Emit the call to the observers
            self.currentCall.onNext(call!)

            //Remove from the cache if the call is over
            if call?.state == .over {
                // TODO save history
                self.calls[callId] = nil
            }
        }
    }

235
    // swiftlint:disable cyclomatic_complexity
236 237
    func didReceiveMessage(withCallId callId: String, fromURI uri: String, message: [String: String]) {

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
        if let vCardKey = message.keys.filter({ $0.hasPrefix(self.ringVCardMIMEType) }).first {

            //Parse the key to get the number of parts and the current part number
            let components = vCardKey.components(separatedBy: ",")

            guard let partComponent = components.filter({$0.hasPrefix("part=")}).first else {
                return
            }

            guard let ofComponent = components.filter({$0.hasPrefix("of=")}).first else {
                return
            }

            guard let idComponent = components.filter({$0.hasPrefix("x-ring/ring.profile.vcard;id=")}).first else {
                return
            }

            guard let part = Int(partComponent.components(separatedBy: "=")[1]) else {
                return
            }

            guard let of = Int(ofComponent.components(separatedBy: "=")[1]) else {
                return
            }

            guard let id = Int(idComponent.components(separatedBy: "=")[1]) else {
                return
            }
            var numberOfReceivedChunk = 1
            if var chunk = self.base64VCards[id] {
                chunk.data[part] = message[vCardKey]
                chunk.partsReceived += 1
                numberOfReceivedChunk = chunk.partsReceived
                self.base64VCards[id] = chunk
            } else {
                let partMessage = message[vCardKey]
                let data: [Int: String] = [part: partMessage!]
                let chunk = Base64VCard(data: data, partsReceived: numberOfReceivedChunk)
                self.base64VCards[id] = chunk
            }

            //Emit the vCard when all data are appended
            if of == numberOfReceivedChunk {
                guard let vcard = self.base64VCards[id] else {
                    return
                }

                let vCardChunks = vcard.data

                //Append data from sorted part numbers
                var vCardData = Data()
                for currentPartNumber in vCardChunks.keys.sorted() {
                    if let currentData = vCardChunks[currentPartNumber]?.data(using: String.Encoding.utf8) {
                        vCardData.append(currentData)
                    }
                }

                //Create the vCard, save and db and emite an event
                do {
                    if let vCard = try CNContactVCardSerialization.contacts(with: vCardData).first {
                        let name = VCardUtils.getName(from: vCard)
                        var stringImage: String?
                        if let image = vCard.imageData {
                            stringImage = image.base64EncodedString()
                        }
                        let uri = uri.replacingOccurrences(of: "@ring.dht", with: "")
                        _ = self.dbManager
                            .createOrUpdateRingProfile(profileUri: uri,
                                                       alias: name,
                                                       image: stringImage,
                                                       status: ProfileStatus.untrasted)
                        var event = ServiceEvent(withEventType: .profileUpdated)
                        event.addEventInput(.uri, value: uri)
                        self.responseStream.onNext(event)
                    }
                } catch {
                   self.log.error(error)
                }
            }
        }
318
    }
319
    // swiftlint:enable cyclomatic_complexity
320 321 322 323

    func receivingCall(withAccountId accountId: String, callId: String, fromURI uri: String) {
        if let callDictionary = self.callsAdapter.callDetails(withCallId: callId) {

324 325 326
            if !isCurrentCall() {
                let call = CallModel(withCallId: callId, callDetails: callDictionary)
                self.newCall.value = call
327
            } else {
328 329 330 331 332 333 334 335 336 337 338 339 340 341
                self.refuse(callId: callId).subscribe(onCompleted: { [weak self] in
                    self?.log.debug("call refused")
                }, onError: { [weak self] _ in
                    self?.log.debug("Could not to refuse a call")
                }).disposed(by: self.disposeBag)
            }
        }
    }

    func isCurrentCall() -> Bool {
        for call in self.calls.values {
            if call.state == .current || call.state == .hold ||
                call.state == .unhold || call.state == .ringing {
                return true
342 343
            }
        }
344
        return false
345 346 347 348 349 350
    }

    func newCallStarted(withAccountId accountId: String, callId: String, toURI uri: String) {
    }

    func callPlacedOnHold(withCallId callId: String, holding: Bool) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
351 352 353 354 355
        guard let call = self.calls[callId] else {
            return
        }
        call.peerHolding = holding
        self.currentCall.onNext(call)
356 357
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
358 359 360 361 362 363
    func audioMuted(call callId: String, mute: Bool) {
        guard let call = self.calls[callId] else {
            return
        }
        call.audioMuted = mute
        self.currentCall.onNext(call)
364 365
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
366 367 368 369 370 371
    func videoMuted(call callId: String, mute: Bool) {
        guard let call = self.calls[callId] else {
            return
        }
        call.videoMuted = mute
        self.currentCall.onNext(call)
372 373
    }
}