Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / ScheduleNotifications.swift
| 1 | import Foundation |
| 2 | import UserNotifications |
| 3 | |
| 4 | struct ScheduleReminder: Equatable, Sendable { |
| 5 | enum Reason: String, Sendable { case review, check } |
| 6 | |
| 7 | let draftID: String |
| 8 | let slot: String |
| 9 | let channel: String |
| 10 | let reason: Reason |
| 11 | |
| 12 | init(_ draft: WorkspaceRecord, reason: Reason) { |
| 13 | draftID = draft.id |
| 14 | slot = draft.schedule["slotAt"] as? String ?? "" |
| 15 | channel = platformName(draft["platform"]) |
| 16 | self.reason = reason |
| 17 | } |
| 18 | |
| 19 | var identifier: String { "schedule:\(draftID):\(slot):\(reason.rawValue)" } |
| 20 | |
| 21 | var title: String { |
| 22 | reason == .review ? "Review your \(channel) post" : "Check your \(channel) post" |
| 23 | } |
| 24 | |
| 25 | var message: String { |
| 26 | switch reason { |
| 27 | case .review: "Open Inkspring to review the scheduled post." |
| 28 | case .check: "Open Inkspring to check the result before trying again." |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | enum ScheduleNotifications { |
| 34 | static let settingKey = "scheduleNotificationsEnabled" |
| 35 | static let draftKey = "scheduleDraftID" |
| 36 | |
| 37 | static func isDenied() async -> Bool { |
| 38 | await UNUserNotificationCenter.current().notificationSettings().authorizationStatus == .denied |
| 39 | } |
| 40 | |
| 41 | static func requestPermission() async throws { |
| 42 | guard try await UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) else { |
| 43 | throw WorkspaceError("Allow notifications for Inkspring in System Settings → Notifications.") |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | static func deliver(_ reminder: ScheduleReminder) async { |
| 48 | let content = UNMutableNotificationContent() |
| 49 | content.title = reminder.title |
| 50 | content.body = reminder.message |
| 51 | content.userInfo = [draftKey: reminder.draftID] |
| 52 | let request = UNNotificationRequest(identifier: reminder.identifier, content: content, trigger: nil) |
| 53 | try? await UNUserNotificationCenter.current().add(request) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | extension Workspace { |
| 58 | func setScheduleNotifications(_ enabled: Bool) async throws { |
| 59 | if enabled { try await ScheduleNotifications.requestPermission() } |
| 60 | try set(ScheduleNotifications.settingKey, to: enabled) |
| 61 | } |
| 62 | } |