MeViewModel.swift 28.2 KB
Newer Older
1
/*
2
 *  Copyright (C) 2017-2019 Savoir-faire Linux Inc.
3 4
 *
 *  Author: Thibault Wittemberg <thibault.wittemberg@savoirfairelinux.com>
5
 *  Author: Kateryna Kostiuk <kateryna.kostiuk@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 23
 *
 *  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 Foundation
24
import RxSwift
25 26
import RxDataSources

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
27
// swiftlint:disable file_length
28 29 30 31
enum SettingsSection: SectionModelType {

    typealias Item = SectionRow

32 33 34 35
    case linkedDevices(items: [SectionRow])
    case linkNewDevice(items: [SectionRow])
    case accountSettings(items: [SectionRow])
    case credentials(items: [SectionRow])
36 37 38 39

    enum SectionRow {
        case device(device: DeviceModel)
        case linkNew
40
        case blockedList
41
        case removeAccount
42
        case shareAccountDetails
43 44
        case sectionHeader(title: String)
        case ordinary(label: String)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
45
        case notifications
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
46 47 48 49
        case sipUserName(value: String)
        case sipPassword(value: String)
        case sipServer(value: String)
        case port(value: String)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
50
        case proxyServer(value: String)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
51 52
        case accountState(state: Variable<String>)
        case enableAccount
53 54 55 56
    }

    var items: [SectionRow] {
        switch self {
57
        case .linkedDevices(let items):
58
            return items
59
        case .linkNewDevice(let items):
60
            return items
61 62 63
        case .accountSettings(let items):
            return items
        case .credentials(let items):
64
            return items
65 66 67 68 69
        }
    }

    public init(original: SettingsSection, items: [SectionRow]) {
        switch original {
70 71 72 73 74 75 76 77
        case .linkedDevices:
            self = .linkedDevices(items: items)
        case .linkNewDevice:
            self = .linkNewDevice(items: items)
        case .accountSettings:
            self = .accountSettings(items: items)
        case .credentials:
            self = .credentials(items: items)
78 79 80
        }
    }
}
81

82 83 84 85 86 87 88 89
enum ActionsState {
    case deviceRevokedWithSuccess(deviceId: String)
    case deviceRevokationError(deviceId: String, errorMessage: String)
    case showLoading
    case hideLoading
    case noAction
}

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
90
// swiftlint:disable type_body_length
91
class MeViewModel: ViewModel, Stateable {
92 93 94

    // MARK: - Rx Stateable
    private let stateSubject = PublishSubject<State>()
95 96 97 98
    lazy var state: Observable<State> = {
        return self.stateSubject.asObservable()
    }()
    let disposeBag = DisposeBag()
99
    var tempBag = DisposeBag()
100

101 102 103 104 105
    let accountService: AccountsService
    let nameService: NameService

     // MARK: - configure table sections

106 107
    var showActionState = Variable<ActionsState>(.noAction)

Quentin Muret's avatar
Quentin Muret committed
108 109 110 111 112 113 114 115
    public func getRingId() -> String? {
        if let uri = self.accountService.currentAccount?.details?.get(withConfigKeyModel: ConfigKeyModel(withKey: .accountUsername)) {
            let ringId = uri.replacingOccurrences(of: "ring:", with: "")
            return ringId
        }
        return nil
    }

116 117 118
    lazy var accountCredentials: Observable<SettingsSection> = {
        return Observable
            .combineLatest(userName.startWith(""), ringId.startWith("")) { (name, ringID) in
119
                var items: [SettingsSection.SectionRow] =  [.sectionHeader(title: L10n.AccountPage.credentialsHeader),
Quentin Muret's avatar
Quentin Muret committed
120
                                                        .ordinary(label: "ID: " + ringID)]
121
            if !name.isEmpty {
122
                items.append(.ordinary(label: L10n.AccountPage.username + " " + name))
123
            } else {
124
                items.append(.ordinary(label: L10n.AccountPage.usernameNotRegistered))
125
            }
126
                items.append(.shareAccountDetails)
127 128 129
            return SettingsSection
                .credentials(items: items)
        }
130
    }()
131

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    var accountInfoToShare: [Any]? {
        var info = [String]()
        guard let account = self.accountService.currentAccount else {return nil}
        var nameToContact = ""
        if self.isAccountSip.value {
            guard let accountDetails = account.details,
                let credentials = account.credentialDetails.first else {return nil}
            if AccountModelHelper.init(withAccount: account).isAccountRing() {
                return nil
            }
            let username = credentials.username
            let server = accountDetails.get(withConfigKeyModel: ConfigKeyModel.init(withKey: .accountHostname))
            if username.isEmpty || server.isEmpty {
                return nil
            }
            nameToContact = username + "@" + server
        }
        if !account.registeredName.isEmpty {
            nameToContact = account.registeredName
        } else if let userNameData = UserDefaults.standard.dictionary(forKey: registeredNamesKey),
            let accountName = userNameData[account.id] as? String,
            !accountName.isEmpty {
            nameToContact = accountName
        }
        if nameToContact.isEmpty {
            nameToContact = account.jamiId
        }
        let title = L10n.AccountPage.contactMeOnJamiContant(nameToContact)
        info.append(title)
        return info
    }

164 165 166
    lazy var linkNewDevice: Observable<SettingsSection> = {
        return Observable.just(.linkNewDevice(items: [.linkNew]))
    }()
167

168 169 170 171 172 173
    lazy var removeAccount: Observable<SettingsSection> = {
        return Observable
            .just(.accountSettings( items: [.sectionHeader(title: ""),
                                            .ordinary(label: L10n.AccountPage.removeAccountTitle)]))
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    lazy var accountStatus: Variable<String> = {
        let accStatus = Variable<String>("")
        Observable
            .combineLatest(accountState,
                           accountEnabled.asObservable()) { (state, enabled) -> String in
                            if !enabled {
                                return L10n.Account.statusOffline
                            }
                            switch state {
                            case .registered:
                                return L10n.Account.statusOnline
                            case .trying:
                                return L10n.Account.statusConnecting
                            case .errorRequestTimeout, .errorNotAcceptable,
                                 .errorServiceUnavailable, .errorExistStun,
                                 .errorConfStun, .errorHost,
                                 .errorNetwork, .errorAuth, .error:
                                return L10n.Account.statusConnectionerror
                            default:
                                return L10n.Account.statusUnknown
                            }
            }.subscribe(onNext: { status in
                accStatus.value = status
            }).disposed(by: self.disposeBag)
        return accStatus
    }()

    lazy var accountJamiSettings: Observable<SettingsSection> = {
202
        return Observable
203
            .just(.accountSettings( items: [.sectionHeader(title: L10n.AccountPage.settingsHeader),
204 205 206
                                            .notifications]))
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
207
    lazy var otherJamiSettings: Observable<SettingsSection> = {
208
        return Observable
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
209 210 211 212 213
            .just(SettingsSection.accountSettings( items: [.sectionHeader(title: L10n.AccountPage.other),
                                                           .blockedList,
                                                           .accountState(state: self.accountStatus),
                                                           .enableAccount,
                                                           .removeAccount]))
214
    }()
215

216 217 218 219 220
    lazy var havePassord: Bool = {
        guard let currentAccount = self.accountService.currentAccount else {return true}
        return AccountModelHelper(withAccount: currentAccount).havePassword
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
221
    lazy var jamiSettings: Observable<[SettingsSection]> = {
222 223 224
        Observable.combineLatest(accountCredentials,
                                 linkNewDevice,
                                 linkedDevices,
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
225 226
                                 accountJamiSettings,
                                 otherJamiSettings) { (credentials, linkNew, devices, settings, other) in
227
            return [credentials, devices, linkNew, settings, other]
228
        }
229 230
    }()

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    let isAccountSip = Variable<Bool>(false)
    var sipInfoUpdated = BehaviorSubject<Bool>(value: true)

    lazy var otherSipSettings: Observable<SettingsSection> = {
        return Observable
            .just(SettingsSection.accountSettings( items: [.sectionHeader(title: ""),
                                            .accountState(state: self.accountStatus),
                                            .enableAccount,
                                            .removeAccount]))
    }()

    lazy var sipCredentials: Observable<SettingsSection> = {
        return sipInfoUpdated.map {_ in
            var username = ""
            var password = ""
            var server = ""
            var port = ""
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
248
            var proxyServer = ""
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
249 250 251 252 253 254 255
            if let account = self.accountService.currentAccount,
                let details = account.details,
                let credentials = account.credentialDetails.first {
                username = credentials.username
                password = credentials.password
                server = details.get(withConfigKeyModel: ConfigKeyModel.init(withKey: .accountHostname))
                port = details.get(withConfigKeyModel: ConfigKeyModel.init(withKey: .localPort))
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
256
                proxyServer = details.get(withConfigKeyModel: ConfigKeyModel.init(withKey: .accountRouteSet))
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
257 258 259 260
                self.sipUsername.value = username
                self.sipPassword.value = password
                self.sipServer.value = server
                self.port.value = port
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
261 262 263 264 265 266 267
                self.proxyServer.value = proxyServer
            }
            //isIP2IP
            if server.isEmpty {
                return .accountSettings( items: [.sectionHeader(title: ""),
                                                 .sipUserName(value: username),
                                                 .sipPassword(value: password),
268 269
                                                 .sipServer(value: server),
                                                 .shareAccountDetails])
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
270 271 272 273 274
            }
            return .accountSettings( items: [.sectionHeader(title: ""),
                                             .sipUserName(value: username),
                                             .sipPassword(value: password),
                                             .sipServer(value: server),
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
275
                                             .port(value: port),
276 277
                                             .proxyServer(value: proxyServer),
                                             .shareAccountDetails])
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
278 279 280 281 282 283 284 285 286 287 288
        }
    }()

    lazy var sipSettings: Observable<[SettingsSection]> = {
        Observable.combineLatest(sipCredentials,
                                 otherSipSettings) { (credentials, other) in
                                    return [credentials, other]
        }
    }()

    lazy var settings: Observable<[SettingsSection]> = {
289 290 291 292 293 294
        self.accountService.currentAccountChanged
            .subscribe(onNext: { [unowned self] account in
                if let currentAccount = account {
                    self.updateDataFor(account: currentAccount)
                }
            }).disposed(by: self.disposeBag)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
295 296 297 298
        if let account = self.accountService.currentAccount {
            self.isAccountSip.value = account.type == AccountType.sip
        }
        return Observable.combineLatest(jamiSettings, sipSettings,
299 300 301 302 303
                                        isAccountSip.asObservable()) {(jami, sip, isSip) in
                                            if isSip == true {
                                                return sip
                                            }
                                            return jami
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
304 305 306 307 308 309 310
        }
    }()

    required init (with injectionBag: InjectionBag) {
        self.accountService = injectionBag.accountService
        self.nameService = injectionBag.nameService
        self.secureTextEntry.onNext(true)
311 312 313 314
    }

    func updateDataFor(account: AccountModel) {
        tempBag = DisposeBag()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        self.currentAccountState.onNext(account.status)
        self.secureTextEntry.onNext(true)
        self.accountEnabled.value = account.enabled
        // subscribe for updating status for current account
        self.accountService.sharedResponseStream
            .filter({ serviceEvent in
                guard let _: String = serviceEvent
                    .getEventInput(ServiceEventInput.registrationState) else {return false}
                guard let accountId: String = serviceEvent
                    .getEventInput(ServiceEventInput.accountId),
                    accountId == account.id else {return false}
                return true
            }).subscribe(onNext: { serviceEvent in
                guard let state: String = serviceEvent
                    .getEventInput(ServiceEventInput.registrationState),
                    let accountState = AccountState(rawValue: state) else {return}
                self.currentAccountState.onNext(accountState)
            }).disposed(by: self.tempBag)
        self.isAccountSip.value = account.type == AccountType.sip
        if account.type == AccountType.sip {
            sipInfoUpdated.onNext(true)
            return
        }
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
        self.nameService.sharedRegistrationStatus
            .filter { (serviceEvent) -> Bool in
                if serviceEvent.getEventInput(ServiceEventInput.accountId) != account.id {return false}
                if serviceEvent.eventType != .nameRegistrationEnded {
                    return false
                }
                return true
            }.subscribe(onNext: { [unowned self] _ in
                if  !self.userNameForAccount(account: account).isEmpty {
                    self.currentAccountUserName
                        .onNext(self.userNameForAccount(account: account))
                }
                }, onError: { _ in
            }).disposed(by: self.tempBag)
        self.currentAccountUserName
            .onNext(self.userNameForAccount(account: account))
354 355 356 357 358 359 360 361 362 363 364 365 366 367
        if let jamiId =  AccountModelHelper.init(withAccount: account).ringId {
            currentAccountJamiId.onNext(jamiId)
        } else {
            currentAccountJamiId.onNext("")
        }
        self.accountService.devicesObservable(account: account)
            .subscribe(onNext: { [unowned self] devices in
                self.currentAccountDevices.onNext(devices)
            }).disposed(by: self.tempBag)
        self.accountService.proxyEnabled(accountID: account.id)
            .asObservable()
            .subscribe(onNext: { [unowned self] enable in
                self.currentAccountProxy.onNext(enable)
            }).disposed(by: self.tempBag)
368 369
    }

370 371 372 373 374 375 376 377 378 379 380 381
    func userNameForAccount(account: AccountModel) -> String {
        if let accountName = account.volatileDetails?.get(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountRegisteredName)),
            !accountName.isEmpty {
            return accountName
        } else if let userNameData = UserDefaults.standard.dictionary(forKey: registeredNamesKey),
            let accountName = userNameData[account.id] as? String,
            !accountName.isEmpty {
            return accountName
        }
        return ""
    }

382 383 384 385 386 387 388 389 390 391 392 393 394
    func linkDevice() {
        self.stateSubject.onNext(MeState.linkNewDevice)
    }

    func showBlockedContacts() {
        self.stateSubject.onNext(MeState.blockedContacts)
    }

    func revokeDevice(deviceId: String, accountPassword password: String) {
        guard let accountId = self.accountService.currentAccount?.id else {
            self.showActionState.value = .hideLoading
            return
        }
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
        self.accountService.sharedResponseStream
            .filter({ (deviceEvent) -> Bool in
                return deviceEvent.eventType == ServiceEventType.deviceRevocationEnded
                    && deviceEvent.getEventInput(.id) == accountId
            })
            .subscribe(onNext: { [unowned self] deviceEvent in
                if let state: Int = deviceEvent.getEventInput(.state),
                    let deviceID: String = deviceEvent.getEventInput(.deviceId) {
                    switch state {
                    case DeviceRevocationState.success.rawValue:
                        self.showActionState.value = .deviceRevokedWithSuccess(deviceId: deviceID)
                    case DeviceRevocationState.wrongPassword.rawValue:
                        self.showActionState.value = .deviceRevokationError(deviceId:deviceID, errorMessage: L10n.AccountPage.deviceRevocationWrongPassword)
                    case DeviceRevocationState.unknownDevice.rawValue:
                        self.showActionState.value = .deviceRevokationError(deviceId:deviceID, errorMessage: L10n.AccountPage.deviceRevocationUnknownDevice)
                    default:
                        self.showActionState.value = .deviceRevokationError(deviceId:deviceID, errorMessage: L10n.AccountPage.deviceRevocationError)
                    }
                }
            }).disposed(by: self.disposeBag)
        self.accountService.revokeDevice(for: accountId, withPassword: password, deviceId: deviceId)
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
418
    // MARK: update for selected account
419 420 421 422
    let currentAccountUserName = PublishSubject<String>()
    let currentAccountJamiId = PublishSubject<String>()
    let currentAccountDevices = PublishSubject<[DeviceModel]>()
    let currentAccountProxy = PublishSubject<Bool>()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    let currentAccountState = PublishSubject<AccountState>()

    lazy var accountState: Observable<AccountState> = {
        var state = AccountState.registered
        if let account = self.accountService.currentAccount {
            state = account.status
            self.accountService.sharedResponseStream
                .filter({ serviceEvent in
                    guard let _: String = serviceEvent
                        .getEventInput(ServiceEventInput.registrationState) else {return false}
                    guard let accountId: String = serviceEvent
                        .getEventInput(ServiceEventInput.accountId),
                        accountId == account.id else {return false}
                    return true
                }).subscribe(onNext: { serviceEvent in
                    guard let state: String = serviceEvent
                        .getEventInput(ServiceEventInput.registrationState),
                        let accountState = AccountState(rawValue: state) else {return}
                    self.currentAccountState.onNext(accountState)
                }).disposed(by: self.tempBag)
        }
        return currentAccountState.share().startWith(state)
    }()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
446

447 448
    lazy var userName: Observable<String> = { [unowned self] in
        var initialValue: String = ""
449
        if let account = self.accountService.currentAccount {
450 451 452 453 454 455 456
            if !account.registeredName.isEmpty {
                initialValue = account.registeredName
            } else if let userNameData = UserDefaults.standard.dictionary(forKey: registeredNamesKey),
                let accountName = userNameData[account.id] as? String,
                !accountName.isEmpty {
                initialValue = accountName
            }
457
        }
458
        return currentAccountUserName.share().startWith(initialValue)
459 460
    }()

461 462
    lazy var ringId: Observable<String> = { [unowned self] in
        var initialValue: String = ""
463
        if let account = self.accountService.currentAccount {
464 465
            let jamiId = account.jamiId
            initialValue = jamiId
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
466
        }
467
        return currentAccountJamiId.share().startWith(initialValue)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
468 469
    }()

470 471 472 473 474 475
    lazy var linkedDevices: Observable<SettingsSection> = { [unowned self] in
        let empptySection: SettingsSection =
            .linkedDevices(items: [.ordinary(label: "")])
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01, execute: {
            if let account = self.accountService.currentAccount {
                self.accountService.devicesObservable(account: account)
476 477 478
                    .subscribe(onNext: { [unowned self] device in
                        self.currentAccountDevices.onNext(device)
                    }).disposed(by: self.tempBag)
479 480 481 482 483 484 485 486 487 488 489
            }
        })
        return self.currentAccountDevices.share()
            .map { devices -> SettingsSection in
                var rows: [SettingsSection.SectionRow]?
                if !devices.isEmpty {
                    rows = [.device(device: devices[0])]
                    for deviceIndex in 1 ..< devices.count {
                        let device = devices[deviceIndex]
                        rows!.append (.device(device: device))
                    }
490 491 492 493 494 495 496 497 498 499 500 501
                } else if let account = self.accountService.currentAccount,
                    let details = account.details {
                    let deviceId = details.get(withConfigKeyModel: ConfigKeyModel.init(withKey: .accountDeviceId))
                    let deviceName = details.get(withConfigKeyModel:
                        ConfigKeyModel.init(withKey: .accountDeviceName))
                    if deviceId.isEmpty {
                        return empptySection
                    }
                    rows = [.device(device:
                        DeviceModel(withDeviceId: deviceId,
                                    deviceName: deviceName,
                                    isCurrent: true))]
502 503 504 505 506 507 508
                }
                if rows != nil {
                    rows?.insert(.sectionHeader(title: L10n.AccountPage.devicesListHeader), at: 0)
                    let devicesSection: SettingsSection = .linkedDevices(items: rows!)
                    return devicesSection
                }
                return empptySection
509
        }
510
        }()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
511

512 513
    lazy var proxyEnabled: Observable<Bool> = { [unowned self] in
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01, execute: {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
514
        if let account = self.accountService.currentAccount {
515 516 517 518 519 520
            self.accountService.proxyEnabled(accountID: account.id)
                .asObservable()
                .take(1)
                .subscribe(onNext: { [unowned self] enable in
                    self.currentAccountProxy.onNext(enable)
                }).disposed(by: self.disposeBag)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
521
        }
522 523
        })
        return currentAccountProxy.share()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
524 525
    }()

526
    // MARK: Notifications
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
527

528 529 530 531 532 533
    lazy var notificationsEnabled: Observable<Bool> = {
        return Observable.combineLatest(self.notificationsPermitted.asObservable(),
                                        self.proxyEnabled.asObservable()) { (notifications, proxy) in
                                            return  proxy && notifications
        }
    }()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
534

535
    lazy var notificationsPermitted: Variable<Bool> = {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
536 537 538 539 540 541 542 543 544 545 546
        let variable = Variable<Bool>(LocalNotificationsHelper.isEnabled())
        UserDefaults.standard.rx
            .observe(Bool.self, enbleNotificationsKey)
            .subscribe(onNext: { enable in
                if let enable = enable {
                    variable.value = enable
                }
            }).disposed(by: self.disposeBag)
        return variable
    }()

547 548 549 550 551 552 553 554
    func enableNotifications(enable: Bool) {
        guard let account = self.accountService.currentAccount else {return}
        if !self.accountService.proxyEnabled() && enable == true {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationName.enablePushNotifications.rawValue), object: nil)
        }
        self.accountService.changeProxyStatus(accountID: account.id, enable: enable)
        // if notiications not allowed open application settings
        if enable == true && enable != notificationsPermitted.value {
555
            if let url = URL(string: UIApplication.openSettingsURLString) {
556 557 558 559
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url, completionHandler: nil)
                } else {
                    UIApplication.shared.openURL(url)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
560 561 562 563 564
                }
            }
        }
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
565
    // MARK: Account State
566 567 568 569 570 571 572 573 574 575 576
    func startAccountRemoving() {
        guard let account = self.accountService.currentAccount else {
            return
        }
        let allAccounts = self.accountService.accounts
        if allAccounts.count < 1 {return}
        if allAccounts.count == 1 {
            UserDefaults.standard.set("", forKey: self.accountService.selectedAccountID)
            self.stateSubject.onNext(MeState.needToOnboard)
            self.accountService.removeAccount(id: account.id)
            return
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
577
        }
578 579 580
        UserDefaults.standard.set(allAccounts[1].id, forKey: self.accountService.selectedAccountID)
        self.accountService.currentAccount = allAccounts[1]
        self.accountService.removeAccount(id: account.id)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
581
        self.stateSubject.onNext(MeState.accountRemoved)
582
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

    lazy var accountEnabled: Variable<Bool> = {
        if let account = self.accountService.currentAccount,
            let details = account.details {
            let enable = details.get(withConfigKeyModel:
                ConfigKeyModel.init(withKey: .accountEnable)).boolValue
            return Variable<Bool>(enable)
        }
        return Variable<Bool>(true)
    }()

    func enableAccount(enable: Bool) {
        if self.accountEnabled.value == enable {return}
        guard let account = self.accountService.currentAccount else {return}
        self.accountService.enableAccount(enable: enable, accountId: account.id)
        accountEnabled.value = enable
    }

    // MARK: Sip Credentials
    let sipUsername = Variable<String>("")
    let sipPassword = Variable<String>("")
    let sipServer = Variable<String>("")
    let port = Variable<String>("")
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
606
    let proxyServer = Variable<String>("")
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
607 608 609 610 611 612 613 614 615 616 617

    func updateSipSettings() {
        guard let account = self.accountService.currentAccount, let details = account.details, let credentials = account.credentialDetails.first else {return}
        if AccountModelHelper.init(withAccount: account).isAccountRing() {
            return
        }
        let username = credentials.username
        let password = credentials.password
        let server = details.get(withConfigKeyModel: ConfigKeyModel.init(withKey: .accountHostname))
        let port = details.get(withConfigKeyModel:
            ConfigKeyModel.init(withKey: .localPort))
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
618
        let proxy = details.get(withConfigKeyModel: ConfigKeyModel.init(withKey: .accountRouteSet))
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
619 620
        if username == sipUsername.value
            && password == sipPassword.value
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
621 622 623
            && server == sipServer.value
            && port == self.port.value
            && proxy == self.proxyServer.value {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
624 625 626 627 628 629 630 631 632 633 634
            return
        }
        if username != sipUsername.value || password != sipPassword.value {
            credentials.username = sipUsername.value
            credentials.password = sipPassword.value
            account.credentialDetails = [credentials]
            let dict = credentials.toDictionary()
            self.accountService.setAccountCrdentials(forAccountId: account.id, crdentials: [dict])
        }
        if server != sipServer.value ||
            port != self.port.value ||
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
635 636
            username != sipUsername.value ||
            proxy != self.proxyServer.value {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
637 638 639
            details.set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountHostname), withValue: sipServer.value)
            details.set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.localPort), withValue: self.port.value)
            details.set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountUsername), withValue: self.sipUsername.value)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
640
            details.set(withConfigKeyModel: ConfigKeyModel(withKey: ConfigKey.accountRouteSet), withValue: self.proxyServer.value)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
641 642 643 644 645 646 647
            account.details = details
            self.accountService.setAccountDetails(forAccountId: account.id, withDetails: details)
        }
        sipInfoUpdated.onNext(true)
    }

    let secureTextEntry = ReplaySubject<Bool>.create(bufferSize: 1)
648
}