CallViewModel.swift 14.3 KB
Newer Older
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
1
/*
Quentin Muret's avatar
Quentin Muret committed
2
 *  Copyright (C) 2017-2018 Savoir-faire Linux Inc.
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
3 4 5
 *
 *  Author: Silbino Gonçalves Matado <silbino.gmatado@savoirfairelinux.com>
 *  Author: Kateryna Kostiuk <kateryna.kostiuk@savoirfairelinux.com>
Quentin Muret's avatar
Quentin Muret committed
6
 *  Author: Quentin Muret <quentin.muret@gmail.com>
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 *  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
26
import RxCocoa
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
27 28 29 30 31 32 33 34 35 36 37 38

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
39
    fileprivate let videoService: VideoService
40
    fileprivate let audioService: AudioService
41
    fileprivate let profileService: ProfilesService
42

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

46 47 48
    var isHeadsetConnected = false
    var isAudioOnly = false

49 50 51 52 53
    var call: CallModel? {
        didSet {
            guard let call = self.call else {
                return
            }
54 55
            isHeadsetConnected = self.audioService.isHeadsetConnected.value
            isAudioOnly = call.isAudioOnly
56

57
            containerViewModel = ButtonsContainerViewModel(isAudioOnly: self.isAudioOnly, with: self.callService, audioService: self.audioService, callID: call.callId)
58 59
        }
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
60

61
    // data for ViewController binding
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    lazy var contactImageData: Observable<Data?>? = {
        guard let call = self.call else {
            return nil
        }
        return self.profileService.getProfile(ringId: call.participantRingId,
                                                        createIfNotexists: true)
            .filter({ profile in
                guard let photo = profile.photo else {
                    return false
                }
                return true
            }).map({ profile in
                return NSData(base64Encoded: profile.photo!,
                              options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) as Data?
            })
    }()
79

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
80 81 82 83 84 85
    lazy var incomingFrame: Observable<UIImage?> = {
        return videoService.incomingVideoFrame.asObservable().map({ frame in
            return frame
        })
    }()
    lazy var capturedFrame: Observable<UIImage?> = {
86
        videoService.startVideoCaptureBeforeCall()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
87 88 89 90 91
        return videoService.capturedVideoFrame.asObservable().map({ frame in
            return frame
        })
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
92
    lazy var dismisVC: Observable<Bool> = {
93 94
        return callService.currentCall.filter({ [weak self] call in
            return call.callId == self?.call?.callId
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
95
        })
96 97 98
            .map({[weak self] call in
                return call.state == .over || call.state == .failure
            }).map({ hide in
99
                if hide {
100
                    self.videoService.setCameraOrientation(orientation: UIDevice.current.orientation)
101
                }
102 103
                return hide
            })
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
104 105
    }()

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
    lazy var callDuration: Driver<String> = {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
121 122 123 124 125 126 127 128
        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
129 130 131 132
            }).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
133 134
        }).flatMap({ _ in
            return timer
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
135
        }).asDriver(onErrorJustReturn: "")
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
136 137 138
    }()

    lazy var bottomInfo: Observable<String> = {
139 140
        return callService.currentCall
            .filter({ [weak self] call in
141 142
                return call.callId == self?.call?.callId &&
                    call.callType == .outgoing
143
            }).map({ [weak self] call in
144 145 146 147 148 149 150 151 152 153
                switch call.state {
                case .connecting :
                        return L10n.Calls.connecting
                case .ringing :
                        return L10n.Calls.ringing
                case .over :
                        return L10n.Calls.callFinished
                default :
                        return ""
                }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
154 155
        })
    }()
156

157
    lazy var isActiveVideoCall: Observable<Bool> = {
158 159 160 161
        return self.callService.currentCall
            .filter({ [weak self] call in
                return call.callId == self?.call?.callId
            }).map({ call in
162
                return call.state == .current && !self.isAudioOnly
163 164 165
            })
    }()

166
    lazy var showCallOptions: Observable<Bool> = {
167
        return Observable.combineLatest(self.screenTapped.asObservable(),
168
                                        isActiveVideoCall) { (tapped, shouldRespond) in
169
            if tapped && shouldRespond {
170 171 172
                return true
            }
            return false
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
173 174 175
        }
    }()

176
    lazy var showCancelOption: Observable<Bool> = {
177 178
        return self.callService.currentCall
            .filter({ [weak self] call in
179 180
                return call.callId == self?.call?.callId &&
                    (call.state == .connecting || call.state == .ringing || call.state == .current)
181
            }).map({ call in
182
            return call.state == .connecting || call.state == .ringing
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
183 184 185
        })
    }()

186 187 188 189 190 191 192 193 194 195
    lazy var showCapturedFrame: Observable<Bool> = {
        return self.callService.currentCall
            .filter({ [weak self] call in
                return call.callId == self?.call?.callId &&
                    (call.state == .connecting || call.state == .ringing || call.state == .current)
            }).map({ call in
                call.state == .current
            })
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
196 197
    var screenTapped = BehaviorSubject(value: false)

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
198 199 200 201
    lazy var videoButtonState: Observable<UIImage?> = {
        let onImage = UIImage(asset: Asset.videoRunning)
        let offImage = UIImage(asset: Asset.videoMuted)

202 203
        return self.videoMuted.map({ [weak self] muted in
            let audioOnly = self?.call?.isAudioOnly ?? false
204
            if audioOnly || muted {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
205 206 207 208 209 210 211
                return offImage
            }
            return onImage
        })
    }()

    lazy var videoMuted: Observable<Bool> = {
212 213
        return self.callService.currentCall.filter({ [weak self] call in
            call.callId == self?.call?.callId &&
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
                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
        })
    }()

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    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
254
    lazy var audioMuted: Observable<Bool> = {
255 256
        return self.callService.currentCall.filter({ [weak self] call in
            call.callId == self?.call?.callId &&
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
257 258 259 260 261 262
                call.state == .current
        }).map({call in
            return call.audioMuted
        })
    }()

263
    lazy var pauseCallButtonState: Observable<UIImage?> = {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
264 265 266 267 268 269 270 271 272 273 274 275
        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> = {
276 277
        return self.callService.currentCall.filter({ [weak self] call in
            call.callId == self?.call?.callId &&
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
278 279 280 281 282 283 284 285 286 287 288 289
                (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
        })
    }()

290 291
    var containerViewModel: ButtonsContainerViewModel?

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
292 293 294 295
    required init(with injectionBag: InjectionBag) {
        self.callService = injectionBag.callService
        self.contactsService = injectionBag.contactsService
        self.accountService = injectionBag.accountService
296
        self.videoService = injectionBag.videoService
297
        self.audioService = injectionBag.audioService
298
        self.profileService = injectionBag.profileService
299 300 301 302 303 304 305 306 307

        callService.currentCall.filter({ [weak self] call in
            return call.callId == self?.call?.callId
        }).map({ call in
            return call.state == .current
        }).subscribe(onNext: { _ in
            self.videoService.setCameraOrientation(orientation: UIDevice.current.orientation)
        }).disposed(by: self.disposeBag)

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
308
    }
309

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
310 311 312 313
    static func formattedDurationFrom(interval: Int) -> String {
        let seconds = interval % 60
        let minutes = (interval / 60) % 60
        let hours = (interval / 3600)
314 315 316 317 318 319
        switch hours {
        case 0:
            return String(format: "%02d:%02d", minutes, seconds)
        default:
            return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
        }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
320 321 322 323 324 325 326 327
    }

    func cancelCall() {
        guard let call = self.call else {
            return
        }
        self.callService.hangUp(callId: call.callId)
            .subscribe(onCompleted: { [weak self] in
328 329 330
                // switch to either spk or headset (if connected) for loud ringtone
                // incase we were using rcv during the call
                self?.audioService.setToRing()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
331 332 333 334 335 336
                self?.log.info("Call canceled")
                }, onError: { [weak self] error in
                    self?.log.error("Failed to cancel the call")
            }).disposed(by: self.disposeBag)
    }

337
    func answerCall() -> Completable {
338 339 340 341
        // switch to rcv if that's what we were last using
        if !self.audioService.isHeadsetConnected.value && !self.audioService.isOutputToSpeaker.value {
            self.audioService.overrideToReceiver()
        }
342
        return self.callService.accept(call: call)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
343 344
    }

345
    func placeCall(with uri: String, userName: String, isAudioOnly: Bool = false) {
346

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
347 348 349
        guard let account = self.accountService.currentAccount else {
            return
        }
350 351
        // switch to rcv if audio only and no headset connected
        if isAudioOnly && !self.audioService.isHeadsetConnected.value {
352 353
            self.audioService.overrideToReceiver()
        }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
354 355
        self.callService.placeCall(withAccount: account,
                                   toRingId: uri,
356 357
                                   userName: userName,
                                   isAudioOnly: isAudioOnly)
358 359
            .subscribe(onSuccess: { [weak self] callModel in
                self?.call = callModel
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
360 361
            }).disposed(by: self.disposeBag)
    }
362

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
363 364 365
    func respondOnTap() {
        self.screenTapped.onNext(true)
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
366 367 368

    // MARK: call options

369
    func togglePauseCall() {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        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)
        }
    }

390
    func toggleMuteAudio() {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
391 392 393 394 395 396 397
        guard let call = self.call else {
            return
        }
        let mute = !call.audioMuted
        self.callService.muteAudio(call: call.callId, mute: mute)
    }

398
    func toggleMuteVideo() {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
399 400 401 402 403 404 405 406 407 408
        guard let call = self.call else {
            return
        }
        let mute = !call.videoMuted
        self.callService.muteVideo(call: call.callId, mute: mute)
    }

    func switchCamera() {
        self.videoService.switchCamera()
    }
409 410 411 412

    func switchSpeaker() {
        self.audioService.switchSpeaker()
    }
413 414 415 416

    func setCameraOrientation(orientation: UIDeviceOrientation) {
        videoService.setCameraOrientation(orientation: orientation)
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
417
}