Cotton code
175 lines · 7.7 KB · SwiftRaw
// MAY THIS PHONE RING? — the question the alarms feature spent a year not// asking.//// "Which scheduler" reads like the whole question because one of its two// answers is called `notification`. It is not: the notification backend has a// gate of its own that AlarmKit does not — the OS notification permission — and// Cotton deliberately never asks for that at boot, because the prompt is spent// once, for ever. So the ordinary path for somebody whose first serious use of// the app is setting an alarm was: permission undetermined, the request handed// to the notification centre anyway, iOS filing it in a queue it would never// present, and the reconciler recording it as done. The alarm did not ring and// no surface anywhere said why.//// There is a second gate beside it and it was equally unread: the person's own// **Alarms** switch. It wrote a preference, and nothing on earth read it — so// turning alarms off left them ringing and turning them on repaired nothing.//// This is the one place both are resolved, and it answers with a REASON rather// than a boolean, because the screen has to say which of them it is: "allow// notifications" and "your Alarms switch is off" are different problems with// different fixes, and a single "alarms are off" line would send half the// people who read it to the wrong place.import Foundation/// Whether a real alarm is possible at all, and whether the person has agreed./// `unavailable` is a normal state (an older OS), not a failure.public enum AlarmAuthorization: String, Equatable, Sendable {    case unavailable    case notDetermined    case denied    case authorized}/// Why nothing will ring. Each one has a different way out.public enum AlarmSilence: String, Equatable, Sendable {    /// The person turned Alarms off. One tap to undo, inside the app.    case switchedOff    /// Never asked. Cotton may still ask — and the Alarms screen is a fair    /// place to do it.    case permissionUndetermined    /// Asked and refused. iOS never re-prompts; only Settings can undo it.    case permissionDenied}public struct AlarmGate: Equatable, Sendable {    /// Which scheduler a pass would use.    public var backend: AlarmBackend    /// May a pass hand anything to it?    public var canSchedule: Bool    /// Why not — `nil` exactly when `canSchedule` is true.    public var silence: AlarmSilence?    public init(backend: AlarmBackend, canSchedule: Bool, silence: AlarmSilence?) {        self.backend = backend        self.canSchedule = canSchedule        self.silence = silence    }}/// The person's own Alarms switch.////// In the previous app this lived inside one `@cotton:notifprefs` record with the/// other four notification categories. That whole record — the categories, the/// mood hour, the "have we asked yet" stamp — belongs to the notifications/// lane, which has not landed here; this protocol is the ONE half the alarm/// gate needs, so the gate is a real question rather than a hardcoded yes. When/// the prefs record lands, this reader moves onto it and the protocol stays.public protocol AlarmPreferences: Sendable {    var alarmsEnabled: Bool { get }}/// `@unchecked Sendable`: the only stored property is `UserDefaults`, which is/// documented thread-safe but is not marked `Sendable`.public struct StoredAlarmPreferences: AlarmPreferences, @unchecked Sendable {    private let defaults: UserDefaults    /// The inherited category name, under this app's key namespace.    public static let key = "cotton.notifications.alarms"    public init(defaults: UserDefaults = .standard) {        self.defaults = defaults    }    /// Defaults ON, which is not the same as "alarms default on": nothing can    /// be scheduled until the OS grants permission, and this app never asks for    /// that at boot. The switch describes what a person would want IF they said    /// yes.    public var alarmsEnabled: Bool {        defaults.object(forKey: Self.key) as? Bool ?? true    }}/// What the OS will tell us, behind a protocol so a test can drive the gate/// without a device and without a prompt.public protocol AlarmAuthorizer: Sendable {    /// Can this binary, on this OS, schedule a real alarm at all? Says nothing    /// about permission.    func alarmKitAvailable() -> Bool    func alarmKitAuthorization() async -> AlarmAuthorization    /// Raise AlarmKit's prompt when undetermined; a plain read once decided.    /// Only `askForAlarmKitIfDue` calls it.    func requestAlarmKitAuthorization() async -> AlarmAuthorization    /// The notification permission, which is the FALLBACK backend's gate.    func notificationAuthorization() async -> AlarmAuthorization}/// Ask for AlarmKit's permission at the first moment it means something.////// Without this nothing ever asked, so AlarmKit stayed `notDetermined` for/// ever and every alarm fell back to a notification that does not ring through/// the silent switch. The prompt is spent once, so it is not raised at boot or/// because a list was looked at, nor by an alarm another device set arriving/// (294 row 4, walker293: the prompt rose at first launch on Me): it is/// raised by the pass after the person sets or switches on an alarm on this/// phone (`setHere`), with their own Alarms switch on. Only `notDetermined`/// asks; a decided answer is never asked again. Answers whether it asked.@discardableResultfunc askForAlarmKitIfDue(    _ authorizer: some AlarmAuthorizer,    preferences: some AlarmPreferences,    alarms: [Alarm],    setHere: Bool) async -> Bool {    guard setHere, preferences.alarmsEnabled,          alarms.contains(where: \.enabled),          authorizer.alarmKitAvailable(),          await authorizer.alarmKitAuthorization() == .notDetermined    else { return false }    _ = await authorizer.requestAlarmKitAuthorization()    return true}/// Which backend is live RIGHT NOW.////// Asked once per pass rather than cached, because the answer changes the/// moment the person grants (or revokes) permission in Settings, and a stale/// `alarmkit` would leave real alarms unscheduled behind a screen claiming they/// ring.public func resolveAlarmBackend(_ authorizer: some AlarmAuthorizer) async -> AlarmBackend {    guard authorizer.alarmKitAvailable() else { return .notification }    return await authorizer.alarmKitAuthorization() == .authorized ? .alarmkit : .notification}/// Decide the gate from the preference and the OS.////// The person's own switch is reported FIRST when both are shut. It is their/// decision rather than the platform's, it is the one they can undo without/// leaving the app, and telling somebody to grant a permission they will then/// find changed nothing is the worse of the two wrong answers.public func resolveAlarmGate(    preferences: some AlarmPreferences,    authorizer: some AlarmAuthorizer) async -> AlarmGate {    let backend = await resolveAlarmBackend(authorizer)    if !preferences.alarmsEnabled {        return AlarmGate(backend: backend, canSchedule: false, silence: .switchedOff)    }    // AlarmKit has no second gate: being on this backend at all IS its    // authorization having been granted, and a real alarm does not travel    // through the notification permission.    if backend == .alarmkit {        return AlarmGate(backend: backend, canSchedule: true, silence: nil)    }    switch await authorizer.notificationAuthorization() {    case .authorized:        return AlarmGate(backend: backend, canSchedule: true, silence: nil)    case .denied:        return AlarmGate(backend: backend, canSchedule: false, silence: .permissionDenied)    case .notDetermined, .unavailable:        return AlarmGate(backend: backend, canSchedule: false, silence: .permissionUndetermined)    }}