// 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)importCottonKitimportFoundationimport UIKitimportUserNotifications/// One mail to ring for (`mail.fetch` `notify`).structPostRing: Decodable, Equatable, Sendable {var id: Stringvar thread: String?var title: Stringvar body: String}@MainActorenumPostRings {/// The key a Post notification's userInfo carries its conversation under. nonisolated staticlet threadKey = "post.thread"/// Posted when a Post notification is tapped: `object` is the conversation id.staticlet opened = Notification.Name("cotton.post.ring.opened")/// A conversation a tap asked for before Post's root was there to open it.private(set) staticvar waiting: String?/// Ring for `rings`, unless Post is in front.staticfunc ring(_ rings: [PostRing]) async {guard !rings.isEmpty, UIApplication.shared.applicationState != .active else { return }let centre = UNUserNotificationCenter.current()guardawait 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.idiflet 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).staticfunc askOnce() async {let centre = UNUserNotificationCenter.current()guardawait 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 staticfunc 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.staticfunc tapped(_ thread: String) { waiting = threadNotificationCenter.default.post(name: opened, object: thread) }/// The conversation a tap is waiting to open, taken once.staticfunc take() -> String? {defer { waiting = nil }return waiting }}#endif