CallsService.swift 12 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
}

35 36 37 38 39
struct Base64VCard {
    var data: [Int: String] //The key is the number of vCard part
    var partsReceived: Int
}

40 41 42 43 44 45 46
class CallsService: CallsAdapterDelegate {

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

    fileprivate var calls = [String: CallModel]()
47 48 49

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

    let currentCall = ReplaySubject<CallModel>.create(bufferSize: 1)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
52
    let newCall = Variable<CallModel>(CallModel(withCallId: "", callDetails: [:]))
53 54 55 56
    //let receivedVCard = PublishSubject<Profile>()
    let dbManager = DBManager(profileHepler: ProfileDataHelper(), conversationHelper: ConversationDataHelper(), interactionHepler: InteractionDataHelper())
    fileprivate let responseStream = PublishSubject<ServiceEvent>()
    var sharedResponseStream: Observable<ServiceEvent>
57 58 59

    init(withCallsAdapter callsAdapter: CallsAdapter) {
        self.callsAdapter = callsAdapter
60 61
        self.responseStream.disposed(by: disposeBag)
        self.sharedResponseStream = responseStream.share()
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
        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 { }
        })
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
125
    func placeCall(withAccount account: AccountModel, toRingId ringId: String, userName: String) -> Single<CallModel> {
126 127

        //Create and emit the call
128 129 130 131 132
        var callDetails = [String: String]()
        callDetails[CallDetailKey.callTypeKey.rawValue] = String(describing: CallType.outgoing)
        callDetails[CallDetailKey.displayNameKey.rawValue] = userName
        callDetails[CallDetailKey.accountIdKey.rawValue] = account.id
        let call = CallModel(withCallId: ringId, callDetails: callDetails)
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        call.state = .connecting
        return Single<CallModel>.create(subscribe: { single in
            if let callId = self.callsAdapter.placeCall(withAccountId: account.id,
                                                        toRingId: "ring:\(ringId)"),
                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 { }
        })
    }

    // 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
160
                self.calls[callId] = call
161 162 163 164 165 166 167
            } else {
                call?.update(withDictionary: callDictionary)
            }

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

168 169 170 171 172 173 174
            //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!)
            }

175 176 177 178 179 180 181 182 183 184 185
            //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
            }
        }
    }

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    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)
    }

207 208
    func didReceiveMessage(withCallId callId: String, fromURI uri: String, message: [String: String]) {

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        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)
                }
            }
        }
289 290 291 292 293 294 295 296 297 298 299 300 301
    }

    func receivingCall(withAccountId accountId: String, callId: String, fromURI uri: String) {
        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)
            } else {
                call?.update(withDictionary: callDictionary)
            }
            //Emit the call to the observers
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
302
            self.newCall.value = call!
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
        }

    }

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

    }

    func callPlacedOnHold(withCallId callId: String, holding: Bool) {

    }

    func muteAudio(call callId: String, mute: Bool) {

    }

    func muteVideo(call callId: String, mute: Bool) {

    }
}