importAppKitimportFoundationimportObservation/// 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@ObservablefinalclassAppModel {enumScreen: 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.staticlet 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.staticlet 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.staticlet home: String = {if flavour != nil, let path = UserDefaults.standard.string(forKey: "CottonHome"), path.hasPrefix("/") { return path }return NSHomeDirectory() }()private(set) var screen: Screen = .startingprivate(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 = falseprivate(set) var recoveryError: String?private(set) var challengeId: String?/// The database the code was sent for, which the sign-in names.privatevar databaseId: String?private(set) var signInBusy = falseprivate(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?privatevar askPolling: Task<Void, Never>?/// What the core says of an ask: its words, and the code once a phone opened it.structAskCard: Decodable, Equatable, Sendable {var state: Stringvar done: Boolvar 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?structSquare: Decodable, Equatable, Sendable {var size: Intvar 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<Source> = []// 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".privatevar runStarts: [Source: (at: Date, sent: Int)] = [:]var popoverOpen = false { didSet { if popoverOpen != oldValue { restartPolling() } } }privatelet stayAwake = StayAwake()privatevar polling: Task<Void, Never>?privatevar pollInFlight = falseprivatelet canned: Boolinit() { version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" #if DEBUG canned = UserDefaults.standard.bool(forKey: "CottonCannedStatus") #else canned = false #endif }// MARK: Launchfunc launch() { #if DEBUGif canned { status = CannedStatus.status() screen = .cardsreturn } #endiflet config = Self.config()Task {let opened = awaitSelf.run { Core.open(configJSON: config) }guardlet 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 = .signInreturn }// The keychain may wait on its own unlock prompt: read it off the main thread.let stored = awaitTask.detached { () -> (token: String?, phone: String?, credentials: [Source: Keychain.Credentials]) invar credentials: [Source: Keychain.Credentials] = [:]for source inSource.allCases where source.takesCredentials { credentials[source] = Keychain.credentials(source) }return (Keychain.read(Keychain.Account.token), Keychain.read(Keychain.Account.phone), credentials) }.valuefor source inSource.allCases where source.takesCredentials { accountAddress[source] = stored.credentials[source]?.addressiflet stored = stored.credentials[source] { _ = await call("command", ["source": source.rawValue,"name": "credentials","args": stored.args, ]) } }iflet token = stored.token {var args: [String: Any] = ["token": token]iflet phone = stored.phone { args["phone"] = phone } _ = await call("start", args) screen = .cards } else { screen = .signIn } restartPolling() } }privatestaticfunc config() -> String {let fileManager = FileManager.defaultlet 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.standardlet deviceId: Stringiflet 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 )guardlet 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.privatestaticfunc appVersion() -> String {let info = Bundle.main.infoDictionary ?? [:]let version = info["CFBundleShortVersionString"] as? String ?? "0"guardlet build = info["CFBundleVersion"] as? Stringelse { return version }return"\(version) (\(build))" }privatestaticfunc hostname() -> String {var buffer = [CChar](repeating: 0, count: 256)guard gethostname(&buffer, buffer.count) == 0else { return"Mac" }returnString(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 privatestaticfunc run(_ work: @escaping @Sendable () -> Data) async -> Data {awaitTask.detached(priority: .userInitiated) { work() }.value } @discardableResultprivatefunc call(_ method: String, _ args: [String: Any]? = nil) async -> Data {let argsJSON = args.map(CoreArgs.json)returnawaitSelf.run { Core.call(method, argsJSON: argsJSON) } }privatefunc answer(_ data: Data) -> CoreAnswer { (try? JSONDecoder().decode(CoreAnswer.self, from: data)) ?? CoreAnswer(ok: false, error: "The importer gave no answer", code: nil) }// MARK: Pollingprivatefunc restartPolling() {guard !canned, screen != .starting else { return } polling?.cancel() polling = Task { [weakself] inwhile !Task.isCancelled {guardletselfelse { return }awaitself.poll()let seconds: Double = self.popoverOpen ? 1 : 10try? awaitTask.sleep(for: .seconds(seconds)) } } }func poll() async {guard !canned, !pollInFlight else { return } pollInFlight = truedefer { pollInFlight = false }let data = await call("status")guardlet 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" }) }privatefunc trackRuns(_ next: CoreStatus) {for source inSource.allCases {let row = next.sources.first { $0.source == source.rawValue }iflet 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? {guardlet total = progress.total, total > progress.sent, let start = runStarts[source] else { returnnil }let elapsed = Date().timeIntervalSince(start.at)let done = progress.sent - start.sentguard elapsed > 1, done > 0else { returnnil }returnDouble(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 = recoveryCodeInputguard !code.trimmingCharacters(in: .whitespaces).isEmpty, !recoveryBusy, !canned else { return } recoveryBusy = true recoveryError = nilTask {let data = await call("openByCode", ["code": code]) recoveryCodeInput = "" recoveryBusy = falselet result = answer(data)if !result.ok { recoveryError = result.error ?? "The code did not open your vault" }await poll() } }// MARK: Sign-infunc askCode() {let phone = phoneInput.filter { !$0.isWhitespace }guard !phone.isEmpty, !signInBusy else { return } signInBusy = true signInError = nilTask {let data = await call("askCode", ["phone": phone]) signInBusy = falsestructAsked: 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 = nilTask {let data = await call("askApproval", ["phone": phone]) signInBusy = falselet 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 = nilTask { _ = await call("signOut")Keychain.delete(Keychain.Account.token) challengeId = nil databaseId = nil codeInput = "" recoveryError = nil screen = .signInawait poll() } }func cancelAsk() { askPolling?.cancel() askPolling = nil asking = nilTask { _ = await call("askCancel") } }privatefunc pollAsk() { askPolling?.cancel() askPolling = Task { [weakself] inwhile !Task.isCancelled {guardletselfelse { return }let seconds = max(self.asking?.pollSeconds ?? 3, 1)try? awaitTask.sleep(for: .seconds(seconds))ifTask.isCancelled { return }let data = awaitself.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) _ = awaitself.call("start", ["token": token, "phone": phone])self.asking = nilself.askPolling = nilself.screen = .cardsself.restartPolling()return }self.asking = cardif card.done {self.askPolling = nilreturn } } } }func signIn() {let code = codeInput.filter(\.isNumber)guardlet challengeId, let databaseId, !code.isEmpty, !signInBusy else { return } signInBusy = true signInError = nilTask {let data = await call("signIn", ["databaseId": databaseId, "challengeId": challengeId, "code": code])structSigned: 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 = falseself.challengeId = nilself.databaseId = nil codeInput = "" screen = .cards restartPolling() } }// MARK: Cardsfunc 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") }privatefunc pair(_ name: String, _ args: [String: String], failed: String = "WhatsApp did not start the link") {guard !canned, !pairBusy else { return } pairBusy = true pairError = nilTask {let data = await call("command", ["source": Source.whatsapp.rawValue, "name": name, "args": args]) pairBusy = falselet result = answer(data)if !result.ok { pairError = result.error ?? failed }await poll() } }func openFullDiskAccess() {iflet 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] = nilTask {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 } elseif result.ok { credentialErrors[source] = "The keychain would not keep it" } else { credentialErrors[source] = result.error ?? "Not accepted" }await poll() } }privatefunc 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 = nilif page == .whatsapp { loadLinked() } } }/// A step that asks first, while it stands.enumConfirm: 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 = falsestructMailFound: 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 {guardlet panel = status?.panel else { returnfalse }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 = nilguard !canned, !pageBusy else { return } pageBusy = trueTask {let result = answer(await call("command", ["source": Source.whatsapp.rawValue, "name": "unlink", "args": [String: String]()])) pageBusy = falseif !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 = nilKeychain.delete(Keychain.Account.credentials(source)) accountAddress[source] = nil mailFound = nilguard !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.maillet draft = credentialDrafts[source] ?? Keychain.Credentials(address: "", password: "")guard !canned, !credentialBusy.contains(source) else { return } credentialBusy.insert(source) credentialErrors[source] = nilTask {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 == trueelse { credentialErrors[source] = object["said"] as? String ?? object["error"] as? Stringif 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 eachprivatevar notified: Set<String> { 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.privatefunc 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() {ifUserDefaults.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? awaitTask.sleep(for: .seconds(4)) }await group.next() group.cancelAll() } NSApp.terminate(nil) } }}