AccountsService.swift 32.4 KB
Newer Older
1
/*
2
 *  Copyright (C) 2017-2019 Savoir-faire Linux Inc.
3 4 5
 *
 *  Authors: Edric Ladent-Milaret <edric.ladent-milaret@savoirfairelinux.com>
 *           Romain Bertozzi <romain.bertozzi@savoirfairelinux.com>
6
 *  Author: Quentin Muret <quentin.muret@savoirfairelinux.com>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 *  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.
 */

23 24
import RxCocoa
import RxSwift
25
import RealmSwift
26
import SwiftyBeaver
27

28 29 30 31
enum LinkNewDeviceError: Error {
    case unknownError
}

32 33 34 35 36 37
enum DeviceRevocationState: Int {
    case success = 0
    case wrongPassword = 1
    case unknownDevice = 2
}

38
enum AddAccountError: Error {
39 40
    case templateNotConform
    case unknownError
41
    case noAccountFound
42 43
}

44 45 46
enum NotificationName: String {
    case enablePushNotifications
    case disablePushNotifications
47 48
    case answerCallFromNotifications
    case refuseCallFromNotifications
49
    case nameRegistered
50 51
}

52 53
// swiftlint:disable type_body_length
// swiftlint:disable file_length
54 55
class AccountsService: AccountAdapterDelegate {
    // MARK: Private members
56 57 58 59 60 61

    /**
     logguer
     */
    private let log = SwiftyBeaver.self

62
    let selectedAccountID = "SELECTED_ACCOUNT_ID"
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
63

64
    /**
65
     Used to register the service to daemon events, injected by constructor.
66
     */
67
    fileprivate let accountAdapter: AccountAdapter
68

69 70 71 72 73 74
    /**
     Fileprivate Accounts list.
     Can be used for all the operations, but won't be accessed from outside this file.

     - SeeAlso: `accounts`
     */
75
    fileprivate var accountList: [AccountModel]
76

77 78 79 80 81 82 83
    fileprivate let disposeBag = DisposeBag()

    /**
     PublishSubject forwarding AccountRxEvent events.
     This stream is used strictly inside this service.
     External observers should use the public shared responseStream.

84
     - SeeAlso: `ServiceEvent`
85 86
     - SeeAlso: `sharedResponseStream`
     */
87
    fileprivate let responseStream = PublishSubject<ServiceEvent>()
88
    let dbManager: DBManager
89

90 91 92 93 94
    // MARK: - Public members
    /**
     Accounts list public interface.
     Can be used to access by constant the list of accounts.
     */
95
    var accounts: [AccountModel] {
96 97 98 99 100 101 102 103 104
        set {
            accountList = newValue
        }
        get {
            let lAccounts = accountList
            return lAccounts
        }
    }

105 106 107 108
    var accountsObservable = Variable<[AccountModel]>([AccountModel]())

    let currentAccountChanged = PublishSubject<AccountModel?>()

109 110 111 112 113
    /**
     Public shared stream forwarding the events of the responseStream.
     External observers must subscribe to this stream to get results.

     - SeeAlso: `responseStream`
114
     - SeeAlso: `ServiceEvent`
115
     */
116
    var sharedResponseStream: Observable<ServiceEvent>
117

118 119 120 121 122 123 124 125
    /**
     Current account computed property

     This will reorganize the order of the accounts. The current account needs to be first.

     - Parameter account: the account to set as current.
     */

126
    var currentAccount: AccountModel? {
127 128 129 130 131 132 133 134 135 136
        get {
            return self.accountList.first
        }

        set {
            //Get the current account from account list if already exists
            let currentAccount = self.accountList.filter({ account in
                return account == newValue
            }).first

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
137 138
            guard let newAccount = newValue else { return }

139
            //If current account already exists in the list, move it to the first index
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
140
            if let currentAccount = currentAccount,
141
                let index = self.accountList.firstIndex(of: currentAccount) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
142
                self.accountList.remove(at: index)
143 144
                self.accountList.insert(currentAccount, at: 0)
            } else {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
145
                self.accountList.append(newAccount)
146
            }
147
            currentAccountChanged.onNext(currentAccount)
148 149
        }
    }
150

151
    init(withAccountAdapter accountAdapter: AccountAdapter, dbManager: DBManager) {
152 153
        self.accountList = []

154
        self.responseStream.disposed(by: disposeBag)
155 156 157

        //~ Create a shared stream based on the responseStream one.
        self.sharedResponseStream = responseStream.share()
158

159
        self.accountAdapter = accountAdapter
160
        self.dbManager = dbManager
161 162 163
        //~ Registering to the accountAdatpter with self as delegate in order to receive delegation
        //~ callbacks.
        AccountAdapter.delegate = self
164 165
    }

166
    fileprivate func loadAccountsFromDaemon() {
167 168
        let selectedAccount = self.currentAccount
        self.accountList.removeAll()
169
        for accountId in accountAdapter.getAccountList() {
170 171 172
            if  let id = accountId as? String {
                self.accountList.append(AccountModel(withAccountId: id))
            }
173 174
        }
        reloadAccounts()
175 176 177 178 179
        accountsObservable.value = self.accountList
        if selectedAccount != nil {
            let currentAccount = self.accountList.filter({ account in
                return account == selectedAccount
            }).first
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
180
            if let currentAccount = currentAccount,
181
                let index = self.accountList.firstIndex(of: currentAccount) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
182
                self.accountList.remove(at: index)
183 184 185
                self.accountList.insert(currentAccount, at: 0)
            }
        }
186 187
    }

188 189 190 191
    fileprivate func loadDatabases() -> Bool {
        for account in accountList {
            if dbManager.isNeedMigrationToAccountDB(accountId: account.id) {
                do {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
192 193 194 195 196
                    if let jamiId = AccountModelHelper
                        .init(withAccount: account).ringId {
                        try dbManager.migrateToAccountDB(accountId: account.id,
                                                         jamiId: jamiId)
                    }
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
                } catch { return false}
            } else {
                do {
                    // return false if could not open database connection
                    if try !dbManager.createDatabaseForAccount(accountId: account.id) {
                        return false
                    }
                    //if tables already exist an exeption will be thrown
                } catch { }
            }
        }
        return true
    }

    func initialAccountsLoading() -> Completable {
        return Completable.create { [unowned self] completable in
            self.loadAccountsFromDaemon()
            if self.accountList.isEmpty {
                completable(.completed)
            }
            if self.loadDatabases() {
                completable(.completed)
            } else {
                completable(.error(DataAccessError.databaseError))
            }
            return Disposables.create {}
        }
    }

226 227 228 229
    func loadAccounts() -> Single<[AccountModel]> {
        return Single<[AccountModel]>.just({
            loadAccountsFromDaemon()
            return accountList
230
            }())
231 232
    }

233 234
    // MARK: - Methods
    func hasAccounts() -> Bool {
235
        return !accountList.isEmpty
236 237
    }

238 239 240 241
    fileprivate func reloadAccounts() {
        for account in accountList {
            account.details = self.getAccountDetails(fromAccountId: account.id)
            account.volatileDetails = self.getVolatileAccountDetails(fromAccountId: account.id)
242
            account.devices = getKnownRingDevices(fromAccountId: account.id)
243 244

            do {
245 246
                let credentialDetails = try self.getAccountCredentials(fromAccountId: account.id)
                account.credentialDetails.removeAll()
247
                account.credentialDetails.append(contentsOf: credentialDetails)
248
            } catch {
249
                log.error("\(error)")
250 251
            }
        }
252 253
    }

254 255 256 257
    func getAccountProfile(accountId: String) -> AccountProfile? {
        return self.dbManager.accountProfile(for: accountId)
    }

258 259 260 261 262 263
    /// Adds a new Ring account.
    ///
    /// - Parameters:
    ///   - username: an optional username for the new account
    ///   - password: the required password for the new account
    /// - Returns: an observable of an AccountModel: the created one
264
    func addRingAccount(username: String?, password: String, enable: Bool) -> Observable<AccountModel> {
265
        //~ Single asking the daemon to add a new account with the associated metadata
266
        var newAccountId = ""
267 268 269 270 271 272 273 274 275
        let createAccountSingle: Single<AccountModel> = Single.create(subscribe: { (single) -> Disposable in
            do {
                var ringDetails = try self.getRingInitialAccountDetails()
                if let username = username {
                    ringDetails.updateValue(username, forKey: ConfigKey.accountRegisteredName.rawValue)
                }
                if !password.isEmpty {
                    ringDetails.updateValue(password, forKey: ConfigKey.archivePassword.rawValue)
                }
276
                ringDetails.updateValue(enable.toString(), forKey: ConfigKey.proxyEnabled.rawValue)
277 278 279
                guard let accountId = self.accountAdapter.addAccount(ringDetails) else {
                    throw AddAccountError.unknownError
                }
280
                newAccountId = accountId
281 282 283 284
                let account = try self.buildAccountFromDaemon(accountId: accountId)
                single(.success(account))
            } catch {
                single(.error(error))
285
            }
286
            return Disposables.create {
287
            }
288 289 290 291 292
        })

        //~ Filter the daemon signals to isolate the "account created" one.
        let filteredDaemonSignals = self.sharedResponseStream
            .filter { (serviceEvent) -> Bool in
293 294 295 296 297 298 299 300 301 302
                if serviceEvent.getEventInput(ServiceEventInput.accountId) != newAccountId {return false}
                if serviceEvent.getEventInput(ServiceEventInput.registrationState) == ErrorGeneric {
                    throw AccountCreationError.generic
                } else if serviceEvent.getEventInput(ServiceEventInput.registrationState) == ErrorNetwork {
                    throw AccountCreationError.network
                }
                let isRegistrationStateChanged = serviceEvent.eventType == ServiceEventType.registrationStateChanged
                let isRegistered = serviceEvent.getEventInput(ServiceEventInput.registrationState) == Registered
                let notRegistered = serviceEvent.getEventInput(ServiceEventInput.registrationState) == Unregistered
                return isRegistrationStateChanged && (isRegistered || notRegistered)
303
        }
304 305 306 307 308 309 310

        //~ Make sure that we have the correct account added in the daemon, and return it.
        return Observable
            .combineLatest(createAccountSingle.asObservable(), filteredDaemonSignals.asObservable()) { (accountModel, serviceEvent) -> AccountModel in
                guard accountModel.id == serviceEvent.getEventInput(ServiceEventInput.accountId) else {
                    throw AddAccountError.unknownError
                }
311 312 313 314 315
                // create database for account and save account profile
                if try !self.dbManager.createDatabaseForAccount(accountId: accountModel.id) {
                    throw AddAccountError.unknownError
                }
                _ = self.dbManager.saveAccountProfile(alias: nil, photo: nil, accountId: accountModel.id)
316
                self.loadAccountsFromDaemon()
317 318 319
                return accountModel
            }.take(1)
            .flatMap({ [unowned self] (accountModel) -> Observable<AccountModel> in
320 321
                self.currentAccount = accountModel
                UserDefaults.standard.set(accountModel.id, forKey: self.selectedAccountID)
322 323 324 325
                return self.getAccountFromDaemon(fromAccountId: accountModel.id).asObservable()
            })
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    func addSipAccount(userName: String,
                       password: String,
                       sipServer: String,
                       port: String) -> Bool {
        do {
            var accountDetails = try self.getInitialAccountDetails(accountType: AccountType.sip.rawValue)
            accountDetails.updateValue(userName, forKey: ConfigKey.accountUsername.rawValue)
            accountDetails.updateValue(sipServer, forKey: ConfigKey.accountHostname.rawValue)
            accountDetails.updateValue(password, forKey: ConfigKey.accountPassword.rawValue)
            if !port.isEmpty {
                accountDetails.updateValue(password, forKey: ConfigKey.localPort.rawValue)
            }
            guard let account = self.accountAdapter.addAccount(accountDetails) else {return false}
            _ = try self.dbManager.createDatabaseForAccount(accountId: account)
            _ = self.dbManager.saveAccountProfile(alias: nil, photo: nil, accountId: account)
            self.loadAccountsFromDaemon()
            let newAccount = self.getAccount(fromAccountId: account)
            self.currentAccount = newAccount
            UserDefaults.standard.set(account, forKey: self.selectedAccountID)
            return true
        } catch {
            return false
        }
    }

351
    func linkToRingAccount(withPin pin: String, password: String, enable: Bool) -> Observable<AccountModel> {
352
        var newAccountId = ""
353 354 355 356 357 358 359 360 361 362
        //~ Single asking the daemon to add a new account with the associated metadata
        let createAccountSingle: Single<AccountModel> = Single.create(subscribe: { (single) -> Disposable in
            do {
                var ringDetails = try self.getRingInitialAccountDetails()
                ringDetails.updateValue(password, forKey: ConfigKey.archivePassword.rawValue)
                ringDetails.updateValue(pin, forKey: ConfigKey.archivePIN.rawValue)
                ringDetails.updateValue(enable.toString(), forKey: ConfigKey.proxyEnabled.rawValue)
                guard let accountId = self.accountAdapter.addAccount(ringDetails) else {
                    throw AddAccountError.unknownError
                }
363
                newAccountId = accountId
364 365 366 367 368 369 370 371 372 373
                let account = try self.buildAccountFromDaemon(accountId: accountId)
                single(.success(account))
            } catch {
                single(.error(error))
            }
            return Disposables.create {
            }
        })
        //~ Filter the daemon signals to isolate the "account created" one.
        let filteredDaemonSignals = self.sharedResponseStream.filter { (serviceEvent) -> Bool in
374
            if serviceEvent.getEventInput(ServiceEventInput.accountId) != newAccountId {return false}
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
            if serviceEvent.getEventInput(ServiceEventInput.registrationState) == ErrorGeneric {
                throw AccountCreationError.linkError
            } else if serviceEvent.getEventInput(ServiceEventInput.registrationState) == ErrorNetwork {
                throw AccountCreationError.network
            }
            let isRegistrationStateChanged = serviceEvent.eventType == ServiceEventType.registrationStateChanged
            let isRegistered = serviceEvent.getEventInput(ServiceEventInput.registrationState) == Registered
            return isRegistrationStateChanged && isRegistered
        }
        //~ Make sure that we have the correct account added in the daemon, and return it.
        return Observable
            .combineLatest(createAccountSingle.asObservable(), filteredDaemonSignals.asObservable()) { (accountModel, serviceEvent) -> AccountModel in
                guard accountModel.id == serviceEvent.getEventInput(ServiceEventInput.accountId) else {
                    throw AddAccountError.unknownError
                }
                // create database for account and save account profile
                if try !self.dbManager.createDatabaseForAccount(accountId: accountModel.id) {
                    throw AddAccountError.unknownError
                }
                _ = self.dbManager.saveAccountProfile(alias: nil, photo: nil, accountId: accountModel.id)
395
                self.loadAccountsFromDaemon()
396 397 398
                return accountModel
            }.take(1)
            .flatMap({ [unowned self] (accountModel) -> Observable<AccountModel> in
399 400
                self.currentAccount = accountModel
                UserDefaults.standard.set(accountModel.id, forKey: self.selectedAccountID)
401 402
                return self.getAccountFromDaemon(fromAccountId: accountModel.id).asObservable()
            })
403 404
    }

405
    func setDetails(forAccountId accountId: String) {
406
        let details = self.getAccountDetails(fromAccountId: accountId)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
407
        var filename = "default.wav"
408
        if #available(iOS 10.0, *) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
409 410
            filename = ""
        }
411
        if details
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
412
            .get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.ringtonePath)) == filename &&
413 414 415 416 417 418
            details
                .get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.dhtPeerDiscovery)) == "false" &&
            details
                .get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountPeerDiscovery)) == "false" &&
            details
                .get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountPublish)) == "false" {
419 420 421 422
            return
        }
        details
            .set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.ringtonePath),
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
423
                 withValue: filename)
424 425 426 427 428 429 430 431 432
        details
            .set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.dhtPeerDiscovery),
                 withValue: "false")
        details
            .set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountPeerDiscovery),
                 withValue: "false")
        details
            .set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountPublish),
                 withValue: "false")
433 434 435
        setAccountDetails(forAccountId: accountId, withDetails: details)
    }

436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
    /**
     Gets an account from the list of accounts handled by the application.

     - Parameter id: the id of the account to get.

     - Returns: the account if found, nil otherwise.
     */
    func getAccount(fromAccountId id: String) -> AccountModel? {
        for account in self.accountList {
            if id.compare(account.id) == ComparisonResult.orderedSame {
                return account
            }
        }
        return nil
    }

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    /// Gets the account from the daemon responding to the given id.
    ///
    /// - Parameter id: the id of the account to get.
    /// - Returns: a single of an AccountModel
    func getAccountFromDaemon(fromAccountId id: String) -> Single<AccountModel> {
        return self.loadAccounts().map({ (accountModels) -> AccountModel in
            guard let account = accountModels.filter({ (accountModel) -> Bool in
                return id == accountModel.id
            }).first else {
                throw AddAccountError.noAccountFound
            }
            return account
        })
    }

467 468 469 470 471
    /**
     Gets all the details of an account from the daemon.

     - Parameter id: the id of the account.

472
     - Returns: the details of the account.
473
     */
474
    func getAccountDetails(fromAccountId id: String) -> AccountConfigModel {
475
        let details: NSDictionary = accountAdapter.getAccountDetails(id) as NSDictionary
476
        let accountDetailsDict = details as NSDictionary? as? [String: String] ?? nil
477 478
        let accountDetails = AccountConfigModel(withDetails: accountDetailsDict)
        return accountDetails
479 480
    }

481 482 483 484 485 486 487 488 489
    /**
     Sets all the details of an account in the daemon.
     - Parameter id: the id of the account.
     - Parameter newDetails: the new details to set for the account.
     */
    func setAccountDetails(forAccountId id: String, withDetails newDetails: AccountConfigModel) {
        let details = newDetails.toDetails()
        accountAdapter.setAccountDetails(id, details: details)
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
490 491 492 493 494 495 496 497 498
    /**
     Sets credentials of an account in the daemon.
     - Parameter id: the id of the account.
     - Parameter crdentials: the new credentials to set for the account.
     */
    func setAccountCrdentials(forAccountId id: String,
                              crdentials: [[String: String]]) {
        accountAdapter.setAccountCredentials(id, credentials: crdentials)
    }
499

500 501 502 503 504
    /**
     Gets all the volatile details of an account from the daemon.

     - Parameter id: the id of the account.

505
     - Returns: the volatile details of the account.
506
     */
507
    func getVolatileAccountDetails(fromAccountId id: String) -> AccountConfigModel {
508
        let details: NSDictionary = accountAdapter.getVolatileAccountDetails(id) as NSDictionary
509
        let accountDetailsDict = details as NSDictionary? as? [String: String] ?? nil
510 511
        let accountDetails = AccountConfigModel(withDetails: accountDetailsDict)
        return accountDetails
512 513 514 515 516 517 518 519 520
    }

    /**
     Gets the credentials of an account from the daemon.

     - Parameter id: the id of the account.

     - Returns: the list of credentials.
     */
521
    func getAccountCredentials(fromAccountId id: String) throws -> [AccountCredentialsModel] {
522
        let creds: NSArray = accountAdapter.getCredentials(id) as NSArray
523
        let rawCredentials = creds as NSArray? as? [[String: String]] ?? nil
524 525

        if let rawCredentials = rawCredentials {
526
            var credentialsList = [AccountCredentialsModel]()
527 528 529 530
            for rawCredentials in rawCredentials {
                do {
                    let credentials = try AccountCredentialsModel(withRawaData: rawCredentials)
                    credentialsList.append(credentials)
531
                } catch CredentialsError.notEnoughData {
532
                    log.error("Not enough data to build a credential object.")
533
                    throw CredentialsError.notEnoughData
534
                } catch {
535
                    log.error("Unexpected error.")
536
                    throw AccountModelError.unexpectedError
537 538 539 540
                }
            }
            return credentialsList
        } else {
541
            throw AccountModelError.unexpectedError
542
        }
543 544 545 546 547 548 549 550 551
    }

    /**
     Gets the known Ring devices of an account from the daemon.

     - Parameter id: the id of the account.

     - Returns: the known Ring devices.
     */
552
    func getKnownRingDevices(fromAccountId id: String) -> [DeviceModel] {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
553
        let knownRingDevices = accountAdapter.getKnownRingDevices(id) as NSDictionary
554 555

        var devices = [DeviceModel]()
556

557 558 559
        let accountDetails = self.getAccountDetails(fromAccountId: id)
        let currentDeviceId = accountDetails.get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountDeviceId))

560
        for key in knownRingDevices.allKeys {
561
            if let key = key as? String {
562 563 564
                devices.append(DeviceModel(withDeviceId: key,
                                           deviceName: knownRingDevices.value(forKey: key) as? String,
                                           isCurrent: key == currentDeviceId))
565
            }
566 567 568
        }

        return devices
569 570
    }

571 572 573 574 575 576
    func revokeDevice(for account: String,
                      withPassword password: String,
                      deviceId: String) {
        accountAdapter.revokeDevice(account, password: password, deviceId: deviceId)
    }

577 578 579 580 581
    /**
     Gathers all the initial default details contained by any accounts, Ring or SIP.

     - Returns the details.
     */
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
582 583
    fileprivate func getInitialAccountDetails(accountType: String) throws -> [String: String] {
        let details: NSMutableDictionary = accountAdapter.getAccountTemplate(accountType)
584
        var accountDetails = details as NSDictionary? as? [String: String] ?? nil
585
        if accountDetails == nil {
586
            throw AddAccountError.templateNotConform
587
        }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
588
        accountDetails!.updateValue("oversip", forKey: ConfigKey.accountDTMFType.rawValue)
589
        accountDetails!.updateValue("true", forKey: ConfigKey.videoEnabled.rawValue)
590
        accountDetails!.updateValue("default.wav", forKey: ConfigKey.ringtonePath.rawValue)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
591 592
        accountDetails!.updateValue(accountType, forKey: ConfigKey.accountType.rawValue)
        accountDetails!.updateValue("true", forKey: ConfigKey.accountUpnpEnabled.rawValue)
593 594 595 596 597
        if accountType == AccountType.ring.rawValue {
            accountDetails!.updateValue("false", forKey: ConfigKey.dhtPeerDiscovery.rawValue)
            accountDetails!.updateValue("false", forKey: ConfigKey.accountPeerDiscovery.rawValue)
            accountDetails!.updateValue("false", forKey: ConfigKey.accountPublish.rawValue)
        }
598 599 600 601 602 603 604 605
        return accountDetails!
    }

    /**
     Gathers all the initial default details contained in a Ring accounts.

     - Returns the details.
     */
606
    fileprivate func getRingInitialAccountDetails() throws -> [String: String] {
607
        do {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
608
            let defaultDetails = try getInitialAccountDetails(accountType: AccountType.ring.rawValue)
609 610 611
            return defaultDetails
        } catch {
            throw error
612 613 614 615 616
        }
    }

    func removeAccount(_ row: Int) {
        if row < accountList.count {
617
            self.accountAdapter.removeAccount(accountList[row].id)
618 619
        }
    }
620

621 622 623 624 625 626 627 628 629
    func removeAccount(id: String) {
        if self.getAccount(fromAccountId: id) == nil {return}
        self.accountAdapter.removeAccount(id)
        self.loadAccountsFromDaemon()
        if self.getAccount(fromAccountId: id) == nil {
            self.dbManager.removeDBForAccount(accountId: id)
        }
    }

630 631
    // MARK: - AccountAdapterDelegate
    func accountsChanged() {
632
        log.debug("Accounts changed.")
633
        reloadAccounts()
634

635
        let event = ServiceEvent(withEventType: .accountsChanged)
636
        self.responseStream.onNext(event)
637
    }
638 639

    func registrationStateChanged(with response: RegistrationResponse) {
640 641
        var event = ServiceEvent(withEventType: .registrationStateChanged)
        event.addEventInput(.registrationState, value: response.state)
642
        event.addEventInput(.accountId, value: response.accountId)
643
        self.responseStream.onNext(event)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
644 645 646
        if let account = self.getAccount(fromAccountId: response.accountId) {
            account.volatileDetails = self.getVolatileAccountDetails(fromAccountId: response.accountId)
        }
647 648
    }

649 650
    func knownDevicesChanged(for account: String, devices: [String: String]) {
        reloadAccounts()
651 652 653
        var event = ServiceEvent(withEventType: .knownDevicesChanged)
        event.addEventInput(.accountId, value: account)
        self.responseStream.onNext(event)
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
    }

    func exportOnRing(withPassword password: String)
        -> Completable {
            return Completable.create { [unowned self] completable in
                let export =  self.accountAdapter.export(onRing: self.currentAccount?.id, password: password)
                if export {
                    completable(.completed)
                } else {
                    completable(.error(LinkNewDeviceError.unknownError))
                }
                return Disposables.create { }
            }
    }

669
    func exportOnRingEnded(for account: String, state: Int, pin: String) {
670 671 672 673 674 675 676 677 678 679 680 681 682
        var event = ServiceEvent(withEventType: .exportOnRingEnded)
        event.addEventInput(.id, value: account)
        event.addEventInput(.state, value: state)
        event.addEventInput(.pin, value: pin)
        self.responseStream.onNext(event)
    }

    func deviceRevocationEnded(for account: String, state: Int, deviceId: String) {
        var event = ServiceEvent(withEventType: .deviceRevocationEnded)
        event.addEventInput(.id, value: account)
        event.addEventInput(.state, value: state)
        event.addEventInput(.deviceId, value: deviceId)
        self.responseStream.onNext(event)
683 684
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
685 686
    // MARK: Push Notifications

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
    func setPushNotificationToken(token: String) {
        self.accountAdapter.setPushNotificationToken(token)
    }

    func pushNotificationReceived(data: [AnyHashable: Any]) {
        var notificationData = [String: String]()
        for key in data.keys {
            if let value = data[key] {
                let valueString = String(describing: value)
                let keyString = String(describing: key)
                notificationData[keyString] = valueString
            }
        }
        self.accountAdapter.pushNotificationReceived("", message: notificationData)
    }

    func getCurrentProxyState(accountID: String) -> Bool {
        var proxyEnabled = false
        let accountDetails = self.getAccountDetails(fromAccountId: accountID)
        if accountDetails.get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.proxyEnabled)) == "true" {
            proxyEnabled = true
        }
        return proxyEnabled
    }

712 713 714 715 716
    func savePushToken(token: String) {
        for account in accounts {
            let accountDetails = self.getAccountDetails(fromAccountId: account.id)
            accountDetails.set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.devicePushToken), withValue: token)
            self.setAccountDetails(forAccountId: account.id, withDetails: accountDetails)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
717 718 719 720 721 722 723 724 725 726
        }
    }

    func proxyEnabled(accountID: String) -> Variable<Bool> {
        let variable = Variable<Bool>(getCurrentProxyState(accountID: accountID))
        self.sharedResponseStream
            .filter({ event -> Bool in
                if let accountId: String = event.getEventInput(.accountId) {
                    return event.eventType == ServiceEventType.proxyEnabled
                        && accountId == accountID
727 728
                }
                return false
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
729 730 731 732 733 734
            }).subscribe(onNext: { (event) in
                if let state: Bool = event.getEventInput(.state) {
                    variable.value = state
                }
            }).disposed(by: self.disposeBag)
        return variable
735 736
    }

737
    func changeProxyStatus(accountID: String, enable: Bool) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
738
        let accountDetails = self.getAccountDetails(fromAccountId: accountID)
739 740 741 742 743 744 745 746
        if accountDetails.get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.proxyEnabled)) != enable.toString() {
            accountDetails.set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.proxyEnabled), withValue: enable.toString())
            self.setAccountDetails(forAccountId: accountID, withDetails: accountDetails)
            var event = ServiceEvent(withEventType: .proxyEnabled)
            event.addEventInput(.state, value: enable)
            event.addEventInput(.accountId, value: accountID)
            self.responseStream.onNext(event)
        }
747 748
    }

749 750 751 752 753 754
    func proxyEnabled() -> Bool {
        for account in self.accounts {
            let accountDetails = self.getAccountDetails(fromAccountId: account.id)
            if accountDetails.get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.proxyEnabled)) == "true" {
                return true
            }
755
        }
756
        return false
757
    }
758

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
759 760 761 762 763 764 765 766
    func enableAccount(enable: Bool, accountId: String) {
        let accountDetails = self.getAccountDetails(fromAccountId: accountId)
        if accountDetails.get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountEnable)) != enable.toString() {
            accountDetails.set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountEnable), withValue: enable.toString())
            self.setAccountDetails(forAccountId: accountId, withDetails: accountDetails)
        }
    }

767 768 769
    // MARK: - observable account data

    func devicesObservable(account: AccountModel) -> Observable<[DeviceModel]> {
770
        let accountDevices: Observable<[DeviceModel]> = Observable.just(account.devices)
771 772 773 774
        let newDevice: Observable<[DeviceModel]> = self
            .sharedResponseStream
            .filter({ (event) in
                return event.eventType == ServiceEventType.knownDevicesChanged &&
775
                    event.getEventInput(ServiceEventInput.accountId) == account.id
776 777 778 779 780
            }).map({ _ in
                return account.devices
            })
        return accountDevices.concat(newDevice)
    }
781
}
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800

// MARK: - Private daemon wrappers
extension AccountsService {

    fileprivate func buildAccountFromDaemon(accountId id: String) throws -> AccountModel {
        let accountModel = AccountModel(withAccountId: id)
        accountModel.details = self.getAccountDetails(fromAccountId: id)
        accountModel.volatileDetails = self.getVolatileAccountDetails(fromAccountId: id)
        accountModel.devices = self.getKnownRingDevices(fromAccountId: id)
        do {
            let credentialDetails = try self.getAccountCredentials(fromAccountId: id)
            accountModel.credentialDetails.removeAll()
            accountModel.credentialDetails.append(contentsOf: credentialDetails)
        } catch {
            throw error
        }
        return accountModel
    }
}