SPB Git

Repository Public

ExpiryReminderScheduler.swift 6.1 KB 136 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Features/Expirations/ExpiryReminderScheduler.swift8// Module           : SPVault9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import UserNotifications4344/// One planned local notification. It names no card.45struct PlannedReminder: Equatable, Sendable {46    var identifier: String47    var fireDate: Date48    var body: String49}5051/// Local expiry reminders. Notification text is generic on purpose: it never52/// contains a card name, an issuer, a number or a date that identifies a document.53@MainActor54final class ExpiryReminderScheduler: ExpiryReminderScheduling {55    nonisolated static let identifierPrefix = "expiry."56    /// iOS keeps at most 64 pending local notifications per app.57    nonisolated static let maximumPending = 605859    private let settings: AppSettings60    private let center: UNUserNotificationCenter6162    init(settings: AppSettings, center: UNUserNotificationCenter = .current()) {63        self.settings = settings64        self.center = center65    }6667    /// Pure planning step: which reminders should exist for these cards.68    nonisolated static func plan(for cards: [Card], now: Date = Date(), calendar: Calendar = .current, hour: Int = 9) -> [PlannedReminder] {69        var planned: [PlannedReminder] = []70        for card in cards {71            guard let expiry = card.expiry else { continue }72            for offset in Set(card.reminderOffsets) {73                guard let day = calendar.date(byAdding: .day, value: -offset, to: calendar.startOfDay(for: expiry)),74                      let fire = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: day), fire > now else { continue }75                planned.append(PlannedReminder(identifier: "\(identifierPrefix)\(card.id.uuidString).\(offset)", fireDate: fire,76                                               body: bodyText(daysBefore: offset)))77            }78        }79        return Array(planned.sorted { $0.fireDate < $1.fireDate }.prefix(maximumPending))80    }8182    private nonisolated static func bodyText(daysBefore: Int) -> String {83        switch daysBefore {84        case 0: "A document in your vault expires today."85        case 1: "A document in your vault expires tomorrow."86        default: "A document in your vault expires in \(daysBefore) days."87        }88    }8990    func authorizationStatus() async -> UNAuthorizationStatus {91        await center.notificationSettings().authorizationStatus92    }9394    @discardableResult95    func requestAuthorization() async -> Bool {96        (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false97    }9899    func reschedule(for cards: [Card]) {100        let planned = settings.remindersEnabled ? Self.plan(for: cards) : []101        let center = center102        Task {103            let pending = await center.pendingNotificationRequests().map(\.identifier).filter { $0.hasPrefix(Self.identifierPrefix) }104            center.removePendingNotificationRequests(withIdentifiers: pending)105            guard await center.notificationSettings().authorizationStatus == .authorized else { return }106            for reminder in planned {107                let content = UNMutableNotificationContent()108                content.title = "SP Vault"109                content.body = reminder.body110                content.sound = .default111                let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: reminder.fireDate)112                try? await center.add(UNNotificationRequest(identifier: reminder.identifier, content: content,113                                                            trigger: UNCalendarNotificationTrigger(dateMatching: components, repeats: false)))114            }115        }116    }117118    /// Generic notice after a screenshot was detected.119    func notifyScreenshot() {120        guard settings.screenshotAlerts else { return }121        let center = center122        Task {123            guard await center.notificationSettings().authorizationStatus == .authorized else { return }124            let content = UNMutableNotificationContent()125            content.title = "SP Vault"126            content.body = "A screenshot was taken while your vault was open. Delete it from Photos if it shows a card."127            try? await center.add(UNNotificationRequest(identifier: "screenshot.\(UUID().uuidString)", content: content,128                                                        trigger: UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)))129        }130    }131132    func pendingCount() async -> Int {133        await center.pendingNotificationRequests().filter { $0.identifier.hasPrefix(Self.identifierPrefix) }.count134    }135}136
Files main
Menu

Theme