Repository Public License
1// ORIX Alarm2// File: App/Alarm/AppShortcuts.swift3// Description: App Intents exposed to Shortcuts and Siri: create, enable and disable alarms, next alarm, bedtime routine, wake dashboard, focus timer.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import AppIntents9import Foundation1011/// An alarm as seen by Shortcuts.12struct AlarmEntity: AppEntity {13 static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Alarm")14 static let defaultQuery = AlarmEntityQuery()15 var id: UUID16 var name: String17 var timeText: String18 var isEnabled: Bool19 var displayRepresentation: DisplayRepresentation {20 DisplayRepresentation(title: "\(name.isEmpty ? timeText : name)", subtitle: "\(timeText) · \(isEnabled ? "On" : "Off")")21 }22 @MainActor init(_ alarm: AlarmDefinition, use24h: Bool?) {23 id = alarm.id; name = alarm.name; isEnabled = alarm.isEnabled24 timeText = Fmt.timeString(alarm.time, use24h: use24h) + " · " + Fmt.recurrence(alarm.weekdays)25 }26}2728struct AlarmEntityQuery: EntityQuery {29 @MainActor func entities(for identifiers: [UUID]) async throws -> [AlarmEntity] {30 guard let model = AppDependencies.model else { return [] }31 return model.alarms.filter { identifiers.contains($0.id) }.map { AlarmEntity($0, use24h: model.settings.use24HourClock) }32 }33 @MainActor func suggestedEntities() async throws -> [AlarmEntity] {34 guard let model = AppDependencies.model else { return [] }35 return model.alarms.map { AlarmEntity($0, use24h: model.settings.use24HourClock) }36 }37}3839enum ShortcutError: Error, CustomLocalizedStringResourceConvertible {40 case appUnavailable, alarmNotFound, scheduling(String)41 var localizedStringResource: LocalizedStringResource {42 switch self {43 case .appUnavailable: "ORIX Alarm is not ready. Open the app once and try again."44 case .alarmNotFound: "This alarm no longer exists."45 case .scheduling(let message): "The alarm was saved but could not be scheduled: \(message)"46 }47 }48}4950private func requireModel() throws -> AppModel {51 guard let model = AppDependencies.model else { throw ShortcutError.appUnavailable }52 return model53}5455struct CreateAlarmIntent: AppIntent {56 static let title: LocalizedStringResource = "Create Alarm"57 static let description = IntentDescription("Creates an ORIX alarm and schedules it with the system.")58 @Parameter(title: "Time") var time: Date59 @Parameter(title: "Name", default: "") var name: String60 @Parameter(title: "Repeat on weekdays", default: false) var weekdaysOnly: Bool61 static var parameterSummary: some ParameterSummary { Summary("Create an alarm at \(\.$time)") { \.$name; \.$weekdaysOnly } }6263 @MainActor func perform() async throws -> some IntentResult & ProvidesDialog & ReturnsValue<AlarmEntity> {64 let model = try requireModel()65 let c = model.calendar.dateComponents([.hour, .minute], from: time)66 var alarm = model.makeDraftAlarm()67 alarm.name = name68 alarm.time = ClockTime(hour: c.hour ?? 7, minute: c.minute ?? 0)69 alarm.weekdays = weekdaysOnly ? Weekday.weekdays : []70 if let error = await model.save(alarm) { throw ShortcutError.scheduling(error) }71 let entity = AlarmEntity(alarm, use24h: model.settings.use24HourClock)72 return .result(value: entity, dialog: "Alarm set for \(Fmt.timeString(alarm.time, use24h: model.settings.use24HourClock)).")73 }74}7576struct EnableAlarmIntent: AppIntent {77 static let title: LocalizedStringResource = "Enable Alarm"78 static let description = IntentDescription("Turns an ORIX alarm on and schedules it.")79 @Parameter(title: "Alarm") var alarm: AlarmEntity80 static var parameterSummary: some ParameterSummary { Summary("Enable \(\.$alarm)") }81 @MainActor func perform() async throws -> some IntentResult & ProvidesDialog {82 let model = try requireModel()83 guard model.alarm(alarm.id) != nil else { throw ShortcutError.alarmNotFound }84 await model.setEnabled(alarm.id, true)85 if let error = model.schedulingErrors[alarm.id] { throw ShortcutError.scheduling(error) }86 return .result(dialog: "Alarm enabled.")87 }88}8990struct DisableAlarmIntent: AppIntent {91 static let title: LocalizedStringResource = "Disable Alarm"92 static let description = IntentDescription("Turns an ORIX alarm off and removes it from the system schedule.")93 @Parameter(title: "Alarm") var alarm: AlarmEntity94 static var parameterSummary: some ParameterSummary { Summary("Disable \(\.$alarm)") }95 @MainActor func perform() async throws -> some IntentResult & ProvidesDialog {96 let model = try requireModel()97 guard model.alarm(alarm.id) != nil else { throw ShortcutError.alarmNotFound }98 await model.setEnabled(alarm.id, false)99 return .result(dialog: "Alarm disabled.")100 }101}102103struct ShowNextAlarmIntent: AppIntent {104 static let title: LocalizedStringResource = "Show Next Alarm"105 static let description = IntentDescription("Tells you when your next ORIX alarm will ring.")106 @MainActor func perform() async throws -> some IntentResult & ProvidesDialog & ReturnsValue<Date?> {107 let model = try requireModel()108 await model.reconcile()109 guard let next = model.nextAlarm else { return .result(value: nil, dialog: "No alarm is set.") }110 let label = next.alarm.name.isEmpty ? "Your next alarm" : next.alarm.name111 let when = next.date.formatted(date: .complete, time: .shortened)112 if model.status(for: next.alarm.id) != .confirmed {113 return .result(value: next.date, dialog: "\(label) is planned for \(when), but ORIX Alarm could not confirm it is scheduled with the system. Open the app to check.")114 }115 return .result(value: next.date, dialog: "\(label) rings \(when), \(Fmt.countdown(to: next.date, from: model.now())).")116 }117}118119struct StartBedtimeRoutineIntent: AppIntent {120 static let title: LocalizedStringResource = "Start Bedtime Routine"121 static let description = IntentDescription("Opens ORIX Alarm on tonight's bedtime routine.")122 static let openAppWhenRun = true123 @MainActor func perform() async throws -> some IntentResult {124 try requireModel().selectedTab = .sleep125 return .result()126 }127}128129struct OpenWakeDashboardIntent: AppIntent {130 static let title: LocalizedStringResource = "Open Wake Dashboard"131 static let description = IntentDescription("Opens the ORIX Alarm dashboard.")132 static let openAppWhenRun = true133 @MainActor func perform() async throws -> some IntentResult {134 try requireModel().selectedTab = .today135 return .result()136 }137}138139struct StartFocusTimerIntent: AppIntent {140 static let title: LocalizedStringResource = "Start Focus Timer"141 static let description = IntentDescription("Starts a countdown that rings like an alarm when it ends.")142 @Parameter(title: "Minutes", default: 25, inclusiveRange: (1, 180)) var minutes: Int143 static var parameterSummary: some ParameterSummary { Summary("Start a \(\.$minutes) minute focus timer") }144 @MainActor func perform() async throws -> some IntentResult & ProvidesDialog {145 let model = try requireModel()146 if let error = await model.startFocusTimer(minutes: minutes) { throw ShortcutError.scheduling(error) }147 return .result(dialog: "Focus timer started for \(minutes) minutes.")148 }149}150151struct ORIXAlarmShortcuts: AppShortcutsProvider {152 static var appShortcuts: [AppShortcut] {153 AppShortcut(intent: ShowNextAlarmIntent(), phrases: ["Show my next \(.applicationName)", "When is my next \(.applicationName)"],154 shortTitle: "Next Alarm", systemImageName: "alarm")155 AppShortcut(intent: CreateAlarmIntent(), phrases: ["Create an \(.applicationName)", "New \(.applicationName)"],156 shortTitle: "Create Alarm", systemImageName: "plus.circle")157 AppShortcut(intent: StartFocusTimerIntent(), phrases: ["Start a focus timer with \(.applicationName)"],158 shortTitle: "Focus Timer", systemImageName: "timer")159 AppShortcut(intent: StartBedtimeRoutineIntent(), phrases: ["Start my bedtime routine with \(.applicationName)"],160 shortTitle: "Bedtime Routine", systemImageName: "moon.stars")161 AppShortcut(intent: OpenWakeDashboardIntent(), phrases: ["Open my \(.applicationName) dashboard"],162 shortTitle: "Wake Dashboard", systemImageName: "sun.horizon")163 AppShortcut(intent: EnableAlarmIntent(), phrases: ["Enable an \(.applicationName)"], shortTitle: "Enable Alarm", systemImageName: "bell")164 AppShortcut(intent: DisableAlarmIntent(), phrases: ["Disable an \(.applicationName)"], shortTitle: "Disable Alarm", systemImageName: "bell.slash")165 }166}167