Cotton code
61 lines · 2.5 KB · SwiftRaw
import CottonKit/// The reminder consumer reads the same native preferences as the device/// page. Only importing the old values touches the legacy store.public protocol NotificationPreferenceSource: Sendable {    func read() async throws -> NotificationPrefs    func markAsked(at stamp: String) async throws}public actor CoreNotificationPreferences: NotificationPreferenceSource {    private let core: any CottonCalling    private let legacy: any NotificationPrefsStore    public init(core: any CottonCalling, legacy: any NotificationPrefsStore = DefaultsNotificationPrefsStore()) {        self.core = core        self.legacy = legacy    }    private struct Read: Decodable {        let needs_import: Bool        let preferences: Preferences?    }    /// All switches must be present: NotificationPrefs's legacy decoder    /// supplies defaults, which an already-native answer must never do.    private struct Preferences: Decodable {        let enabled: Bool        let categories: [String: Bool]        let askedAt: String?        func value() throws -> NotificationPrefs {            var flags: [NotificationCategory: Bool] = [:]            for category in NotificationCategory.allCases {                guard let on = categories[category.rawValue] else {                    throw ActionRefused(ShellLines.line("reminders", "notifications.unreadable"))                }                flags[category] = on            }            return NotificationPrefs(enabled: enabled, categories: flags, askedAt: askedAt)        }    }    private struct Import: Encodable { let preferences: NotificationPrefs }    public func read() async throws -> NotificationPrefs {        var answer = try await core.call("device.preferences.read", as: Read.self)        if answer.needs_import {            _ = try await core.callJSON("device.preferences.import", Import(preferences: legacy.read()))            answer = try await core.call("device.preferences.read", as: Read.self)        }        guard !answer.needs_import, let preferences = answer.preferences else {            throw ActionRefused(ShellLines.line("reminders", "notifications.unreadable"))        }        return try preferences.value()    }    public func markAsked(at stamp: String) async throws {        // The core's own record of the ask (`device.notifications.asked`): it keeps the switches, starts from the        // defaults on a phone with none stored, and announces the change, as Android's.        _ = try await core.callJSON("device.notifications.asked", ["at": stamp])    }}