Files
luxe-macos-tray-notifier/Sources/LuxeNotifier/BannerPoster.swift

54 lines
2.6 KiB
Swift
Raw Normal View History

import Foundation
import NotifierCore
import UserNotifications
/// UNUserNotificationCenter crashes without an app bundle, which a bare `swift run` lacks, so
/// fall back to osascript there. The installed .app bundle takes the native path.
enum BannerPoster {
private static var hasBundle: Bool { Bundle.main.bundleIdentifier != nil }
/// Asks once, then reports the resulting status. `onStatus` runs on a background queue.
static func requestPermission(onStatus: @escaping (BannerPermission) -> Void) {
guard hasBundle else { return }
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { _, error in
if let error { StatusFile.set("permission-error", "\(error)") }
refreshStatus(onStatus)
}
}
/// Re-read the setting, since the user can change it in System Settings while the app runs.
static func refreshStatus(_ onStatus: @escaping (BannerPermission) -> Void) {
guard hasBundle else { return }
UNUserNotificationCenter.current().getNotificationSettings { settings in
let status = BannerPermission(authorizationRawValue: settings.authorizationStatus.rawValue)
StatusFile.set("authorization", "\(settings.authorizationStatus.rawValue) -> \(status)")
onStatus(status)
}
}
static func post(title: String, message: String, terminalBundleID: String? = nil) {
guard hasBundle else { return postWithOsascript(title: title, message: message) }
let content = UNMutableNotificationContent()
content.title = title
content.body = message
content.sound = .default
if let terminalBundleID { content.userInfo = [BannerClickHandler.terminalKey: terminalBundleID] }
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error { NSLog("LuxeNotifier: could not post banner: \(error)") }
}
}
private static func postWithOsascript(title: String, message: String) {
let script = "display notification \(quoted(message)) with title \(quoted(title))"
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")
process.arguments = ["-e", script]
do { try process.run() } catch { NSLog("LuxeNotifier: osascript failed: \(error)") }
}
private static func quoted(_ text: String) -> String {
"\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
}