taler-ios

iOS apps for GNU Taler (wallet)
Log | Files | Refs | README | LICENSE

Controller.swift (31738B)


      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     case addContact
     61 #endif
     62 
     63     var isOutgoing: Bool {
     64         switch self {
     65             case .pay, .payPull, .payTemplate:
     66                 true
     67             default:
     68                 false
     69         }
     70     }
     71 
     72     var localizedCommand: String {
     73         switch self {
     74             case .unknown:          String(EMPTYSTRING)
     75             case .withdraw,
     76                  .withdrawExchange: String(localized: "Withdraw",
     77                                              comment: "UrlCommand")
     78             case .addExchange:      String(localized: "Add payment service",
     79                                              comment: "UrlCommand")
     80             case .pay:              String(localized: "Pay merchant",
     81                                              comment: "UrlCommand")
     82             case .payPull:          String(localized: "Pay others",
     83                                              comment: "UrlCommand")
     84             case .payPush:          String(localized: "Receive",
     85                                              comment: "UrlCommand")
     86             case .payTemplate:      String(localized: "Pay ...",
     87                                              comment: "UrlCommand")
     88             case .refund:           String(localized: "Refund",
     89                                              comment: "UrlCommand")
     90 #if GNU_TALER || TALER_NIGHTLY
     91             case .devExperiment:    String("DevExperiment")
     92             case .addContact:       String(localized: "Add contact",
     93                                              comment: "UrlCommand")
     94 #endif
     95         }
     96     }
     97     var transactionType: TransactionType {
     98         switch self {
     99             case .unknown:          .dummy
    100             case .withdraw:         .withdrawal
    101             case .withdrawExchange: .withdrawal
    102             case .addExchange:      .dummy
    103             case .pay:              .payment
    104             case .payPull:          .scanPullDebit
    105             case .payPush:          .scanPushCredit
    106             case .payTemplate:      .payment
    107             case .refund:           .refund
    108 #if GNU_TALER || TALER_NIGHTLY
    109             case .devExperiment:    .dummy
    110             case .addContact:       .dummy
    111 #endif
    112         }
    113     }
    114 }
    115 
    116 struct ScannedURL: Identifiable {
    117     var id: String {
    118         url.absoluteString
    119     }
    120     var url: URL
    121     var command: UrlCommand
    122     var amount: Amount?
    123     var baseURL: String?
    124     var scope: ScopeInfo?
    125     var time: Date
    126 }
    127 
    128 // MARK: -
    129 class Controller: ObservableObject {
    130     public static let shared = Controller()
    131     private let symLog = SymLogC()
    132 
    133     @Published var haveProdBalance: Bool = false
    134     @Published var exchanges: [Exchange] = []
    135     @Published var balances: [Balance] = []
    136     @Published var discounts: [TalerToken] = []
    137     @Published var subscriptions: [TalerToken] = []
    138     @Published var defaultExchanges: [DefaultExchange] = []
    139     @Published var scannedURLs: [ScannedURL] = []
    140     @Published var contacts: [ContactEntry] = []
    141     @Published var mailboxConfiguration: MailboxConfiguration? = nil
    142     @Published var messages: [MailboxMessage] = []
    143 
    144     @Published var backendState: BackendState = .none       // only used for launch animation
    145     @Published var currencyTicker: Int = 0                  // updates whenever a new currency is added
    146     @Published var userAction: Int = 0                      // make Action button jump
    147 
    148     @Published var tcDelay: Int = 0
    149     @Published var fake500: Int = 0
    150     @Published var isConnected: Bool = true
    151     @Published var networkUnavailable: Bool = false
    152     @Published var slowConnection: Bool = false
    153     @Published var stalledConnection: Bool = false
    154     @Published var errorConnection: Bool = false
    155     @Published var oimModeActive: Bool = false
    156     @Published var oimSheetActive: Bool = false
    157     @Published var diagnosticModeEnabled: Bool = false
    158     @Published var talerURI: URL? = nil
    159     @Published var choicesTuple: ChoicesTuple = (nil, nil)
    160 
    161     @AppStorage("useHaptics") var useHaptics: Bool = true   // extension mustn't define this, so it must be here
    162     @AppStorage("playSounds") var playSounds: Bool = false
    163     @AppStorage("talerFontIndex") var talerFontIndex: Int = 0         // extension mustn't define this, so it must be here
    164 #if DEBUG
    165     @AppStorage("developerMode") var developerMode: Bool = true
    166 #else
    167     @AppStorage("developerMode") var developerMode: Bool = false
    168 #endif
    169     @AppStorage("deviceTokenAPNs") var deviceTokenAPNs: String?
    170 
    171     let hapticCapability = CHHapticEngine.capabilitiesForHardware()
    172     let logger = Logger(subsystem: "net.taler.gnu", category: "Controller")
    173     let player = AVQueuePlayer()
    174     let semaphore = AsyncSemaphore(value: 1)
    175     private var currencyInfos: [ScopeInfo : CurrencyInfo]
    176     var messageForSheet: String? = nil
    177     var isLoadingChoices: String? = nil
    178 
    179     var lastNewBalances: UInt = 0
    180     var lastProgressError: RequestProgressError? = nil
    181     var lastProgressPhase: RequestProgressPhase? = nil
    182     var progressOperation: String? = nil
    183     var progressToken: String? = nil
    184 
    185     private let monitor = NWPathMonitor()
    186     private var isMonitoringConnection = false
    187 
    188     private var diagnosticModeObservation: NSKeyValueObservation?
    189 #if OIM
    190     private var lastOIMmode: UIDeviceOrientation = .portrait
    191     func setOIMmode(for newOrientation: UIDeviceOrientation, _ sheetActive: Bool) {
    192         if lastOIMmode == .landscapeRight {
    193             if newOrientation == .faceUp {
    194                 return
    195             }
    196         }
    197         let isLandscapeRight = newOrientation == .landscapeRight
    198         lastOIMmode = newOrientation
    199         oimSheetActive = sheetActive && isLandscapeRight
    200          oimModeActive = sheetActive ? false
    201                                      : isLandscapeRight
    202 //        print("😱 oimSheetActive = \(oimSheetActive)")
    203     }
    204 #endif
    205 
    206     var localizedAppName: String {
    207 #if TALER_WALLET
    208         let appName = "Taler Wallet"
    209 #elseif TALER_NIGHTLY
    210         let appName = "Taler Nightly"
    211 #else
    212         let appName = "GNU Taler"
    213 #endif
    214         return Bundle.main.bundleName ?? appName
    215     }
    216 
    217     func biometryType() -> LABiometryType? {
    218         let context = LAContext()
    219         var error: NSError? = nil
    220         if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
    221             return context.biometryType
    222         }
    223         // else device has no enabled biometrics
    224 #if DEBUG
    225         if let error {
    226             print(error)
    227         }
    228 #endif
    229         return nil
    230     }
    231 
    232     @discardableResult
    233     func saveURL(_ passedURL: URL, urlCommand: UrlCommand) -> Bool {
    234         let savedURL = scannedURLs.first { scannedURL in
    235             scannedURL.url == passedURL
    236         }
    237         if savedURL == nil {        // doesn't exist yet
    238             var save = false
    239             switch urlCommand {
    240                 case .addExchange:      save = true
    241                 case .withdraw:         save = true
    242                 case .withdrawExchange: save = true
    243                 case .pay:              save = true
    244                 case .payPull:          save = true
    245                 case .payPush:          save = true
    246                 case .payTemplate:      save = true
    247 
    248                 default:    break
    249             }
    250             if save {
    251                 let scannedURL = ScannedURL(url: passedURL, command: urlCommand, time: .now)
    252                 if scannedURLs.count > 5 {
    253                     self.logger.trace("removing: \(self.scannedURLs.first?.command.rawValue ?? EMPTYSTRING)")
    254                     scannedURLs.remove(at: 0)
    255                 }
    256                 scannedURLs.append(scannedURL)
    257                 self.logger.trace("saveURL: \(urlCommand.rawValue)")
    258                 return true
    259             }
    260         }
    261         return false
    262     }
    263 
    264     func removeURL(_ passedURL: URL) {
    265         scannedURLs.removeAll { scannedURL in
    266             scannedURL.url == passedURL
    267         }
    268     }
    269     func removeURLs(after: TimeInterval) {
    270         let now = Date.now
    271         scannedURLs.removeAll { scannedURL in
    272             let timeInterval = now.timeIntervalSince(scannedURL.time)
    273             self.logger.trace("timeInterval: \(timeInterval)")
    274             return timeInterval > after
    275         }
    276     }
    277     func updateAmount(_ amount: Amount, forSaved url: URL) {
    278         if let index = scannedURLs.firstIndex(where: { $0.url == url }) {
    279             var savedURL = scannedURLs[index]
    280             savedURL.amount = amount
    281             scannedURLs[index] = savedURL
    282         }
    283     }
    284     func updateBase(_ baseURL: String, forSaved url: URL) {
    285         if let index = scannedURLs.firstIndex(where: { $0.url == url }) {
    286             var savedURL = scannedURLs[index]
    287             savedURL.baseURL = baseURL
    288             scannedURLs[index] = savedURL
    289         }
    290     }
    291 
    292     func startObserving() {
    293         let defaults = UserDefaults.standard
    294         self.diagnosticModeObservation = defaults.observe(\.diagnosticModeEnabled, options: [.new, .old,.prior,.initial]) {  [weak self](_, _) in
    295             self?.diagnosticModeEnabled = UserDefaults.standard.diagnosticModeEnabled
    296         }
    297     }
    298 
    299     // NWPathMonitor cannot be restarted after `cancel()` - so we just keep it running forever
    300 //    func stopCheckingConnection() {
    301 //        self.logger.log("Stop monitoring internet connection")
    302 //        isMonitoringConnection = false
    303 //        monitor.cancel()
    304 //    }
    305 
    306     func checkInternetConnection() {
    307         guard !isMonitoringConnection else { return }      // don't try to start NWPathMonitor a second time
    308         isMonitoringConnection = true
    309         monitor.pathUpdateHandler = { path in
    310             let status = switch path.status {
    311                 case .satisfied: "active"
    312                 case .unsatisfied: "inactive"
    313                 default: "unknown"
    314             }
    315             self.logger.log("Internet connection is \(status)")
    316             DispatchQueue.main.async {
    317                 if path.status == .unsatisfied {
    318                     self.isConnected = false
    319                     Task.detached {
    320                         await WalletModel.shared.hintNetworkAvailabilityT(false)
    321                     }
    322                 } else {
    323                     self.isConnected = true
    324                     Task.detached {
    325                         await WalletModel.shared.hintNetworkAvailabilityT(true)
    326                     }
    327                 }
    328             }
    329         }
    330         self.logger.log("Start monitoring internet connection")
    331         let queue = DispatchQueue(label: "InternetMonitor")
    332         monitor.start(queue: queue)
    333     }
    334 
    335     func printFonts() {
    336         for family in UIFont.familyNames {
    337             print(family)
    338             for names in UIFont.fontNames(forFamilyName: family) {
    339                 print("== \(names)")
    340             }
    341         }
    342     }
    343 
    344     init() {
    345         backendState = .instantiated
    346         currencyTicker = 0
    347         currencyInfos = [:]
    348         exchanges = []
    349         balances = []
    350         discounts = []
    351         subscriptions = []
    352         defaultExchanges = []
    353         contacts = []
    354 //        printFonts()
    355 //        checkInternetConnection()
    356         startObserving()
    357     }
    358 // MARK: -
    359     @MainActor
    360     @discardableResult
    361     func loadBalances(_ stack: CallStack) async -> Int? {
    362         let model = WalletModel.shared
    363         if let (response, debugId) = try? await model.getBalances(stack.push()) {
    364             let reloaded = response.balances
    365             if reloaded != balances {
    366                 for balance in reloaded {
    367                     let scope = balance.scopeInfo
    368                     checkInfo(stack.push() ,for: scope)
    369                 }
    370 #if DEBUG
    371                 self.logger.log("\(debugId) ••Got new balances, will redraw")
    372 #endif
    373                 lastNewBalances = debugId
    374                 balances = reloaded         // redraw
    375             } else {
    376 #if DEBUG
    377                 self.logger.log("\(debugId) ••Same balances as \(self.lastNewBalances), no redraw")
    378 #endif
    379             }
    380             haveProdBalance = response.haveProdBalance
    381             return reloaded.count
    382         }
    383         return nil
    384     }
    385 
    386     func balance(for scope: ScopeInfo) -> Balance? {
    387         for balance in balances {
    388             if balance.scopeInfo == scope {
    389                 return balance
    390             }
    391         }
    392         return nil
    393     }
    394     // MARK: -
    395     @MainActor
    396     @discardableResult
    397     func createMailbox() async ->MailboxConfiguration? {
    398         if mailboxConfiguration == nil {
    399             let model = WalletModel.shared
    400             let configuration = try? await model.initializeMailbox()
    401             mailboxConfiguration = configuration
    402         }
    403         return mailboxConfiguration
    404     }
    405     @MainActor
    406     @discardableResult
    407     func loadContacts(_ stack: CallStack) async -> Int? {
    408         // Do we have a mailbox?
    409         let model = WalletModel.shared
    410         if mailboxConfiguration == nil {
    411             let configuration = try? await model.getMailbox()
    412             mailboxConfiguration = configuration
    413         }
    414         // if yes, then return how many contacts changed
    415         if mailboxConfiguration != nil {
    416             if let response = try? await model.getContacts() {
    417                 let count = contacts.count
    418                 contacts = response//.sorted(by: { })
    419                 return response.count - count
    420             }
    421         }
    422         return nil
    423     }
    424     @MainActor
    425     func refreshMailbox(_ stack: CallStack) async {
    426         if let mailboxConfiguration {            // Do we have a mailbox?
    427             let model = WalletModel.shared
    428             if let response = try? await model.refreshMailbox(mailboxConfiguration) {
    429                 let countNew = response.messages.count
    430                 if let response2 = try? await model.getMailboxMessages() {
    431                     messages = response2.messages
    432                 } else {
    433                     messages = response.messages
    434                 }
    435 #if DEBUG   // TODO: tell user?
    436                 if let expiration = response.mailboxExpiration {
    437                     if expiration != mailboxConfiguration.expiration {
    438                         let expirationDate = TalerDater.dateString(expiration)
    439                         self.logger.log("••Mailbox expiration changed: \(expirationDate.0)")
    440                     }
    441                 }
    442 #endif
    443             }
    444         }
    445     }
    446 // MARK: -
    447     @MainActor
    448     @discardableResult
    449     func loadDiscounts(_ stack: CallStack) async -> Int? {
    450         let model = WalletModel.shared
    451         if let response = try? await model.listDiscounts(stack.push()) {
    452             let reloaded = response.discounts
    453             if reloaded != discounts {
    454                 self.logger.log("••Got new discounts, will redraw")
    455                 discounts = reloaded         // redraw
    456             } else {
    457                 self.logger.log("••Same discounts, no redraw")
    458             }
    459             return reloaded.count
    460         }
    461         return nil
    462     }
    463 // MARK: -
    464     @MainActor
    465     @discardableResult
    466     func loadSubscriptions(_ stack: CallStack) async -> Int? {
    467         let model = WalletModel.shared
    468         if let response = try? await model.listSubscriptions(stack.push()) {
    469             let reloaded = response.subscriptions
    470             if reloaded != subscriptions {
    471                 self.logger.log("••Got new passes, will redraw")
    472                 subscriptions = reloaded         // redraw
    473             } else {
    474                 self.logger.log("••Same passes, no redraw")
    475             }
    476             return reloaded.count
    477         }
    478         return nil
    479     }
    480     // MARK: -
    481     @MainActor
    482     @discardableResult
    483     func loadChoicesForPayment(_ stack: CallStack,
    484                                   txId: String) async -> Bool {
    485         let model = WalletModel.shared
    486         if isLoadingChoices != txId {
    487             isLoadingChoices = txId
    488             if let choiceResponse = try? await model.getChoicesForPayment(txId) {
    489                 choicesTuple = (txId, choiceResponse)
    490                 isLoadingChoices = nil
    491                 return true
    492             } else {
    493                 isLoadingChoices = nil
    494                 self.logger.log("getChoicesForPayment failed: \(txId)")
    495             }
    496         } else {
    497             self.logger.log("getChoicesForPayment already in progress: \(txId)")
    498         }
    499         return false
    500     }
    501 // MARK: -
    502     func info(for scope: ScopeInfo) -> CurrencyInfo? {
    503 //        return CurrencyInfo.euro()              // Fake EUR instead of the real Currency
    504 //        return CurrencyInfo.francs()            // Fake CHF instead of the real Currency
    505         return currencyInfos[scope]
    506     }
    507     func info(for scope: ScopeInfo, _ ticker: Int) -> CurrencyInfo {
    508         if ticker != currencyTicker {
    509             print("  ❗️Yikes - race condition while getting info for \(scope.currency)")
    510         }
    511         return info(for: scope) ?? CurrencyInfo.zero(scope.currency)
    512     }
    513 
    514     func info2(for currency: String) -> CurrencyInfo? {
    515 //        return CurrencyInfo.euro()              // Fake EUR instead of the real Currency
    516 //        return CurrencyInfo.francs()            // Fake CHF instead of the real Currency
    517         for (scope, info) in currencyInfos {
    518             if scope.currency == currency {
    519                 return info
    520             }
    521         }
    522 //        logger.log("  ❗️ no info for \(currency)")
    523         return nil
    524     }
    525     func info2(for currency: String, _ ticker: Int) -> CurrencyInfo {
    526         if ticker != currencyTicker {
    527             print("  ❗️Yikes - race condition while getting info for \(currency)")
    528         }
    529         return info2(for: currency) ?? CurrencyInfo.zero(currency)
    530     }
    531 
    532     func hasInfo(for currency: String) -> Bool {
    533         for (scope, info) in currencyInfos {
    534             if scope.currency == currency {
    535                 return true
    536             }
    537         }
    538 //        logger.log("  ❗️ no info for \(currency)")
    539         return false
    540     }
    541 
    542     @MainActor
    543     func exchange(for baseUrl: String?) async -> Exchange? {
    544         if let baseUrl {
    545             if let exchange = exchanges.first(where: {$0.exchangeBaseUrl == baseUrl}) {
    546                 return exchange
    547             }
    548             let model = WalletModel.shared
    549             if let exchange2 = try? await model.getExchangeByUrl(url: baseUrl) {
    550 //                logger.log("  ❗️ will add \(baseUrl)")
    551                 exchanges.append(exchange2)
    552                 return exchange2
    553             }
    554         }
    555         return nil
    556     }
    557     @MainActor
    558     func checkToS(for baseUrl: String?) async -> Bool? {
    559 //        print("  🫆 checkToS: \(baseUrl)")
    560         if let exchange = await exchange(for: baseUrl) {
    561             return exchange.tosStatus == .accepted
    562                 || exchange.tosStatus == .missingTos       // no ToS to accept
    563         }
    564         return nil
    565     }
    566     @MainActor
    567     func exchange(for scope: ScopeInfo) -> Exchange? {
    568         if let baseUrl = scope.url {
    569             if let exchange = exchanges.first(where: {$0.exchangeBaseUrl == baseUrl}) {
    570                 return exchange
    571             }
    572         }
    573         return nil
    574     }
    575     @MainActor
    576     func setTosAccepted(for baseUrl: String) async -> Exchange? {
    577         let model = WalletModel.shared
    578         _ = try? await model.setExchangeTOSAccepted(baseUrl)
    579         return await updateExchange(for: baseUrl)
    580     }
    581     @MainActor
    582     func updateExchange(for baseUrl: String) async -> Exchange? {
    583         let model = WalletModel.shared
    584         if let exchange2 = try? await model.getExchangeByUrl(url: baseUrl, viewHandles: true) {
    585             if let index = exchanges.firstIndex(where: {$0.exchangeBaseUrl == baseUrl}) {
    586                 let exchange1 = exchanges[index]
    587                 if exchange1.tosStatus != exchange2.tosStatus ||
    588                    exchange1.masterPub != exchange2.masterPub ||
    589                    exchange1.unconfirmedKeyChange != exchange2.unconfirmedKeyChange
    590                 {
    591                     logger.log("  🫆 updating cached exchange: \(baseUrl)")
    592                     exchanges[index] = exchange2
    593                 }
    594             } else {
    595                 logger.log("  🫆 caching exchange: \(baseUrl)")
    596                 exchanges.append(exchange2)
    597             }
    598             return exchange2
    599         }
    600         return nil
    601     }
    602     @MainActor
    603     func updateExchange(for baseUrl: String, state: ExchangeState) {
    604         Task {  // reload/update the cache - ignoring the notification state
    605             await updateExchange(for: baseUrl)
    606         }
    607     }
    608 
    609     @MainActor
    610     func updateInfo2(_ scope: ScopeInfo) async {
    611         let model = WalletModel.shared
    612         if let info = try? await model.getCurrencyInfo(scope: scope) {
    613             await setInfo(info, for: scope)
    614 //            logger.log("  ❗️info set for \(scope.currency)")
    615         }
    616     }
    617 
    618     @MainActor
    619     func checkCurrencyInfo(for baseUrl: String) async -> Exchange? {
    620         if let exchange = await exchange(for: baseUrl) {
    621             let scope = exchange.scopeInfo
    622             if currencyInfos[scope] == nil {
    623                 logger.log("  ❗️got no info for \(baseUrl.trimURL) \(scope.currency) -> will update")
    624                 await updateInfo2(scope)
    625             }
    626             return exchange
    627         } else {
    628             // Yikes❗️  TODO: error?
    629         }
    630         return nil
    631     }
    632 
    633     /// called whenever a new currency pops up - will first load the Exchange and then currencyInfos
    634     func checkInfo(_ stack: CallStack, for scope: ScopeInfo) {
    635         if currencyInfos[scope] == nil {
    636             Task {
    637                 let exchange = await exchange(for: scope.url)
    638                 if let scope2 = exchange?.scopeInfo {
    639                     let exchangeName = scope2.url ?? "UNKNOWN"
    640                     let caller = stack.peek()
    641                     logger.log("  ❗️got no info for \(scope.currency) -> will update \(exchangeName.trimURL)")
    642                     await updateInfo2(scope)
    643                 } else {
    644                     logger.error("  ❗️got no info for \(scope.currency), and couldn't load the exchange info❗️")
    645                 }
    646             }
    647         }
    648     }
    649 
    650     @MainActor
    651     func getInfo(from baseUrl: String, model: WalletModel) async throws -> CurrencyInfo? {
    652         let exchange = try await model.getExchangeByUrl(url: baseUrl)
    653         let scope = exchange.scopeInfo
    654         if let info = info(for: scope) {
    655             return info
    656         }
    657         let info = try await model.getCurrencyInfo(scope: scope)
    658         await setInfo(info, for: scope)
    659         return info
    660     }
    661 
    662     @MainActor
    663     func setInfo(_ newInfo: CurrencyInfo, for scope: ScopeInfo) async {
    664         await semaphore.wait()
    665         defer { semaphore.signal() }
    666 
    667         currencyInfos[scope] = newInfo
    668         currencyTicker += 1         // triggers published view update
    669     }
    670 #if GNU_TALER || TALER_NIGHTLY
    671     @MainActor
    672     func setDelayAsync(_ delay: Int, _ f500: Int) async {
    673         let delayTime = delay > 0 ? 3000
    674                       : delay < 0 ? 6000
    675                                   : 0
    676         let fakeValue = delay != 0 ? ( f500 > 0 ? 2
    677                                      : f500 < 0 ? 4
    678                                                 : 0 ) : 0
    679         symLog.log(delay != 0 ? "wallet-core delaying by \(delayTime) milliseconds, with \(fakeValue) fake_500"
    680                               : "wallet-core stop delaying")
    681         tcDelay = delay
    682         fake500 = f500
    683         let model = WalletModel.shared
    684         try? await model.setConfig(setTesting: true)
    685         try? await model.devExperimentT("taler://dev-experiment/start-tc?fake_500_count=\(fakeValue)&delay_resp=\(delayTime)")
    686     }
    687     @MainActor
    688     func setDelay(_ delay: Int, _ f500: Int) {
    689         Task {
    690             await setDelayAsync(delay, f500)
    691         }
    692     }
    693 #endif 
    694 // MARK: -
    695     @MainActor
    696     func initWalletCore(stack: CallStack, setTesting: Bool, delay: TimeInterval)
    697       async throws {
    698         if backendState == .instantiated {
    699             backendState = .initing
    700             do {
    701                 let walletCore = WalletCore.shared
    702                 let model = WalletModel.shared
    703                 let response = try await model.initWalletCore(setTesting: setTesting)
    704 //  throw WalletBackendError.initializationError      // check how the app behaves if initWalletCore throws
    705                 walletCore.versionInfo = response.versionInfo
    706                 walletCore.nativeDB = (response.databaseBackend == "sqlite")
    707                 if developerMode {
    708                     do {
    709 //                        try await model.setConfig(setTesting: true)
    710 //                        try await model.devExperimentT("taler://dev-experiment/default-exchange-demo?val=1")
    711 //                        try await model.devExperimentT(
    712 //                            "taler://dev-experiment/demo-shortcuts?val=KUDOS:4,KUDOS:8,KUDOS:16,KUDOS:32")
    713                     } catch {
    714                         self.logger.error("developer-mode setup failed, continuing without it: \(error.localizedDescription)")
    715                     }
    716                 }
    717                 defaultExchanges = await model.getDefaultExchanges()
    718 #if GNU_TALER
    719                 if defaultExchanges.count == 1 {
    720                     if let talerOps = defaultExchanges.first {
    721                         let stageURI = "taler://withdraw-exchange/exchange.stage.taler-ops.ch/"
    722                         let baseUrl = "https://exchange.stage.taler-ops.ch/"
    723                         if talerOps.talerUri != stageURI {
    724                             let stageExc = DefaultExchange(talerUri: stageURI,
    725                                                     exchangeBaseUrl: baseUrl,
    726                                                            currency: talerOps.currency,
    727                                                        currencySpec: talerOps.currencySpec,
    728                                                 exchangeEntryStatus: .preset,
    729                                                exchangeUpdateStatus: .initial
    730                             )
    731                             defaultExchanges.append(stageExc)
    732                         }
    733                     }
    734                 }
    735 #endif
    736                 let launchDelay: TimeInterval = walletCore.nativeDB ? 0.1 : delay
    737                 DispatchQueue.main.asyncAfter(deadline: .now() + launchDelay) {
    738                     // dismiss the launch animation after delay
    739                     self.symLog.log("backendState = ready")
    740                     self.backendState = walletCore.nativeDB ? .ready : .update
    741                 }
    742 //                await loadBalances(stack.push())
    743 //                await loadContacts(stack.push())
    744             } catch {
    745                 self.logger.error("\(error.localizedDescription)")
    746                 backendState = .error(error.toEquatableError())                 // ❗️Yikes app cannot continue
    747             }
    748         } else {
    749             self.logger.fault("Yikes❗️ wallet-core already initialized")
    750         }
    751     }
    752 }
    753 // MARK: -
    754 extension Controller {
    755     func urlCommand(_ url: URL, stack: CallStack) -> (UrlCommand, URL) {
    756         guard let scheme = url.scheme else {return (UrlCommand.unknown, url) }
    757 #if DEBUG
    758         symLog.log(url)
    759 #else
    760         let host = url.host ?? "  <- no command"
    761         self.logger.trace("urlCommand(\(scheme)\(host)")
    762 #endif
    763         var urlCommand = UrlCommand.unknown
    764         var talerURI: URL = url
    765         switch scheme.lowercased() {
    766             case "https":
    767                 (urlCommand, talerURI) = httpsScheme(url)
    768 //            case "payto":
    769 //                messageForSheet = url.absoluteString
    770 //                return paytoScheme(url)
    771             case "taler":
    772                 urlCommand = talerScheme(url)
    773             default:
    774                 self.logger.error("unknown scheme: <\(scheme)>")       // should never happen
    775         }
    776         saveURL(talerURI, urlCommand: urlCommand)
    777         return (urlCommand, talerURI)
    778     }
    779 }
    780 // MARK: -
    781 extension Controller {
    782     func httpsScheme(_ url: URL) -> (UrlCommand, URL) {
    783         // https://wallet.taler.net/link/#taler://${action}/${rest}
    784         // https://wallet.taler.net/link/#/${action}/${rest}
    785         // https://wallet.taler.net/link/#${action}/${rest}
    786         // are all mapped to taler://${action}/${rest}
    787         if let host = url.host, host == "wallet.taler.net" {
    788             if url.path == "/link" {
    789                 if let fragment = url.fragment {
    790                     // 'fragment(percentEncoded:)' is only available in iOS 16.0 or newer
    791                     var split = fragment.split(separator: "/")  // SLASH
    792                     if split.first == "taler:" {
    793                         split.removeFirst()
    794                     }
    795                     if let action = split.first {
    796                         let joined = split.joined(separator: SLASH)
    797                         if let talerURI = URL(string: TALER + joined) {
    798                             return (command(String(action)), talerURI)
    799                         }
    800                     }
    801                 }
    802             }
    803         }
    804         self.logger.error("❗️unknown url:\(url.absoluteString)")
    805         return (.unknown, url)
    806     }
    807 
    808 //    func paytoScheme(_ url:URL) -> UrlCommand {
    809 //        let logItem = "scheme payto:// is not yet implemented"
    810 //        // TODO: write logItem to somewhere in Debug section of SettingsView
    811 //        symLog.log(logItem)        // TODO: symLog.error(logItem)
    812 //        return UrlCommand.unknown
    813 //    }
    814     
    815     func command(_ command:String) -> UrlCommand {
    816         let lcCommand = command.lowercased()
    817         switch lcCommand {
    818             case "withdraw":            return .withdraw
    819             case "withdraw-exchange":   return .withdrawExchange
    820             case "add-exchange":        return .addExchange
    821             case "pay":                 return .pay
    822             case "pay-pull":            return .payPull
    823             case "pay-push":            return .payPush
    824             case "pay-template":        return .payTemplate
    825             case "refund":              return .refund
    826 #if GNU_TALER || TALER_NIGHTLY
    827             case "dev-experiment":      return .devExperiment
    828             case "add-contact":         return .addContact
    829 #endif
    830             default:
    831                 self.logger.error("❗️unknown command taler://\(command)")
    832         }
    833         messageForSheet = lcCommand
    834         return .unknown
    835     }
    836 
    837     func talerScheme(_ url:URL) -> UrlCommand {
    838         if let command = url.host {
    839             return self.command(command)
    840         } else {
    841             self.logger.error("❗️No taler command")
    842         }
    843         return .unknown
    844     }
    845 }