CallViewModel.swift 13.1 KB
Newer Older
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 *  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
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
25
import RxCocoa
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
26 27 28 29 30 31 32 33 34 35 36 37

class CallViewModel: Stateable, ViewModel {

    //stateable
    private let stateSubject = PublishSubject<State>()
    lazy var state: Observable<State> = {
        return self.stateSubject.asObservable()
    }()

    fileprivate let callService: CallsService
    fileprivate let contactsService: ContactsService
    fileprivate let accountService: AccountsService
38
    fileprivate let videoService: VideoService
39 40
    fileprivate let audioService: AudioService

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
41 42 43
    private let disposeBag = DisposeBag()
    fileprivate let log = SwiftyBeaver.self

44 45 46
    var isHeadsetConnected = false
    var isAudioOnly = false

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    var call: CallModel? {
        didSet {
            guard let call = self.call else {
                return
            }
            self.contactsService.getProfileForUri(uri: call.participantRingId)
                .subscribe(onNext: { [unowned self] profile in
                    self.profileUpdated(profile: profile)
                })
                .disposed(by: self.disposeBag)

            self.callService
                .sharedResponseStream
                .filter({ (event) in
                    if let uri: String = event.getEventInput(ServiceEventInput.uri) {
                        return event.eventType == ServiceEventType.profileUpdated
                            && uri == call.participantRingId
                    }
                    return false
                })
                .subscribe(onNext: { [unowned self] _ in
                    self.contactsService.getProfileForUri(uri: call.participantRingId)
                        .subscribe(onNext: { profile in
                            self.profileUpdated(profile: profile)
                        })
                        .disposed(by: self.disposeBag)
                })
                .disposed(by: disposeBag)
75 76 77

            isHeadsetConnected = self.audioService.isHeadsetConnected.value
            isAudioOnly = call.isAudioOnly
78 79

            containerViewModel = ButtonsContainerViewModel(with: self.callService, audioService: self.audioService, callID: call.callId)
80 81
        }
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
82 83 84

    // data for ViewCintroller binding

85 86
    var contactImageData = Variable<Data?>(nil)

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
87 88 89 90 91 92 93 94 95 96 97
    lazy var incomingFrame: Observable<UIImage?> = {
        return videoService.incomingVideoFrame.asObservable().map({ frame in
            return frame
        })
    }()
    lazy var capturedFrame: Observable<UIImage?> = {
        return videoService.capturedVideoFrame.asObservable().map({ frame in
            return frame
        })
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
98 99 100 101 102 103 104 105
    lazy var dismisVC: Observable<Bool> = {
        return callService.currentCall.map({[weak self] call in
            return call.state == .over || call.state == .failure && call.callId == self?.call?.callId
        }).map({ hide in
            return hide
        })
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
106
    lazy var contactName: Driver<String> = {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
107 108 109 110 111 112 113 114 115 116
        return callService.currentCall.filter({ [weak self] call in
            return call.state != .over && call.state != .inactive && call.callId == self?.call?.callId
        }).map({ call in
            if !call.displayName.isEmpty {
                return call.displayName
            } else if !call.registeredName.isEmpty {
                return call.registeredName
            } else {
                return L10n.Calls.unknown
            }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
117
        }).asDriver(onErrorJustReturn: "")
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
118 119
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
120 121
    //let timer: Observable<String>

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
122
    lazy var callDuration: Driver<String> = {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
123 124 125 126 127 128 129 130
        let timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
            .takeUntil(self.callService.currentCall
                .filter { [weak self] call in
                    call.state == .over &&
                        call.callId == self?.call?.callId
            })
            .map({ elapsed in
                return CallViewModel.formattedDurationFrom(interval: elapsed)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
131 132 133 134
            }).share()
        return self.callService.currentCall.filter({ [weak self] call in
            return call.state == .current &&
                call.callId == self?.call?.callId
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
135 136
        }).flatMap({ _ in
            return timer
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
137
        }).asDriver(onErrorJustReturn: "")
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
138 139 140 141
    }()

    lazy var bottomInfo: Observable<String> = {
        return callService.currentCall.map({ [weak self] call in
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
142 143 144
            if call.state == .connecting || call.state == .ringing &&
                call.callType == .outgoing &&
                call.callId == self?.call?.callId {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
145 146 147 148 149 150 151 152
                return L10n.Calls.calling
            } else if call.state == .over {
                return L10n.Calls.callFinished
            } else {
                return ""
            }
        })
    }()
153

154 155 156 157 158 159 160 161 162
    lazy var showCallOptions: Observable<Bool> = {
        return Observable.combineLatest(self.screenTapped.asObservable(), callPaused) { (tapped, paused) in
            if self.isAudioOnly {
                return false
            }
            if tapped && !paused {
                return true
            }
            return false
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
163 164 165
        }
    }()

166 167 168
    lazy var showCancelOption: Observable<Bool> = {
        return self.callService.currentCall.map({ call in
            return call.state == .connecting || call.state == .ringing
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
169 170 171 172 173
        })
    }()

    var screenTapped = BehaviorSubject(value: false)

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
174 175 176 177
    lazy var videoButtonState: Observable<UIImage?> = {
        let onImage = UIImage(asset: Asset.videoRunning)
        let offImage = UIImage(asset: Asset.videoMuted)

178 179 180
        return self.videoMuted.map({ [unowned self] muted in
            let audioOnly = self.call?.isAudioOnly ?? false
            if audioOnly || muted {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
                return offImage
            }
            return onImage
        })
    }()

    lazy var videoMuted: Observable<Bool> = {
        return self.callService.currentCall.filter({ call in
            call.callId == self.call?.callId &&
                call.state == .current
        }).map({call in
            return call.videoMuted
        })
    }()

    lazy var audioButtonState: Observable<UIImage?> = {
        let onImage = UIImage(asset: Asset.audioRunning)
        let offImage = UIImage(asset: Asset.audioMuted)

        return self.audioMuted.map({ muted in
            if muted {
                return offImage
            }
            return onImage
        })
    }()

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    lazy var speakerButtonState: Observable<UIImage?> = {
        let offImage = UIImage(asset: Asset.disableSpeakerphone)
        let onImage = UIImage(asset: Asset.enableSpeakerphone)

        return self.isOutputToSpeaker
            .map({ speaker in
                if speaker {
                    return onImage
                }
                return offImage
            })
    }()

    lazy var isOutputToSpeaker: Observable<Bool> = {
        return self.audioService.isOutputToSpeaker.asObservable()
    }()

    lazy var speakerSwitchable: Observable<Bool> = {
        return self.audioService.isHeadsetConnected.asObservable()
            .map { value in return !value }
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
230 231 232 233 234 235 236 237 238
    lazy var audioMuted: Observable<Bool> = {
        return self.callService.currentCall.filter({ call in
            call.callId == self.call?.callId &&
                call.state == .current
        }).map({call in
            return call.audioMuted
        })
    }()

239
    lazy var pauseCallButtonState: Observable<UIImage?> = {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
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
        let unpauseCall = UIImage(asset: Asset.unpauseCall)
        let pauseCall = UIImage(asset: Asset.pauseCall)

        return self.callPaused.map({ muted in
            if muted {
                return unpauseCall
            }
            return pauseCall
        })
    }()

    lazy var callPaused: Observable<Bool> = {
        return self.callService.currentCall.filter({ call in
            call.callId == self.call?.callId &&
                (call.state == .hold ||
                    call.state == .unhold ||
                    call.state == .current)
        }).map({call in
            if  call.state == .hold ||
                (call.state == .current && call.peerHolding) {
                return true
            }
            return false
        })
    }()

266 267 268 269 270
    var containerViewModel: ButtonsContainerViewModel?

//    lazy var containerViewModel: ButtonsContainerViewModel = {
//        return ButtonsContainerViewModel(with: self.callService, audioService: self.audioService, callID: (self.call?.callId)!)
//    }()
271

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
272 273 274 275
    required init(with injectionBag: InjectionBag) {
        self.callService = injectionBag.callService
        self.contactsService = injectionBag.contactsService
        self.accountService = injectionBag.accountService
276
        self.videoService = injectionBag.videoService
277
        self.audioService = injectionBag.audioService
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
278
    }
279

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
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
    static func formattedDurationFrom(interval: Int) -> String {
        let seconds = interval % 60
        let minutes = (interval / 60) % 60
        let hours = (interval / 3600)
        return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
    }

    func cancelCall() {
        guard let call = self.call else {
            return
        }
        self.callService.hangUp(callId: call.callId)
            .subscribe(onCompleted: { [weak self] in
                self?.log.info("Call canceled")
                }, onError: { [weak self] error in
                    self?.log.error("Failed to cancel the call")
            }).disposed(by: self.disposeBag)
    }

    func answerCall() {
        guard let call = self.call else {
            return
        }
        self.callService.accept(callId: call.callId)
            .subscribe(onCompleted: { [weak self] in
                self?.log.info("Call answered")
                }, onError: { [weak self] error in
                    self?.log.error("Failed to answer the call")
            }).disposed(by: self.disposeBag)
    }

311
    func placeCall(with uri: String, userName: String, isAudioOnly: Bool = false) {
312

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
313 314 315
        guard let account = self.accountService.currentAccount else {
            return
        }
316 317 318 319 320
        if isAudioOnly {
            self.audioService.overrideToReceiver()
        } else {
            self.audioService.overrideToSpeaker()
        }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
321 322
        self.callService.placeCall(withAccount: account,
                                   toRingId: uri,
323 324
                                   userName: userName,
                                   isAudioOnly: isAudioOnly)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
325 326 327 328
            .subscribe(onSuccess: { [unowned self] callModel in
                self.call = callModel
            }).disposed(by: self.disposeBag)
    }
329 330 331 332 333

    func profileUpdated(profile: Profile) {
        guard let photo = profile.photo else {
            return
        }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
334 335 336
        guard let data = NSData(base64Encoded: photo,
                                options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) as Data? else {
                                    return
337 338 339
        }
        self.contactImageData.value = data
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
340 341 342 343

    func respondOnTap() {
        self.screenTapped.onNext(true)
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
344 345 346

    // MARK: call options

347
    func togglePauseCall() {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
        guard let call = self.call else {
            return
        }
        if call.state == .current {
            self.callService.hold(callId: call.callId)
                .subscribe(onCompleted: { [weak self] in
                    self?.log.info("call paused")
                    }, onError: { [weak self](error) in
                        self?.log.info(error)
                }).disposed(by: self.disposeBag)
        } else if call.state == .hold {
            self.callService.unhold(callId: call.callId)
                .subscribe(onCompleted: { [weak self] in
                    self?.log.info("call unpaused")
                    }, onError: { [weak self](error) in
                        self?.log.info(error)
                }).disposed(by: self.disposeBag)
        }
    }

368
    func toggleMuteAudio() {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
369 370 371 372 373 374 375
        guard let call = self.call else {
            return
        }
        let mute = !call.audioMuted
        self.callService.muteAudio(call: call.callId, mute: mute)
    }

376
    func toggleMuteVideo() {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
377 378 379 380 381 382 383 384 385 386
        guard let call = self.call else {
            return
        }
        let mute = !call.videoMuted
        self.callService.muteVideo(call: call.callId, mute: mute)
    }

    func switchCamera() {
        self.videoService.switchCamera()
    }
387 388 389 390

    func switchSpeaker() {
        self.audioService.switchSpeaker()
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
391
}