-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathNotificationService.swift
More file actions
257 lines (220 loc) · 10.4 KB
/
NotificationService.swift
File metadata and controls
257 lines (220 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import AppKit
import Foundation
import UserNotifications
/// Sound options for notifications
enum NotificationSound {
case `default`
case focusLost
case focusRegained
case none
var unSound: UNNotificationSound? {
switch self {
case .default:
return .default
case .focusLost, .focusRegained:
// Custom sounds are played manually via NSSound (see playCustomSound)
// because UNNotificationSound(named:) can't find SPM-bundled resources.
return nil
case .none:
return nil
}
}
/// Play the custom sound manually from the SPM resource bundle.
func playCustomSound() {
let filename: String
switch self {
case .focusLost:
filename = "focus-lost"
case .focusRegained:
filename = "focus-regained"
default:
return
}
guard let url = Bundle.resourceBundle.url(forResource: filename, withExtension: "aiff") else {
log("NotificationSound: Could not find \(filename).aiff in bundle")
return
}
guard let sound = NSSound(contentsOf: url, byReference: true) else {
log("NotificationSound: Could not load sound from \(url)")
return
}
sound.play()
}
}
@MainActor
class NotificationService: NSObject, UNUserNotificationCenterDelegate {
static let shared = NotificationService()
/// Category ID for notifications that track dismissal
private static let trackableCategoryId = "omi.trackable"
/// Category ID for screen capture reset notifications with action button
private static let screenCaptureResetCategoryId = "omi.screen_capture_reset"
/// Action ID for the "Reset Now" button
private static let resetNowActionId = "RESET_SCREEN_CAPTURE_NOW"
/// Title that identifies screen capture reset notifications
static let screenCaptureResetTitle = "Screen Recording Needs Reset"
/// Stores metadata for sent notifications so we can retrieve it in delegate callbacks
/// Key: notification identifier, Value: (title, assistantId)
private var notificationMetadata: [String: (title: String, assistantId: String)] = [:]
/// Last time we triggered a notification repair (debounce to avoid hammering lsregister)
private var lastRepairAttempt: Date?
private override init() {
super.init()
// Set ourselves as the delegate to show notifications even when app is in foreground
UNUserNotificationCenter.current().delegate = self
// Set up notification categories for tracking
setupNotificationCategories()
// Track that delegate is ready
AnalyticsManager.shared.notificationDelegateReady()
log("NotificationService: Delegate initialized and ready")
}
/// Set up notification categories to enable dismiss tracking
private func setupNotificationCategories() {
// Create a category that tracks custom dismiss action
// This allows us to know when a user explicitly dismisses a notification
let trackableCategory = UNNotificationCategory(
identifier: Self.trackableCategoryId,
actions: [],
intentIdentifiers: [],
options: [.customDismissAction] // This enables didReceive callback on dismiss
)
// Create "Reset Now" action for screen capture reset notifications
let resetNowAction = UNNotificationAction(
identifier: Self.resetNowActionId,
title: "Reset Now",
options: [.foreground] // Bring app to foreground when tapped
)
// Create category for screen capture reset with the action button
let screenCaptureResetCategory = UNNotificationCategory(
identifier: Self.screenCaptureResetCategoryId,
actions: [resetNowAction],
intentIdentifiers: [],
options: [.customDismissAction]
)
UNUserNotificationCenter.current().setNotificationCategories([trackableCategory, screenCaptureResetCategory])
}
// MARK: - UNUserNotificationCenterDelegate
// This allows notifications to be displayed even when the app is in the foreground
nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Track that willPresent was called (confirms delegate is working)
let notificationId = notification.request.identifier
let title = notification.request.content.title
Task { @MainActor in
AnalyticsManager.shared.notificationWillPresent(notificationId: notificationId, title: title)
}
// Show banner and badge; only include .sound if the notification has a sound attached
// (custom focus sounds are played via NSSound, so their content.sound is nil)
var options: UNNotificationPresentationOptions = [.banner, .badge]
if notification.request.content.sound != nil {
options.insert(.sound)
}
completionHandler(options)
}
// Handle notification interactions (click or dismiss)
nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let notificationId = response.notification.request.identifier
Task { @MainActor in
// Retrieve stored metadata
let metadata = self.notificationMetadata[notificationId]
let title = metadata?.title ?? response.notification.request.content.title
let assistantId = metadata?.assistantId ?? "unknown"
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
// User clicked/tapped the notification
print("[\(assistantId)] Notification clicked: \(title)")
AnalyticsManager.shared.notificationClicked(
notificationId: notificationId,
title: title,
assistantId: assistantId
)
// If this is a screen capture reset notification, trigger the reset
if title == Self.screenCaptureResetTitle {
self.handleScreenCaptureResetAction(source: "notification_click")
}
case UNNotificationDismissActionIdentifier:
// User explicitly dismissed the notification (X button, swipe, or Clear)
print("[\(assistantId)] Notification dismissed: \(title)")
AnalyticsManager.shared.notificationDismissed(
notificationId: notificationId,
title: title,
assistantId: assistantId
)
case Self.resetNowActionId:
// User clicked the "Reset Now" action button
print("[\(assistantId)] Reset Now action clicked: \(title)")
AnalyticsManager.shared.notificationClicked(
notificationId: notificationId,
title: title,
assistantId: assistantId
)
self.handleScreenCaptureResetAction(source: "notification_action_button")
default:
// Custom action (if we add action buttons in the future)
print("[\(assistantId)] Notification action: \(response.actionIdentifier)")
}
// Clean up metadata
self.notificationMetadata.removeValue(forKey: notificationId)
}
completionHandler()
}
/// Handle screen capture reset action from notification click or action button
private func handleScreenCaptureResetAction(source: String) {
log("Screen capture reset triggered from \(source)")
AnalyticsManager.shared.screenCaptureResetClicked(source: source)
ScreenCaptureService.resetScreenCapturePermissionAndRestart()
}
func sendNotification(title: String, message: String, assistantId: String = "default", sound: NotificationSound = .default) {
FloatingControlBarManager.shared.showNotification(
title: title,
message: message,
assistantId: assistantId,
sound: sound
)
}
private func deliverNotification(title: String, message: String, assistantId: String, sound: NotificationSound) {
let content = UNMutableNotificationContent()
content.title = title
content.body = message
content.sound = sound.unSound
// Use screen capture reset category for reset notifications (adds "Reset Now" button)
if title == Self.screenCaptureResetTitle {
content.categoryIdentifier = Self.screenCaptureResetCategoryId
} else {
content.categoryIdentifier = Self.trackableCategoryId // Enable dismiss tracking
}
let notificationId = UUID().uuidString
let request = UNNotificationRequest(
identifier: notificationId,
content: content,
trigger: nil // Deliver immediately
)
// Store metadata for later retrieval in delegate callbacks
notificationMetadata[notificationId] = (title: title, assistantId: assistantId)
// Play custom sound manually (SPM resources aren't found by UNNotificationSound)
sound.playCustomSound()
print("[\(assistantId)] Sending notification: \(title) - \(message)")
UNUserNotificationCenter.current().add(request) { [weak self] error in
if let error = error {
print("Notification error: \(error)")
logError("Notification error", error: error)
// Clean up metadata on error
Task { @MainActor in
self?.notificationMetadata.removeValue(forKey: notificationId)
}
} else {
print("Notification sent successfully")
// Track notification sent
Task { @MainActor in
AnalyticsManager.shared.notificationSent(
notificationId: notificationId,
title: title,
assistantId: assistantId
)
}
}
}
}
}