wechat-clawbot 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/README.zh.md +19 -0
- package/assets/icon.svg +7 -0
- package/cordis.patch.yml +4 -0
- package/lib/backlog.d.ts +14 -0
- package/lib/backlog.d.ts.map +1 -1
- package/lib/backlog.js +65 -4
- package/lib/backlog.js.map +1 -1
- package/lib/bridge.d.ts +29 -3
- package/lib/bridge.d.ts.map +1 -1
- package/lib/bridge.js +172 -13
- package/lib/bridge.js.map +1 -1
- package/lib/claude-peer.js +11 -11
- package/lib/claude-peer.js.map +1 -1
- package/lib/client.js +288 -2
- package/lib/config.d.ts +56 -2
- package/lib/config.d.ts.map +1 -1
- package/lib/config.js +55 -0
- package/lib/config.js.map +1 -1
- package/lib/dsh-sessions.d.ts.map +1 -1
- package/lib/dsh-sessions.js +2 -1
- package/lib/dsh-sessions.js.map +1 -1
- package/lib/idle-compact.d.ts +5 -0
- package/lib/idle-compact.d.ts.map +1 -1
- package/lib/idle-compact.js +10 -8
- package/lib/idle-compact.js.map +1 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +132 -18
- package/lib/index.js.map +1 -1
- package/lib/instance-guard.d.ts.map +1 -1
- package/lib/instance-guard.js +32 -7
- package/lib/instance-guard.js.map +1 -1
- package/lib/localtime.d.ts +4 -3
- package/lib/localtime.d.ts.map +1 -1
- package/lib/localtime.js +7 -6
- package/lib/localtime.js.map +1 -1
- package/lib/mac-alarms.d.ts +168 -0
- package/lib/mac-alarms.d.ts.map +1 -0
- package/lib/mac-alarms.js +610 -0
- package/lib/mac-alarms.js.map +1 -0
- package/lib/mac-calendar.d.ts +239 -0
- package/lib/mac-calendar.d.ts.map +1 -0
- package/lib/mac-calendar.js +1201 -0
- package/lib/mac-calendar.js.map +1 -0
- package/lib/mcp-route.d.ts.map +1 -1
- package/lib/mcp-route.js +8 -2
- package/lib/mcp-route.js.map +1 -1
- package/lib/memory-auto.js +4 -4
- package/lib/memory-auto.js.map +1 -1
- package/lib/memory.d.ts.map +1 -1
- package/lib/memory.js +12 -1
- package/lib/memory.js.map +1 -1
- package/lib/models-route.d.ts +1 -1
- package/lib/pending.d.ts +9 -1
- package/lib/pending.d.ts.map +1 -1
- package/lib/pending.js +18 -1
- package/lib/pending.js.map +1 -1
- package/lib/prompt.d.ts.map +1 -1
- package/lib/prompt.js +12 -11
- package/lib/prompt.js.map +1 -1
- package/lib/secretary.d.ts +60 -0
- package/lib/secretary.d.ts.map +1 -0
- package/lib/secretary.js +281 -0
- package/lib/secretary.js.map +1 -0
- package/lib/time-context.d.ts +57 -0
- package/lib/time-context.d.ts.map +1 -0
- package/lib/time-context.js +90 -0
- package/lib/time-context.js.map +1 -0
- package/lib/tool.js +1 -1
- package/lib/typing.d.ts +0 -1
- package/lib/typing.d.ts.map +1 -1
- package/lib/typing.js +7 -1
- package/lib/typing.js.map +1 -1
- package/native/macos-calendar/main.swift +1006 -0
- package/package.json +4 -1
- package/wechat-clawbot-INSTALL.md +77 -2
|
@@ -0,0 +1,1006 @@
|
|
|
1
|
+
// Clawbot-Calendar: the WeChat bot's bridge to the macOS Calendar (EventKit)
|
|
2
|
+
// and to Reminders, for alarms (ReminderKit).
|
|
3
|
+
//
|
|
4
|
+
// The plugin builds this file into Clawbot-Calendar.app and launches it through
|
|
5
|
+
// LaunchServices (`open -W -n -g -a … --args --request <file> --response <file>`),
|
|
6
|
+
// so macOS treats the app as its own "responsible process": the calendar and
|
|
7
|
+
// reminders permission prompts name this app, and the grants do not depend on
|
|
8
|
+
// whatever started DSH (a menu-bar app, a terminal). Each launch handles one
|
|
9
|
+
// request and exits.
|
|
10
|
+
//
|
|
11
|
+
// Request (JSON file): { "cmd": "...", "timeZone": "America/New_York", "deadline": <epoch ms>, ... }
|
|
12
|
+
// Response (JSON file): { "ok": true, ... } or { "ok": false, "error": "...", "code": "..." }
|
|
13
|
+
//
|
|
14
|
+
// Commands
|
|
15
|
+
// status both authorization states, whether alarms can work here, the protocol; no prompt
|
|
16
|
+
// request ask for full access to the calendar, then to reminders (each prompt once;
|
|
17
|
+
// `calendar` / `reminders`: false skips one)
|
|
18
|
+
// calendars every event calendar with its account
|
|
19
|
+
// events occurrences in [from, to), recurring ones expanded
|
|
20
|
+
// ensureCalendar the dedicated calendar: a known id, an adopted one, or a new one
|
|
21
|
+
// add add one event (and report what it overlaps)
|
|
22
|
+
// update / delete change or remove one occurrence (or the series from it on)
|
|
23
|
+
// ensureAlarmList the reminders list alarms go into: a known id, one of that name, or a new one
|
|
24
|
+
// alarmAdd one alarm: an urgent reminder at a time of day
|
|
25
|
+
// alarms the reminders in the alarm list
|
|
26
|
+
// alarmDelete remove one alarm
|
|
27
|
+
// alarmComplete mark alarms done (ones that rang hours ago, so they do not pile up as overdue)
|
|
28
|
+
// rkcheck which ReminderKit pieces this macOS lacks (no permission needed)
|
|
29
|
+
//
|
|
30
|
+
// Times in: "2026-10-15T14:00" (local wall clock in timeZone), "2026-10-15"
|
|
31
|
+
// (a date), or ISO 8601 with an offset. Times out: ISO 8601 with offset.
|
|
32
|
+
//
|
|
33
|
+
// All-day events follow EventKit's own rule: the end is the LAST day, inclusive
|
|
34
|
+
// (EventKit stores 23:59:59 of that day). Passing the next midnight, the usual
|
|
35
|
+
// exclusive convention, makes a one-day event two days long.
|
|
36
|
+
|
|
37
|
+
import EventKit
|
|
38
|
+
import Foundation
|
|
39
|
+
|
|
40
|
+
// MARK: - I/O
|
|
41
|
+
|
|
42
|
+
struct Failure: Error {
|
|
43
|
+
let code: String
|
|
44
|
+
let message: String
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
func argument(_ name: String) -> String? {
|
|
48
|
+
let args = CommandLine.arguments
|
|
49
|
+
guard let i = args.firstIndex(of: name), i + 1 < args.count else { return nil }
|
|
50
|
+
return args[i + 1]
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let responseLock = NSLock()
|
|
54
|
+
var responded = false
|
|
55
|
+
|
|
56
|
+
/// Write the one response this launch gives, then never again (a watchdog may race the real answer).
|
|
57
|
+
func respond(_ object: [String: Any], to path: String) {
|
|
58
|
+
responseLock.lock()
|
|
59
|
+
defer { responseLock.unlock() }
|
|
60
|
+
guard !responded else { return }
|
|
61
|
+
responded = true
|
|
62
|
+
let data = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]))
|
|
63
|
+
?? Data("{\"ok\":false,\"code\":\"error\",\"error\":\"unencodable response\"}".utf8)
|
|
64
|
+
let url = URL(fileURLWithPath: path)
|
|
65
|
+
try? data.write(to: url, options: .atomic)
|
|
66
|
+
// Only the owner may read what the calendar said.
|
|
67
|
+
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// MARK: - Time
|
|
71
|
+
|
|
72
|
+
var zone = TimeZone.current
|
|
73
|
+
var calendar: Calendar {
|
|
74
|
+
var c = Calendar(identifier: .gregorian)
|
|
75
|
+
c.timeZone = zone
|
|
76
|
+
return c
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// Past this instant nothing is written: the caller has given up and told the model so.
|
|
80
|
+
var deadline: Date? = nil
|
|
81
|
+
|
|
82
|
+
func beforeDeadline() throws {
|
|
83
|
+
if let d = deadline, Date() >= d {
|
|
84
|
+
throw Failure(code: "deadline", message: "took too long; nothing was changed")
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
func localFormatter(_ format: String) -> DateFormatter {
|
|
89
|
+
let f = DateFormatter()
|
|
90
|
+
f.locale = Locale(identifier: "en_US_POSIX")
|
|
91
|
+
f.calendar = calendar
|
|
92
|
+
f.timeZone = zone
|
|
93
|
+
f.dateFormat = format
|
|
94
|
+
f.isLenient = false
|
|
95
|
+
return f
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// Reject 2026-09-31, 2026-02-30, 25:00 instead of rolling them over to another day.
|
|
99
|
+
func checkFields(_ text: String, field: String) throws {
|
|
100
|
+
let pattern = #"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?"#
|
|
101
|
+
guard let re = try? NSRegularExpression(pattern: pattern),
|
|
102
|
+
let m = re.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) else { return }
|
|
103
|
+
func int(_ i: Int) -> Int? {
|
|
104
|
+
guard let r = Range(m.range(at: i), in: text) else { return nil }
|
|
105
|
+
return Int(text[r])
|
|
106
|
+
}
|
|
107
|
+
var parts = DateComponents()
|
|
108
|
+
parts.year = int(1)
|
|
109
|
+
parts.month = int(2)
|
|
110
|
+
parts.day = int(3)
|
|
111
|
+
let hour = int(4) ?? 0, minute = int(5) ?? 0, second = int(6) ?? 0
|
|
112
|
+
if !parts.isValidDate(in: Calendar(identifier: .gregorian)) || hour > 23 || minute > 59 || second > 59 {
|
|
113
|
+
throw Failure(code: "bad_request", message: "\(field) is not a real date or time: \(text)")
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/// A parsed time, and whether it named only a date.
|
|
118
|
+
func parseTime(_ raw: Any?, field: String) throws -> (date: Date, dateOnly: Bool) {
|
|
119
|
+
guard let text = (raw as? String)?.trimmingCharacters(in: .whitespaces), !text.isEmpty else {
|
|
120
|
+
throw Failure(code: "bad_request", message: "\(field) is missing")
|
|
121
|
+
}
|
|
122
|
+
try checkFields(text, field: field)
|
|
123
|
+
let iso = ISO8601DateFormatter()
|
|
124
|
+
iso.formatOptions = [.withInternetDateTime]
|
|
125
|
+
if let d = iso.date(from: text) { return (d, false) }
|
|
126
|
+
iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
127
|
+
if let d = iso.date(from: text) { return (d, false) }
|
|
128
|
+
let normalized = text.replacingOccurrences(of: " ", with: "T")
|
|
129
|
+
for format in ["yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm"] {
|
|
130
|
+
if let d = localFormatter(format).date(from: normalized) { return (d, false) }
|
|
131
|
+
}
|
|
132
|
+
if let d = localFormatter("yyyy-MM-dd").date(from: text) { return (d, true) }
|
|
133
|
+
throw Failure(code: "bad_request", message: "\(field) is not a time: \(text)")
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
func isoString(_ date: Date) -> String {
|
|
137
|
+
let f = ISO8601DateFormatter()
|
|
138
|
+
f.formatOptions = [.withInternetDateTime]
|
|
139
|
+
f.timeZone = zone
|
|
140
|
+
return f.string(from: date)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/// `day` at the clock time of `clock` (both in the owner's zone).
|
|
144
|
+
func combine(day: Date, clock: Date) -> Date {
|
|
145
|
+
let t = calendar.dateComponents([.hour, .minute, .second], from: clock)
|
|
146
|
+
return calendar.date(bySettingHour: t.hour ?? 0, minute: t.minute ?? 0, second: t.second ?? 0, of: day) ?? day
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// MARK: - EventKit helpers
|
|
150
|
+
|
|
151
|
+
let store = EKEventStore()
|
|
152
|
+
|
|
153
|
+
func authorization() -> String {
|
|
154
|
+
switch EKEventStore.authorizationStatus(for: .event) {
|
|
155
|
+
case .notDetermined: return "notDetermined"
|
|
156
|
+
case .restricted: return "restricted"
|
|
157
|
+
case .denied: return "denied"
|
|
158
|
+
case .fullAccess: return "fullAccess"
|
|
159
|
+
case .writeOnly: return "writeOnly"
|
|
160
|
+
@unknown default: return "unknown"
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
func requireFullAccess() throws {
|
|
165
|
+
let state = authorization()
|
|
166
|
+
guard state == "fullAccess" else {
|
|
167
|
+
throw Failure(code: "not_authorized", message: state)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/// Wait for an async EventKit callback without a UI run loop of our own.
|
|
172
|
+
func waitFor(seconds: TimeInterval, _ done: () -> Bool) -> Bool {
|
|
173
|
+
let until = Date().addingTimeInterval(seconds)
|
|
174
|
+
while !done() && Date() < until {
|
|
175
|
+
RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.1))
|
|
176
|
+
}
|
|
177
|
+
return done()
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
func sourceType(_ type: EKSourceType) -> String {
|
|
181
|
+
switch type {
|
|
182
|
+
case .local: return "local"
|
|
183
|
+
case .exchange: return "exchange"
|
|
184
|
+
case .calDAV: return "caldav"
|
|
185
|
+
case .mobileMe: return "mobileme"
|
|
186
|
+
case .subscribed: return "subscribed"
|
|
187
|
+
case .birthdays: return "birthdays"
|
|
188
|
+
@unknown default: return "other"
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
func describe(_ calendar: EKCalendar) -> [String: Any] {
|
|
193
|
+
[
|
|
194
|
+
"id": calendar.calendarIdentifier,
|
|
195
|
+
"title": calendar.title,
|
|
196
|
+
"account": calendar.source?.title ?? "",
|
|
197
|
+
"accountType": calendar.source.map { sourceType($0.sourceType) } ?? "",
|
|
198
|
+
"writable": calendar.allowsContentModifications,
|
|
199
|
+
]
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
func eventCalendars() -> [EKCalendar] {
|
|
203
|
+
store.calendars(for: .event)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
func calendar(id: String) throws -> EKCalendar {
|
|
207
|
+
guard let cal = store.calendar(withIdentifier: id) else {
|
|
208
|
+
throw Failure(code: "no_calendar", message: "calendar \(id) not found")
|
|
209
|
+
}
|
|
210
|
+
return cal
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
func describe(_ event: EKEvent) -> [String: Any] {
|
|
214
|
+
var out: [String: Any] = [
|
|
215
|
+
"id": event.eventIdentifier ?? "",
|
|
216
|
+
"calendarId": event.calendar?.calendarIdentifier ?? "",
|
|
217
|
+
"calendar": event.calendar?.title ?? "",
|
|
218
|
+
"account": event.calendar?.source?.title ?? "",
|
|
219
|
+
"title": event.title ?? "",
|
|
220
|
+
"start": isoString(event.startDate),
|
|
221
|
+
"end": isoString(event.endDate),
|
|
222
|
+
"allDay": event.isAllDay,
|
|
223
|
+
"recurring": event.hasRecurrenceRules,
|
|
224
|
+
]
|
|
225
|
+
if let location = event.location, !location.isEmpty { out["location"] = location }
|
|
226
|
+
if let notes = event.notes, !notes.isEmpty { out["notes"] = notes }
|
|
227
|
+
if let url = event.url { out["url"] = url.absoluteString }
|
|
228
|
+
if let occurrence = event.occurrenceDate { out["occurrence"] = isoString(occurrence) }
|
|
229
|
+
if let attendees = event.attendees, !attendees.isEmpty {
|
|
230
|
+
out["attendees"] = attendees.count
|
|
231
|
+
out["organizerIsMe"] = event.organizer?.isCurrentUser ?? false
|
|
232
|
+
}
|
|
233
|
+
if let alarms = event.alarms, !alarms.isEmpty {
|
|
234
|
+
out["alertMinutes"] = alarms.compactMap { $0.absoluteDate == nil ? alertMinutes($0) : nil }
|
|
235
|
+
}
|
|
236
|
+
return out
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/// An alert's minutes before the start; nil for one no calendar app would set
|
|
240
|
+
/// (Int() would trap on an absurd offset from some calendar server).
|
|
241
|
+
func alertMinutes(_ alarm: EKAlarm) -> Int? {
|
|
242
|
+
let minutes = -alarm.relativeOffset / 60
|
|
243
|
+
return minutes.isFinite && abs(minutes) < 1e9 ? Int(minutes) : nil
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/// One occurrence by its event id. Recurring occurrences share an id, so the
|
|
247
|
+
/// caller also gives the occurrence's ORIGINAL date (it never changes, even when
|
|
248
|
+
/// that occurrence was moved) and its current start; both are searched.
|
|
249
|
+
func occurrence(id: String, original raw: Any?, current rawCurrent: Any?) throws -> EKEvent {
|
|
250
|
+
guard let master = store.event(withIdentifier: id) else {
|
|
251
|
+
throw Failure(code: "no_event", message: "event not found (it may have been deleted)")
|
|
252
|
+
}
|
|
253
|
+
guard master.hasRecurrenceRules, raw != nil else { return master }
|
|
254
|
+
let original = try parseTime(raw, field: "occurrence").date
|
|
255
|
+
let current = rawCurrent == nil ? original : try parseTime(rawCurrent, field: "start").date
|
|
256
|
+
let from = min(original, current).addingTimeInterval(-86_400)
|
|
257
|
+
let to = max(original, current).addingTimeInterval(86_400)
|
|
258
|
+
let predicate = store.predicateForEvents(withStart: from, end: to, calendars: [master.calendar])
|
|
259
|
+
let match = store.events(matching: predicate).first {
|
|
260
|
+
$0.eventIdentifier == id && abs(($0.occurrenceDate ?? $0.startDate).timeIntervalSince(original)) < 60
|
|
261
|
+
}
|
|
262
|
+
guard let found = match else {
|
|
263
|
+
throw Failure(code: "no_event", message: "that occurrence is not in the calendar any more")
|
|
264
|
+
}
|
|
265
|
+
return found
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/// Events in a window that overlap [start, end), apart from `except`.
|
|
269
|
+
func overlaps(_ start: Date, _ end: Date, except: String?) -> [[String: Any]] {
|
|
270
|
+
let predicate = store.predicateForEvents(withStart: start, end: end, calendars: nil)
|
|
271
|
+
return store.events(matching: predicate)
|
|
272
|
+
.filter { !$0.isAllDay && $0.eventIdentifier != except && $0.startDate < end && $0.endDate > start }
|
|
273
|
+
.prefix(10)
|
|
274
|
+
.map { ["title": $0.title ?? "", "calendar": $0.calendar?.title ?? "", "start": isoString($0.startDate), "end": isoString($0.endDate)] }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/// Apply the requested fields. On update an event keeps being all-day or timed
|
|
278
|
+
/// unless `allDay` says otherwise, and a date-only start moves a timed event to
|
|
279
|
+
/// that day at its own time.
|
|
280
|
+
func applyFields(_ event: EKEvent, _ request: [String: Any], creating: Bool) throws {
|
|
281
|
+
if let title = request["title"] as? String { event.title = title }
|
|
282
|
+
if let location = request["location"] as? String { event.location = location.isEmpty ? nil : location }
|
|
283
|
+
if let notes = request["notes"] as? String { event.notes = notes.isEmpty ? nil : notes }
|
|
284
|
+
if let more = request["addNotes"] as? String, !more.isEmpty {
|
|
285
|
+
let existing = event.notes ?? ""
|
|
286
|
+
event.notes = existing.isEmpty ? more : "\(existing)\n\(more)"
|
|
287
|
+
}
|
|
288
|
+
if let url = request["url"] as? String { event.url = url.isEmpty ? nil : URL(string: url) }
|
|
289
|
+
|
|
290
|
+
let allDayAsked = request["allDay"] as? Bool
|
|
291
|
+
let hasStart = request["start"] != nil
|
|
292
|
+
let hasEnd = request["end"] != nil
|
|
293
|
+
if hasStart || hasEnd || allDayAsked != nil {
|
|
294
|
+
let parsedStart = hasStart ? try parseTime(request["start"], field: "start") : nil
|
|
295
|
+
let wholeDay: Bool = creating
|
|
296
|
+
? (allDayAsked ?? parsedStart?.dateOnly ?? false)
|
|
297
|
+
: (allDayAsked ?? event.isAllDay)
|
|
298
|
+
let parsedEnd = hasEnd ? try parseTime(request["end"], field: "end") : nil
|
|
299
|
+
|
|
300
|
+
if wholeDay {
|
|
301
|
+
// Days, inclusive: EventKit's rule for all-day events.
|
|
302
|
+
let oldFirst = calendar.startOfDay(for: event.startDate ?? Date())
|
|
303
|
+
let oldLast = calendar.startOfDay(for: event.endDate ?? Date())
|
|
304
|
+
let first = parsedStart.map { calendar.startOfDay(for: $0.date) } ?? oldFirst
|
|
305
|
+
var last: Date
|
|
306
|
+
if let end = parsedEnd {
|
|
307
|
+
// A date is the last day; a time is an exclusive end (so 10-16 00:00 means through 10-15).
|
|
308
|
+
last = calendar.startOfDay(for: end.dateOnly ? end.date : end.date.addingTimeInterval(-1))
|
|
309
|
+
} else if creating || !event.isAllDay {
|
|
310
|
+
last = first
|
|
311
|
+
} else {
|
|
312
|
+
let days = calendar.dateComponents([.day], from: oldFirst, to: oldLast).day ?? 0
|
|
313
|
+
last = calendar.date(byAdding: .day, value: days, to: first) ?? first
|
|
314
|
+
}
|
|
315
|
+
if last < first { throw Failure(code: "bad_request", message: "the last day is before the first") }
|
|
316
|
+
event.isAllDay = true
|
|
317
|
+
event.startDate = first
|
|
318
|
+
event.endDate = last
|
|
319
|
+
} else {
|
|
320
|
+
var start: Date
|
|
321
|
+
if let s = parsedStart {
|
|
322
|
+
// A bare date on a timed event: that day, at the event's own time.
|
|
323
|
+
start = s.dateOnly && !creating && !event.isAllDay ? combine(day: s.date, clock: event.startDate) : s.date
|
|
324
|
+
} else {
|
|
325
|
+
start = event.startDate
|
|
326
|
+
}
|
|
327
|
+
var end: Date
|
|
328
|
+
if let e = parsedEnd {
|
|
329
|
+
end = e.dateOnly && !creating && !event.isAllDay ? combine(day: e.date, clock: event.endDate) : e.date
|
|
330
|
+
} else if creating || event.isAllDay {
|
|
331
|
+
end = start.addingTimeInterval(3_600)
|
|
332
|
+
} else if hasStart {
|
|
333
|
+
end = start.addingTimeInterval(event.endDate.timeIntervalSince(event.startDate))
|
|
334
|
+
} else {
|
|
335
|
+
end = event.endDate
|
|
336
|
+
}
|
|
337
|
+
if end <= start { throw Failure(code: "bad_request", message: "the end must be after the start") }
|
|
338
|
+
event.isAllDay = false
|
|
339
|
+
event.startDate = start
|
|
340
|
+
event.endDate = end
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if let minutes = request["alertMinutes"] as? [Any] {
|
|
344
|
+
for alarm in event.alarms ?? [] { event.removeAlarm(alarm) }
|
|
345
|
+
for value in minutes {
|
|
346
|
+
if let m = (value as? NSNumber)?.doubleValue, m >= 0 { event.addAlarm(EKAlarm(relativeOffset: -m * 60)) }
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
func span(_ request: [String: Any]) -> EKSpan {
|
|
352
|
+
(request["span"] as? String) == "future" ? .futureEvents : .thisEvent
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/// The dedicated calendar.
|
|
356
|
+
/// - `knownId`: the one this plugin created or the owner approved before.
|
|
357
|
+
/// - `adoptId`: an existing calendar with that title the owner just approved.
|
|
358
|
+
/// - Otherwise a writable calendar with the same title is NOT taken silently
|
|
359
|
+
/// (it may be shared, or the owner's real "Work"): it comes back as
|
|
360
|
+
/// `name_taken` so the owner can be asked. If none exists, a new one is made,
|
|
361
|
+
/// iCloud first so it reaches the phone (Google refuses new calendars over
|
|
362
|
+
/// CalDAV; a default in a work Exchange account is not where private planning
|
|
363
|
+
/// belongs).
|
|
364
|
+
func ensureCalendar(_ request: [String: Any]) throws -> [String: Any] {
|
|
365
|
+
guard let name = (request["name"] as? String)?.trimmingCharacters(in: .whitespaces), !name.isEmpty else {
|
|
366
|
+
throw Failure(code: "bad_request", message: "name is missing")
|
|
367
|
+
}
|
|
368
|
+
if let known = request["knownId"] as? String, let cal = store.calendar(withIdentifier: known), cal.allowsContentModifications {
|
|
369
|
+
return ["ok": true, "calendar": describe(cal), "created": false]
|
|
370
|
+
}
|
|
371
|
+
if let adopt = request["adoptId"] as? String {
|
|
372
|
+
guard let cal = store.calendar(withIdentifier: adopt), cal.allowsContentModifications, cal.title == name else {
|
|
373
|
+
throw Failure(code: "no_calendar", message: "that calendar is gone or read-only")
|
|
374
|
+
}
|
|
375
|
+
return ["ok": true, "calendar": describe(cal), "created": false]
|
|
376
|
+
}
|
|
377
|
+
let same = eventCalendars().filter { $0.title == name && $0.allowsContentModifications }
|
|
378
|
+
if !same.isEmpty {
|
|
379
|
+
return ["ok": false, "code": "name_taken", "error": "a writable calendar named \(name) already exists",
|
|
380
|
+
"calendars": same.map(describe)]
|
|
381
|
+
}
|
|
382
|
+
try beforeDeadline()
|
|
383
|
+
var sources: [EKSource] = []
|
|
384
|
+
sources += store.sources.filter { $0.sourceType == .calDAV && $0.title.lowercased().contains("icloud") }
|
|
385
|
+
if let preferred = store.defaultCalendarForNewEvents?.source { sources.append(preferred) }
|
|
386
|
+
sources += store.sources.filter { $0.sourceType == .calDAV || $0.sourceType == .exchange }
|
|
387
|
+
sources += store.sources.filter { $0.sourceType == .local }
|
|
388
|
+
var seen = Set<String>()
|
|
389
|
+
var lastError = "no account accepts new calendars"
|
|
390
|
+
for source in sources where seen.insert(source.sourceIdentifier).inserted {
|
|
391
|
+
let cal = EKCalendar(for: .event, eventStore: store)
|
|
392
|
+
cal.title = name
|
|
393
|
+
cal.source = source
|
|
394
|
+
do {
|
|
395
|
+
try store.saveCalendar(cal, commit: true)
|
|
396
|
+
return ["ok": true, "calendar": describe(cal), "created": true]
|
|
397
|
+
} catch {
|
|
398
|
+
lastError = "\(source.title): \(error.localizedDescription)"
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
throw Failure(code: "create_failed", message: lastError)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/// The occurrence an update or delete names, in the calendar the caller saw it in.
|
|
405
|
+
func target(_ request: [String: Any]) throws -> EKEvent {
|
|
406
|
+
let event = try occurrence(id: request["eventId"] as? String ?? "", original: request["occurrence"], current: request["currentStart"])
|
|
407
|
+
if let expected = request["expectCalendarId"] as? String, expected != event.calendar.calendarIdentifier {
|
|
408
|
+
throw Failure(code: "calendar_changed", message: event.calendar.title)
|
|
409
|
+
}
|
|
410
|
+
guard event.calendar.allowsContentModifications else {
|
|
411
|
+
throw Failure(code: "read_only", message: "calendar \(event.calendar.title) is read-only")
|
|
412
|
+
}
|
|
413
|
+
return event
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// MARK: - Alarms: urgent reminders through ReminderKit
|
|
417
|
+
//
|
|
418
|
+
// An alarm is an urgent reminder: Reminders rings it like an alarm on the
|
|
419
|
+
// owner's devices (macOS and iOS 26 and later), and iCloud carries it to the
|
|
420
|
+
// phone, so it rings even when WeChat could not deliver a message. EventKit,
|
|
421
|
+
// the public API, has no "urgent", so alarms go through ReminderKit, the
|
|
422
|
+
// private framework Reminders.app itself uses: the same remindd, the same
|
|
423
|
+
// Reminders permission. Private means any macOS update may change it, so every
|
|
424
|
+
// call first checks that the method is still there and fails with
|
|
425
|
+
// "reminderkit_missing" instead of crashing; `rkcheck` lists what is missing.
|
|
426
|
+
//
|
|
427
|
+
// Where it rings: only on the device Find My uses as the owner's location
|
|
428
|
+
// (usually the iPhone); other devices show a plain notification. And the phone
|
|
429
|
+
// has its own say: Reminders there asks to allow urgent alarms only the first
|
|
430
|
+
// time someone marks a reminder urgent there by hand.
|
|
431
|
+
//
|
|
432
|
+
// Protocol 2 = this file has the alarm commands; 3 = also alarmComplete, and
|
|
433
|
+
// `status` says whether alarms can work on this macOS. The plugin reads it
|
|
434
|
+
// from `status` and tells an older build apart without asking it anything new.
|
|
435
|
+
// Every change to this file bumps it (a regression test holds the two together).
|
|
436
|
+
let helperProtocol = 3
|
|
437
|
+
|
|
438
|
+
func remindersAuthorization() -> String {
|
|
439
|
+
switch EKEventStore.authorizationStatus(for: .reminder) {
|
|
440
|
+
case .notDetermined: return "notDetermined"
|
|
441
|
+
case .restricted: return "restricted"
|
|
442
|
+
case .denied: return "denied"
|
|
443
|
+
case .fullAccess: return "fullAccess"
|
|
444
|
+
case .writeOnly: return "writeOnly"
|
|
445
|
+
@unknown default: return "unknown"
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
func requireRemindersAccess() throws {
|
|
450
|
+
let state = remindersAuthorization()
|
|
451
|
+
guard state == "fullAccess" else {
|
|
452
|
+
throw Failure(code: "reminders_not_authorized", message: state)
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/// Typed calls into ReminderKit through the Objective-C runtime. Its objects keep
|
|
457
|
+
/// most fields in a storage object they forward to, so "does it answer" asks both.
|
|
458
|
+
enum RK {
|
|
459
|
+
static var loaded = false
|
|
460
|
+
|
|
461
|
+
static func load() throws {
|
|
462
|
+
if loaded { return }
|
|
463
|
+
guard let bundle = Bundle(path: "/System/Library/PrivateFrameworks/ReminderKit.framework"), bundle.load() else {
|
|
464
|
+
throw Failure(code: "reminderkit_missing", message: "ReminderKit could not be loaded")
|
|
465
|
+
}
|
|
466
|
+
loaded = true
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
static func missing(_ what: String) -> Failure {
|
|
470
|
+
Failure(code: "reminderkit_missing", message: "ReminderKit changed: \(what) is gone")
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
static func answers(_ target: NSObject, _ sel: Selector) -> Bool {
|
|
474
|
+
if target.responds(to: sel) { return true }
|
|
475
|
+
if let other = target.forwardingTarget(for: sel) as? NSObject { return other.responds(to: sel) }
|
|
476
|
+
return false
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
static func selector(_ target: NSObject, _ name: String) throws -> Selector {
|
|
480
|
+
let sel = NSSelectorFromString(name)
|
|
481
|
+
guard answers(target, sel) else { throw missing("\(type(of: target)).\(name)") }
|
|
482
|
+
return sel
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/// An object-returning method with up to three object arguments. Not owned (+0).
|
|
486
|
+
static func object(_ target: NSObject, _ name: String, _ args: AnyObject?...) throws -> NSObject? {
|
|
487
|
+
let sel = try selector(target, name)
|
|
488
|
+
let imp = target.method(for: sel)
|
|
489
|
+
switch args.count {
|
|
490
|
+
case 0:
|
|
491
|
+
typealias F = @convention(c) (NSObject, Selector) -> Unmanaged<NSObject>?
|
|
492
|
+
return unsafeBitCast(imp, to: F.self)(target, sel)?.takeUnretainedValue()
|
|
493
|
+
case 1:
|
|
494
|
+
typealias F = @convention(c) (NSObject, Selector, AnyObject?) -> Unmanaged<NSObject>?
|
|
495
|
+
return unsafeBitCast(imp, to: F.self)(target, sel, args[0])?.takeUnretainedValue()
|
|
496
|
+
case 2:
|
|
497
|
+
typealias F = @convention(c) (NSObject, Selector, AnyObject?, AnyObject?) -> Unmanaged<NSObject>?
|
|
498
|
+
return unsafeBitCast(imp, to: F.self)(target, sel, args[0], args[1])?.takeUnretainedValue()
|
|
499
|
+
case 3:
|
|
500
|
+
typealias F = @convention(c) (NSObject, Selector, AnyObject?, AnyObject?, AnyObject?) -> Unmanaged<NSObject>?
|
|
501
|
+
return unsafeBitCast(imp, to: F.self)(target, sel, args[0], args[1], args[2])?.takeUnretainedValue()
|
|
502
|
+
default:
|
|
503
|
+
throw Failure(code: "error", message: "too many arguments for \(name)")
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/// A fetch that reports failure through a trailing NSError**.
|
|
508
|
+
static func fetch(_ target: NSObject, _ name: String, _ args: AnyObject?...) throws -> NSObject? {
|
|
509
|
+
let sel = try selector(target, name)
|
|
510
|
+
let imp = target.method(for: sel)
|
|
511
|
+
var error: Unmanaged<NSError>? = nil
|
|
512
|
+
let result: NSObject?
|
|
513
|
+
switch args.count {
|
|
514
|
+
case 0:
|
|
515
|
+
typealias F = @convention(c) (NSObject, Selector, UnsafeMutablePointer<Unmanaged<NSError>?>) -> Unmanaged<NSObject>?
|
|
516
|
+
result = unsafeBitCast(imp, to: F.self)(target, sel, &error)?.takeUnretainedValue()
|
|
517
|
+
case 1:
|
|
518
|
+
typealias F = @convention(c) (NSObject, Selector, AnyObject?, UnsafeMutablePointer<Unmanaged<NSError>?>) -> Unmanaged<NSObject>?
|
|
519
|
+
result = unsafeBitCast(imp, to: F.self)(target, sel, args[0], &error)?.takeUnretainedValue()
|
|
520
|
+
default:
|
|
521
|
+
throw Failure(code: "error", message: "too many arguments for \(name)")
|
|
522
|
+
}
|
|
523
|
+
if result == nil, let e = error?.takeUnretainedValue() {
|
|
524
|
+
throw Failure(code: "reminders_error", message: e.localizedDescription)
|
|
525
|
+
}
|
|
526
|
+
return result
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
static func bool(_ target: NSObject, _ name: String) throws -> Bool {
|
|
530
|
+
let sel = try selector(target, name)
|
|
531
|
+
typealias F = @convention(c) (NSObject, Selector) -> Bool
|
|
532
|
+
return unsafeBitCast(target.method(for: sel), to: F.self)(target, sel)
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/// A void method with no argument or one object argument.
|
|
536
|
+
static func perform(_ target: NSObject, _ name: String, _ arg: AnyObject? = nil, hasArgument: Bool = false) throws {
|
|
537
|
+
let sel = try selector(target, name)
|
|
538
|
+
let imp = target.method(for: sel)
|
|
539
|
+
if hasArgument {
|
|
540
|
+
typealias F = @convention(c) (NSObject, Selector, AnyObject?) -> Void
|
|
541
|
+
unsafeBitCast(imp, to: F.self)(target, sel, arg)
|
|
542
|
+
} else {
|
|
543
|
+
typealias F = @convention(c) (NSObject, Selector) -> Void
|
|
544
|
+
unsafeBitCast(imp, to: F.self)(target, sel)
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
static func setBool(_ target: NSObject, _ name: String, _ value: Bool) throws {
|
|
549
|
+
let sel = try selector(target, name)
|
|
550
|
+
typealias F = @convention(c) (NSObject, Selector, Bool) -> Void
|
|
551
|
+
unsafeBitCast(target.method(for: sel), to: F.self)(target, sel, value)
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/// `[[ClassName alloc] initName:arg]`, owned by the caller. The init gets its
|
|
555
|
+
/// own reference to consume, so this stays balanced whether it returns the
|
|
556
|
+
/// allocated object or another one.
|
|
557
|
+
static func make(_ className: String, _ initName: String, object arg: AnyObject? = nil, bool flag: Bool? = nil) throws -> NSObject {
|
|
558
|
+
try load()
|
|
559
|
+
guard let cls: AnyClass = NSClassFromString(className), let meta = object_getClass(cls) else { throw missing(className) }
|
|
560
|
+
let allocSel = NSSelectorFromString("alloc")
|
|
561
|
+
typealias Alloc = @convention(c) (AnyClass, Selector) -> Unmanaged<NSObject>?
|
|
562
|
+
guard let allocIMP = class_getMethodImplementation(meta, allocSel),
|
|
563
|
+
let raw = unsafeBitCast(allocIMP, to: Alloc.self)(cls, allocSel)?.takeRetainedValue() else {
|
|
564
|
+
throw missing("\(className) alloc")
|
|
565
|
+
}
|
|
566
|
+
let sel = try selector(raw, initName)
|
|
567
|
+
let imp = raw.method(for: sel)
|
|
568
|
+
_ = Unmanaged.passUnretained(raw).retain()
|
|
569
|
+
let made: NSObject?
|
|
570
|
+
if let flag {
|
|
571
|
+
typealias F = @convention(c) (NSObject, Selector, Bool) -> Unmanaged<NSObject>?
|
|
572
|
+
made = unsafeBitCast(imp, to: F.self)(raw, sel, flag)?.takeRetainedValue()
|
|
573
|
+
} else {
|
|
574
|
+
typealias F = @convention(c) (NSObject, Selector, AnyObject?) -> Unmanaged<NSObject>?
|
|
575
|
+
made = unsafeBitCast(imp, to: F.self)(raw, sel, arg)?.takeRetainedValue()
|
|
576
|
+
}
|
|
577
|
+
guard let made else { throw Failure(code: "reminders_error", message: "\(className) \(initName) returned nil") }
|
|
578
|
+
return made
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
static func save(_ request: NSObject) throws {
|
|
582
|
+
let sel = try selector(request, "saveSynchronouslyWithError:")
|
|
583
|
+
typealias F = @convention(c) (NSObject, Selector, UnsafeMutablePointer<Unmanaged<NSError>?>) -> Bool
|
|
584
|
+
var error: Unmanaged<NSError>? = nil
|
|
585
|
+
guard unsafeBitCast(request.method(for: sel), to: F.self)(request, sel, &error) else {
|
|
586
|
+
throw Failure(code: "save_failed", message: error?.takeUnretainedValue().localizedDescription ?? "Reminders did not save")
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
var remindersStore: NSObject? = nil
|
|
592
|
+
|
|
593
|
+
func reminderStore() throws -> NSObject {
|
|
594
|
+
if let s = remindersStore { return s }
|
|
595
|
+
try requireRemindersAccess()
|
|
596
|
+
let s = try RK.make("REMStore", "initUserInteractive:", bool: true)
|
|
597
|
+
remindersStore = s
|
|
598
|
+
return s
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
func uuidOf(_ object: NSObject?) -> String? {
|
|
602
|
+
guard let object, let oid = try? RK.object(object, "objectID"), let uuid = try? RK.object(oid, "uuid") else { return nil }
|
|
603
|
+
return (uuid as? NSUUID)?.uuidString
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
func text(_ object: NSObject, _ name: String) -> String? {
|
|
607
|
+
((try? RK.object(object, name)) ?? nil) as? String
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/// Lists only (groups hold lists and take no reminders).
|
|
611
|
+
func reminderLists(_ rem: NSObject) throws -> [NSObject] {
|
|
612
|
+
let lists = (try RK.fetch(rem, "fetchEligibleDefaultListsWithError:") as? [NSObject]) ?? []
|
|
613
|
+
return lists.filter { !((try? RK.bool($0, "isGroup")) ?? false) }
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
func accountName(_ account: NSObject?) -> String {
|
|
617
|
+
guard let account else { return "" }
|
|
618
|
+
return text(account, "name") ?? ""
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
func describeList(_ list: NSObject) -> [String: Any] {
|
|
622
|
+
["id": uuidOf(list) ?? "", "name": text(list, "name") ?? "", "account": accountName((try? RK.object(list, "account")) ?? nil)]
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/// Where alarms live: the primary iCloud account, which must support urgent alarms.
|
|
626
|
+
func alarmAccount(_ rem: NSObject) throws -> NSObject {
|
|
627
|
+
guard let account = try RK.fetch(rem, "fetchPrimaryActiveCloudKitAccountWithError:") else {
|
|
628
|
+
throw Failure(code: "no_icloud", message: "Reminders has no active iCloud account")
|
|
629
|
+
}
|
|
630
|
+
if let capabilities = try RK.object(account, "capabilities"), try !RK.bool(capabilities, "supportsUrgentAlarm") {
|
|
631
|
+
throw Failure(code: "no_urgent", message: "the iCloud account \(accountName(account)) does not support urgent reminders")
|
|
632
|
+
}
|
|
633
|
+
return account
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/// The alarm list:
|
|
637
|
+
/// - `knownId`: the one used before.
|
|
638
|
+
/// - Otherwise a list with exactly this name in the alarm account (the owner
|
|
639
|
+
/// made it, or it outlived the record of it): an alarm list is what it is for.
|
|
640
|
+
/// - Otherwise a new one in that account.
|
|
641
|
+
func ensureAlarmList(_ request: [String: Any]) throws -> [String: Any] {
|
|
642
|
+
guard let name = (request["name"] as? String)?.trimmingCharacters(in: .whitespaces), !name.isEmpty else {
|
|
643
|
+
throw Failure(code: "bad_request", message: "name is missing")
|
|
644
|
+
}
|
|
645
|
+
let rem = try reminderStore()
|
|
646
|
+
let lists = try reminderLists(rem)
|
|
647
|
+
if let known = (request["knownId"] as? String)?.uppercased(), let list = lists.first(where: { uuidOf($0) == known }) {
|
|
648
|
+
return ["ok": true, "list": describeList(list), "created": false]
|
|
649
|
+
}
|
|
650
|
+
let account = try alarmAccount(rem)
|
|
651
|
+
let accountID = uuidOf(account)
|
|
652
|
+
if let same = lists.first(where: { text($0, "name") == name && uuidOf((try? RK.object($0, "account")) ?? nil) == accountID }) {
|
|
653
|
+
return ["ok": true, "list": describeList(same), "created": false, "adopted": true]
|
|
654
|
+
}
|
|
655
|
+
try beforeDeadline()
|
|
656
|
+
let save = try RK.make("REMSaveRequest", "initWithStore:", object: rem)
|
|
657
|
+
guard let accountChange = try RK.object(save, "updateAccount:", account),
|
|
658
|
+
let listChange = try RK.object(save, "addListWithName:toAccountChangeItem:listObjectID:", name as NSString, accountChange, nil),
|
|
659
|
+
let id = uuidOf(listChange) else {
|
|
660
|
+
throw Failure(code: "create_failed", message: "Reminders did not make the list")
|
|
661
|
+
}
|
|
662
|
+
try RK.save(save)
|
|
663
|
+
// Made: a read that fails from here on is not a failure (the next call finds it by name).
|
|
664
|
+
let made = ((try? reminderLists(rem)) ?? []).first { uuidOf($0) == id }
|
|
665
|
+
return ["ok": true, "list": made.map(describeList) ?? ["id": id, "name": name, "account": accountName(account)], "created": true]
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
func alarmList(_ rem: NSObject, _ raw: Any?) throws -> NSObject {
|
|
669
|
+
let id = ((raw as? String) ?? "").uppercased()
|
|
670
|
+
guard let list = try reminderLists(rem).first(where: { uuidOf($0) == id }) else {
|
|
671
|
+
throw Failure(code: "no_list", message: "the alarm list is gone")
|
|
672
|
+
}
|
|
673
|
+
return list
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
func remindersIn(_ rem: NSObject, _ list: NSObject) throws -> [NSObject] {
|
|
677
|
+
guard let listID = try RK.object(list, "objectID") else { throw RK.missing("REMList.objectID") }
|
|
678
|
+
return (try RK.fetch(rem, "fetchRemindersForEventKitBridgingWithListIDs:error:", [listID] as NSArray) as? [NSObject]) ?? []
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/// A due date as Reminders keeps it (wall clock, maybe with a zone) as an instant.
|
|
682
|
+
func instant(_ raw: NSObject?) -> Date? {
|
|
683
|
+
guard var parts = raw as? DateComponents ?? (raw as? NSDateComponents).map({ $0 as DateComponents }) else { return nil }
|
|
684
|
+
var cal = Calendar(identifier: .gregorian)
|
|
685
|
+
cal.timeZone = parts.timeZone ?? zone
|
|
686
|
+
parts.timeZone = nil
|
|
687
|
+
parts.calendar = nil
|
|
688
|
+
return cal.date(from: parts)
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/// No fallback through urgentAlarmContext: that context only forwards to this
|
|
692
|
+
/// same getter, so where the getter is gone it would crash instead of saying no.
|
|
693
|
+
func isUrgent(_ reminder: NSObject) -> Bool {
|
|
694
|
+
(try? RK.bool(reminder, "isUrgentStateEnabledForCurrentUser")) ?? false
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
func describeAlarm(_ reminder: NSObject) -> [String: Any] {
|
|
698
|
+
var out: [String: Any] = [
|
|
699
|
+
"id": uuidOf(reminder) ?? "",
|
|
700
|
+
"title": text(reminder, "titleAsString") ?? "",
|
|
701
|
+
"completed": (try? RK.bool(reminder, "isCompleted")) ?? false,
|
|
702
|
+
"urgent": isUrgent(reminder),
|
|
703
|
+
]
|
|
704
|
+
if let due = instant((try? RK.object(reminder, "dueDateComponents")) ?? nil) { out["due"] = isoString(due) }
|
|
705
|
+
if let notes = text(reminder, "notesAsString"), !notes.isEmpty { out["notes"] = notes }
|
|
706
|
+
return out
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
func addAlarm(_ request: [String: Any]) throws -> [String: Any] {
|
|
710
|
+
// The request is checked before Reminders is opened: that needs no permission.
|
|
711
|
+
guard let title = (request["title"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty else {
|
|
712
|
+
throw Failure(code: "bad_request", message: "title is missing")
|
|
713
|
+
}
|
|
714
|
+
let due = try parseTime(request["due"], field: "due")
|
|
715
|
+
if due.dateOnly { throw Failure(code: "bad_request", message: "an alarm needs a time of day") }
|
|
716
|
+
if due.date <= Date() { throw Failure(code: "past", message: "that time has already passed") }
|
|
717
|
+
var parts = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: due.date)
|
|
718
|
+
parts.timeZone = zone
|
|
719
|
+
// Reminders keeps a wall clock and a zone. In the hour the clocks go back one
|
|
720
|
+
// wall time names two instants and reads back as the first: refuse the second
|
|
721
|
+
// rather than ring an hour early.
|
|
722
|
+
if let back = instant(parts as NSDateComponents), abs(back.timeIntervalSince(due.date)) > 1 {
|
|
723
|
+
throw Failure(code: "ambiguous", message: "that wall-clock time happens twice (clocks going back); only the first can be set")
|
|
724
|
+
}
|
|
725
|
+
let rem = try reminderStore()
|
|
726
|
+
let list = try alarmList(rem, request["listId"])
|
|
727
|
+
try beforeDeadline()
|
|
728
|
+
let save = try RK.make("REMSaveRequest", "initWithStore:", object: rem)
|
|
729
|
+
guard let listChange = try RK.object(save, "updateList:", list),
|
|
730
|
+
let change = try RK.object(save, "addReminderWithTitle:toListChangeItem:", title as NSString, listChange),
|
|
731
|
+
let id = uuidOf(change) else {
|
|
732
|
+
throw Failure(code: "create_failed", message: "Reminders did not make the alarm")
|
|
733
|
+
}
|
|
734
|
+
// A due time with its default alert, then the urgent state on top of it.
|
|
735
|
+
try RK.perform(change, "setDueDateComponentsWithAlarmsIfNeeded:", parts as NSDateComponents, hasArgument: true)
|
|
736
|
+
if let notes = request["notes"] as? String, !notes.isEmpty {
|
|
737
|
+
try RK.perform(change, "setNotesAsString:", notes as NSString, hasArgument: true)
|
|
738
|
+
}
|
|
739
|
+
guard let urgent = try RK.object(change, "urgentAlarmContext") else { throw RK.missing("urgentAlarmContext") }
|
|
740
|
+
try RK.setBool(urgent, "setIsUrgentStateEnabledForCurrentUser:", true)
|
|
741
|
+
try RK.save(save)
|
|
742
|
+
// What Reminders actually kept, urgent state included. The alarm exists from
|
|
743
|
+
// here on, so a read that fails now is not a failure: reporting one would
|
|
744
|
+
// have the caller set it again, and the owner would get two.
|
|
745
|
+
let saved = ((try? remindersIn(rem, list)) ?? []).first { uuidOf($0) == id }
|
|
746
|
+
return ["ok": true, "alarm": saved.map(describeAlarm) ?? ["id": id, "title": title, "due": isoString(due.date), "urgent": true, "completed": false]]
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/// Alarms that rang a while ago stay open in Reminders (ringing does not
|
|
750
|
+
/// complete them) and would pile up as overdue items: mark them done.
|
|
751
|
+
func completeAlarms(_ request: [String: Any]) throws -> [String: Any] {
|
|
752
|
+
let rem = try reminderStore()
|
|
753
|
+
let list = try alarmList(rem, request["listId"])
|
|
754
|
+
let wanted = Set(((request["ids"] as? [Any]) ?? []).compactMap { ($0 as? String)?.uppercased() })
|
|
755
|
+
let open = try remindersIn(rem, list).filter {
|
|
756
|
+
guard let id = uuidOf($0), wanted.contains(id) else { return false }
|
|
757
|
+
return !((try? RK.bool($0, "isCompleted")) ?? false)
|
|
758
|
+
}
|
|
759
|
+
if open.isEmpty { return ["ok": true, "completed": 0] }
|
|
760
|
+
try beforeDeadline()
|
|
761
|
+
let save = try RK.make("REMSaveRequest", "initWithStore:", object: rem)
|
|
762
|
+
for reminder in open {
|
|
763
|
+
guard let change = try RK.object(save, "updateReminder:", reminder) else { throw RK.missing("updateReminder:") }
|
|
764
|
+
try RK.setBool(change, "setCompleted:", true)
|
|
765
|
+
}
|
|
766
|
+
try RK.save(save)
|
|
767
|
+
return ["ok": true, "completed": open.count]
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
func deleteAlarm(_ request: [String: Any]) throws -> [String: Any] {
|
|
771
|
+
let rem = try reminderStore()
|
|
772
|
+
let list = try alarmList(rem, request["listId"])
|
|
773
|
+
let id = ((request["id"] as? String) ?? "").uppercased()
|
|
774
|
+
guard let reminder = try remindersIn(rem, list).first(where: { uuidOf($0) == id }) else {
|
|
775
|
+
throw Failure(code: "no_alarm", message: "that alarm is not in the list any more")
|
|
776
|
+
}
|
|
777
|
+
let gone = describeAlarm(reminder)
|
|
778
|
+
try beforeDeadline()
|
|
779
|
+
let save = try RK.make("REMSaveRequest", "initWithStore:", object: rem)
|
|
780
|
+
guard let change = try RK.object(save, "updateReminder:", reminder) else { throw RK.missing("updateReminder:") }
|
|
781
|
+
try RK.perform(change, "removeFromList")
|
|
782
|
+
try RK.save(save)
|
|
783
|
+
return ["ok": true, "alarm": gone]
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/// What the alarm commands rely on, checked on the classes alone: no rem, no permission.
|
|
787
|
+
func reminderKitCheck() -> [String] {
|
|
788
|
+
guard (try? RK.load()) != nil else { return ["ReminderKit.framework"] }
|
|
789
|
+
let needs: [(String, String)] = [
|
|
790
|
+
("REMStore", "initUserInteractive:"),
|
|
791
|
+
("REMStore", "fetchEligibleDefaultListsWithError:"),
|
|
792
|
+
("REMStore", "fetchPrimaryActiveCloudKitAccountWithError:"),
|
|
793
|
+
("REMStore", "fetchRemindersForEventKitBridgingWithListIDs:error:"),
|
|
794
|
+
("REMSaveRequest", "initWithStore:"),
|
|
795
|
+
("REMSaveRequest", "updateAccount:"),
|
|
796
|
+
("REMSaveRequest", "updateList:"),
|
|
797
|
+
("REMSaveRequest", "updateReminder:"),
|
|
798
|
+
("REMSaveRequest", "addListWithName:toAccountChangeItem:listObjectID:"),
|
|
799
|
+
("REMSaveRequest", "addReminderWithTitle:toListChangeItem:"),
|
|
800
|
+
("REMSaveRequest", "saveSynchronouslyWithError:"),
|
|
801
|
+
("REMAccount", "capabilities"),
|
|
802
|
+
("REMAccountCapabilities", "supportsUrgentAlarm"),
|
|
803
|
+
("REMAccountStorage", "name"),
|
|
804
|
+
("REMListStorage", "name"),
|
|
805
|
+
("REMListStorage", "objectID"),
|
|
806
|
+
("REMListStorage", "isGroup"),
|
|
807
|
+
("REMReminderStorage", "objectID"),
|
|
808
|
+
("REMReminderStorage", "titleAsString"),
|
|
809
|
+
("REMReminderStorage", "dueDateComponents"),
|
|
810
|
+
("REMReminderStorage", "isCompleted"),
|
|
811
|
+
("REMReminderStorage", "isUrgentStateEnabledForCurrentUser"),
|
|
812
|
+
("REMReminderStorage", "setIsUrgentStateEnabledForCurrentUser:"),
|
|
813
|
+
("REMReminderStorage", "notesAsString"),
|
|
814
|
+
("REMReminderStorage", "setNotesAsString:"),
|
|
815
|
+
("REMReminderStorage", "setCompleted:"),
|
|
816
|
+
("REMAccountStorage", "objectID"),
|
|
817
|
+
("REMReminderChangeItem", "setDueDateComponentsWithAlarmsIfNeeded:"),
|
|
818
|
+
("REMReminderChangeItem", "setNotesAsString:"),
|
|
819
|
+
("REMReminderChangeItem", "urgentAlarmContext"),
|
|
820
|
+
("REMReminderChangeItem", "removeFromList"),
|
|
821
|
+
("REMReminderChangeItem", "setCompleted:"),
|
|
822
|
+
("REMList", "account"),
|
|
823
|
+
("REMReminderUrgentAlarmContextChangeItem", "setIsUrgentStateEnabledForCurrentUser:"),
|
|
824
|
+
("REMObjectID", "uuid"),
|
|
825
|
+
]
|
|
826
|
+
return needs.compactMap { cls, sel in
|
|
827
|
+
guard let c: AnyClass = NSClassFromString(cls) else { return cls }
|
|
828
|
+
return class_getInstanceMethod(c, NSSelectorFromString(sel)) == nil ? "\(cls).\(sel)" : nil
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// MARK: - Commands
|
|
833
|
+
|
|
834
|
+
func handle(_ request: [String: Any]) throws -> [String: Any] {
|
|
835
|
+
if let id = request["timeZone"] as? String, let tz = TimeZone(identifier: id) {
|
|
836
|
+
zone = tz
|
|
837
|
+
// EventKit floats all-day dates in the process's default zone: keep it the same.
|
|
838
|
+
NSTimeZone.default = tz
|
|
839
|
+
}
|
|
840
|
+
let cmd = request["cmd"] as? String ?? ""
|
|
841
|
+
switch cmd {
|
|
842
|
+
case "status":
|
|
843
|
+
let missing = reminderKitCheck()
|
|
844
|
+
var out: [String: Any] = ["ok": true, "authorization": authorization(), "reminders": remindersAuthorization(),
|
|
845
|
+
"protocol": helperProtocol, "alarms": missing.isEmpty ? "supported" : "unsupported"]
|
|
846
|
+
if !missing.isEmpty { out["missing"] = missing }
|
|
847
|
+
return out
|
|
848
|
+
|
|
849
|
+
case "request":
|
|
850
|
+
// Both prompts in one go, while the owner is at the Mac: one for the
|
|
851
|
+
// calendar, then one for reminders (alarms). Each shows only once. No
|
|
852
|
+
// reminders prompt where urgent alarms cannot work: it would ask for nothing.
|
|
853
|
+
let wait = (request["waitSeconds"] as? NSNumber)?.doubleValue ?? 120
|
|
854
|
+
if (request["calendar"] as? Bool ?? true) && authorization() == "notDetermined" {
|
|
855
|
+
var finished = false
|
|
856
|
+
store.requestFullAccessToEvents { _, _ in finished = true }
|
|
857
|
+
_ = waitFor(seconds: wait) { finished }
|
|
858
|
+
}
|
|
859
|
+
if (request["reminders"] as? Bool ?? true) && remindersAuthorization() == "notDetermined" && reminderKitCheck().isEmpty {
|
|
860
|
+
var finished = false
|
|
861
|
+
store.requestFullAccessToReminders { _, _ in finished = true }
|
|
862
|
+
_ = waitFor(seconds: wait) { finished }
|
|
863
|
+
}
|
|
864
|
+
return ["ok": true, "authorization": authorization(), "reminders": remindersAuthorization(), "protocol": helperProtocol]
|
|
865
|
+
|
|
866
|
+
case "ensureAlarmList":
|
|
867
|
+
return try ensureAlarmList(request)
|
|
868
|
+
|
|
869
|
+
case "alarmAdd":
|
|
870
|
+
return try addAlarm(request)
|
|
871
|
+
|
|
872
|
+
case "alarms":
|
|
873
|
+
let rem = try reminderStore()
|
|
874
|
+
let list = try alarmList(rem, request["listId"])
|
|
875
|
+
return ["ok": true, "alarms": try remindersIn(rem, list).map(describeAlarm), "list": describeList(list)]
|
|
876
|
+
|
|
877
|
+
case "alarmDelete":
|
|
878
|
+
return try deleteAlarm(request)
|
|
879
|
+
|
|
880
|
+
case "alarmComplete":
|
|
881
|
+
return try completeAlarms(request)
|
|
882
|
+
|
|
883
|
+
case "rkcheck":
|
|
884
|
+
return ["ok": true, "missing": reminderKitCheck(), "protocol": helperProtocol]
|
|
885
|
+
|
|
886
|
+
case "calendars":
|
|
887
|
+
try requireFullAccess()
|
|
888
|
+
return ["ok": true, "calendars": eventCalendars().map(describe)]
|
|
889
|
+
|
|
890
|
+
case "events":
|
|
891
|
+
try requireFullAccess()
|
|
892
|
+
let from = try parseTime(request["from"], field: "from").date
|
|
893
|
+
let to = try parseTime(request["to"], field: "to").date
|
|
894
|
+
guard to > from else { throw Failure(code: "bad_request", message: "to must be after from") }
|
|
895
|
+
// 92 calendar days, with room for a daylight-saving hour.
|
|
896
|
+
guard to.timeIntervalSince(from) <= 92 * 86_400 + 3_600 else {
|
|
897
|
+
throw Failure(code: "bad_request", message: "at most 92 days at a time")
|
|
898
|
+
}
|
|
899
|
+
let predicate = store.predicateForEvents(withStart: from, end: to, calendars: nil)
|
|
900
|
+
let events = store.events(matching: predicate).sorted { $0.startDate < $1.startDate }
|
|
901
|
+
return ["ok": true, "events": events.map(describe), "calendars": eventCalendars().map(describe)]
|
|
902
|
+
|
|
903
|
+
case "ensureCalendar":
|
|
904
|
+
try requireFullAccess()
|
|
905
|
+
return try ensureCalendar(request)
|
|
906
|
+
|
|
907
|
+
case "add":
|
|
908
|
+
try requireFullAccess()
|
|
909
|
+
let cal = try calendar(id: request["calendarId"] as? String ?? "")
|
|
910
|
+
guard cal.allowsContentModifications else {
|
|
911
|
+
throw Failure(code: "read_only", message: "calendar \(cal.title) is read-only")
|
|
912
|
+
}
|
|
913
|
+
guard let title = request["title"] as? String, !title.isEmpty else {
|
|
914
|
+
throw Failure(code: "bad_request", message: "title is missing")
|
|
915
|
+
}
|
|
916
|
+
let event = EKEvent(eventStore: store)
|
|
917
|
+
event.calendar = cal
|
|
918
|
+
try applyFields(event, request, creating: true)
|
|
919
|
+
try beforeDeadline()
|
|
920
|
+
try store.save(event, span: .thisEvent, commit: true)
|
|
921
|
+
return ["ok": true, "event": describe(event),
|
|
922
|
+
"overlaps": overlaps(event.startDate, event.endDate, except: event.eventIdentifier)]
|
|
923
|
+
|
|
924
|
+
case "update":
|
|
925
|
+
try requireFullAccess()
|
|
926
|
+
let event = try target(request)
|
|
927
|
+
if let moveTo = request["calendarId"] as? String, moveTo != event.calendar.calendarIdentifier {
|
|
928
|
+
let moved = try calendar(id: moveTo)
|
|
929
|
+
guard moved.allowsContentModifications else {
|
|
930
|
+
throw Failure(code: "read_only", message: "calendar \(moved.title) is read-only")
|
|
931
|
+
}
|
|
932
|
+
event.calendar = moved
|
|
933
|
+
}
|
|
934
|
+
try applyFields(event, request, creating: false)
|
|
935
|
+
try beforeDeadline()
|
|
936
|
+
try store.save(event, span: span(request), commit: true)
|
|
937
|
+
return ["ok": true, "event": describe(event),
|
|
938
|
+
"overlaps": overlaps(event.startDate, event.endDate, except: event.eventIdentifier)]
|
|
939
|
+
|
|
940
|
+
case "delete":
|
|
941
|
+
try requireFullAccess()
|
|
942
|
+
let event = try target(request)
|
|
943
|
+
let gone = describe(event)
|
|
944
|
+
try beforeDeadline()
|
|
945
|
+
try store.remove(event, span: span(request), commit: true)
|
|
946
|
+
return ["ok": true, "event": gone]
|
|
947
|
+
|
|
948
|
+
case "selftest":
|
|
949
|
+
// Runs applyFields on events that are never saved: needs no permission and
|
|
950
|
+
// touches no calendar. Lets the tests check EventKit's real date rules
|
|
951
|
+
// (all-day ends are inclusive) instead of a fake's.
|
|
952
|
+
var results: [[String: Any]] = []
|
|
953
|
+
for c in (request["cases"] as? [[String: Any]]) ?? [] {
|
|
954
|
+
let event = EKEvent(eventStore: store)
|
|
955
|
+
var row: [String: Any] = ["name": c["name"] as? String ?? ""]
|
|
956
|
+
do {
|
|
957
|
+
if let setup = c["setup"] as? [String: Any] { try applyFields(event, setup, creating: true) }
|
|
958
|
+
try applyFields(event, c["fields"] as? [String: Any] ?? [:], creating: c["setup"] == nil)
|
|
959
|
+
row["start"] = isoString(event.startDate)
|
|
960
|
+
row["end"] = isoString(event.endDate)
|
|
961
|
+
row["allDay"] = event.isAllDay
|
|
962
|
+
row["alerts"] = (event.alarms ?? []).compactMap(alertMinutes)
|
|
963
|
+
if let notes = event.notes { row["notes"] = notes }
|
|
964
|
+
} catch let f as Failure {
|
|
965
|
+
row["error"] = f.code
|
|
966
|
+
}
|
|
967
|
+
results.append(row)
|
|
968
|
+
}
|
|
969
|
+
return ["ok": true, "results": results]
|
|
970
|
+
|
|
971
|
+
default:
|
|
972
|
+
throw Failure(code: "bad_request", message: "unknown command \(cmd)")
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
// MARK: - Main
|
|
977
|
+
|
|
978
|
+
guard let requestPath = argument("--request"), let responsePath = argument("--response") else {
|
|
979
|
+
FileHandle.standardError.write(Data("usage: Clawbot-Calendar --request <file> --response <file>\n".utf8))
|
|
980
|
+
exit(2)
|
|
981
|
+
}
|
|
982
|
+
do {
|
|
983
|
+
let data = try Data(contentsOf: URL(fileURLWithPath: requestPath))
|
|
984
|
+
guard let request = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
|
985
|
+
throw Failure(code: "bad_request", message: "request is not a JSON object")
|
|
986
|
+
}
|
|
987
|
+
if let ms = (request["deadline"] as? NSNumber)?.doubleValue {
|
|
988
|
+
let at = Date(timeIntervalSince1970: ms / 1000)
|
|
989
|
+
deadline = at
|
|
990
|
+
// Answer before the caller stops waiting, even if EventKit hangs: a write
|
|
991
|
+
// that lands after the caller gave up would be reported as a failure.
|
|
992
|
+
let wait = max(0.5, at.timeIntervalSinceNow)
|
|
993
|
+
DispatchQueue.global().asyncAfter(deadline: .now() + wait) {
|
|
994
|
+
// Unlike a refusal before committing ("deadline"), this one cannot know
|
|
995
|
+
// whether a save already in progress went through.
|
|
996
|
+
respond(["ok": false, "code": "timeout", "error": "took too long; a change may or may not have been saved"], to: responsePath)
|
|
997
|
+
exit(0)
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
respond(try handle(request), to: responsePath)
|
|
1001
|
+
} catch let failure as Failure {
|
|
1002
|
+
respond(["ok": false, "code": failure.code, "error": failure.message], to: responsePath)
|
|
1003
|
+
} catch {
|
|
1004
|
+
respond(["ok": false, "code": "error", "error": error.localizedDescription], to: responsePath)
|
|
1005
|
+
}
|
|
1006
|
+
exit(0)
|