| 1 | import Foundation |
| 2 | import RastrilloApple |
| 3 | |
| 4 | /// Ask set up during sign-in, with no code to approve (spec 3.8, P1, P2): |
| 5 | /// the app fetches an Oficina ID assertion addressed to Equipo and posts it |
| 6 | /// to Base, which finishes Equipo's own native sign-in for the person and |
| 7 | /// keeps the key. Equipo's key from Oficina ID lasts seven days, so Base |
| 8 | /// says when to renew it (`renew_after`) and this does, silently. |
| 9 | /// |
| 10 | /// It runs when `/ask/state` says `connect` or `reconnect` (a write's 409 |
| 11 | /// reconnect too), or `renew_after` has passed: |
| 12 | /// |
| 13 | /// 1. `assertion(for: equipo_origin)`; |
| 14 | /// 2. `POST /api/v1/ask/oficina`; |
| 15 | /// 3. read `/ask/state` again, whatever happened. |
| 16 | /// |
| 17 | /// - `ready`: done. `not_linked` (Equipo doesn't know this person): Ask |
| 18 | /// shows it, with the web's set-up; never retried by itself. |
| 19 | /// - `422 failed`: once more at once, with a fresh assertion. |
| 20 | /// - `409 superseded` (the person disconnected or reconnected another way |
| 21 | /// meanwhile): not retried; the state read afresh says how things are. |
| 22 | /// - The kit's CancellationError (the sign-in changed while Home answered, |
| 23 | /// its own silent re-sign-in after a 401 included): nothing shown, tried |
| 24 | /// again at the next foreground or state load. |
| 25 | /// - `409 disconnected` (an automatic set-up while the member has |
| 26 | /// disconnected, on any client): stop; Ask shows Set up. |
| 27 | /// - Anything else: Ask stays as Base reports it; tried again later. |
| 28 | /// |
| 29 | /// Never more than once a minute, whatever triggers it, but for a person |
| 30 | /// pressing Set it up. |
| 31 | @MainActor public final class AskSetup { |
| 32 | public typealias Assertion = @MainActor (URL) async throws -> (assertion: String, verifier: String) |
| 33 | |
| 34 | let client: BaseClient |
| 35 | let ask: AskModel |
| 36 | let assertion: Assertion |
| 37 | let now: () -> Date |
| 38 | /// The Equipo Ask relays to, when `/ask/state` hasn't said yet. |
| 39 | var fallbackEquipo: () -> URL? |
| 40 | /// Whether the session that made this is still the one (the account |
| 41 | /// hasn't changed or signed out). |
| 42 | var isCurrent: () -> Bool = { true } |
| 43 | /// The person disconnected Ask: no set-up by itself until they set it |
| 44 | /// up again (`force`) or sign in afresh. Base's word (`/ask/state`'s |
| 45 | /// `disconnected`) when it says; the device's cache otherwise. |
| 46 | var heldOff: () -> Bool = { false } |
| 47 | /// Base answered an automatic set-up `409 disconnected`. |
| 48 | var onDisconnected: () -> Void = {} |
| 49 | /// Bumped by `invalidate()`: a set-up already running lands nothing. |
| 50 | private var epoch = 0 |
| 51 | |
| 52 | /// Disconnect: whatever set-up is running must not undo it. |
| 53 | public func invalidate() { epoch += 1 } |
| 54 | private(set) var lastAttempt: Date? |
| 55 | /// The epoch of the run in flight, if any. |
| 56 | private var runningEpoch: Int? |
| 57 | var running: Bool { runningEpoch != nil } |
| 58 | /// Equipo answered not_linked: no more automatic attempts this session. |
| 59 | private(set) var notLinked = false |
| 60 | |
| 61 | public init(client: BaseClient, ask: AskModel, assertion: @escaping Assertion, now: @escaping () -> Date = Date.init, |
| 62 | fallbackEquipo: @escaping () -> URL? = { nil }) { |
| 63 | self.client = client; self.ask = ask; self.assertion = assertion; self.now = now; self.fallbackEquipo = fallbackEquipo |
| 64 | } |
| 65 | |
| 66 | /// Whether Ask wants setting up now, by its state. |
| 67 | public var wanted: Bool { |
| 68 | switch ask.phase { |
| 69 | case .connect, .reconnect: true |
| 70 | case .ready, .norunner, .oldrunner: ask.renewAfter.map { $0 <= now() } ?? false |
| 71 | default: false |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /// Runs the set-up if Ask wants it and the minute has passed (`force`: |
| 76 | /// the person pressed Set it up, which also clears a not_linked). |
| 77 | @discardableResult |
| 78 | public func runIfNeeded(force: Bool = false) async -> Bool { |
| 79 | // Base still says connect after not_linked: Ask keeps saying why. |
| 80 | if !force, heldOff() { return false } |
| 81 | if notLinked, !force, ask.phase == .connect || ask.phase == .reconnect { ask.show(.notLinked); return false } |
| 82 | // One run at a time; but the person's own Set it up goes ahead when |
| 83 | // the run in flight was invalidated (a Disconnect, Set it up), and |
| 84 | // that one lands nothing. |
| 85 | if let inFlight = runningEpoch, !(force && inFlight != epoch) { return false } |
| 86 | guard wanted || (force && ask.phase != .loading) else { return false } |
| 87 | if !force { |
| 88 | guard !notLinked else { return false } |
| 89 | if let last = lastAttempt, now().timeIntervalSince(last) < 60 { return false } |
| 90 | } |
| 91 | guard let equipo = ask.equipoOrigin ?? fallbackEquipo() else { return false } |
| 92 | let activity = ask.activity, started = epoch |
| 93 | runningEpoch = started |
| 94 | defer { if runningEpoch == started { runningEpoch = nil } } |
| 95 | let previousAttempt = lastAttempt, thisAttempt = now() |
| 96 | lastAttempt = thisAttempt |
| 97 | notLinked = false |
| 98 | // After every suspension: the account, Ask's activity (a pause, a |
| 99 | // sign-out) and this task must all be as they were, or nothing lands. |
| 100 | func live() -> Bool { isCurrent() && epoch == started && ask.activity == activity && !ask.paused && !ask.disposed && !Task.isCancelled } |
| 101 | // A run that ends because it no longer counts spends no minute: the |
| 102 | // next trigger may try at once. |
| 103 | func abandon() -> Bool { |
| 104 | if lastAttempt == thisAttempt { lastAttempt = previousAttempt } |
| 105 | return false |
| 106 | } |
| 107 | var tries = 0 |
| 108 | while tries < 2 { |
| 109 | tries += 1 |
| 110 | let proof: (assertion: String, verifier: String) |
| 111 | do { |
| 112 | proof = try await assertion(equipo) |
| 113 | } catch { |
| 114 | // CancellationError (the sign-in moved under it) and any other |
| 115 | // failure to get a proof: nothing to show; next time. Abandoned |
| 116 | // meanwhile (the account went, a pause, an invalidation): it |
| 117 | // spends no minute either. |
| 118 | return live() ? false : abandon() |
| 119 | } |
| 120 | guard live() else { return abandon() } |
| 121 | do { |
| 122 | let answer = try await client.connectAsk(assertion: proof.assertion, verifier: proof.verifier, auto: !force) |
| 123 | guard live() else { return abandon() } |
| 124 | if answer.state == .notLinked { notLinked = true; ask.show(.notLinked); return false } |
| 125 | await ask.load() |
| 126 | return true |
| 127 | } catch .server(422, _, "failed") where tries < 2 { |
| 128 | guard live() else { return abandon() } |
| 129 | continue |
| 130 | } catch .server(409, _, "disconnected") { |
| 131 | // The member disconnected (here or on another device): stop, |
| 132 | // and let Ask show Set up. |
| 133 | guard live() else { return abandon() } |
| 134 | onDisconnected() |
| 135 | await ask.load() |
| 136 | return false |
| 137 | } catch .server(409, _, "not_linked") { |
| 138 | guard live() else { return abandon() } |
| 139 | notLinked = true |
| 140 | ask.show(.notLinked) |
| 141 | return false |
| 142 | } catch { |
| 143 | // superseded, unavailable, Ask off, a refused session: Ask as |
| 144 | // Base says it is now. |
| 145 | guard live() else { return abandon() } |
| 146 | await ask.load() |
| 147 | return false |
| 148 | } |
| 149 | } |
| 150 | guard live() else { return abandon() } |
| 151 | await ask.load() |
| 152 | return false |
| 153 | } |
| 154 | } |
| 155 | |