import Foundation
import UserNotifications
private func authorizationName(_ status: UNAuthorizationStatus) -> String {
switch status {
case .notDetermined: return "not_determined"
case .authorized: return "authorized"
case .provisional: return "provisional"
case .denied: return "denied"
default: return "unknown"
}
}
struct Banner: Decodable {
typealias Trace = @Sendable (String, UNAuthorizationStatus?, Error?) -> Void
static func diagnostic(_ stage: String, status: UNAuthorizationStatus?, error: Error?) -> [String: Any] {
var fields: [String: Any] = ["stage": stage]
if let status = status { fields["authorization"] = authorizationName(status) }
if let error = error as NSError? {
let domains = [UNErrorDomain, NSPOSIXErrorDomain, NSCocoaErrorDomain, NSOSStatusErrorDomain]
fields["domain"] = domains.contains(error.domain) ? error.domain : "other"
fields["code"] = error.code
if let cause = error.userInfo[NSUnderlyingErrorKey] as? NSError {
fields["underlying_domain"] = domains.contains(cause.domain) ? cause.domain : "other"
fields["underlying_code"] = cause.code
}
}
return fields
}
let id: UUID
let attempt: UUID
let title: String
let body: String
var diagnose: Bool? = nil
func submit(using permission: NotificationPermission, trace: @escaping Trace = { _, _, _ in },
accepted: @escaping @Sendable (Bool) -> Void) {
permission.check(trace: trace) { status in
switch status {
case .authorized, .provisional:
let center = permission.center
let identifier = id.uuidString.lowercased()
center.wasDelivered(identifier) { delivered in
// Retry after an interrupted acknowledgment or cursor write.
if delivered {
trace("already_delivered", status, nil)
accepted(true)
return
}
let content = UNMutableNotificationContent()
content.title = title
content.body = body
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
trace("submission_requested", status, nil)
center.add(request) { error in
trace(error == nil ? "submitted" : "submission_error", status, error)
accepted(error == nil)
}
}
default:
accepted(false)
}
}
}
}
// Both the GUI launch and an arriving event can observe an undecided setting.
final class NotificationPermission {
let center: NotificationCenterClient
private let lock = NSLock()
private var requesting = false
init(_ center: NotificationCenterClient) { self.center = center }
func check(trace: @escaping Banner.Trace = { _, _, _ in },
completion: @escaping @Sendable (UNAuthorizationStatus) -> Void = { _ in }) {
trace("settings_requested", nil, nil)
center.authorization { status in
trace("settings_received", status, nil)
guard status == .notDetermined else { completion(status); return }
let start = self.lock.withLock {
if self.requesting { return false }
self.requesting = true
return true
}
guard start else {
trace("permission_pending", status, nil)
completion(status)
return
}
trace("permission_requested", status, nil)
self.center.requestAuthorization(options: [.alert]) { granted, error in
self.lock.withLock { self.requesting = false }
trace(error != nil ? "permission_error" : granted ? "permission_granted" : "permission_not_granted", status, error)
// An open dialog may outlive the account session. The watcher
// re-reads the account and event before submitting a banner.
completion(.notDetermined)
}
}
}
}
protocol NotificationCenterClient {
func wasDelivered(_ id: String, reply: @escaping @Sendable (Bool) -> Void)
func authorization(_ reply: @escaping @Sendable (UNAuthorizationStatus) -> Void)
func requestAuthorization(options: UNAuthorizationOptions,
completionHandler: @escaping @Sendable (Bool, Error?) -> Void)
func add(_ request: UNNotificationRequest, withCompletionHandler: (@Sendable (Error?) -> Void)?)
}
extension UNUserNotificationCenter: NotificationCenterClient {
func wasDelivered(_ id: String, reply: @escaping @Sendable (Bool) -> Void) {
getDeliveredNotifications { reply($0.contains { $0.request.identifier == id }) }
}
func authorization(_ reply: @escaping @Sendable (UNAuthorizationStatus) -> Void) {
getNotificationSettings { reply($0.authorizationStatus) }
}
}
// The supervisor advances the inbox cursor only after this attempt's native reply.
final class NativeNotifications {
typealias Send = ([String: Any]) -> Void
private let permission: NotificationPermission?
private let send: Send
init(center: NotificationCenterClient?, send: @escaping Send) {
self.permission = center.map(NotificationPermission.init)
self.send = send
}
func prepare() { permission?.check() }
func receive(_ banner: Banner) {
let attempt = banner.attempt.uuidString.lowercased()
let trace: Banner.Trace = { [send] stage, status, error in
guard banner.diagnose == true else { return }
DispatchQueue.main.async {
var fields = Banner.diagnostic(stage, status: status, error: error)
fields["op"] = "notification_diagnostic"
fields["attempt"] = attempt
send(fields)
}
}
let reply: @Sendable (Bool) -> Void = { [send] accepted in
DispatchQueue.main.async {
send(["op":"notification_result", "attempt":attempt, "accepted":accepted])
}
}
guard let permission else {
trace("registration_unavailable", nil, nil)
reply(false)
return
}
banner.submit(using: permission, trace: trace, accepted: reply)
}
}