AppDelegate.swift 24.2 KB
Newer Older
Guillaume Roguez's avatar
Guillaume Roguez committed
1
/*
2
 *  Copyright (C) 2017-2019 Savoir-faire Linux Inc.
Guillaume Roguez's avatar
Guillaume Roguez committed
3 4
 *
 *  Author: Edric Ladent-Milaret <edric.ladent-milaret@savoirfairelinux.com>
5
 *  Author: Romain Bertozzi <romain.bertozzi@savoirfairelinux.com>
6
 *  Author: Thibault Wittemberg <thibault.wittemberg@savoirfairelinux.com>
7
 *  Author: Quentin Muret <quentin.muret@savoirfairelinux.com>
Guillaume Roguez's avatar
Guillaume Roguez committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 *  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 UIKit
25
import SwiftyBeaver
26
import RxSwift
27
import PushKit
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
28
import ContactsUI
Guillaume Roguez's avatar
Guillaume Roguez committed
29

30
// swiftlint:disable identifier_name
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
31
// swiftlint:disable type_body_length
Guillaume Roguez's avatar
Guillaume Roguez committed
32
@UIApplicationMain
33
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
Guillaume Roguez's avatar
Guillaume Roguez committed
34
    var window: UIWindow?
35 36 37 38
    let dBManager = DBManager(profileHepler: ProfileDataHelper(),
                              conversationHelper: ConversationDataHelper(),
                              interactionHepler: InteractionDataHelper(),
                              dbConnections: DBContainer())
39 40
    private let daemonService = DaemonService(dRingAdaptor: DRingAdapter())
    private let nameService = NameService(withNameRegistrationAdapter: NameRegistrationAdapter())
41
    private let presenceService = PresenceService(withPresenceAdapter: PresenceAdapter())
42
    private let videoService = VideoService(withVideoAdapter: VideoAdapter())
43
    private let audioService = AudioService(withAudioAdapter: AudioAdapter())
44
    private let networkService = NetworkService()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
45
    private let callsProvider: CallsProviderDelegate = CallsProviderDelegate()
46
    private var conversationManager: ConversationsManager?
47
    private var interactionsManager: GeneratedInteractionsManager?
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    private lazy var callService: CallsService = {
        CallsService(withCallsAdapter: CallsAdapter(), dbManager: self.dBManager)
    }()
    private lazy var accountService: AccountsService = {
        AccountsService(withAccountAdapter: AccountAdapter(), dbManager: self.dBManager)
    }()
    private lazy var contactsService: ContactsService = {
        ContactsService(withContactsAdapter: ContactsAdapter(), dbManager: self.dBManager)
    }()
    private lazy var profileService: ProfilesService = {
        ProfilesService(dbManager: self.dBManager)
    }()
    private lazy var dataTransferService: DataTransferService = {
        DataTransferService(withDataTransferAdapter: DataTransferAdapter(),
                            dbManager: self.dBManager)
    }()
    private lazy var conversationsService: ConversationsService = {
        ConversationsService(withMessageAdapter: MessagesAdapter(), dbManager: self.dBManager)
    }()
67

68 69
    private let voipRegistry = PKPushRegistry(queue: DispatchQueue.main)

70 71 72 73 74
    public lazy var injectionBag: InjectionBag = {
        return InjectionBag(withDaemonService: self.daemonService,
                            withAccountService: self.accountService,
                            withNameService: self.nameService,
                            withConversationService: self.conversationsService,
75
                            withContactsService: self.contactsService,
76
                            withPresenceService: self.presenceService,
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
77
                            withNetworkService: self.networkService,
78
                            withCallService: self.callService,
79
                            withVideoService: self.videoService,
80
                            withAudioService: self.audioService,
81
                            withDataTransferService: self.dataTransferService,
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
82 83
                            withProfileService: self.profileService,
                            withCallsProvider: self.callsProvider)
84 85 86 87
    }()
    private lazy var appCoordinator: AppCoordinator = {
        return AppCoordinator(with: self.injectionBag)
    }()
88

89
    private let log = SwiftyBeaver.self
Guillaume Roguez's avatar
Guillaume Roguez committed
90

91 92
    fileprivate let disposeBag = DisposeBag()

93
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
94

95
        // ignore sigpipe
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
96
        // swiftlint:disable nesting
97 98 99
        typealias SigHandler = @convention(c) (Int32) -> Void
        let SIG_IGN = unsafeBitCast(OpaquePointer(bitPattern: 1), to: SigHandler.self)
        signal(SIGPIPE, SIG_IGN)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
100
        // swiftlint:enable nesting
101

102 103
        self.window = UIWindow(frame: UIScreen.main.bounds)

104
        UserDefaults.standard.setValue(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")
105 106 107
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
        }
108 109 110 111 112
        // initialize log format
        let console = ConsoleDestination()
        console.format = "$Dyyyy-MM-dd HH:mm:ss.SSS$d $C$L$c: $M"
        log.addDestination(console)

113
        // starts the daemon
114
        SystemAdapter().registerConfigurationHandler()
115
        self.startDaemon()
116

117 118 119
        // sets output device to whatever is currently available (either spk / headset)
        self.audioService.startAVAudioSession()

120 121 122 123 124
        // requests permission to use the camera
        // will enumerate and add devices once permission has been granted
        self.videoService.setupInputs()

        // start monitoring for network changes
125 126
        self.networkService.monitorNetworkType()

127 128 129 130 131 132 133
        // Observe connectivity changes and reconnect DHT
        self.networkService.connectionStateObservable
            .subscribe(onNext: { _ in
                self.daemonService.connectivityChanged()
            })
            .disposed(by: self.disposeBag)

134 135 136 137
        self.interactionsManager = GeneratedInteractionsManager(accountService: self.accountService,
                                                                contactService: self.contactsService,
                                                                conversationService: self.conversationsService,
                                                                callService: self.callService)
138

139 140
        // load accounts during splashscreen
        // and ask the AppCoordinator to handle the first screen once loading is finished
141 142 143
        self.conversationManager = ConversationsManager(with: self.conversationsService,
                                                        accountsService: self.accountService,
                                                        nameService: self.nameService,
144 145
                                                        dataTransferService: self.dataTransferService,
                                                        callService: self.callService)
146 147 148
        self.window?.rootViewController = self.appCoordinator.rootViewController
        self.window?.makeKeyAndVisible()

149 150
        prepareVideoAcceleration()

151
        self.accountService.initialAccountsLoading().subscribe(onCompleted: {
152
            //set selected account if exists
153
            self.appCoordinator.start()
154 155 156 157
            if let selectedAccountId = UserDefaults.standard.string(forKey: self.accountService.selectedAccountID),
                let account = self.accountService.getAccount(fromAccountId: selectedAccountId) {
                self.accountService.currentAccount = account
            }
158 159
            guard let currentAccount = self.accountService.currentAccount else {
                self.log.error("Can't get current account!")
160 161 162 163
                //if we don't have any account means it is first run, so enable hardware acceleration
                self.videoService.setDecodingAccelerated(withState: true)
                self.videoService.setEncodingAccelerated(withState: true)
                UserDefaults.standard.set(true, forKey: hardareAccelerationKey)
164 165
                return
            }
166 167

            for account in self.accountService.accounts {
168
                self.accountService.setDetails(forAccountId: account.id)
169
            }
170 171 172 173 174 175
            self.reloadDataFor(account: currentAccount)
            if self.accountService.proxyEnabled() {
                self.registerVoipNotifications()
            } else {
                self.unregisterVoipNotifications()
            }
176
            if #available(iOS 10.0, *) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
177 178
                return
            }
179 180
            // reimit new call signal to show incoming call alert
            self.callService.checkForIncomingCall()
181 182 183 184 185 186 187
        }, onError: { _ in
            self.appCoordinator.start()
            let time = DispatchTime.now() + 1
            DispatchQueue.main.asyncAfter(deadline: time) {
                self.appCoordinator.showDatabaseError()
            }
        }).disposed(by: self.disposeBag)
188 189 190 191 192 193

        self.accountService.currentAccountChanged
            .subscribe(onNext: { account in
                guard let currentAccount = account else {return}
                self.reloadDataFor(account: currentAccount)
            }).disposed(by: self.disposeBag)
194 195 196 197
        self.voipRegistry.delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(registerVoipNotifications),
                                               name: NSNotification.Name(rawValue: NotificationName.enablePushNotifications.rawValue),
                                               object: nil)
198
        self.clearBadgeNumber()
Guillaume Roguez's avatar
Guillaume Roguez committed
199 200
        return true
    }
Edric Milaret's avatar
Edric Milaret committed
201

202 203 204 205
    func reloadDataFor(account: AccountModel) {
        self.contactsService.loadContacts(withAccount: account)
        self.contactsService.loadContactRequests(withAccount: account)
        self.presenceService.subscribeBuddies(withAccount: account, withContacts: self.contactsService.contacts.value)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
206 207
        self.conversationManager?
                .prepareConversationsForAccount(accountId: account.id)
208 209
    }

210 211
    func applicationDidEnterBackground(_ application: UIApplication) {
        self.log.warning("entering background")
212
        self.callService.muteCurrentCallVideoVideo( mute: true)
213 214 215 216 217
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        self.log.warning("entering foreground")
        self.daemonService.connectivityChanged()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
218
        self.updateNotificationAvailability()
219
        self.callService.muteCurrentCallVideoVideo( mute: false)
220 221
    }

222
    func applicationWillTerminate(_ application: UIApplication) {
223
        self.stopDaemon()
Guillaume Roguez's avatar
Guillaume Roguez committed
224 225
    }

226 227
    func applicationDidBecomeActive(_ application: UIApplication) {
        self.clearBadgeNumber()
228
        if #available(iOS 10.0, *) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
229 230 231
            return
        }
        self.callService.checkForIncomingCall()
232 233
    }

234 235 236 237
    func prepareVideoAcceleration() {
        // we want enable hardware acceleration by default so if key does not exists,
        // means it was not disabled by user 
        let keyExists = UserDefaults.standard.object(forKey: hardareAccelerationKey) != nil
238
        let enable = keyExists ? UserDefaults.standard.bool(forKey: hardareAccelerationKey) : true
239 240 241 242
        self.videoService.setDecodingAccelerated(withState: enable)
        self.videoService.setEncodingAccelerated(withState: enable)
    }

243 244 245
    // MARK: - Ring Daemon
    fileprivate func startDaemon() {
        do {
246
            try self.daemonService.startDaemon()
247
        } catch StartDaemonError.initializationFailure {
248
            log.error("Daemon failed to initialize.")
249
        } catch StartDaemonError.startFailure {
250
            log.error("Daemon failed to start.")
251
        } catch StartDaemonError.daemonAlreadyRunning {
252
            log.error("Daemon already running.")
253
        } catch {
254
            log.error("Unknown error in Daemon start.")
255 256 257 258 259
        }
    }

    fileprivate func stopDaemon() {
        do {
260
            try self.daemonService.stopDaemon()
261
        } catch StopDaemonError.daemonNotRunning {
262
            log.error("Daemon failed to stop because it was not already running.")
263
        } catch {
264
            log.error("Unknown error in Daemon stop.")
265 266
        }
    }
267

268
    // swiftlint:disable cyclomatic_complexity
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
269 270 271 272 273 274 275 276 277 278 279 280
    func updateNotificationAvailability() {
        let enabled = LocalNotificationsHelper.isEnabled()
        if #available(iOS 10.0, *) {
            let currentSettings = UNUserNotificationCenter.current()
            currentSettings.getNotificationSettings(completionHandler: { settings in
                switch settings.authorizationStatus {
                case .notDetermined:
                    break
                case .denied:
                    if enabled { LocalNotificationsHelper.setNotification(enable: false) }
                case .authorized:
                    if !enabled { LocalNotificationsHelper.setNotification(enable: true)}
281 282
                case .provisional:
                    if !enabled { LocalNotificationsHelper.setNotification(enable: true)}
283 284
                @unknown default:
                    break
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
285 286 287 288 289 290 291 292 293 294 295
                }
            })
        } else {
            if UIApplication.shared.isRegisteredForRemoteNotifications {
                if !enabled {LocalNotificationsHelper.setNotification(enable: true)}
            } else {
                if enabled {LocalNotificationsHelper.setNotification(enable: false)}
            }
        }
    }

296 297
    @objc private func registerVoipNotifications() {
        self.requestNotificationAuthorization()
298 299 300
        if self.voipRegistry.desiredPushTypes == nil {
            self.voipRegistry.desiredPushTypes = Set([PKPushType.voIP])
        }
301 302
    }

303 304 305
    private func unregisterVoipNotifications() {
        self.voipRegistry.desiredPushTypes = nil
        self.accountService.savePushToken(token: "")
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
306
        self.accountService.setPushNotificationToken(token: "")
307 308
    }

309
    private func requestNotificationAuthorization() {
310 311
        let application = UIApplication.shared
        if #available(iOS 10.0, *) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
312 313 314 315 316 317 318 319 320 321 322
            DispatchQueue.main.async {
                UNUserNotificationCenter.current().delegate = application.delegate as? UNUserNotificationCenterDelegate
                let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
                UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (enable, _) in
                    if enable {
                        LocalNotificationsHelper.setNotification(enable: true)
                    } else {
                        LocalNotificationsHelper.setNotification(enable: false)
                    }
                })
            }
323 324 325 326 327
        } else {
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
    }
328

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
329 330 331 332 333 334 335 336 337
    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        let enabled = notificationSettings.types.contains(.alert)
        if enabled {
            LocalNotificationsHelper.setNotification(enable: true)
        } else {
            LocalNotificationsHelper.setNotification(enable: false)
        }
    }

338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    private func clearBadgeNumber() {
        UIApplication.shared.applicationIconBadgeNumber = 0
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.removeAllDeliveredNotifications()
            center.removeAllPendingNotificationRequests()
        } else {
            UIApplication.shared.cancelAllLocalNotifications()
        }
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let data = response.notification.request.content.userInfo
        self.handleNotificationActions(data: data, responseIdentifier: response.actionIdentifier)
        completionHandler()
    }

    func handleNotificationActions(data: [AnyHashable: Any], responseIdentifier: String) {
357 358 359 360 361 362 363
        guard let currentAccount = self.accountService
            .currentAccount,
            let accountId = data[NotificationUserInfoKeys.accountID.rawValue] as? String,
            let account = self.accountService.getAccount(fromAccountId: accountId) else { return }
        if currentAccount.id != accountId && responseIdentifier != CallAcition.refuse.rawValue {
            self.accountService.currentAccount = account
        }
364 365 366 367 368
        // if notification contains messageContent this is message notification
        if let participantID = data[NotificationUserInfoKeys.participantID.rawValue] as? String {
            self.appCoordinator.openConversation(participantID: participantID)
            return
        }
369 370 371 372 373 374 375 376 377 378 379 380 381 382
        guard let callID = data[NotificationUserInfoKeys.callID.rawValue] as? String else {
            return
        }
        switch responseIdentifier {
        case CallAcition.accept.rawValue:
            NotificationCenter.default.post(name: NSNotification.Name(NotificationName.answerCallFromNotifications.rawValue),
                                            object: nil,
                                            userInfo: data)
        case CallAcition.refuse.rawValue:
            self.callService.refuse(callId: callID)
                .subscribe({_ in
                    print("Call ignored")
                }).disposed(by: self.disposeBag)
        default:
383 384 385 386
            // automatically answer call when user tap the notifications
            NotificationCenter.default.post(name: NSNotification.Name(NotificationName.answerCallFromNotifications.rawValue),
                                            object: nil,
                                            userInfo: data)
387 388 389 390 391 392 393 394 395
        }
    }

    func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) {
        if let identifier = identifier, let data = notification.userInfo {
            self.handleNotificationActions(data: data, responseIdentifier: identifier)
        }
        completionHandler()
    }
396

397 398 399 400 401 402 403 404 405 406
    // handle notifications click before iOS 10.0
    func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
        guard let info = notification.userInfo else {return}
        if (info[NotificationUserInfoKeys.callID.rawValue] as? String) != nil {
             handleNotificationActions(data: info, responseIdentifier: CallAcition.accept.rawValue)
        } else if (info[NotificationUserInfoKeys.messageContent.rawValue] as? String) != nil {
            handleNotificationActions(data: info, responseIdentifier: "messageReceived")
        }
    }

407 408
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if let rootViewController = self.topViewControllerWithRootViewController(rootViewController: window?.rootViewController) {
409
            if rootViewController.responds(to: #selector(CallViewController.canRotate)) {
410 411 412 413 414 415 416 417 418 419 420
                return .all
            }
        }
        return .portrait
    }

    private func topViewControllerWithRootViewController(rootViewController: UIViewController!) -> UIViewController? {
        if rootViewController == nil {
            return nil
        }
        if rootViewController.isKind(of: (UITabBarController).self) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
421
            return topViewControllerWithRootViewController(rootViewController: (rootViewController as? UITabBarController)?.selectedViewController)
422
        } else if rootViewController.isKind(of: (UINavigationController).self) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
423
            return topViewControllerWithRootViewController(rootViewController: (rootViewController as? UINavigationController)?.visibleViewController)
424 425 426 427 428
        } else if rootViewController.presentedViewController != nil {
            return topViewControllerWithRootViewController(rootViewController: rootViewController.presentedViewController)
        }
        return rootViewController
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

    func findContactAndStartCall(hash: String, isVideo: Bool) {
        //if saved jami hash
        if hash.isSHA1() {
            let contactUri = JamiURI(schema: URIType.ring, infoHach: hash)
            self.findAccountAndStartCall(uri: contactUri, isVideo: isVideo, type: AccountType.ring)
            return
        }
        //if saved jami registered name
        self.nameService.usernameLookupStatus
            .observeOn(MainScheduler.instance)
            .filter({ usernameLookupStatus in
                usernameLookupStatus.name == hash
            })
            .take(1)
            .subscribe(onNext: { usernameLookupStatus in
                if usernameLookupStatus.state == .found {
                    guard let address = usernameLookupStatus.address else {return}
                    let contactUri = JamiURI(schema: URIType.ring, infoHach: address)
                    self.findAccountAndStartCall(uri: contactUri, isVideo: isVideo, type: AccountType.ring)
                } else {
                    //if saved sip contact
                    let contactUri = JamiURI(schema: URIType.sip, infoHach: hash)
                    self.findAccountAndStartCall(uri: contactUri, isVideo: isVideo, type: AccountType.sip)
                }
            }).disposed(by: self.disposeBag)
        self.nameService.lookupName(withAccount: "", nameserver: "", name: hash)
    }

    func findAccountAndStartCall(uri: JamiURI, isVideo: Bool, type: AccountType) {
        guard let currentAccount = self.accountService
            .currentAccount else { return }
        var hash = uri.hash ?? ""
        var uriString = uri.uriString ?? ""
        for account in self.accountService.accounts where account.type == type {
            if type == AccountType.sip {
                let conatactUri = JamiURI(schema: URIType.sip,
                                          infoHach: hash,
                                          account: account)
                hash = conatactUri.hash ?? ""
                uriString = conatactUri.uriString ?? ""
            }
            if hash.isEmpty || uriString.isEmpty {return}
            self.contactsService
                .getProfileForUri(uri: uriString,
                                  accountId: account.id)
                .subscribe(onNext: { (profile) in
                    if currentAccount != account {
                        self.accountService.currentAccount = account
                    }
                    self.appCoordinator
                        .startCall(participant: hash,
                                   name: profile.alias ?? "",
                                   isVideo: isVideo)
                }).disposed(by: self.disposeBag)
        }
    }

    func application(_ application: UIApplication,
                     continue userActivity: NSUserActivity,
                     restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
490
        if #available(iOS 10.0, *) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
491 492 493 494 495 496 497 498
            guard let handle = userActivity.startCallHandle else {
                return false
            }
            self.findContactAndStartCall(hash: handle.hash, isVideo: handle.isVideo)
            return true
        }
        return false
    }
499 500 501 502 503
}

extension AppDelegate: PKPushRegistryDelegate {

    func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenFor type: PKPushType) {
504
        self.accountService.savePushToken(token: "")
505 506 507 508
        self.accountService.setPushNotificationToken(token: "")
    }

    func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
509
        self.accountService.pushNotificationReceived(data: payload.dictionaryPayload)
510
        if #available(iOS 10.0, *) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
511 512
            return
        }
513 514 515
        if UIApplication.shared.applicationState != .active {
            self.audioService.startAVAudioSession()
        }
516 517 518 519 520
    }

    func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
        if type == PKPushType.voIP {
            let deviceTokenString = pushCredentials.token.map { String(format: "%02.2hhx", $0) }.joined()
521
            self.accountService.savePushToken(token: deviceTokenString)
522 523 524
            self.accountService.setPushNotificationToken(token: deviceTokenString)
        }
    }
Guillaume Roguez's avatar
Guillaume Roguez committed
525
}