Controller.swift (25053B)
1 /* 2 * This file is part of GNU Taler, ©2022-26 Taler Systems S.A. 3 * See LICENSE.md 4 */ 5 /** 6 * Controller 7 * 8 * @author Marc Stibane 9 */ 10 import Foundation 11 import AVFoundation 12 import LocalAuthentication 13 import SwiftUI 14 import SymLog 15 import os.log 16 import CoreHaptics 17 import Network 18 import taler_swift 19 20 enum BackendState: Equatable { 21 case none 22 case instantiated 23 case initing 24 case update 25 case ready 26 case error(EquatableError) 27 28 static func == (lhs: BackendState, rhs: BackendState) -> Bool { 29 switch (lhs, rhs) { 30 case (.none, .none): 31 return true 32 case (.instantiated, .instantiated): 33 return true 34 case (.initing, .initing): 35 return true 36 case (.update, .update): 37 return true 38 case (.ready, .ready): 39 return true 40 case (.error(let lhsError), .error(let rhsError)): 41 return lhsError == rhsError 42 default: 43 return false 44 } 45 } 46 } 47 48 enum UrlCommand: String, Codable { 49 case unknown 50 case withdraw 51 case withdrawExchange 52 case addExchange 53 case pay 54 case payPull 55 case payPush 56 case payTemplate 57 case refund 58 #if GNU_TALER || TALER_NIGHTLY 59 case devExperiment 60 #endif 61 62 var isOutgoing: Bool { 63 switch self { 64 case .pay, .payPull, .payTemplate: 65 true 66 default: 67 false 68 } 69 } 70 71 var localizedCommand: String { 72 switch self { 73 case .unknown: String(EMPTYSTRING) 74 case .withdraw, 75 .withdrawExchange: String(localized: "Withdraw", 76 comment: "UrlCommand") 77 case .addExchange: String(localized: "Add payment service", 78 comment: "UrlCommand") 79 case .pay: String(localized: "Pay merchant", 80 comment: "UrlCommand") 81 case .payPull: String(localized: "Pay others", 82 comment: "UrlCommand") 83 case .payPush: String(localized: "Receive", 84 comment: "UrlCommand") 85 case .payTemplate: String(localized: "Pay ...", 86 comment: "UrlCommand") 87 case .refund: String(localized: "Refund", 88 comment: "UrlCommand") 89 #if GNU_TALER || TALER_NIGHTLY 90 case .devExperiment: String("DevExperiment") 91 #endif 92 } 93 } 94 var transactionType: TransactionType { 95 switch self { 96 case .unknown: .dummy 97 case .withdraw: .withdrawal 98 case .withdrawExchange: .withdrawal 99 case .addExchange: .dummy 100 case .pay: .payment 101 case .payPull: .scanPullDebit 102 case .payPush: .scanPushCredit 103 case .payTemplate: .payment 104 case .refund: .refund 105 #if GNU_TALER || TALER_NIGHTLY 106 case .devExperiment: .dummy 107 #endif 108 } 109 } 110 } 111 112 struct ScannedURL: Identifiable { 113 var id: String { 114 url.absoluteString 115 } 116 var url: URL 117 var command: UrlCommand 118 var amount: Amount? 119 var baseURL: String? 120 var scope: ScopeInfo? 121 var time: Date 122 } 123 124 // MARK: - 125 class Controller: ObservableObject { 126 public static let shared = Controller() 127 private let symLog = SymLogC() 128 129 @Published var haveProdBalance: Bool = false 130 @Published var balances: [Balance] = [] 131 @Published var discounts: [TalerToken] = [] 132 @Published var subscriptions: [TalerToken] = [] 133 @Published var defaultExchanges: [DefaultExchange] = [] 134 @Published var scannedURLs: [ScannedURL] = [] 135 136 @Published var backendState: BackendState = .none // only used for launch animation 137 @Published var currencyTicker: Int = 0 // updates whenever a new currency is added 138 @Published var userAction: Int = 0 // make Action button jump 139 140 @Published var isConnected: Bool = true 141 @Published var networkUnavailable: Bool = false 142 @Published var slowConnection: Bool = false 143 @Published var stalledConnection: Bool = false 144 @Published var errorConnection: Bool = false 145 @Published var oimModeActive: Bool = false 146 @Published var oimSheetActive: Bool = false 147 @Published var diagnosticModeEnabled: Bool = false 148 @Published var talerURI: URL? = nil 149 @Published var choicesTuple: ChoicesTuple = (nil, nil) 150 151 @AppStorage("useHaptics") var useHaptics: Bool = true // extension mustn't define this, so it must be here 152 @AppStorage("playSounds") var playSounds: Bool = false 153 @AppStorage("talerFontIndex") var talerFontIndex: Int = 0 // extension mustn't define this, so it must be here 154 #if DEBUG 155 @AppStorage("developerMode") var developerMode: Bool = true 156 #else 157 @AppStorage("developerMode") var developerMode: Bool = false 158 #endif 159 @AppStorage("deviceTokenAPNs") var deviceTokenAPNs: String? 160 @AppStorage("developDelay") var developDelay: Bool = false 161 let hapticCapability = CHHapticEngine.capabilitiesForHardware() 162 let logger = Logger(subsystem: "net.taler.gnu", category: "Controller") 163 let player = AVQueuePlayer() 164 let semaphore = AsyncSemaphore(value: 1) 165 private var currencyInfos: [ScopeInfo : CurrencyInfo] 166 var exchanges: [Exchange] 167 var messageForSheet: String? = nil 168 var isLoadingChoices: String? = nil 169 170 var lastProgressError: RequestProgressError? = nil 171 var lastProgressPhase: RequestProgressPhase? = nil 172 var progressOperation: String? = nil 173 var progressToken: String? = nil 174 175 private let monitor = NWPathMonitor() 176 private var isMonitoringConnection = false 177 178 private var diagnosticModeObservation: NSKeyValueObservation? 179 #if OIM 180 private var lastOIMmode: UIDeviceOrientation = .portrait 181 func setOIMmode(for newOrientation: UIDeviceOrientation, _ sheetActive: Bool) { 182 if lastOIMmode == .landscapeRight { 183 if newOrientation == .faceUp { 184 return 185 } 186 } 187 let isLandscapeRight = newOrientation == .landscapeRight 188 lastOIMmode = newOrientation 189 oimSheetActive = sheetActive && isLandscapeRight 190 oimModeActive = sheetActive ? false 191 : isLandscapeRight 192 // print("😱 oimSheetActive = \(oimSheetActive)") 193 } 194 #endif 195 196 var localizedAppName: String { 197 #if TALER_WALLET 198 let appName = "Taler Wallet" 199 #elseif TALER_NIGHTLY 200 let appName = "Taler Nightly" 201 #else 202 let appName = "GNU Taler" 203 #endif 204 return Bundle.main.bundleName ?? appName 205 } 206 207 func biometryType() -> LABiometryType? { 208 let context = LAContext() 209 var error: NSError? = nil 210 if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { 211 return context.biometryType 212 } 213 // else device has no enabled biometrics 214 #if DEBUG 215 if let error { 216 print(error) 217 } 218 #endif 219 return nil 220 } 221 222 @discardableResult 223 func saveURL(_ passedURL: URL, urlCommand: UrlCommand) -> Bool { 224 let savedURL = scannedURLs.first { scannedURL in 225 scannedURL.url == passedURL 226 } 227 if savedURL == nil { // doesn't exist yet 228 var save = false 229 switch urlCommand { 230 case .addExchange: save = true 231 case .withdraw: save = true 232 case .withdrawExchange: save = true 233 case .pay: save = true 234 case .payPull: save = true 235 case .payPush: save = true 236 case .payTemplate: save = true 237 238 default: break 239 } 240 if save { 241 let scannedURL = ScannedURL(url: passedURL, command: urlCommand, time: .now) 242 if scannedURLs.count > 5 { 243 self.logger.trace("removing: \(self.scannedURLs.first?.command.rawValue ?? EMPTYSTRING)") 244 scannedURLs.remove(at: 0) 245 } 246 scannedURLs.append(scannedURL) 247 self.logger.trace("saveURL: \(urlCommand.rawValue)") 248 return true 249 } 250 } 251 return false 252 } 253 254 func removeURL(_ passedURL: URL) { 255 scannedURLs.removeAll { scannedURL in 256 scannedURL.url == passedURL 257 } 258 } 259 func removeURLs(after: TimeInterval) { 260 let now = Date.now 261 scannedURLs.removeAll { scannedURL in 262 let timeInterval = now.timeIntervalSince(scannedURL.time) 263 self.logger.trace("timeInterval: \(timeInterval)") 264 return timeInterval > after 265 } 266 } 267 func updateAmount(_ amount: Amount, forSaved url: URL) { 268 if let index = scannedURLs.firstIndex(where: { $0.url == url }) { 269 var savedURL = scannedURLs[index] 270 savedURL.amount = amount 271 scannedURLs[index] = savedURL 272 } 273 } 274 func updateBase(_ baseURL: String, forSaved url: URL) { 275 if let index = scannedURLs.firstIndex(where: { $0.url == url }) { 276 var savedURL = scannedURLs[index] 277 savedURL.baseURL = baseURL 278 scannedURLs[index] = savedURL 279 } 280 } 281 282 func startObserving() { 283 let defaults = UserDefaults.standard 284 self.diagnosticModeObservation = defaults.observe(\.diagnosticModeEnabled, options: [.new, .old,.prior,.initial]) { [weak self](_, _) in 285 self?.diagnosticModeEnabled = UserDefaults.standard.diagnosticModeEnabled 286 } 287 } 288 289 // NWPathMonitor cannot be restarted after `cancel()` - so we just keep it running forever 290 // func stopCheckingConnection() { 291 // self.logger.log("Stop monitoring internet connection") 292 // isMonitoringConnection = false 293 // monitor.cancel() 294 // } 295 296 func checkInternetConnection() { 297 guard !isMonitoringConnection else { return } // don't try to start NWPathMonitor a second time 298 isMonitoringConnection = true 299 monitor.pathUpdateHandler = { path in 300 let status = switch path.status { 301 case .satisfied: "active" 302 case .unsatisfied: "inactive" 303 default: "unknown" 304 } 305 self.logger.log("Internet connection is \(status)") 306 DispatchQueue.main.async { 307 if path.status == .unsatisfied { 308 self.isConnected = false 309 Task.detached { 310 await WalletModel.shared.hintNetworkAvailabilityT(false) 311 } 312 } else { 313 self.isConnected = true 314 Task.detached { 315 await WalletModel.shared.hintNetworkAvailabilityT(true) 316 } 317 } 318 } 319 } 320 self.logger.log("Start monitoring internet connection") 321 let queue = DispatchQueue(label: "InternetMonitor") 322 monitor.start(queue: queue) 323 } 324 325 func printFonts() { 326 for family in UIFont.familyNames { 327 print(family) 328 for names in UIFont.fontNames(forFamilyName: family) { 329 print("== \(names)") 330 } 331 } 332 } 333 334 init() { 335 backendState = .instantiated 336 currencyTicker = 0 337 currencyInfos = [:] 338 exchanges = [] 339 balances = [] 340 discounts = [] 341 subscriptions = [] 342 defaultExchanges = [] 343 // printFonts() 344 // checkInternetConnection() 345 startObserving() 346 } 347 // MARK: - 348 @MainActor 349 @discardableResult 350 func loadBalances(_ stack: CallStack,_ model: WalletModel) async -> Int? { 351 if let response = try? await model.getBalances(stack.push()) { 352 let reloaded = response.balances 353 if reloaded != balances { 354 for balance in reloaded { 355 let scope = balance.scopeInfo 356 checkInfo(for: scope, model: model) 357 } 358 self.logger.log("••Got new balances, will redraw") 359 balances = reloaded // redraw 360 } else { 361 self.logger.log("••Same balances, no redraw") 362 } 363 haveProdBalance = response.haveProdBalance 364 return reloaded.count 365 } 366 return nil 367 } 368 369 func balance(for scope: ScopeInfo) -> Balance? { 370 for balance in balances { 371 if balance.scopeInfo == scope { 372 return balance 373 } 374 } 375 return nil 376 } 377 // MARK: - 378 @MainActor 379 @discardableResult 380 func loadDiscounts(_ stack: CallStack,_ model: WalletModel) async -> Int? { 381 if let response = try? await model.listDiscounts(stack.push()) { 382 let reloaded = response.discounts 383 if reloaded != discounts { 384 self.logger.log("••Got new discounts, will redraw") 385 discounts = reloaded // redraw 386 } else { 387 self.logger.log("••Same discounts, no redraw") 388 } 389 return reloaded.count 390 } 391 return nil 392 } 393 // MARK: - 394 @MainActor 395 @discardableResult 396 func loadSubscriptions(_ stack: CallStack,_ model: WalletModel) async -> Int? { 397 if let response = try? await model.listSubscriptions(stack.push()) { 398 let reloaded = response.subscriptions 399 if reloaded != subscriptions { 400 self.logger.log("••Got new passes, will redraw") 401 subscriptions = reloaded // redraw 402 } else { 403 self.logger.log("••Same passes, no redraw") 404 } 405 return reloaded.count 406 } 407 return nil 408 } 409 // MARK: - 410 @MainActor 411 @discardableResult 412 func loadChoicesForPayment(_ stack: CallStack, 413 _ model: WalletModel, 414 txId: String) async -> Bool { 415 self.logger.log("getChoicesForPayment: \(txId)") 416 if isLoadingChoices != txId { 417 isLoadingChoices = txId 418 if let choiceResponse = try? await model.getChoicesForPayment(txId) { 419 choicesTuple = (txId, choiceResponse) 420 isLoadingChoices = nil 421 return true 422 } else { 423 isLoadingChoices = nil 424 self.logger.log("getChoicesForPayment failed: \(txId)") 425 } 426 } else { 427 self.logger.log("getChoicesForPayment already in progress: \(txId)") 428 } 429 return false 430 } 431 // MARK: - 432 func exchange(for baseUrl: String) -> Exchange? { 433 for exchange in exchanges { 434 if exchange.exchangeBaseUrl == baseUrl { 435 return exchange 436 } 437 } 438 return nil 439 } 440 441 func info(for scope: ScopeInfo) -> CurrencyInfo? { 442 // return CurrencyInfo.euro() // Fake EUR instead of the real Currency 443 // return CurrencyInfo.francs() // Fake CHF instead of the real Currency 444 return currencyInfos[scope] 445 } 446 func info(for scope: ScopeInfo, _ ticker: Int) -> CurrencyInfo { 447 if ticker != currencyTicker { 448 print(" ❗️Yikes - race condition while getting info for \(scope.currency)") 449 } 450 return info(for: scope) ?? CurrencyInfo.zero(scope.currency) 451 } 452 453 func info2(for currency: String) -> CurrencyInfo? { 454 // return CurrencyInfo.euro() // Fake EUR instead of the real Currency 455 // return CurrencyInfo.francs() // Fake CHF instead of the real Currency 456 for (scope, info) in currencyInfos { 457 if scope.currency == currency { 458 return info 459 } 460 } 461 // logger.log(" ❗️ no info for \(currency)") 462 return nil 463 } 464 func info2(for currency: String, _ ticker: Int) -> CurrencyInfo { 465 if ticker != currencyTicker { 466 print(" ❗️Yikes - race condition while getting info for \(currency)") 467 } 468 return info2(for: currency) ?? CurrencyInfo.zero(currency) 469 } 470 471 func hasInfo(for currency: String) -> Bool { 472 for (scope, info) in currencyInfos { 473 if scope.currency == currency { 474 return true 475 } 476 } 477 // logger.log(" ❗️ no info for \(currency)") 478 return false 479 } 480 481 @MainActor 482 func exchange(for baseUrl: String?, model: WalletModel) async -> Exchange? { 483 if let baseUrl { 484 if let exchange1 = exchange(for: baseUrl) { 485 return exchange1 486 } 487 if let exchange2 = try? await model.getExchangeByUrl(url: baseUrl) { 488 // logger.log(" ❗️ will add \(baseUrl)") 489 exchanges.append(exchange2) 490 return exchange2 491 } 492 } 493 return nil 494 } 495 496 @MainActor 497 func updateInfo(_ scope: ScopeInfo, model: WalletModel) async { 498 if let info = try? await model.getCurrencyInfo(scope: scope) { 499 await setInfo(info, for: scope) 500 // logger.log(" ❗️info set for \(scope.currency)") 501 } 502 } 503 504 func checkCurrencyInfo(for baseUrl: String, model: WalletModel) async -> Exchange? { 505 if let exchange = await exchange(for: baseUrl, model: model) { 506 let scope = exchange.scopeInfo 507 if currencyInfos[scope] == nil { 508 logger.log(" ❗️got no info for \(baseUrl.trimURL) \(scope.currency) -> will update") 509 await updateInfo(scope, model: model) 510 } 511 return exchange 512 } else { 513 // Yikes❗️ TODO: error? 514 } 515 return nil 516 } 517 518 /// called whenever a new currency pops up - will first load the Exchange and then currencyInfos 519 func checkInfo(for scope: ScopeInfo, model: WalletModel) { 520 if currencyInfos[scope] == nil { 521 Task { 522 let exchange = await exchange(for: scope.url, model: model) 523 if let scope2 = exchange?.scopeInfo { 524 let exchangeName = scope2.url ?? "UNKNOWN" 525 logger.log(" ❗️got no info for \(scope.currency) -> will update \(exchangeName.trimURL)") 526 await updateInfo(scope2, model: model) 527 } else { 528 logger.error(" ❗️got no info for \(scope.currency), and couldn't load the exchange info❗️") 529 } 530 } 531 } 532 } 533 534 @MainActor 535 func getInfo(from baseUrl: String, model: WalletModel) async throws -> CurrencyInfo? { 536 let exchange = try await model.getExchangeByUrl(url: baseUrl) 537 let scope = exchange.scopeInfo 538 if let info = info(for: scope) { 539 return info 540 } 541 let info = try await model.getCurrencyInfo(scope: scope) 542 await setInfo(info, for: scope) 543 return info 544 } 545 546 @MainActor 547 func setInfo(_ newInfo: CurrencyInfo, for scope: ScopeInfo) async { 548 await semaphore.wait() 549 defer { semaphore.signal() } 550 551 currencyInfos[scope] = newInfo 552 currencyTicker += 1 // triggers published view update 553 } 554 // MARK: - 555 @MainActor 556 func initWalletCore(_ model: WalletModel, setTesting: Bool, delay: TimeInterval) 557 async throws { 558 if backendState == .instantiated { 559 backendState = .initing 560 do { 561 let walletCore = WalletCore.shared 562 let response = try await model.initWalletCore(setTesting: setTesting) 563 walletCore.versionInfo = response.versionInfo 564 walletCore.nativeDB = (response.databaseBackend == "sqlite") 565 if developerMode { 566 // best-effort dev-mode setup: a network hiccup here must not abort 567 // wallet-core startup (see the force `try!` at the call site) 568 do { 569 try await model.setConfig(setTesting: true) 570 if developDelay == true { 571 try await model.devExperimentT( 572 "taler://dev-experiment/start-tc?delay_resp=\(TCDELAY)") 573 } 574 // try await model.devExperimentT("taler://dev-experiment/start-tc?fake_500=0.7") 575 // try await model.devExperimentT("taler://dev-experiment/default-exchange-demo?val=1") 576 try await model.devExperimentT( 577 "taler://dev-experiment/demo-shortcuts?val=KUDOS:4,KUDOS:8,KUDOS:16,KUDOS:32") 578 } catch { 579 self.logger.error("developer-mode setup failed, continuing without it: \(error.localizedDescription)") 580 } 581 } 582 defaultExchanges = await model.getDefaultExchanges() 583 #if GNU_TALER 584 if defaultExchanges.count == 1 { 585 if let talerOps = defaultExchanges.first { 586 let stageURI = "taler://withdraw-exchange/exchange.stage.taler-ops.ch/" 587 let baseUrl = "https://exchange.stage.taler-ops.ch/" 588 if talerOps.talerUri != stageURI { 589 let stageExc = DefaultExchange(talerUri: stageURI, 590 exchangeBaseUrl: baseUrl, 591 currency: talerOps.currency, 592 currencySpec: talerOps.currencySpec, 593 exchangeEntryStatus: .preset, 594 exchangeUpdateStatus: .initial 595 ) 596 defaultExchanges.append(stageExc) 597 } 598 } 599 } 600 #endif 601 let launchDelay: TimeInterval = walletCore.nativeDB ? 0.1 : delay 602 DispatchQueue.main.asyncAfter(deadline: .now() + launchDelay) { 603 // dismiss the launch animation 604 self.backendState = walletCore.nativeDB ? .ready : .update 605 } 606 await loadBalances(CallStack(), model) 607 } catch { // rethrows 608 self.logger.error("\(error.localizedDescription)") 609 backendState = .error(error.toEquatableError()) // ❗️Yikes app cannot continue 610 throw error 611 } 612 } else { 613 self.logger.fault("Yikes❗️ wallet-core already initialized") 614 } 615 } 616 } 617 618 // MARK: - 619 extension Controller { 620 func urlCommand(_ url: URL, stack: CallStack) -> UrlCommand { 621 guard let scheme = url.scheme else {return UrlCommand.unknown} 622 #if DEBUG 623 symLog.log(url) 624 #else 625 let host = url.host ?? " <- no command" 626 self.logger.trace("urlCommand(\(scheme)\(host)") 627 #endif 628 var urlCommand = UrlCommand.unknown 629 switch scheme.lowercased() { 630 case "taler": 631 urlCommand = talerScheme(url) 632 // case "payto": 633 // messageForSheet = url.absoluteString 634 // return paytoScheme(url) 635 default: 636 self.logger.error("unknown scheme: <\(scheme)>") // should never happen 637 } 638 saveURL(url, urlCommand: urlCommand) 639 return urlCommand 640 } 641 } 642 // MARK: - 643 extension Controller { 644 // func paytoScheme(_ url:URL) -> UrlCommand { 645 // let logItem = "scheme payto:// is not yet implemented" 646 // // TODO: write logItem to somewhere in Debug section of SettingsView 647 // symLog.log(logItem) // TODO: symLog.error(logItem) 648 // return UrlCommand.unknown 649 // } 650 651 func talerScheme(_ url:URL) -> UrlCommand { 652 if let command = url.host { 653 switch command.lowercased() { 654 case "withdraw": return .withdraw 655 case "withdraw-exchange": return .withdrawExchange 656 case "add-exchange": return .addExchange 657 case "pay": return .pay 658 case "pay-pull": return .payPull 659 case "pay-push": return .payPush 660 case "pay-template": return .payTemplate 661 case "refund": return .refund 662 #if GNU_TALER || TALER_NIGHTLY 663 case "dev-experiment": return .devExperiment 664 #endif 665 default: 666 self.logger.error("❗️unknown command taler://\(command)") 667 } 668 messageForSheet = command.lowercased() 669 } else { 670 self.logger.error("❗️No taler command") 671 } 672 return .unknown 673 } 674 }