Files
MikeMail/MailNotifications.swift
2026-11-08 22:00:47 +01:00

71 lines
2.3 KiB
Swift

import AppKit
import UserNotifications
final class MailNotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
static let shared = MailNotificationDelegate()
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
completionHandler([.banner, .list, .sound])
}
}
struct NewMailNotification: Sendable {
let sender: String
let subject: String
}
@MainActor
enum MailNotifications {
static let enabledKey = "newMailNotifications"
static func configure() {
UNUserNotificationCenter.current().delegate = MailNotificationDelegate.shared
}
static func requestAuthorization() async -> Bool {
let center = UNUserNotificationCenter.current()
let settings = await center.notificationSettings()
switch settings.authorizationStatus {
case .authorized, .provisional:
return true
case .notDetermined:
return (try? await center.requestAuthorization(options: [.alert, .sound])) == true
default:
return false
}
}
static func postNewMail(_ messages: [NewMailNotification], badgeCount: Int) async {
guard !messages.isEmpty, UserDefaults.standard.bool(forKey: enabledKey) else { return }
guard await requestAuthorization() else { return }
for message in messages {
let content = UNMutableNotificationContent()
content.title = String(localized: "Neue Mail")
content.subtitle = message.sender.isEmpty
? String(localized: "Unbekannter Absender")
: message.sender
content.body = message.subject.isEmpty
? String(localized: "(Ohne Betreff)")
: message.subject
content.sound = .default
content.badge = NSNumber(value: badgeCount)
let request = UNNotificationRequest(
identifier: UUID().uuidString,
content: content,
trigger: nil
)
try? await UNUserNotificationCenter.current().add(request)
}
}
static func updateBadge(_ count: Int) {
NSApp.dockTile.badgeLabel = count > 0 ? String(count) : nil
}
}