// POST'S NOTIFICATIONS: new mail This phone fetches brought in, rung as the core says (`mail.fetch` `notify`, by You's // Notifications: people only by default, everyone, or none). Each is one local notification, its title who wrote and // its body the subject, both the core's words. A round while Post is in front rings nothing: the open inbox already // shows the mail. A tap opens that conversation. // // The permission is asked once, when an account is added (the moment new mail starts to matter), never in the // background where iOS cannot show the question. #if os(iOS) import CottonKit import Foundation import UIKit import UserNotifications /// One mail to ring for (`mail.fetch` `notify`). struct PostRing: Decodable, Equatable, Sendable { var id: String var thread: String? var title: String var body: String } @MainActor enum PostRings { /// The key a Post notification's userInfo carries its conversation under. nonisolated static let threadKey = "post.thread" /// Posted when a Post notification is tapped: `object` is the conversation id. static let opened = Notification.Name("cotton.post.ring.opened") /// A conversation a tap asked for before Post's root was there to open it. private(set) static var waiting: String? /// Ring for `rings`, unless Post is in front. static func ring(_ rings: [PostRing]) async { guard !rings.isEmpty, UIApplication.shared.applicationState != .active else { return } let centre = UNUserNotificationCenter.current() guard await centre.notificationSettings().authorizationStatus == .authorized else { return } for ring in rings { let content = UNMutableNotificationContent() content.title = ring.title content.body = ring.body content.sound = .default content.threadIdentifier = ring.thread ?? ring.id if let thread = ring.thread { content.userInfo = [threadKey: thread] } let request = UNNotificationRequest(identifier: "post.\(ring.id)", content: content, trigger: nil) try? await centre.add(request) } } /// Ask once whether Post may notify, in the foreground (after an account is added). static func askOnce() async { let centre = UNUserNotificationCenter.current() guard await centre.notificationSettings().authorizationStatus == .notDetermined else { return } _ = try? await centre.requestAuthorization(options: [.alert, .sound]) } /// The conversation a tapped notification names, if it is Post's. nonisolated static func thread(of userInfo: [AnyHashable: Any]) -> String? { (userInfo[threadKey] as? String).flatMap { $0.isEmpty ? nil : $0 } } /// A tap on a Post notification: the root opens the conversation now, or when it is there. static func tapped(_ thread: String) { waiting = thread NotificationCenter.default.post(name: opened, object: thread) } /// The conversation a tap is waiting to open, taken once. static func take() -> String? { defer { waiting = nil } return waiting } } #endif