Sources/OrgApp/CalendarEvents.swift

191 lines · 9197 bytes

  1import CoreGraphics
  2import EventKit
  3import Foundation
  4import OrgCore
  5import OrgPresentation
  6
  7/// What the agenda reads from a calendar event: `EKEvent`, or a value made in tests.
  8public protocol CalendarEventRecord {
  9    var recordID: String { get }
 10    var recordTitle: String { get }
 11    var recordStart: Date { get }
 12    var recordEnd: Date { get }
 13    var recordIsAllDay: Bool { get }
 14    var recordLocation: String? { get }
 15    var recordCalendarID: String { get }
 16    var recordCalendarTitle: String { get }
 17    var recordCalendarColor: CGColor? { get }
 18}
 19
 20extension EKEvent: CalendarEventRecord {
 21    /// A repeating event's occurrences share an identifier; the start tells them apart.
 22    public var recordID: String { (eventIdentifier ?? calendarItemIdentifier) + "@" + String(Int(startDate.timeIntervalSince1970)) }
 23    public var recordTitle: String { title ?? "" }
 24    public var recordStart: Date { startDate }
 25    public var recordEnd: Date { endDate }
 26    public var recordIsAllDay: Bool { isAllDay }
 27    public var recordLocation: String? { location.flatMap { $0.isEmpty ? nil : $0 } }
 28    public var recordCalendarID: String { calendar?.calendarIdentifier ?? "" }
 29    public var recordCalendarTitle: String { calendar?.title ?? "" }
 30    public var recordCalendarColor: CGColor? { calendar?.cgColor }
 31}
 32
 33/// Read-only events from the system Calendar for the agenda (`calendar-events` in
 34/// config.toml), from the calendars `calendar-event-calendars` names.
 35public final class CalendarEvents: @unchecked Sendable {
 36    private let store = EKEventStore()
 37
 38    public init() {}
 39
 40    /// Reading events needs full access; EventKit has no read-only level.
 41    public static var isAuthorized: Bool { EKEventStore.authorizationStatus(for: .event) == .fullAccess }
 42
 43    /// Asks for access once; later calls answer with what the person chose.
 44    public func requestAccess() async -> Bool {
 45        if Self.isAuthorized { return true }
 46        return (try? await store.requestFullAccessToEvents()) ?? false
 47    }
 48
 49    /// The event calendars, for choosing among them.
 50    public func calendars() -> [(id: String, title: String, color: RGBA?)] {
 51        guard Self.isAuthorized else { return [] }
 52        return store.calendars(for: .event).map { ($0.calendarIdentifier, $0.title, $0.cgColor.flatMap(Self.rgba)) }
 53    }
 54
 55    /// Events overlapping `start..<end` in the chosen calendars (all when `chosen` is empty),
 56    /// by start. None without access.
 57    public func events(from start: Date, to end: Date, chosen: [String]) -> [AgendaEvent] {
 58        guard Self.isAuthorized else { return [] }
 59        let calendars = store.calendars(for: .event).filter { Self.chooses(id: $0.calendarIdentifier, title: $0.title, chosen: chosen) }
 60        guard !calendars.isEmpty else { return [] }
 61        let predicate = store.predicateForEvents(withStart: start, end: end, calendars: calendars)
 62        return store.events(matching: predicate).map(Self.event).sorted { $0.start < $1.start }
 63    }
 64
 65    /// Whether a calendar is among those chosen by identifier or title; every calendar is when
 66    /// none are.
 67    public static func chooses(id: String, title: String, chosen: [String]) -> Bool {
 68        chosen.isEmpty || chosen.contains(id) || chosen.contains(title)
 69    }
 70
 71    public static func event(_ record: some CalendarEventRecord) -> AgendaEvent {
 72        AgendaEvent(
 73            id: record.recordID, title: record.recordTitle, calendarID: record.recordCalendarID, calendarTitle: record.recordCalendarTitle,
 74            color: record.recordCalendarColor.flatMap(rgba), start: record.recordStart, end: record.recordEnd,
 75            isAllDay: record.recordIsAllDay, location: record.recordLocation
 76        )
 77    }
 78
 79    /// A color in sRGB.
 80    static func rgba(_ color: CGColor) -> RGBA? {
 81        guard let space = CGColorSpace(name: CGColorSpace.sRGB),
 82              let converted = color.converted(to: space, intent: .defaultIntent, options: nil),
 83              let c = converted.components, c.count >= 3 else { return nil }
 84        return RGBA(red: Double(c[0]), green: Double(c[1]), blue: Double(c[2]), alpha: Double(converted.alpha))
 85    }
 86}
 87
 88/// An event's fields while it is edited or made.
 89public struct EventDraft: Sendable, Equatable {
 90    public var title: String
 91    public var start: Date
 92    public var end: Date
 93    public var isAllDay: Bool
 94    public var location: String
 95    /// The calendar it goes in; empty for the default calendar for new events.
 96    public var calendarID: String
 97
 98    public init(title: String, start: Date, end: Date, isAllDay: Bool, location: String = "", calendarID: String = "") {
 99        self.title = title
100        self.start = start
101        self.end = end
102        self.isAllDay = isAllDay
103        self.location = location
104        self.calendarID = calendarID
105    }
106
107    public init(_ event: AgendaEvent) {
108        self.init(title: event.title, start: event.start, end: event.end, isAllDay: event.isAllDay,
109                  location: event.location ?? "", calendarID: event.calendarID)
110    }
111
112    /// An agenda entry on `day` as an event: at its time (`start` and `end` as `hhmm`), an
113    /// hour long when it has no end, or all day without a time. An all-day event's dates are
114    /// its first and last day.
115    public static func entry(_ title: String, day: Int, start: Int?, end: Int?, calendar: Calendar = .current) -> EventDraft {
116        let d = Days.date(day)
117        let midnight = calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
118        guard let start else {
119            return EventDraft(title: title, start: midnight, end: midnight, isAllDay: true)
120        }
121        func at(_ hhmm: Int) -> Date { calendar.date(bySettingHour: hhmm / 100, minute: hhmm % 100, second: 0, of: midnight) ?? midnight }
122        let from = at(start)
123        var to = end.map(at) ?? from.addingTimeInterval(3600)
124        if to <= from { to = from.addingTimeInterval(3600) }
125        return EventDraft(title: title, start: from, end: to, isAllDay: false)
126    }
127}
128
129extension CalendarEvents {
130    /// The calendars events can be added to or changed in.
131    public func writableCalendars() -> [(id: String, title: String, color: RGBA?)] {
132        guard Self.isAuthorized else { return [] }
133        return store.calendars(for: .event).filter(\.allowsContentModifications)
134            .map { ($0.calendarIdentifier, $0.title, $0.cgColor.flatMap(Self.rgba)) }
135    }
136
137    /// The calendar new events go in.
138    public var defaultCalendarID: String { store.defaultCalendarForNewEvents?.calendarIdentifier ?? "" }
139
140    public enum SaveError: Error, CustomStringConvertible {
141        case noAccess, gone, noCalendar, failed(String)
142
143        public var description: String {
144            switch self {
145            case .noAccess: "orgstar may not change your calendars."
146            case .gone: "The event is no longer in Calendar."
147            case .noCalendar: "Choose a calendar."
148            case .failed(let message): message
149            }
150        }
151    }
152
153    /// Writes `draft` into the event `replacing` (only that occurrence of a repeating event), or
154    /// as a new event. Returns the event's agenda identifier.
155    @discardableResult
156    public func save(_ draft: EventDraft, replacing event: AgendaEvent? = nil) throws -> String {
157        guard Self.isAuthorized else { throw SaveError.noAccess }
158        let target: EKEvent
159        if let event {
160            let predicate = store.predicateForEvents(withStart: event.start.addingTimeInterval(-1), end: event.end.addingTimeInterval(1), calendars: nil)
161            guard let found = store.events(matching: predicate).first(where: { $0.recordID == event.id }) else { throw SaveError.gone }
162            target = found
163        } else {
164            target = EKEvent(eventStore: store)
165        }
166        let calendarID = draft.calendarID.isEmpty ? defaultCalendarID : draft.calendarID
167        guard let calendar = store.calendar(withIdentifier: calendarID) else { throw SaveError.noCalendar }
168        target.calendar = calendar
169        target.title = draft.title
170        target.isAllDay = draft.isAllDay
171        // EventKit takes an all-day event's days from the dates.
172        target.startDate = draft.isAllDay ? Calendar.current.startOfDay(for: draft.start) : draft.start
173        target.endDate = max(draft.isAllDay ? Calendar.current.startOfDay(for: draft.end) : draft.end, target.startDate)
174        target.location = draft.location.isEmpty ? nil : draft.location
175        do {
176            try store.save(target, span: .thisEvent, commit: true)
177        } catch {
178            throw SaveError.failed(error.localizedDescription)
179        }
180        return target.recordID
181    }
182}
183
184extension CalendarEvents {
185    /// Whether the event repeats, so that a change applies to one occurrence.
186    public func isRepeating(_ event: AgendaEvent) -> Bool {
187        guard Self.isAuthorized else { return false }
188        let predicate = store.predicateForEvents(withStart: event.start.addingTimeInterval(-1), end: event.end.addingTimeInterval(1), calendars: nil)
189        return store.events(matching: predicate).first { $0.recordID == event.id }?.hasRecurrenceRules ?? false
190    }
191}