import AppKit import Foundation import Observation /// Everything the popover shows and every action it takes, over the core. /// /// Launch: open the core, hand it the stored Mail credentials, /// then the stored token (`start`) — or show sign-in when there is none. /// `status` is polled about once a second while the popover is open and every /// ten seconds otherwise; a status that says `signedOut` drops the token from /// the keychain and shows sign-in again. @MainActor @Observable final class AppModel { enum Screen: Equatable { case starting, signIn, cards } /// A build under another bundle id (`com.decemberfm.cotton.mac.dev`, made /// to walk the importer against the DEV Worker beside the person's own /// app) is a flavour: its own data folder, keychain items, device key and /// login item, and the host its `CottonObjectURL` default names. The app /// a person installs has none and always speaks to cottondb.com. static let flavour: String? = { let id = Bundle.main.bundleIdentifier ?? "" let base = "com.decemberfm.cotton.mac" return id.hasPrefix(base + ".") ? String(id.dropFirst(base.count + 1)) : nil }() /// The open host, as the phone signs in: the code finds the number's /// database, and the credential names it from then on. static let objectURL: String = { if flavour != nil, let url = UserDefaults.standard.string(forKey: "CottonObjectURL"), url.hasPrefix("https://") { return url } return "https://cottondb.com" }() /// Where Photos and Calls are read from: the person's home, or, in a flavour only, the folder its `CottonHome` /// default names, so a walk by hand reads invented libraries and never the Mac owner's. static let home: String = { if flavour != nil, let path = UserDefaults.standard.string(forKey: "CottonHome"), path.hasPrefix("/") { return path } return NSHomeDirectory() }() private(set) var screen: Screen = .starting private(set) var status: CoreStatus? /// The core could not open; said in the header instead of the number. private(set) var openError: String? let version: String // Sign-in. var phoneInput = "" { didSet { if phoneInput != oldValue { challengeId = nil; databaseId = nil; codeInput = "" } } } var codeInput = "" /// The recovery code, typed once to open the vault on this Mac with no phone at hand; dropped as soon as it is used. var recoveryCodeInput = "" private(set) var recoveryBusy = false private(set) var recoveryError: String? private(set) var challengeId: String? /// The database the code was sent for, which the sign-in names. private var databaseId: String? private(set) var signInBusy = false private(set) var signInError: String? /// The approval this Mac asks a signed-in phone for (the core's `askApproval` / `askPoll` card), while it stands. private(set) var asking: AskCard? private var askPolling: Task? /// What the core says of an ask: its words, and the code once a phone opened it. struct AskCard: Decodable, Equatable, Sendable { var state: String var done: Bool var heading: String? var line: String? var code: String? var check: String? var left: String? var pollSeconds: Double? var cancel: String? var again: String? var credential: String? var phone: String? /// The square code the other device scans (GETTING-IN.md): one string per row, `1` dark. Never a link. var qr: Square? var codeLine: String? var noDevice: String? var signOut: String? struct Square: Decodable, Equatable, Sendable { var size: Int var rows: [String] } } // Mail: what is being typed into each card, and its answer. var credentialDrafts: [Source: Keychain.Credentials] = [:] private(set) var credentialErrors: [Source: String] = [:] private(set) var credentialBusy: Set = [] // WhatsApp's link: the number typed for a code (the signed-in one until // changed), and what the helper answered. var whatsappNumber: String? private(set) var pairError: String? private(set) var pairBusy = false /// When each running source started and what it had sent then: the /// card's "about N s left". private var runStarts: [Source: (at: Date, sent: Int)] = [:] var popoverOpen = false { didSet { if popoverOpen != oldValue { restartPolling() } } } private let stayAwake = StayAwake() private var polling: Task? private var pollInFlight = false private let canned: Bool init() { version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" #if DEBUG canned = UserDefaults.standard.bool(forKey: "CottonCannedStatus") #else canned = false #endif } // MARK: Launch func launch() { #if DEBUG if canned { status = CannedStatus.status() screen = .cards return } #endif let config = Self.config() Task { let opened = await Self.run { Core.open(configJSON: config) } guard let answer = try? JSONDecoder().decode(CoreAnswer.self, from: opened), answer.ok else { let words = (try? JSONDecoder().decode(CoreAnswer.self, from: opened))?.error openError = words ?? "The importer could not open" screen = .signIn return } // The keychain may wait on its own unlock prompt: read it off the main thread. let stored = await Task.detached { () -> (token: String?, phone: String?, credentials: [Source: Keychain.Credentials]) in var credentials: [Source: Keychain.Credentials] = [:] for source in Source.allCases where source.takesCredentials { credentials[source] = Keychain.credentials(source) } return (Keychain.read(Keychain.Account.token), Keychain.read(Keychain.Account.phone), credentials) }.value for source in Source.allCases where source.takesCredentials { accountAddress[source] = stored.credentials[source]?.address if let stored = stored.credentials[source] { _ = await call("command", [ "source": source.rawValue, "name": "credentials", "args": stored.args, ]) } } if let token = stored.token { var args: [String: Any] = ["token": token] if let phone = stored.phone { args["phone"] = phone } _ = await call("start", args) screen = .cards } else { screen = .signIn } restartPolling() } } private static func config() -> String { let fileManager = FileManager.default let support = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] .appendingPathComponent(flavour.map { "Cotton (\($0))" } ?? "Cotton", isDirectory: true) try? fileManager.createDirectory(at: support, withIntermediateDirectories: true) let defaults = UserDefaults.standard let deviceId: String if let stored = defaults.string(forKey: "deviceId"), !stored.isEmpty { deviceId = stored } else { deviceId = UUID().uuidString.lowercased() defaults.set(deviceId, forKey: "deviceId") } let config = CoreConfig( dataDir: support.path, objectUrl: objectURL, deviceId: deviceId, machine: hostname(), deviceName: Host.current().localizedName ?? hostname(), appVersion: appVersion(), home: Self.home, helpersDir: Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers").path ) guard let data = try? JSONEncoder().encode(config), let text = String(data: data, encoding: .utf8) else { return "{}" } return text } /// This Mac's host name, from `gethostname` — `ProcessInfo.hostName` /// resolves through DNS and can hold the main thread for seconds. /// "0.3.0 (12)": the version and build, as a phone says its own. private static func appVersion() -> String { let info = Bundle.main.infoDictionary ?? [:] let version = info["CFBundleShortVersionString"] as? String ?? "0" guard let build = info["CFBundleVersion"] as? String else { return version } return "\(version) (\(build))" } private static func hostname() -> String { var buffer = [CChar](repeating: 0, count: 256) guard gethostname(&buffer, buffer.count) == 0 else { return "Mac" } return String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) } // MARK: Calling the core /// Run a blocking core call off the main thread. nonisolated private static func run(_ work: @escaping @Sendable () -> Data) async -> Data { await Task.detached(priority: .userInitiated) { work() }.value } @discardableResult private func call(_ method: String, _ args: [String: Any]? = nil) async -> Data { let argsJSON = args.map(CoreArgs.json) return await Self.run { Core.call(method, argsJSON: argsJSON) } } private func answer(_ data: Data) -> CoreAnswer { (try? JSONDecoder().decode(CoreAnswer.self, from: data)) ?? CoreAnswer(ok: false, error: "The importer gave no answer", code: nil) } // MARK: Polling private func restartPolling() { guard !canned, screen != .starting else { return } polling?.cancel() polling = Task { [weak self] in while !Task.isCancelled { guard let self else { return } await self.poll() let seconds: Double = self.popoverOpen ? 1 : 10 try? await Task.sleep(for: .seconds(seconds)) } } } func poll() async { guard !canned, !pollInFlight else { return } pollInFlight = true defer { pollInFlight = false } let data = await call("status") guard let next = try? JSONDecoder().decode(CoreStatus.self, from: data) else { return } if next.signedOut, screen == .cards { Keychain.delete(Keychain.Account.token) challengeId = nil databaseId = nil codeInput = "" screen = .signIn } trackRuns(next) status = next notifyProblems(next.panel) stayAwake.update(importing: next.sources.contains { $0.phase == "running" }) } private func trackRuns(_ next: CoreStatus) { for source in Source.allCases { let row = next.sources.first { $0.source == source.rawValue } if let row, row.phase == "running", let progress = row.progress { if runStarts[source] == nil || progress.sent < (runStarts[source]?.sent ?? 0) { runStarts[source] = (Date(), progress.sent) } } else { runStarts[source] = nil } } } /// Seconds left in a running source's run, when the rate can be read. func secondsLeft(_ source: Source, _ progress: SourceStatus.Progress) -> Double? { guard let total = progress.total, total > progress.sent, let start = runStarts[source] else { return nil } let elapsed = Date().timeIntervalSince(start.at) let done = progress.sent - start.sent guard elapsed > 1, done > 0 else { return nil } return Double(total - progress.sent) / (Double(done) / elapsed) } // MARK: The vault /// Open the vault with the recovery code (the core's `openByCode`): the core checks it, proves it to the object /// and makes this Mac a device of the vault. The field is cleared whatever the answer. func openByRecoveryCode() { let code = recoveryCodeInput guard !code.trimmingCharacters(in: .whitespaces).isEmpty, !recoveryBusy, !canned else { return } recoveryBusy = true recoveryError = nil Task { let data = await call("openByCode", ["code": code]) recoveryCodeInput = "" recoveryBusy = false let result = answer(data) if !result.ok { recoveryError = result.error ?? "The code did not open your vault" } await poll() } } // MARK: Sign-in func askCode() { let phone = phoneInput.filter { !$0.isWhitespace } guard !phone.isEmpty, !signInBusy else { return } signInBusy = true signInError = nil Task { let data = await call("askCode", ["phone": phone]) signInBusy = false struct Asked: Decodable { let challengeId: String?; let databaseId: String? } let result = answer(data) if result.ok, let asked = try? JSONDecoder().decode(Asked.self, from: data), let id = asked.challengeId, let database = asked.databaseId { challengeId = id databaseId = database } else { signInError = result.error ?? "No code was sent" } } } /// Ask a phone already signed in to this number to approve this Mac: the core shows a code to type there, and /// the approval signs this Mac in and lets it in to the person's data in one step. func askApproval() { let phone = phoneInput.filter { !$0.isWhitespace } guard !phone.isEmpty, !signInBusy else { return } signInBusy = true signInError = nil Task { let data = await call("askApproval", ["phone": phone]) signInBusy = false let result = answer(data) guard result.ok, let card = try? JSONDecoder().decode(AskCard.self, from: data) else { signInError = result.error ?? "No phone could be asked" return } asking = card pollAsk() } } /// From the not-let-in panel: ask a signed-in phone with the number this Mac signed in with. func askApprovalHere() { if phoneInput.filter({ !$0.isWhitespace }).isEmpty, let phone = status?.phone ?? Keychain.read(Keychain.Account.phone) { phoneInput = phone } askApproval() } /// Sign this Mac out (the core's `signOut`): the kept sign-in is dropped and Sign in shows, to sign in again /// another way. Nothing imported or queued is lost. func signOut() { askPolling?.cancel() askPolling = nil asking = nil Task { _ = await call("signOut") Keychain.delete(Keychain.Account.token) challengeId = nil databaseId = nil codeInput = "" recoveryError = nil screen = .signIn await poll() } } func cancelAsk() { askPolling?.cancel() askPolling = nil asking = nil Task { _ = await call("askCancel") } } private func pollAsk() { askPolling?.cancel() askPolling = Task { [weak self] in while !Task.isCancelled { guard let self else { return } let seconds = max(self.asking?.pollSeconds ?? 3, 1) try? await Task.sleep(for: .seconds(seconds)) if Task.isCancelled { return } let data = await self.call("askPoll") let result = self.answer(data) guard result.ok, let card = try? JSONDecoder().decode(AskCard.self, from: data) else { // The open host away for a moment: the ask stands, the next poll tries again. continue } if card.state == "approved", let token = card.credential { let phone = card.phone ?? self.phoneInput.filter { !$0.isWhitespace } Keychain.write(Keychain.Account.token, token) Keychain.write(Keychain.Account.phone, phone) _ = await self.call("start", ["token": token, "phone": phone]) self.asking = nil self.askPolling = nil self.screen = .cards self.restartPolling() return } self.asking = card if card.done { self.askPolling = nil return } } } } func signIn() { let code = codeInput.filter(\.isNumber) guard let challengeId, let databaseId, !code.isEmpty, !signInBusy else { return } signInBusy = true signInError = nil Task { let data = await call("signIn", ["databaseId": databaseId, "challengeId": challengeId, "code": code]) struct Signed: Decodable { let credential: String?; let phone: String? } let result = answer(data) guard result.ok, let signed = try? JSONDecoder().decode(Signed.self, from: data), let token = signed.credential else { signInBusy = false signInError = result.error ?? "That code did not work" return } let phone = signed.phone ?? phoneInput.filter { !$0.isWhitespace } Keychain.write(Keychain.Account.token, token) Keychain.write(Keychain.Account.phone, phone) await call("start", ["token": token, "phone": phone]) signInBusy = false self.challengeId = nil self.databaseId = nil codeInput = "" screen = .cards restartPolling() } } // MARK: Cards func row(_ source: Source) -> SourceStatus? { status?.sources.first { $0.source == source.rawValue } } func runNow(_ source: Source) { act("runNow", source) } func pause(_ source: Source) { act("pause", source) } func resume(_ source: Source) { act("resume", source) } /// Link WhatsApp by the code it shows for the number typed (or signed in with). func pairByCode() { let number = (whatsappNumber ?? status?.phone ?? "").filter { !$0.isWhitespace } guard !number.isEmpty else { return } pair("pairByCode", ["phone": number]) } /// Link WhatsApp by scanning a QR instead. func pairByQr() { pair("pairByQr", [:]) } /// Ask WhatsApp's passkey again in Chrome, after it could not. func passkeyUse() { pair("passkeyUse", [:], failed: "Chrome did not open") } /// The code the card shows matches the phone's: WhatsApp links. func passkeyConfirm() { pair("passkeyConfirm", [:], failed: "WhatsApp did not take the confirmation") } /// End the link under way (and its Chrome tab). func pairCancel() { pair("pairCancel", [:], failed: "The link did not stop") } private func pair(_ name: String, _ args: [String: String], failed: String = "WhatsApp did not start the link") { guard !canned, !pairBusy else { return } pairBusy = true pairError = nil Task { let data = await call("command", ["source": Source.whatsapp.rawValue, "name": name, "args": args]) pairBusy = false let result = answer(data) if !result.ok { pairError = result.error ?? failed } await poll() } } func openFullDiskAccess() { if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles") { NSWorkspace.shared.open(url) } } func saveCredentials(_ source: Source) { let draft = credentialDrafts[source] ?? Keychain.Credentials(address: "", password: "") let address = draft.address.trimmingCharacters(in: .whitespaces) guard !address.isEmpty, !draft.password.isEmpty, !credentialBusy.contains(source) else { return } let server = draft.server?.trimmingCharacters(in: .whitespaces) let credentials = Keychain.Credentials(address: address, password: draft.password, server: server?.isEmpty == false ? server : nil) guard !canned else { return } credentialBusy.insert(source) credentialErrors[source] = nil Task { let data = await call("command", [ "source": source.rawValue, "name": "credentials", "args": credentials.args, ]) credentialBusy.remove(source) let result = answer(data) // Kept only once the core took it: a refused server address is // never handed back at the next launch. if result.ok, Keychain.saveCredentials(credentials, for: source) { credentialDrafts[source] = nil accountAddress[source] = credentials.address } else if result.ok { credentialErrors[source] = "The keychain would not keep it" } else { credentialErrors[source] = result.error ?? "Not accepted" } await poll() } } private func act(_ method: String, _ source: Source) { guard !canned else { return } Task { await call(method, ["source": source.rawValue]) await poll() } } // MARK: The panel's pages and guided steps (build/panel.html, section 4) /// The source page open in the panel; none shows the rows. var page: Source? { didSet { guard page != oldValue else { return } // Leaving WhatsApp's page while a link is under way ends it: backing out links nothing, and the row goes // back to Add instead of standing as a link half done. if oldValue == .whatsapp, row(.whatsapp)?.probe.need?.by != nil { pairCancel() } pageNote = nil confirming = nil mailFound = nil askServer = false pairError = nil if page == .whatsapp { loadLinked() } } } /// A step that asks first, while it stands. enum Confirm: Equatable { case unlink, remove(Source), quit } var confirming: Confirm? /// What the last step on the page did, in the core's words. private(set) var pageNote: String? private(set) var pageBusy = false struct MailFound: Equatable { var mailbox: String; var count: Int; var oldest: Date? } /// The mail test's answer, shown once the account is added. var mailFound: MailFound? /// The mail test could not name the server: the page shows the IMAP field. private(set) var askServer = false /// The numbers this Mac is a WhatsApp linked device of. private(set) var linkedNumbers: [String] = [] /// The address each credentialed source signs in with, as the keychain holds it. private(set) var accountAddress: [Source: String] = [:] /// Check for updates, when this build has a feed (CottonApp sets it). var updatesCheck: (() -> Void)? func checkForUpdates() { updatesCheck?() } /// Whether the person must act: the menu bar's dot. var needsYou: Bool { guard let panel = status?.panel else { return false } return panel.screen == "step" || panel.headline?.needs == true } func bringAgain(_ source: Source) { act("bringAgain", source) } func loadLinked() { guard !canned else { return } Task { let data = await call("command", ["source": Source.whatsapp.rawValue, "name": "linked", "args": [String: String]()]) let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] linkedNumbers = object?["numbers"] as? [String] ?? [] } } func unlinkWhatsapp() { confirming = nil guard !canned, !pageBusy else { return } pageBusy = true Task { let result = answer(await call("command", ["source": Source.whatsapp.rawValue, "name": "unlink", "args": [String: String]()])) pageBusy = false if !result.ok { pageNote = result.error } linkedNumbers = [] await poll() } } /// Remove the account on this Mac: the keychain forgets the app password and the source stops. What is in /// Cotton stays there. func removeCredentials(_ source: Source) { confirming = nil Keychain.delete(Keychain.Account.credentials(source)) accountAddress[source] = nil mailFound = nil guard !canned else { return } Task { _ = await call("command", ["source": source.rawValue, "name": "credentials", "args": ["address": "", "password": ""]]) await poll() } } /// Mail's guided step: test the address and app password (read only), then add them and say what was found. func testAndAddMail() { let source = Source.mail let draft = credentialDrafts[source] ?? Keychain.Credentials(address: "", password: "") guard !canned, !credentialBusy.contains(source) else { return } credentialBusy.insert(source) credentialErrors[source] = nil Task { let data = await call("command", ["source": source.rawValue, "name": "test", "args": draft.args]) let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] credentialBusy.remove(source) guard object["tested"] as? Bool == true else { credentialErrors[source] = object["said"] as? String ?? object["error"] as? String if object["askServer"] as? Bool == true { askServer = true } return } let oldest = (object["oldest"] as? Double).map { Date(timeIntervalSince1970: $0 / 1000) } mailFound = MailFound(mailbox: object["mailbox"] as? String ?? "", count: object["count"] as? Int ?? 0, oldest: oldest) saveCredentials(source) } } // MARK: Problems: the dot and one notification each private var notified: Set { get { Set(UserDefaults.standard.stringArray(forKey: "CottonNotified") ?? []) } set { UserDefaults.standard.set(Array(newValue), forKey: "CottonNotified") } } /// One notification per problem, the first time it is seen; a problem that clears may be said again later. private func notifyProblems(_ panel: CoreStatus.Panel?) { let problems = (panel?.rows ?? []).filter { $0.kind == "problem" } let keys = Set(problems.map { "\($0.source):\($0.line)" }) let fresh = problems.filter { !notified.contains("\($0.source):\($0.line)") } notified = notified.intersection(keys).union(keys) guard !fresh.isEmpty, let headline = panel?.headline, !popoverOpen else { return } Notifications.post(title: headline.line, body: fresh.map(\.line).joined(separator: " ")) } // MARK: Quit /// Quit says once what it does (the panel asks before the first quit), then quits. func askQuit() { if UserDefaults.standard.bool(forKey: "CottonQuitSaid") { quit() } else { confirming = .quit } } func quitAfterSaying() { UserDefaults.standard.set(true, forKey: "CottonQuitSaid") quit() } func quit() { polling?.cancel() stayAwake.update(importing: false) guard !canned else { NSApp.terminate(nil); return } Task { // `stop` waits for the source threads; a run is cancelled first, // so this is short, and the app goes regardless after a few seconds. let stopped = Task.detached { _ = Core.call("stop", argsJSON: nil) } await withTaskGroup(of: Void.self) { group in group.addTask { await stopped.value } group.addTask { try? await Task.sleep(for: .seconds(4)) } await group.next() group.cancelAll() } NSApp.terminate(nil) } } }