|
| 1 | +#if canImport(SwiftUI) |
| 2 | + import Foundation |
| 3 | + import Observation |
| 4 | + import Security |
| 5 | + import ZBugs |
| 6 | + import Zero |
| 7 | + |
| 8 | + /// The app's state outside its views: where the servers are, who is |
| 9 | + /// logged in, and the client for them. |
| 10 | + @Observable |
| 11 | + @MainActor |
| 12 | + public final class AppModel { |
| 13 | + /// zero-cache. |
| 14 | + public private(set) var cacheURL: String |
| 15 | + /// The zbugs API server: login, and the queries and mutators zero-cache |
| 16 | + /// forwards. |
| 17 | + public private(set) var apiURL: String |
| 18 | + public private(set) var auth: AuthData? |
| 19 | + /// A new client whenever the servers or the user change, as zbugs' |
| 20 | + /// `ZeroProvider` makes one. |
| 21 | + public private(set) var zero: Zero<AuthData?> |
| 22 | + @ObservationIgnored private var token: String? |
| 23 | + private let defaults: UserDefaults |
| 24 | + |
| 25 | + public static let projectName = zeroProjectName |
| 26 | + |
| 27 | + public init(defaults: UserDefaults = .standard) { |
| 28 | + self.defaults = defaults |
| 29 | + let cacheURL = defaults.string(forKey: "cacheURL") ?? "http://localhost:4848" |
| 30 | + let apiURL = defaults.string(forKey: "apiURL") ?? "http://localhost:5173" |
| 31 | + // An expired token logs out. |
| 32 | + let auth = Keychain.token.flatMap { AuthData(jwt: $0, now: Date().timeIntervalSince1970) } |
| 33 | + let token = auth == nil ? nil : Keychain.token |
| 34 | + self.cacheURL = cacheURL |
| 35 | + self.apiURL = apiURL |
| 36 | + self.token = token |
| 37 | + self.auth = auth |
| 38 | + zero = Self.makeZero(cacheURL: cacheURL, apiURL: apiURL, token: token, auth: auth) |
| 39 | + preload() |
| 40 | + } |
| 41 | + |
| 42 | + /// Logs in with a zbugs JWT, from the GitHub login or a dev token. |
| 43 | + public func logIn(token: String) throws { |
| 44 | + let token = token.trimmingCharacters(in: .whitespacesAndNewlines) |
| 45 | + guard let auth = AuthData(jwt: token, now: Date().timeIntervalSince1970) else { |
| 46 | + throw LoginError("That is not a current zbugs token.") |
| 47 | + } |
| 48 | + Keychain.token = token |
| 49 | + self.token = token |
| 50 | + self.auth = auth |
| 51 | + restart() |
| 52 | + } |
| 53 | + |
| 54 | + public func logOut() { |
| 55 | + Keychain.token = nil |
| 56 | + token = nil |
| 57 | + auth = nil |
| 58 | + restart() |
| 59 | + } |
| 60 | + |
| 61 | + public func setServers(cacheURL: String, apiURL: String) { |
| 62 | + defaults.set(cacheURL, forKey: "cacheURL") |
| 63 | + defaults.set(apiURL, forKey: "apiURL") |
| 64 | + self.cacheURL = cacheURL |
| 65 | + self.apiURL = apiURL |
| 66 | + restart() |
| 67 | + } |
| 68 | + |
| 69 | + /// Why the last mutation failed, for an alert; nil once seen. |
| 70 | + public var mutationError: String? |
| 71 | + |
| 72 | + /// Runs a mutator and reports its failure, on the client or the server. |
| 73 | + public func mutate(_ request: MutateRequest<AuthData?>) { |
| 74 | + let result = zero.mutate(request) |
| 75 | + if case .success(let outcome)? = result.client.result, let message = outcome.errorMessage { |
| 76 | + mutationError = message |
| 77 | + return |
| 78 | + } |
| 79 | + Task { [weak self] in |
| 80 | + if let message = try? await result.server.value.errorMessage { |
| 81 | + self?.mutationError = message |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + /// The URL that starts the GitHub login and ends at `callbackScheme` |
| 87 | + /// with the token. |
| 88 | + public var loginURL: URL? { |
| 89 | + var c = URLComponents(string: apiURL + "/api/login/github") |
| 90 | + c?.queryItems = [URLQueryItem(name: "redirect", value: "\(Self.callbackScheme)://auth")] |
| 91 | + return c?.url |
| 92 | + } |
| 93 | + |
| 94 | + public static let callbackScheme = "zbugs-swift" |
| 95 | + |
| 96 | + private func restart() { |
| 97 | + zero.close() |
| 98 | + zero = Self.makeZero(cacheURL: cacheURL, apiURL: apiURL, token: token, auth: auth) |
| 99 | + preload() |
| 100 | + } |
| 101 | + |
| 102 | + /// What zbugs preloads: the project's issues with their first comments, |
| 103 | + /// and the users, labels, and projects. |
| 104 | + private func preload() { |
| 105 | + let ttl = TTL.seconds(10) |
| 106 | + _ = zero.preload( |
| 107 | + Queries.issuePreloadV2(ProjectArgs(projectName: Self.projectName)), ttl: ttl) |
| 108 | + _ = zero.preload(Queries.allUsers(), ttl: ttl) |
| 109 | + _ = zero.preload(Queries.allLabels(), ttl: ttl) |
| 110 | + _ = zero.preload(Queries.allProjects(), ttl: ttl) |
| 111 | + } |
| 112 | + |
| 113 | + private static func makeZero( |
| 114 | + cacheURL: String, apiURL: String, token: String?, auth: AuthData? |
| 115 | + ) -> Zero<AuthData?> { |
| 116 | + var options = ZeroOptions(cacheURL: cacheURL, userID: auth?.sub, auth: token) |
| 117 | + options.mutateURL = apiURL + "/api/mutate" |
| 118 | + options.queryURL = apiURL + "/api/query" |
| 119 | + options.logLevel = .info |
| 120 | + do { |
| 121 | + return try Zero(schema: .zbugs, context: auth, mutators: Mutators.all, options: options) |
| 122 | + } catch { |
| 123 | + // Only a mutator registered twice fails; storage falls back to |
| 124 | + // memory on its own. |
| 125 | + preconditionFailure("zbugs' mutators: \(error)") |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + extension MutationOutcome { |
| 131 | + var errorMessage: String? { |
| 132 | + switch self { |
| 133 | + case .success: nil |
| 134 | + case .appError(let message, _), .zeroError(let message): message |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + public struct LoginError: Error, CustomStringConvertible { |
| 140 | + public let description: String |
| 141 | + init(_ description: String) { self.description = description } |
| 142 | + } |
| 143 | + |
| 144 | + /// The token in the keychain, so it outlives the app. |
| 145 | + enum Keychain { |
| 146 | + private static var query: [String: Any] { |
| 147 | + [ |
| 148 | + kSecClass as String: kSecClassGenericPassword, |
| 149 | + kSecAttrService as String: "dev.rocicorp.zbugs", |
| 150 | + kSecAttrAccount as String: "jwt", |
| 151 | + ] |
| 152 | + } |
| 153 | + |
| 154 | + static var token: String? { |
| 155 | + get { |
| 156 | + var q = query |
| 157 | + q[kSecReturnData as String] = true |
| 158 | + var item: CFTypeRef? |
| 159 | + guard SecItemCopyMatching(q as CFDictionary, &item) == errSecSuccess, |
| 160 | + let data = item as? Data |
| 161 | + else { return nil } |
| 162 | + return String(data: data, encoding: .utf8) |
| 163 | + } |
| 164 | + set { |
| 165 | + SecItemDelete(query as CFDictionary) |
| 166 | + guard let newValue else { return } |
| 167 | + var q = query |
| 168 | + q[kSecValueData as String] = Data(newValue.utf8) |
| 169 | + SecItemAdd(q as CFDictionary, nil) |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | +#endif |
0 commit comments