SPB Git

Repository Public License

SystemAlarmService.swift 11.8 KB 257 lines swift

1// ORIX Alarm2// File: App/Alarm/SystemAlarmService.swift3// Description: Abstraction over the system alarm scheduler, its AlarmKit implementation and an in-memory fake for tests and UI tests.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import ActivityKit8import AlarmCore9import AlarmKit10import AppIntents11import SwiftUI1213enum AlarmAuthorization: String, Sendable { case notDetermined, denied, authorized }1415/// One system alarm to register.16struct SystemAlarmRequest: Sendable, Equatable {17    enum Trigger: Sendable, Equatable {18        /// Wall-clock time, optionally repeating weekly. Follows the device time zone.19        case relative(time: ClockTime, weekdays: Set<Weekday>)20        /// Countdown that alerts after `duration` (snooze follow-up, focus timer). Shows a Live Activity while counting.21        case countdown(duration: TimeInterval)22    }23    var systemID: UUID24    var alarmID: UUID25    var title: String26    var trigger: Trigger27    var soundFileName: String?28    var role: ORIXAlarmMetadata.Role29    /// Offer a snooze button on the alert.30    var offersSnooze: Bool31    /// Stopping the alert opens the app on the wake mission.32    var opensMission: Bool33}3435protocol SystemAlarmService: AnyObject {36    var authorization: AlarmAuthorization { get }37    func requestAuthorization() async -> AlarmAuthorization38    func schedule(_ request: SystemAlarmRequest) async throws39    /// Removes an alarm whatever its state. Unknown identifiers are ignored.40    func cancel(systemID: UUID)41    func stop(systemID: UUID)42    /// Current system alarms of this app; throws when the state cannot be read.43    func snapshots() throws -> [SystemAlarmSnapshot]44    func updates() -> AsyncStream<[SystemAlarmSnapshot]>45}4647enum SystemAlarmError: LocalizedError {48    case notAuthorized, limitReached, system(String)49    var errorDescription: String? {50        switch self {51        case .notAuthorized: "ORIX Alarm is not allowed to schedule alarms. Allow alarms for ORIX Alarm in Settings."52        case .limitReached: "The system limit of scheduled alarms has been reached. Delete an alarm and try again."53        case .system(let message): message54        }55    }56}5758// MARK: - AlarmKit5960final class AlarmKitService: SystemAlarmService {61    nonisolated(unsafe) private let manager = AlarmManager.shared   // AlarmManager is a thread-safe system singleton that is not marked Sendable6263    var authorization: AlarmAuthorization { Self.map(manager.authorizationState) }6465    private static func map(_ state: AlarmManager.AuthorizationState) -> AlarmAuthorization {66        switch state {67        case .authorized: .authorized68        case .denied: .denied69        case .notDetermined: .notDetermined70        @unknown default: .notDetermined71        }72    }7374    func requestAuthorization() async -> AlarmAuthorization {75        guard manager.authorizationState == .notDetermined else { return authorization }76        return (try? await manager.requestAuthorization()).map(Self.map) ?? authorization77    }7879    func schedule(_ r: SystemAlarmRequest) async throws {80        guard await requestAuthorization() == .authorized else { throw SystemAlarmError.notAuthorized }8182        let stopIntent: any LiveActivityIntent = r.opensMission83            ? StopAndOpenMissionIntent(systemID: r.systemID, alarmID: r.alarmID)84            : StopAlarmIntent(systemID: r.systemID, alarmID: r.alarmID)85        var secondaryButton: AlarmButton?86        var secondaryIntent: (any LiveActivityIntent)?87        if r.offersSnooze {88            secondaryButton = AlarmButton(text: "Snooze", textColor: .white, systemImageName: "zzz")89            secondaryIntent = SnoozeAlarmIntent(systemID: r.systemID, alarmID: r.alarmID)90        } else if r.opensMission {91            secondaryButton = AlarmButton(text: "Mission", textColor: .white, systemImageName: "figure.walk")92            secondaryIntent = OpenMissionIntent(systemID: r.systemID, alarmID: r.alarmID)93        }94        let alert = AlarmPresentation.Alert(title: LocalizedStringResource(stringLiteral: r.title), secondaryButton: secondaryButton,95                                            secondaryButtonBehavior: secondaryButton == nil ? nil : .custom)96        var presentation = AlarmPresentation(alert: alert)97        let metadata = ORIXAlarmMetadata(alarmID: r.alarmID, name: r.title, role: r.role, hasMission: r.opensMission,98                                         symbol: r.role == .focusTimer ? "timer" : (r.role == .snooze ? "zzz" : "alarm.fill"))99        let sound: AlertConfiguration.AlertSound = r.soundFileName.map { .named($0) } ?? .default100101        let configuration: AlarmManager.AlarmConfiguration<ORIXAlarmMetadata>102        switch r.trigger {103        case .relative(let time, let weekdays):104            let relative = Alarm.Schedule.Relative(time: .init(hour: time.hour, minute: time.minute),105                                                   repeats: weekdays.isEmpty ? .never : .weekly(weekdays.sorted().map(\.localeWeekday)))106            let attributes = AlarmAttributes(presentation: presentation, metadata: metadata, tintColor: Theme.sunrise)107            configuration = .alarm(schedule: .relative(relative), attributes: attributes, stopIntent: stopIntent, secondaryIntent: secondaryIntent, sound: sound)108        case .countdown(let duration):109            if r.role == .focusTimer {110                presentation.countdown = .init(title: LocalizedStringResource(stringLiteral: r.title),111                                               pauseButton: AlarmButton(text: "Pause", textColor: .white, systemImageName: "pause.fill"))112                presentation.paused = .init(title: "Paused", resumeButton: AlarmButton(text: "Resume", textColor: .white, systemImageName: "play.fill"))113            } else {114                presentation.countdown = .init(title: "Snoozing")115            }116            let attributes = AlarmAttributes(presentation: presentation, metadata: metadata, tintColor: Theme.violet)117            configuration = .timer(duration: max(duration, 1), attributes: attributes, stopIntent: stopIntent, secondaryIntent: secondaryIntent, sound: sound)118        }119        do {120            _ = try await manager.schedule(id: r.systemID, configuration: configuration)121        } catch AlarmManager.AlarmError.maximumLimitReached {122            throw SystemAlarmError.limitReached123        } catch {124            throw SystemAlarmError.system(error.localizedDescription)125        }126    }127128    func cancel(systemID: UUID) { try? manager.cancel(id: systemID) }129    func stop(systemID: UUID) { try? manager.stop(id: systemID) }130131    func snapshots() throws -> [SystemAlarmSnapshot] {132        guard authorization == .authorized else { throw SystemAlarmError.notAuthorized }133        return try manager.alarms.map(Self.snapshot)134    }135136    func updates() -> AsyncStream<[SystemAlarmSnapshot]> {137        AsyncStream { continuation in138            let task = Task {139                for await alarms in AlarmManager.shared.alarmUpdates { continuation.yield(alarms.map(Self.snapshot)) }140                continuation.finish()141            }142            continuation.onTermination = { _ in task.cancel() }143        }144    }145146    nonisolated private static func snapshot(_ alarm: Alarm) -> SystemAlarmSnapshot {147        let state: SystemAlarmSnapshot.State = switch alarm.state {148        case .scheduled: .scheduled149        case .countdown: .countdown150        case .paused: .paused151        case .alerting: .alerting152        @unknown default: .scheduled153        }154        let schedule: SystemAlarmSnapshot.Schedule = switch alarm.schedule {155        case .relative(let r)?:156            .relative(time: ClockTime(hour: r.time.hour, minute: r.time.minute), weekdays: {157                if case .weekly(let days) = r.repeats { return Set(days.map(Weekday.init(locale:))) }158                return []159            }())160        case .fixed(let date)?: .fixed(date)161        default: SystemAlarmSnapshot.Schedule.none162        }163        return SystemAlarmSnapshot(id: alarm.id, state: state, schedule: schedule)164    }165}166167extension Weekday {168    nonisolated var localeWeekday: Locale.Weekday {169        switch self {170        case .sunday: .sunday; case .monday: .monday; case .tuesday: .tuesday; case .wednesday: .wednesday171        case .thursday: .thursday; case .friday: .friday; case .saturday: .saturday172        }173    }174    nonisolated init(locale: Locale.Weekday) {175        switch locale {176        case .sunday: self = .sunday; case .monday: self = .monday; case .tuesday: self = .tuesday; case .wednesday: self = .wednesday177        case .thursday: self = .thursday; case .friday: self = .friday; case .saturday: self = .saturday178        @unknown default: self = .monday179        }180    }181}182183// MARK: - Fake (tests, UI tests, previews)184185/// In-memory scheduler that mimics the observable behaviour of AlarmKit, including failures.186final class FakeAlarmService: SystemAlarmService {187    var authorization: AlarmAuthorization188    /// Authorization returned when the user is asked.189    var authorizationOnRequest: AlarmAuthorization = .authorized190    private(set) var alarms: [UUID: (request: SystemAlarmRequest, state: SystemAlarmSnapshot.State)] = [:]191    var failNextSchedule: SystemAlarmError?192    var snapshotsUnreadable = false193    private(set) var scheduleCount = 0194    private var continuations: [UUID: AsyncStream<[SystemAlarmSnapshot]>.Continuation] = [:]195196    init(authorization: AlarmAuthorization = .authorized) { self.authorization = authorization }197198    func requestAuthorization() async -> AlarmAuthorization {199        if authorization == .notDetermined { authorization = authorizationOnRequest }200        return authorization201    }202203    func schedule(_ request: SystemAlarmRequest) async throws {204        guard await requestAuthorization() == .authorized else { throw SystemAlarmError.notAuthorized }205        if let error = failNextSchedule { failNextSchedule = nil; throw error }206        scheduleCount += 1207        let state: SystemAlarmSnapshot.State = if case .countdown = request.trigger { .countdown } else { .scheduled }208        alarms[request.systemID] = (request, state)209        publish()210    }211212    func cancel(systemID: UUID) { alarms[systemID] = nil; publish() }213214    func stop(systemID: UUID) {215        guard let entry = alarms[systemID] else { return }216        if case .relative(_, let weekdays) = entry.request.trigger, !weekdays.isEmpty {217            alarms[systemID] = (entry.request, .scheduled)      // a repeating alarm stays scheduled218        } else {219            alarms[systemID] = nil220        }221        publish()222    }223224    func snapshots() throws -> [SystemAlarmSnapshot] {225        if snapshotsUnreadable || authorization != .authorized { throw SystemAlarmError.notAuthorized }226        return current()227    }228229    func updates() -> AsyncStream<[SystemAlarmSnapshot]> {230        let key = UUID()231        return AsyncStream { continuation in232            self.continuations[key] = continuation233        }234    }235236    // Test controls237    /// Simulates the system starting to alert.238    func simulateFire(systemID: UUID) {239        guard let entry = alarms[systemID] else { return }240        alarms[systemID] = (entry.request, .alerting); publish()241    }242    /// Simulates the system losing an alarm (restore from backup, system reset…).243    func simulateLoss(systemID: UUID) { alarms[systemID] = nil; publish() }244    func request(for systemID: UUID) -> SystemAlarmRequest? { alarms[systemID]?.request }245246    private func current() -> [SystemAlarmSnapshot] {247        alarms.values.map { entry in248            let schedule: SystemAlarmSnapshot.Schedule = switch entry.request.trigger {249            case .relative(let time, let weekdays): .relative(time: time, weekdays: weekdays)250            case .countdown: SystemAlarmSnapshot.Schedule.none251            }252            return SystemAlarmSnapshot(id: entry.request.systemID, state: entry.state, schedule: schedule)253        }254    }255    private func publish() { let now = current(); continuations.values.forEach { $0.yield(now) } }256}257
Files main
Menu

Theme