← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Services/Prompts/PromptNotification.swift (6660B)

1import Foundation
2import UserNotifications
3
4/// The notifications prompts are sent as: their categories, actions,
5/// content and identifiers.
6enum PromptNotification {
7    static let promptCategory = "prompt"
8    static let reminderCategory = "reminder"
9    static let instantReportAction = "instant-report"
10    static let snoozeAction = "snooze"
11
12    /// Where a snoozed prompt keeps when the original prompt fired, as
13    /// seconds since the reference date.
14    static let promptedAtKey = "promptedAt"
15
16    /// What a pending notification's identifier says it is, or `nil` for one
17    /// that isn't the scheduler's.
18    enum Kind: String {
19        case prompt
20        case reminder
21        case snoozed
22    }
23
24    static func kind(ofIdentifier identifier: String) -> Kind? {
25        identifier.split(separator: ".", maxSplits: 1).first.flatMap { Kind(rawValue: String($0)) }
26    }
27
28    /// Instant Report and Snooze both run in the background: neither opens
29    /// the app.
30    static var categories: Set<UNNotificationCategory> {
31        let log = UNNotificationAction(
32            identifier: instantReportAction,
33            title: String(localized: "Instant Report", comment: "Notification action that files an instant report"),
34            icon: UNNotificationActionIcon(systemImageName: "bolt.fill"))
35        let snooze = UNNotificationAction(
36            identifier: snoozeAction,
37            title: String(localized: "Snooze", comment: "Notification action that repeats the prompt later"),
38            icon: UNNotificationActionIcon(systemImageName: "clock"))
39        return [
40            UNNotificationCategory(identifier: promptCategory, actions: [log, snooze], intentIdentifiers: []),
41            UNNotificationCategory(identifier: reminderCategory, actions: [], intentIdentifiers: []),
42        ]
43    }
44
45    static func request(for prompt: PlannedPrompt) -> UNNotificationRequest {
46        let content =
47            switch prompt.kind {
48            case .prompt: promptContent(promptedAt: nil)
49            case .reminder: reminderContent()
50            }
51        return UNNotificationRequest(
52            identifier: prompt.identifier,
53            content: content,
54            trigger: UNCalendarNotificationTrigger(dateMatching: prompt.components, repeats: false))
55    }
56
57    /// A prompt repeated after `delay`, keeping when it was first sent.
58    static func snoozeRequest(promptedAt: Date, delay: TimeInterval) -> UNNotificationRequest {
59        UNNotificationRequest(
60            identifier: "\(Kind.snoozed.rawValue).\(UUID().uuidString)",
61            content: promptContent(promptedAt: promptedAt),
62            trigger: UNTimeIntervalNotificationTrigger(timeInterval: max(delay, 1), repeats: false))
63    }
64
65    private static func promptContent(promptedAt: Date?) -> UNMutableNotificationContent {
66        let content = UNMutableNotificationContent()
67        content.title = String(
68            localized: "Reporting Time",
69            comment: "The title of a random prompt notification")
70        content.body = String(
71            localized: "How are things going?",
72            comment: "The body of a random prompt notification")
73        content.sound = .default
74        content.categoryIdentifier = promptCategory
75        if let promptedAt {
76            content.userInfo = [promptedAtKey: promptedAt.timeIntervalSinceReferenceDate]
77        }
78        return content
79    }
80
81    private static func reminderContent() -> UNMutableNotificationContent {
82        let content = UNMutableNotificationContent()
83        content.title = String(
84            localized: "Reminders Ending",
85            comment: "The title of the notification that ends the scheduled prompts")
86        content.body = String(
87            localized: "Open Reportage to keep reminders enabled.",
88            comment: "The body of the notification that ends the scheduled prompts")
89        content.categoryIdentifier = reminderCategory
90        return content
91    }
92}
93
94/// What the user did with a delivered notification, taken out of the
95/// `UNNotificationResponse` so it can cross actors.
96struct PromptResponse: Sendable {
97    var category: String
98    var action: String
99    /// When the notification was delivered.
100    var deliveredAt: Date
101    /// When the prompt was first sent, for a snoozed prompt.
102    var promptedAt: Date?
103
104    init(category: String, action: String, deliveredAt: Date, promptedAt: Date? = nil) {
105        self.category = category
106        self.action = action
107        self.deliveredAt = deliveredAt
108        self.promptedAt = promptedAt
109    }
110
111    init(_ response: UNNotificationResponse) {
112        let notification = response.notification
113        let content = notification.request.content
114        self.init(
115            category: content.categoryIdentifier,
116            action: response.actionIdentifier,
117            deliveredAt: notification.date,
118            promptedAt: (content.userInfo[PromptNotification.promptedAtKey] as? Double)
119                .map(Date.init(timeIntervalSinceReferenceDate:)))
120    }
121
122    /// When the prompt first fired: the original time for a snoozed prompt.
123    var firedAt: Date { promptedAt ?? deliveredAt }
124}
125
126/// Carries out the user's response to a prompt.
127struct PromptResponder: Sendable {
128    let store: ReportStore
129    var center: any NotificationScheduling = SystemNotifications()
130    var capture: @Sendable () async -> Context = { await ContextCapture.background.capture() }
131
132    /// Logs or snoozes the prompt, and returns the survey to open when the
133    /// notification itself was tapped.
134    func respond(
135        to response: PromptResponse, settings: PromptSettings, now: Date = Date()
136    ) async throws -> SurveyRequest? {
137        guard response.category == PromptNotification.promptCategory else { return nil }
138        switch response.action {
139        case PromptNotification.instantReportAction:
140            try await PassiveLog(store: store, capture: capture)
141                .log(kind: .random, trigger: .notification, date: now, promptedAt: response.firedAt)
142            return nil
143        case PromptNotification.snoozeAction:
144            try await center.add(
145                PromptNotification.snoozeRequest(
146                    promptedAt: response.firedAt, delay: TimeInterval(settings.snooze * 60)))
147            return nil
148        case UNNotificationDefaultActionIdentifier:
149            // The report describes when the notification was tapped, not
150            // when it came.
151            return SurveyRequest(
152                kind: .random, date: now, trigger: .notification,
153                promptedAt: response.firedAt)
154        default:
155            return nil
156        }
157    }
158}