@windowkit/appkit 0.6.0 → 0.8.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 +242 -7
- package/binding.gyp +4 -2
- package/index.js +94 -7
- package/package.json +2 -2
- package/prebuilds/darwin-arm64/calayers.node +0 -0
- package/prebuilds/darwin-x64/calayers.node +0 -0
- package/src/addon.mm +4 -0
- package/src/backend.mm +148 -1
- package/src/calendars.mm +1706 -0
- package/src/permissions.mm +181 -31
package/src/calendars.mm
ADDED
|
@@ -0,0 +1,1706 @@
|
|
|
1
|
+
// @windowkit/appkit calendars.mm — the user's calendars, the occurrences in
|
|
2
|
+
// a date range, and the writes — an event put in, changed, or taken out —
|
|
3
|
+
// through EventKit (EKEventStore).
|
|
4
|
+
//
|
|
5
|
+
// Every account the user added in System Settings › Internet Accounts —
|
|
6
|
+
// iCloud, Google, Exchange, CalDAV, a subscribed feed — is served by this one
|
|
7
|
+
// framework, the macOS counterpart of Evolution Data Server plus GNOME Online
|
|
8
|
+
// Accounts: the desktop did the OAuth, and the app never sees a credential.
|
|
9
|
+
//
|
|
10
|
+
// calendars(cb) cb(err, [calendar])
|
|
11
|
+
// eventsBetween({ start, end, calendars? }, cb) cb(err, [event]) — epoch ms
|
|
12
|
+
// defaultCalendar(cb) cb(err, calendar | null)
|
|
13
|
+
// saveEvent(props, opts?, cb) cb(err, id)
|
|
14
|
+
// removeEvent(id, opts?, cb) cb(err)
|
|
15
|
+
// commitCalendarStore(cb) cb(err) — a batch saved with commit: false
|
|
16
|
+
// resetCalendarStore(cb) cb(null) — forgets such a batch
|
|
17
|
+
// event: calendar-store-changed {} EKEventStoreChangedNotification
|
|
18
|
+
//
|
|
19
|
+
// Mechanism only, policy stays in the renderer: which calendars to show, how
|
|
20
|
+
// to render an all-day span, when to re-query, what to put in an event.
|
|
21
|
+
//
|
|
22
|
+
// Three things EventKit does that a D-Bus (Evolution) rung has to do for
|
|
23
|
+
// itself: the predicate answers *occurrences*, so recurrences are already
|
|
24
|
+
// expanded and no iCalendar parser is needed here; one notification is posted
|
|
25
|
+
// for any change at all, whose documented contract is "re-fetch"; and it
|
|
26
|
+
// answers fast enough not to matter as long as the fetch is off the JS
|
|
27
|
+
// thread.
|
|
28
|
+
//
|
|
29
|
+
// Threading. eventsMatchingPredicate: is synchronous and can take a while
|
|
30
|
+
// over many calendars, so both reads run on a background queue and answer
|
|
31
|
+
// through a thread-safe function — the automation request in permissions.mm
|
|
32
|
+
// is the shape. Fetches are documented thread-safe on EKEventStore; the
|
|
33
|
+
// store itself is taken on the JS thread (it is a process-wide singleton,
|
|
34
|
+
// and reaching for it from two queues at once would be a race), and what the
|
|
35
|
+
// framework hands back is copied into the plain C++ shapes below on the
|
|
36
|
+
// background queue, so nothing EventKit-owned crosses to JS. The writes take
|
|
37
|
+
// a serial queue of their own at the same QoS: off the JS thread like the
|
|
38
|
+
// reads, but one after another, so a batch — saves with commit: false, then
|
|
39
|
+
// commitCalendarStore — is applied in the order it was asked, and two saves
|
|
40
|
+
// never touch the store at once.
|
|
41
|
+
//
|
|
42
|
+
// All-day events cross as the store reports them: allDay true, startDate at
|
|
43
|
+
// local midnight and endDate at the last second of the last day. Normalising
|
|
44
|
+
// that to an exclusive end is the renderer's job; the bridge is mechanism,
|
|
45
|
+
// and its test pins the convention so the renderer's normalisation has
|
|
46
|
+
// something to be checked against. A write takes the same convention.
|
|
47
|
+
//
|
|
48
|
+
// A store without a grant answers cb(err) naming the status — never [] — so
|
|
49
|
+
// "no events" and "not allowed to look" stay distinguishable. The grant
|
|
50
|
+
// itself is permissions.mm's ('calendars', windowkit/appkit#39); the store is
|
|
51
|
+
// shared with it, and no verb here prompts. Reading needs the full grant; a
|
|
52
|
+
// write is content with macOS 14's write-only one, which is why #39 carries
|
|
53
|
+
// { access }.
|
|
54
|
+
//
|
|
55
|
+
// A write. A new EKEvent comes from eventWithEventStore:, an existing one
|
|
56
|
+
// from eventWithIdentifier: — the first occurrence of a recurring event, or
|
|
57
|
+
// the occurrence at props.occurrenceDate, found through the same predicate
|
|
58
|
+
// the reads use — and goes to saveEvent:span:commit:error: /
|
|
59
|
+
// removeEvent:span:commit:error:. What the framework refuses crosses as the
|
|
60
|
+
// EKErrorDomain code and message (EKErrorCalendarReadOnly, EKErrorNoCalendar,
|
|
61
|
+
// EKErrorDatesInverted, …), never as a bare boolean; what it *raises* — a
|
|
62
|
+
// recurrence it cannot build, an object from another store — is caught and
|
|
63
|
+
// crosses the same way rather than ending the process, since an exception
|
|
64
|
+
// escaping a dispatch block is fatal. The recurrence shape is
|
|
65
|
+
// EKRecurrenceRule's own vocabulary, what its initialisers take, not an
|
|
66
|
+
// RRULE string: a consumer holding iCalendar text parses it on its own side,
|
|
67
|
+
// and the bridge carries no grammar. A successful commit is followed by the
|
|
68
|
+
// store's own change notification, which is how the reader learns of it —
|
|
69
|
+
// and how the consumer's own change and someone else's look the same.
|
|
70
|
+
//
|
|
71
|
+
// A store holding only the write-only grant can save but not read back:
|
|
72
|
+
// eventWithIdentifier: answers nil there, so changing or removing an event
|
|
73
|
+
// by id is refused as the EKError it is (EKErrorEventStoreNotAuthorized)
|
|
74
|
+
// rather than reported as success.
|
|
75
|
+
//
|
|
76
|
+
// The change observer is installed when that store is created, so it is in
|
|
77
|
+
// place before any listener could be; the event goes out through the same
|
|
78
|
+
// backend callback every other event takes, and one that arrives before
|
|
79
|
+
// there is a listener is held and replayed at the next pump, as
|
|
80
|
+
// notifications.mm does. The framework coalesces changes, and a duplicate is
|
|
81
|
+
// harmless to a renderer whose answer to one is to re-query.
|
|
82
|
+
|
|
83
|
+
#include <napi.h>
|
|
84
|
+
#import <Cocoa/Cocoa.h>
|
|
85
|
+
#import <EventKit/EventKit.h>
|
|
86
|
+
|
|
87
|
+
#include <cmath>
|
|
88
|
+
#include <cstdint>
|
|
89
|
+
#include <cstring>
|
|
90
|
+
#include <optional>
|
|
91
|
+
#include <string>
|
|
92
|
+
#include <utility>
|
|
93
|
+
#include <vector>
|
|
94
|
+
|
|
95
|
+
// backend.mm: the one backend event callback
|
|
96
|
+
bool CALHasBackendCb();
|
|
97
|
+
void CALEmitBackendEvent(Napi::Env env, Napi::Object ev);
|
|
98
|
+
|
|
99
|
+
// permissions.mm: the process's one EKEventStore — created by the first
|
|
100
|
+
// EventKit verb and never before, since creating one never prompts — and
|
|
101
|
+
// EventKit's authorization word for events, Apple's mapping kept in one
|
|
102
|
+
// place.
|
|
103
|
+
EKEventStore* CALEventStore();
|
|
104
|
+
const char* CALEventsAuthorizationStatus();
|
|
105
|
+
|
|
106
|
+
// EventKit's own limit on predicateForEventsWithStartDate:endDate:calendars:
|
|
107
|
+
// is a four-year span, taken here as 1461 days (four years with one leap
|
|
108
|
+
// day). A longer request is refused at the bridge rather than silently
|
|
109
|
+
// truncated by the framework; the renderer chunks.
|
|
110
|
+
static const double kMaxSpanMs = 1461.0 * 24 * 60 * 60 * 1000;
|
|
111
|
+
|
|
112
|
+
// Where to look for one occurrence of a recurring event: the predicate's
|
|
113
|
+
// widest span, centred on the occurrence's place in the series. A detached
|
|
114
|
+
// occurrence lives where it was moved to, not where the series put it, and
|
|
115
|
+
// this finds one moved by up to two years either way.
|
|
116
|
+
static const double kOccurrenceWindowS = 730.0 * 24 * 60 * 60;
|
|
117
|
+
|
|
118
|
+
// --- Apple's enums, as words -----------------------------------------------
|
|
119
|
+
|
|
120
|
+
static const char* CalendarTypeName(EKCalendarType t) {
|
|
121
|
+
switch (t) {
|
|
122
|
+
case EKCalendarTypeCalDAV: return "calDAV";
|
|
123
|
+
case EKCalendarTypeExchange: return "exchange";
|
|
124
|
+
case EKCalendarTypeSubscription: return "subscription";
|
|
125
|
+
case EKCalendarTypeBirthday: return "birthday";
|
|
126
|
+
case EKCalendarTypeLocal:
|
|
127
|
+
default: return "local";
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
static const char* SourceTypeName(EKSourceType t) {
|
|
132
|
+
switch (t) {
|
|
133
|
+
case EKSourceTypeExchange: return "exchange";
|
|
134
|
+
case EKSourceTypeCalDAV: return "calDAV";
|
|
135
|
+
case EKSourceTypeMobileMe: return "mobileMe";
|
|
136
|
+
case EKSourceTypeSubscribed: return "subscribed";
|
|
137
|
+
case EKSourceTypeBirthdays: return "birthdays";
|
|
138
|
+
case EKSourceTypeLocal:
|
|
139
|
+
default: return "local";
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
static const char* EventStatusName(EKEventStatus s) {
|
|
144
|
+
switch (s) {
|
|
145
|
+
case EKEventStatusConfirmed: return "confirmed";
|
|
146
|
+
case EKEventStatusTentative: return "tentative";
|
|
147
|
+
case EKEventStatusCanceled: return "cancelled";
|
|
148
|
+
case EKEventStatusNone:
|
|
149
|
+
default: return "none";
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
static const char* AvailabilityName(EKEventAvailability a) {
|
|
154
|
+
switch (a) {
|
|
155
|
+
case EKEventAvailabilityBusy: return "busy";
|
|
156
|
+
case EKEventAvailabilityFree: return "free";
|
|
157
|
+
case EKEventAvailabilityTentative: return "tentative";
|
|
158
|
+
case EKEventAvailabilityUnavailable: return "unavailable";
|
|
159
|
+
case EKEventAvailabilityNotSupported:
|
|
160
|
+
default: return "notSupported";
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
static const char* ParticipantStatusName(EKParticipantStatus s) {
|
|
165
|
+
switch (s) {
|
|
166
|
+
case EKParticipantStatusPending: return "pending";
|
|
167
|
+
case EKParticipantStatusAccepted: return "accepted";
|
|
168
|
+
case EKParticipantStatusDeclined: return "declined";
|
|
169
|
+
case EKParticipantStatusTentative: return "tentative";
|
|
170
|
+
case EKParticipantStatusDelegated: return "delegated";
|
|
171
|
+
case EKParticipantStatusCompleted: return "completed";
|
|
172
|
+
case EKParticipantStatusInProcess: return "inProcess";
|
|
173
|
+
case EKParticipantStatusUnknown:
|
|
174
|
+
default: return "unknown";
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
static const char* ParticipantRoleName(EKParticipantRole r) {
|
|
179
|
+
switch (r) {
|
|
180
|
+
case EKParticipantRoleRequired: return "required";
|
|
181
|
+
case EKParticipantRoleOptional: return "optional";
|
|
182
|
+
case EKParticipantRoleChair: return "chair";
|
|
183
|
+
case EKParticipantRoleNonParticipant: return "nonParticipant";
|
|
184
|
+
case EKParticipantRoleUnknown:
|
|
185
|
+
default: return "unknown";
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
static const char* ParticipantTypeName(EKParticipantType t) {
|
|
190
|
+
switch (t) {
|
|
191
|
+
case EKParticipantTypePerson: return "person";
|
|
192
|
+
case EKParticipantTypeRoom: return "room";
|
|
193
|
+
case EKParticipantTypeResource: return "resource";
|
|
194
|
+
case EKParticipantTypeGroup: return "group";
|
|
195
|
+
case EKParticipantTypeUnknown:
|
|
196
|
+
default: return "unknown";
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
static const char* FrequencyName(EKRecurrenceFrequency f) {
|
|
201
|
+
switch (f) {
|
|
202
|
+
case EKRecurrenceFrequencyWeekly: return "weekly";
|
|
203
|
+
case EKRecurrenceFrequencyMonthly: return "monthly";
|
|
204
|
+
case EKRecurrenceFrequencyYearly: return "yearly";
|
|
205
|
+
case EKRecurrenceFrequencyDaily:
|
|
206
|
+
default: return "daily";
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
static bool ParseFrequency(const std::string& s, EKRecurrenceFrequency* out) {
|
|
211
|
+
if (s == "daily") *out = EKRecurrenceFrequencyDaily;
|
|
212
|
+
else if (s == "weekly") *out = EKRecurrenceFrequencyWeekly;
|
|
213
|
+
else if (s == "monthly") *out = EKRecurrenceFrequencyMonthly;
|
|
214
|
+
else if (s == "yearly") *out = EKRecurrenceFrequencyYearly;
|
|
215
|
+
else return false;
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// The four a consumer can set; notSupported is what a source answers, not a
|
|
220
|
+
// thing to ask for.
|
|
221
|
+
static bool ParseAvailability(const std::string& s, EKEventAvailability* out) {
|
|
222
|
+
if (s == "busy") *out = EKEventAvailabilityBusy;
|
|
223
|
+
else if (s == "free") *out = EKEventAvailabilityFree;
|
|
224
|
+
else if (s == "tentative") *out = EKEventAvailabilityTentative;
|
|
225
|
+
else if (s == "unavailable") *out = EKEventAvailabilityUnavailable;
|
|
226
|
+
else return false;
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// EKErrorCode's names, so an error crosses as the word the framework's own
|
|
231
|
+
// header uses and not only as its number. nullptr for a code this SDK's
|
|
232
|
+
// header does not name.
|
|
233
|
+
static const char* EKErrorName(NSInteger code) {
|
|
234
|
+
switch (code) {
|
|
235
|
+
#define EK(name) case name: return #name;
|
|
236
|
+
EK(EKErrorEventNotMutable)
|
|
237
|
+
EK(EKErrorNoCalendar)
|
|
238
|
+
EK(EKErrorNoStartDate)
|
|
239
|
+
EK(EKErrorNoEndDate)
|
|
240
|
+
EK(EKErrorDatesInverted)
|
|
241
|
+
EK(EKErrorInternalFailure)
|
|
242
|
+
EK(EKErrorCalendarReadOnly)
|
|
243
|
+
EK(EKErrorDurationGreaterThanRecurrence)
|
|
244
|
+
EK(EKErrorAlarmGreaterThanRecurrence)
|
|
245
|
+
EK(EKErrorStartDateTooFarInFuture)
|
|
246
|
+
EK(EKErrorStartDateCollidesWithOtherOccurrence)
|
|
247
|
+
EK(EKErrorObjectBelongsToDifferentStore)
|
|
248
|
+
EK(EKErrorInvitesCannotBeMoved)
|
|
249
|
+
EK(EKErrorInvalidSpan)
|
|
250
|
+
EK(EKErrorCalendarHasNoSource)
|
|
251
|
+
EK(EKErrorCalendarSourceCannotBeModified)
|
|
252
|
+
EK(EKErrorCalendarIsImmutable)
|
|
253
|
+
EK(EKErrorSourceDoesNotAllowCalendarAddDelete)
|
|
254
|
+
EK(EKErrorRecurringReminderRequiresDueDate)
|
|
255
|
+
EK(EKErrorStructuredLocationsNotSupported)
|
|
256
|
+
EK(EKErrorReminderLocationsNotSupported)
|
|
257
|
+
EK(EKErrorAlarmProximityNotSupported)
|
|
258
|
+
EK(EKErrorCalendarDoesNotAllowEvents)
|
|
259
|
+
EK(EKErrorCalendarDoesNotAllowReminders)
|
|
260
|
+
EK(EKErrorSourceDoesNotAllowReminders)
|
|
261
|
+
EK(EKErrorSourceDoesNotAllowEvents)
|
|
262
|
+
EK(EKErrorPriorityIsInvalid)
|
|
263
|
+
EK(EKErrorInvalidEntityType)
|
|
264
|
+
EK(EKErrorProcedureAlarmsNotMutable)
|
|
265
|
+
EK(EKErrorEventStoreNotAuthorized)
|
|
266
|
+
EK(EKErrorOSNotSupported)
|
|
267
|
+
EK(EKErrorInvalidInviteReplyCalendar)
|
|
268
|
+
EK(EKErrorNotificationsCollectionFlagNotSet)
|
|
269
|
+
EK(EKErrorSourceMismatch)
|
|
270
|
+
EK(EKErrorNotificationCollectionMismatch)
|
|
271
|
+
EK(EKErrorNotificationSavedWithoutCollection)
|
|
272
|
+
EK(EKErrorReminderAlarmContainsEmailOrUrl)
|
|
273
|
+
#undef EK
|
|
274
|
+
default: return nullptr;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// --- what the framework said, copied out of it ------------------------------
|
|
279
|
+
|
|
280
|
+
// A field the store may not have: it crosses as null rather than as an empty
|
|
281
|
+
// string, so "no location" and "an empty location" stay apart.
|
|
282
|
+
using MaybeString = std::optional<std::string>;
|
|
283
|
+
|
|
284
|
+
static MaybeString Copy(NSString* s) {
|
|
285
|
+
if (!s) return std::nullopt;
|
|
286
|
+
const char* c = s.UTF8String;
|
|
287
|
+
if (!c) return std::nullopt;
|
|
288
|
+
return std::string(c);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
static MaybeString Copy(NSURL* u) { return Copy(u.absoluteString); }
|
|
292
|
+
|
|
293
|
+
static std::string CopyRequired(NSString* s) {
|
|
294
|
+
MaybeString m = Copy(s);
|
|
295
|
+
return m ? *m : std::string();
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Epoch ms, as the store reports the date.
|
|
299
|
+
static double Millis(NSDate* d) { return d.timeIntervalSince1970 * 1000.0; }
|
|
300
|
+
|
|
301
|
+
// A calendar's colour in sRGB, the space every colour crosses this bridge in
|
|
302
|
+
// (the 0.5.1 rule) — EKCalendar keeps a CGColor whose space is whatever the
|
|
303
|
+
// account gave it.
|
|
304
|
+
static bool CopyColor(CGColorRef c, double out[4]) {
|
|
305
|
+
if (!c) return false;
|
|
306
|
+
CGColorSpaceRef rgb = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
|
|
307
|
+
CGColorRef conv = CGColorCreateCopyByMatchingToColorSpace(
|
|
308
|
+
rgb, kCGRenderingIntentDefault, c, NULL);
|
|
309
|
+
CGColorSpaceRelease(rgb);
|
|
310
|
+
CGColorRef src = conv ? conv : c;
|
|
311
|
+
const CGFloat* comps = CGColorGetComponents(src);
|
|
312
|
+
size_t n = CGColorGetNumberOfComponents(src);
|
|
313
|
+
bool ok = true;
|
|
314
|
+
if (n == 4) {
|
|
315
|
+
for (int i = 0; i < 4; i++) out[i] = (double)comps[i];
|
|
316
|
+
} else if (n == 2) { // greyscale
|
|
317
|
+
out[0] = out[1] = out[2] = (double)comps[0];
|
|
318
|
+
out[3] = (double)comps[1];
|
|
319
|
+
} else {
|
|
320
|
+
ok = false;
|
|
321
|
+
}
|
|
322
|
+
if (conv) CGColorRelease(conv);
|
|
323
|
+
return ok;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
struct CalInfo {
|
|
327
|
+
std::string id, title;
|
|
328
|
+
bool hasColor = false;
|
|
329
|
+
double color[4] = {0, 0, 0, 0};
|
|
330
|
+
const char* type = "local";
|
|
331
|
+
std::string sourceId, sourceTitle;
|
|
332
|
+
const char* sourceType = "local";
|
|
333
|
+
bool immutable = false, allowsModifications = false, subscribed = false;
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
struct CalParticipant {
|
|
337
|
+
MaybeString name, url;
|
|
338
|
+
const char* status = "unknown";
|
|
339
|
+
const char* role = "unknown";
|
|
340
|
+
const char* type = "unknown";
|
|
341
|
+
bool isCurrentUser = false;
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
// A recurrence rule in EKRecurrenceRule's own vocabulary — what its
|
|
345
|
+
// designated initialiser takes — the same shape read and written. The arrays
|
|
346
|
+
// are absent rather than empty when the rule has none.
|
|
347
|
+
struct DayOfWeek {
|
|
348
|
+
int day = 1; // 1..7, Sunday = 1 (EKWeekday)
|
|
349
|
+
int week = 0; // 0: every such day; ±1..: the nth (from the end) in the period
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
struct RuleInfo {
|
|
353
|
+
EKRecurrenceFrequency frequency = EKRecurrenceFrequencyDaily;
|
|
354
|
+
int interval = 1;
|
|
355
|
+
std::optional<double> until; // epoch ms; or
|
|
356
|
+
std::optional<uint32_t> count; // occurrences; neither: never ends
|
|
357
|
+
std::optional<std::vector<DayOfWeek>> daysOfWeek;
|
|
358
|
+
std::optional<std::vector<int>> daysOfMonth, monthsOfYear, weeksOfYear,
|
|
359
|
+
daysOfYear, setPositions;
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
// An alarm: relative to the start (seconds, negative before it) or absolute.
|
|
363
|
+
struct AlarmInfo {
|
|
364
|
+
bool absolute = false;
|
|
365
|
+
double value = 0; // seconds from the start, or epoch ms when absolute
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
struct CalEventInfo {
|
|
369
|
+
MaybeString id, itemId, externalId;
|
|
370
|
+
std::string calendar;
|
|
371
|
+
MaybeString title, location, notes, url, timeZone;
|
|
372
|
+
double start = 0, end = 0;
|
|
373
|
+
bool allDay = false;
|
|
374
|
+
const char* status = "none";
|
|
375
|
+
const char* availability = "notSupported";
|
|
376
|
+
bool recurring = false, detached = false;
|
|
377
|
+
std::optional<double> occurrenceDate;
|
|
378
|
+
std::optional<CalParticipant> organizer;
|
|
379
|
+
std::optional<std::vector<CalParticipant>> attendees;
|
|
380
|
+
std::optional<RuleInfo> recurrence;
|
|
381
|
+
std::optional<std::vector<AlarmInfo>> alarms;
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
// One verb's answer, all plain C++: an error, or what the verb answers with.
|
|
385
|
+
// Every verb shares it so there is one path from a background queue back to
|
|
386
|
+
// JS.
|
|
387
|
+
enum class Answer { Calendars, Events, Calendar, Id, Done };
|
|
388
|
+
|
|
389
|
+
struct CalAnswer {
|
|
390
|
+
std::string error; // non-empty: cb(err)
|
|
391
|
+
// the framework's own coordinates for the error, when it was its
|
|
392
|
+
bool fromFramework = false;
|
|
393
|
+
double code = 0;
|
|
394
|
+
std::string domain;
|
|
395
|
+
MaybeString reason; // the EKErrorCode's name, when the header has one
|
|
396
|
+
Answer kind = Answer::Calendars;
|
|
397
|
+
std::vector<CalInfo> calendars;
|
|
398
|
+
std::vector<CalEventInfo> events;
|
|
399
|
+
std::optional<CalInfo> calendar;
|
|
400
|
+
MaybeString id;
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
static void SetFrameworkError(CalAnswer* a, const char* fn, NSError* e) {
|
|
404
|
+
const char* name =
|
|
405
|
+
[e.domain isEqualToString:EKErrorDomain] ? EKErrorName(e.code) : nullptr;
|
|
406
|
+
a->error = std::string(fn) + ": " + CopyRequired(e.localizedDescription);
|
|
407
|
+
if (name) a->error += std::string(" (") + name + ")";
|
|
408
|
+
a->fromFramework = true;
|
|
409
|
+
a->code = (double)e.code;
|
|
410
|
+
a->domain = CopyRequired(e.domain);
|
|
411
|
+
if (name) a->reason = std::string(name);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
static CalParticipant CopyParticipant(EKParticipant* p) {
|
|
415
|
+
CalParticipant c;
|
|
416
|
+
c.name = Copy(p.name);
|
|
417
|
+
c.url = Copy(p.URL);
|
|
418
|
+
c.status = ParticipantStatusName(p.participantStatus);
|
|
419
|
+
c.role = ParticipantRoleName(p.participantRole);
|
|
420
|
+
c.type = ParticipantTypeName(p.participantType);
|
|
421
|
+
c.isCurrentUser = p.isCurrentUser;
|
|
422
|
+
return c;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
static CalInfo CopyCalendar(EKCalendar* c) {
|
|
426
|
+
CalInfo i;
|
|
427
|
+
i.id = CopyRequired(c.calendarIdentifier);
|
|
428
|
+
i.title = CopyRequired(c.title);
|
|
429
|
+
i.hasColor = CopyColor(c.CGColor, i.color);
|
|
430
|
+
i.type = CalendarTypeName(c.type);
|
|
431
|
+
EKSource* s = c.source;
|
|
432
|
+
i.sourceId = CopyRequired(s.sourceIdentifier);
|
|
433
|
+
i.sourceTitle = CopyRequired(s.title);
|
|
434
|
+
i.sourceType = SourceTypeName(s.sourceType);
|
|
435
|
+
i.immutable = c.immutable;
|
|
436
|
+
i.allowsModifications = c.allowsContentModifications;
|
|
437
|
+
i.subscribed = c.subscribed;
|
|
438
|
+
return i;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// An empty array from the framework means the same as none: absent.
|
|
442
|
+
static std::optional<std::vector<int>> CopyInts(NSArray<NSNumber*>* a) {
|
|
443
|
+
if (!a || a.count == 0) return std::nullopt;
|
|
444
|
+
std::vector<int> v;
|
|
445
|
+
v.reserve(a.count);
|
|
446
|
+
for (NSNumber* n in a) v.push_back(n.intValue);
|
|
447
|
+
return v;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
static RuleInfo CopyRule(EKRecurrenceRule* r) {
|
|
451
|
+
RuleInfo i;
|
|
452
|
+
i.frequency = r.frequency;
|
|
453
|
+
i.interval = (int)r.interval;
|
|
454
|
+
EKRecurrenceEnd* end = r.recurrenceEnd;
|
|
455
|
+
if (end && end.endDate) i.until = Millis(end.endDate);
|
|
456
|
+
else if (end && end.occurrenceCount) i.count = (uint32_t)end.occurrenceCount;
|
|
457
|
+
if (r.daysOfTheWeek.count) {
|
|
458
|
+
std::vector<DayOfWeek> ds;
|
|
459
|
+
for (EKRecurrenceDayOfWeek* d in r.daysOfTheWeek) {
|
|
460
|
+
ds.push_back({(int)d.dayOfTheWeek, (int)d.weekNumber});
|
|
461
|
+
}
|
|
462
|
+
i.daysOfWeek = std::move(ds);
|
|
463
|
+
}
|
|
464
|
+
i.daysOfMonth = CopyInts(r.daysOfTheMonth);
|
|
465
|
+
i.monthsOfYear = CopyInts(r.monthsOfTheYear);
|
|
466
|
+
i.weeksOfYear = CopyInts(r.weeksOfTheYear);
|
|
467
|
+
i.daysOfYear = CopyInts(r.daysOfTheYear);
|
|
468
|
+
i.setPositions = CopyInts(r.setPositions);
|
|
469
|
+
return i;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
static AlarmInfo CopyAlarm(EKAlarm* a) {
|
|
473
|
+
AlarmInfo i;
|
|
474
|
+
if (a.absoluteDate) {
|
|
475
|
+
i.absolute = true;
|
|
476
|
+
i.value = Millis(a.absoluteDate);
|
|
477
|
+
} else {
|
|
478
|
+
i.value = a.relativeOffset;
|
|
479
|
+
}
|
|
480
|
+
return i;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
static CalEventInfo CopyEvent(EKEvent* e) {
|
|
484
|
+
CalEventInfo i;
|
|
485
|
+
i.id = Copy(e.eventIdentifier);
|
|
486
|
+
i.itemId = Copy(e.calendarItemIdentifier);
|
|
487
|
+
i.externalId = Copy(e.calendarItemExternalIdentifier);
|
|
488
|
+
i.calendar = CopyRequired(e.calendar.calendarIdentifier);
|
|
489
|
+
i.title = Copy(e.title);
|
|
490
|
+
i.location = Copy(e.location);
|
|
491
|
+
i.notes = Copy(e.notes);
|
|
492
|
+
i.url = Copy(e.URL);
|
|
493
|
+
i.timeZone = Copy(e.timeZone.name);
|
|
494
|
+
i.start = Millis(e.startDate);
|
|
495
|
+
i.end = Millis(e.endDate);
|
|
496
|
+
i.allDay = e.allDay;
|
|
497
|
+
i.status = EventStatusName(e.status);
|
|
498
|
+
i.availability = AvailabilityName(e.availability);
|
|
499
|
+
i.recurring = e.hasRecurrenceRules;
|
|
500
|
+
i.detached = e.isDetached;
|
|
501
|
+
if (e.occurrenceDate) i.occurrenceDate = Millis(e.occurrenceDate);
|
|
502
|
+
if (e.organizer) i.organizer = CopyParticipant(e.organizer);
|
|
503
|
+
if (e.attendees) {
|
|
504
|
+
std::vector<CalParticipant> as;
|
|
505
|
+
as.reserve(e.attendees.count);
|
|
506
|
+
for (EKParticipant* p in e.attendees) as.push_back(CopyParticipant(p));
|
|
507
|
+
i.attendees = std::move(as);
|
|
508
|
+
}
|
|
509
|
+
// the flags are cheap and the arrays are not, so only an item that has
|
|
510
|
+
// them is asked; the first rule is carried — Calendar and every account
|
|
511
|
+
// write exactly one, though the framework allows several
|
|
512
|
+
if (e.hasRecurrenceRules) {
|
|
513
|
+
NSArray<EKRecurrenceRule*>* rules = e.recurrenceRules;
|
|
514
|
+
if (rules.count) i.recurrence = CopyRule(rules[0]);
|
|
515
|
+
}
|
|
516
|
+
if (e.hasAlarms) {
|
|
517
|
+
NSArray<EKAlarm*>* alarms = e.alarms;
|
|
518
|
+
if (alarms) {
|
|
519
|
+
std::vector<AlarmInfo> as;
|
|
520
|
+
as.reserve(alarms.count);
|
|
521
|
+
for (EKAlarm* a in alarms) as.push_back(CopyAlarm(a));
|
|
522
|
+
i.alarms = std::move(as);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return i;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// --- the fetches (background queue) -----------------------------------------
|
|
529
|
+
|
|
530
|
+
// A read needs the full grant: write-only (macOS 14) may save what it cannot
|
|
531
|
+
// read, and the other words are not a grant at all. The status names itself
|
|
532
|
+
// in the error, so the renderer can tell a refusal from an empty calendar.
|
|
533
|
+
static bool Authorized(const char* fn, CalAnswer* a) {
|
|
534
|
+
const char* st = CALEventsAuthorizationStatus();
|
|
535
|
+
if (strcmp(st, "authorized") == 0) return true;
|
|
536
|
+
a->error = std::string(fn) +
|
|
537
|
+
": not authorized to read calendars (the 'calendars' "
|
|
538
|
+
"authorization is '" +
|
|
539
|
+
st + "')";
|
|
540
|
+
if (strcmp(st, "writeOnly") == 0) {
|
|
541
|
+
a->error += " — macOS 14's write-only grant saves events but cannot read them";
|
|
542
|
+
}
|
|
543
|
+
return false;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
static bool WriteOnly() {
|
|
547
|
+
return strcmp(CALEventsAuthorizationStatus(), "writeOnly") == 0;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// A write is content with either grant.
|
|
551
|
+
static bool Writable(const char* fn, CalAnswer* a) {
|
|
552
|
+
const char* st = CALEventsAuthorizationStatus();
|
|
553
|
+
if (strcmp(st, "authorized") == 0 || strcmp(st, "writeOnly") == 0) return true;
|
|
554
|
+
a->error = std::string(fn) +
|
|
555
|
+
": not authorized to write calendars (the 'calendars' "
|
|
556
|
+
"authorization is '" +
|
|
557
|
+
st + "')";
|
|
558
|
+
return false;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
static void FetchCalendars(EKEventStore* store, CalAnswer* a) {
|
|
562
|
+
// so a calendar the user just added in Settings is here; the refresh
|
|
563
|
+
// itself is asynchronous, and what it pulls in arrives as a change event
|
|
564
|
+
[store refreshSourcesIfNecessary];
|
|
565
|
+
for (EKCalendar* c in [store calendarsForEntityType:EKEntityTypeEvent]) {
|
|
566
|
+
a->calendars.push_back(CopyCalendar(c));
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
struct EventsQuery {
|
|
571
|
+
double start = 0, end = 0;
|
|
572
|
+
std::vector<std::string> calendarIds; // empty: every calendar
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
static void FetchEvents(EKEventStore* store, const EventsQuery& q,
|
|
576
|
+
CalAnswer* a) {
|
|
577
|
+
NSMutableArray<EKCalendar*>* cals = nil;
|
|
578
|
+
if (!q.calendarIds.empty()) {
|
|
579
|
+
cals = [NSMutableArray arrayWithCapacity:q.calendarIds.size()];
|
|
580
|
+
for (const std::string& id : q.calendarIds) {
|
|
581
|
+
EKCalendar* c = [store
|
|
582
|
+
calendarWithIdentifier:[NSString stringWithUTF8String:id.c_str()]];
|
|
583
|
+
// nil calendars means *every* calendar to the predicate, so an id that
|
|
584
|
+
// names nothing is an error rather than a silently widened query
|
|
585
|
+
if (!c) {
|
|
586
|
+
a->error = "eventsBetween: no calendar with identifier '" + id +
|
|
587
|
+
"' (it may have been removed; list them again)";
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
[cals addObject:c];
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
NSPredicate* p = [store
|
|
594
|
+
predicateForEventsWithStartDate:[NSDate dateWithTimeIntervalSince1970:
|
|
595
|
+
q.start / 1000.0]
|
|
596
|
+
endDate:[NSDate dateWithTimeIntervalSince1970:
|
|
597
|
+
q.end / 1000.0]
|
|
598
|
+
calendars:cals];
|
|
599
|
+
NSArray<EKEvent*>* events = [store eventsMatchingPredicate:p];
|
|
600
|
+
events = [events sortedArrayUsingSelector:@selector(compareStartDateWithEvent:)];
|
|
601
|
+
a->events.reserve(events.count);
|
|
602
|
+
for (EKEvent* e in events) a->events.push_back(CopyEvent(e));
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// --- the answer path --------------------------------------------------------
|
|
606
|
+
|
|
607
|
+
static Napi::Value StringOrNull(Napi::Env env, const MaybeString& s) {
|
|
608
|
+
if (!s) return env.Null();
|
|
609
|
+
return Napi::String::New(env, *s);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
static Napi::Object ParticipantJs(Napi::Env env, const CalParticipant& p) {
|
|
613
|
+
Napi::Object o = Napi::Object::New(env);
|
|
614
|
+
o.Set("name", StringOrNull(env, p.name));
|
|
615
|
+
o.Set("url", StringOrNull(env, p.url));
|
|
616
|
+
o.Set("status", p.status);
|
|
617
|
+
o.Set("role", p.role);
|
|
618
|
+
o.Set("type", p.type);
|
|
619
|
+
o.Set("isCurrentUser", p.isCurrentUser);
|
|
620
|
+
return o;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
static Napi::Object CalendarJs(Napi::Env env, const CalInfo& c) {
|
|
624
|
+
Napi::Object o = Napi::Object::New(env);
|
|
625
|
+
o.Set("id", c.id);
|
|
626
|
+
o.Set("title", c.title);
|
|
627
|
+
if (c.hasColor) {
|
|
628
|
+
Napi::Array col = Napi::Array::New(env, 4);
|
|
629
|
+
for (uint32_t i = 0; i < 4; i++) col.Set(i, c.color[i]);
|
|
630
|
+
o.Set("color", col);
|
|
631
|
+
} else {
|
|
632
|
+
o.Set("color", env.Null());
|
|
633
|
+
}
|
|
634
|
+
o.Set("type", c.type);
|
|
635
|
+
Napi::Object src = Napi::Object::New(env);
|
|
636
|
+
src.Set("id", c.sourceId);
|
|
637
|
+
src.Set("title", c.sourceTitle);
|
|
638
|
+
src.Set("type", c.sourceType);
|
|
639
|
+
o.Set("source", src);
|
|
640
|
+
o.Set("immutable", c.immutable);
|
|
641
|
+
o.Set("allowsModifications", c.allowsModifications);
|
|
642
|
+
o.Set("subscribed", c.subscribed);
|
|
643
|
+
return o;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
static Napi::Value IntsJs(Napi::Env env,
|
|
647
|
+
const std::optional<std::vector<int>>& v) {
|
|
648
|
+
if (!v) return env.Null();
|
|
649
|
+
Napi::Array a = Napi::Array::New(env, v->size());
|
|
650
|
+
for (uint32_t i = 0; i < v->size(); i++) a.Set(i, (*v)[i]);
|
|
651
|
+
return a;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
static Napi::Object RuleJs(Napi::Env env, const RuleInfo& r) {
|
|
655
|
+
Napi::Object o = Napi::Object::New(env);
|
|
656
|
+
o.Set("frequency", FrequencyName(r.frequency));
|
|
657
|
+
o.Set("interval", r.interval);
|
|
658
|
+
o.Set("until", r.until ? Napi::Number::New(env, *r.until)
|
|
659
|
+
: env.Null().As<Napi::Value>());
|
|
660
|
+
o.Set("count", r.count ? Napi::Number::New(env, *r.count)
|
|
661
|
+
: env.Null().As<Napi::Value>());
|
|
662
|
+
if (r.daysOfWeek) {
|
|
663
|
+
Napi::Array ds = Napi::Array::New(env, r.daysOfWeek->size());
|
|
664
|
+
for (uint32_t i = 0; i < r.daysOfWeek->size(); i++) {
|
|
665
|
+
Napi::Object d = Napi::Object::New(env);
|
|
666
|
+
d.Set("day", (*r.daysOfWeek)[i].day);
|
|
667
|
+
d.Set("week", (*r.daysOfWeek)[i].week);
|
|
668
|
+
ds.Set(i, d);
|
|
669
|
+
}
|
|
670
|
+
o.Set("daysOfWeek", ds);
|
|
671
|
+
} else {
|
|
672
|
+
o.Set("daysOfWeek", env.Null());
|
|
673
|
+
}
|
|
674
|
+
o.Set("daysOfMonth", IntsJs(env, r.daysOfMonth));
|
|
675
|
+
o.Set("monthsOfYear", IntsJs(env, r.monthsOfYear));
|
|
676
|
+
o.Set("weeksOfYear", IntsJs(env, r.weeksOfYear));
|
|
677
|
+
o.Set("daysOfYear", IntsJs(env, r.daysOfYear));
|
|
678
|
+
o.Set("setPositions", IntsJs(env, r.setPositions));
|
|
679
|
+
return o;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
static Napi::Object AlarmJs(Napi::Env env, const AlarmInfo& a) {
|
|
683
|
+
Napi::Object o = Napi::Object::New(env);
|
|
684
|
+
o.Set(a.absolute ? "at" : "offset", a.value);
|
|
685
|
+
return o;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
static Napi::Object EventJs(Napi::Env env, const CalEventInfo& e) {
|
|
689
|
+
Napi::Object o = Napi::Object::New(env);
|
|
690
|
+
o.Set("id", StringOrNull(env, e.id));
|
|
691
|
+
o.Set("itemId", StringOrNull(env, e.itemId));
|
|
692
|
+
o.Set("externalId", StringOrNull(env, e.externalId));
|
|
693
|
+
o.Set("calendar", e.calendar);
|
|
694
|
+
o.Set("title", StringOrNull(env, e.title));
|
|
695
|
+
o.Set("location", StringOrNull(env, e.location));
|
|
696
|
+
o.Set("notes", StringOrNull(env, e.notes));
|
|
697
|
+
o.Set("url", StringOrNull(env, e.url));
|
|
698
|
+
o.Set("start", e.start);
|
|
699
|
+
o.Set("end", e.end);
|
|
700
|
+
o.Set("allDay", e.allDay);
|
|
701
|
+
o.Set("timeZone", StringOrNull(env, e.timeZone));
|
|
702
|
+
o.Set("status", e.status);
|
|
703
|
+
o.Set("availability", e.availability);
|
|
704
|
+
o.Set("recurring", e.recurring);
|
|
705
|
+
o.Set("detached", e.detached);
|
|
706
|
+
o.Set("occurrenceDate", e.occurrenceDate
|
|
707
|
+
? Napi::Number::New(env, *e.occurrenceDate)
|
|
708
|
+
: env.Null().As<Napi::Value>());
|
|
709
|
+
if (e.organizer) o.Set("organizer", ParticipantJs(env, *e.organizer));
|
|
710
|
+
if (e.attendees) {
|
|
711
|
+
Napi::Array as = Napi::Array::New(env, e.attendees->size());
|
|
712
|
+
for (uint32_t i = 0; i < e.attendees->size(); i++) {
|
|
713
|
+
as.Set(i, ParticipantJs(env, (*e.attendees)[i]));
|
|
714
|
+
}
|
|
715
|
+
o.Set("attendees", as);
|
|
716
|
+
}
|
|
717
|
+
if (e.recurrence) o.Set("recurrence", RuleJs(env, *e.recurrence));
|
|
718
|
+
if (e.alarms) {
|
|
719
|
+
Napi::Array as = Napi::Array::New(env, e.alarms->size());
|
|
720
|
+
for (uint32_t i = 0; i < e.alarms->size(); i++) {
|
|
721
|
+
as.Set(i, AlarmJs(env, (*e.alarms)[i]));
|
|
722
|
+
}
|
|
723
|
+
o.Set("alarms", as);
|
|
724
|
+
}
|
|
725
|
+
return o;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// An error the framework reported carries its coordinates — code, domain,
|
|
729
|
+
// and the EKErrorCode's name as reason — the way a notification error does;
|
|
730
|
+
// one the bridge found for itself is the message alone.
|
|
731
|
+
static Napi::Value ErrorJs(Napi::Env env, const CalAnswer& a) {
|
|
732
|
+
Napi::Error err = Napi::Error::New(env, a.error);
|
|
733
|
+
if (a.fromFramework) {
|
|
734
|
+
err.Set("code", a.code);
|
|
735
|
+
err.Set("domain", a.domain);
|
|
736
|
+
err.Set("reason", StringOrNull(env, a.reason));
|
|
737
|
+
}
|
|
738
|
+
return err.Value();
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// cb(err) or cb(null, ...) on the JS thread, from a background queue, then
|
|
742
|
+
// the thread-safe function goes — which is what was holding the loop open
|
|
743
|
+
// for the length of the fetch or the write.
|
|
744
|
+
static void Deliver(Napi::ThreadSafeFunction tsfn, CalAnswer* a) {
|
|
745
|
+
napi_status st = tsfn.BlockingCall(
|
|
746
|
+
a, [](Napi::Env env, Napi::Function cb, CalAnswer* a) {
|
|
747
|
+
if (!a->error.empty()) {
|
|
748
|
+
cb.Call({ErrorJs(env, *a)});
|
|
749
|
+
} else if (a->kind == Answer::Events) {
|
|
750
|
+
Napi::Array out = Napi::Array::New(env, a->events.size());
|
|
751
|
+
for (uint32_t i = 0; i < a->events.size(); i++) {
|
|
752
|
+
out.Set(i, EventJs(env, a->events[i]));
|
|
753
|
+
}
|
|
754
|
+
cb.Call({env.Null(), out});
|
|
755
|
+
} else if (a->kind == Answer::Calendars) {
|
|
756
|
+
Napi::Array out = Napi::Array::New(env, a->calendars.size());
|
|
757
|
+
for (uint32_t i = 0; i < a->calendars.size(); i++) {
|
|
758
|
+
out.Set(i, CalendarJs(env, a->calendars[i]));
|
|
759
|
+
}
|
|
760
|
+
cb.Call({env.Null(), out});
|
|
761
|
+
} else if (a->kind == Answer::Calendar) {
|
|
762
|
+
cb.Call({env.Null(), a->calendar
|
|
763
|
+
? CalendarJs(env, *a->calendar)
|
|
764
|
+
: env.Null().As<Napi::Value>()});
|
|
765
|
+
} else if (a->kind == Answer::Id) {
|
|
766
|
+
cb.Call({env.Null(), StringOrNull(env, a->id)});
|
|
767
|
+
} else {
|
|
768
|
+
cb.Call({env.Null()});
|
|
769
|
+
}
|
|
770
|
+
delete a;
|
|
771
|
+
});
|
|
772
|
+
if (st != napi_ok) delete a;
|
|
773
|
+
tsfn.Release();
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// --- the store's change notification ----------------------------------------
|
|
777
|
+
|
|
778
|
+
static void CallJsChanged(Napi::Env env, Napi::Function, void*, void*);
|
|
779
|
+
using ChangedTsfn = Napi::TypedThreadSafeFunction<void, void, CallJsChanged>;
|
|
780
|
+
static ChangedTsfn gChanged;
|
|
781
|
+
// One change waiting for a listener. The event carries nothing and the
|
|
782
|
+
// framework coalesces, so what is held is that a change happened at all.
|
|
783
|
+
static bool gHeldChange = false;
|
|
784
|
+
|
|
785
|
+
static void EmitOrHoldChange(Napi::Env env) {
|
|
786
|
+
if (!CALHasBackendCb()) {
|
|
787
|
+
gHeldChange = true;
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
Napi::HandleScope scope(env);
|
|
791
|
+
Napi::Object ev = Napi::Object::New(env);
|
|
792
|
+
ev.Set("type", "calendar-store-changed");
|
|
793
|
+
CALEmitBackendEvent(env, ev);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// Called at the start of pump2 (backend.mm): a change from before the
|
|
797
|
+
// listener existed goes out ahead of that tick's input.
|
|
798
|
+
void CALCalendarsReplayHeld(Napi::Env env) {
|
|
799
|
+
if (!gHeldChange || !CALHasBackendCb()) return;
|
|
800
|
+
gHeldChange = false;
|
|
801
|
+
EmitOrHoldChange(env);
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
static void CallJsChanged(Napi::Env env, Napi::Function, void*, void*) {
|
|
805
|
+
if ((napi_env)env == nullptr) return; // the function is being torn down
|
|
806
|
+
EmitOrHoldChange(env);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// permissions.mm calls this the once, as it creates the process's store: the
|
|
810
|
+
// observer is in place from the store's first moment, whichever verb made it.
|
|
811
|
+
// EKEventStoreChangedNotification carries no guarantee about its thread, so
|
|
812
|
+
// the crossing to node's loop is the same hand-off a notification response
|
|
813
|
+
// takes.
|
|
814
|
+
void CALCalendarsObserveStore(EKEventStore* store) {
|
|
815
|
+
static id observer = nil;
|
|
816
|
+
if (observer) return;
|
|
817
|
+
observer = [NSNotificationCenter.defaultCenter
|
|
818
|
+
addObserverForName:EKEventStoreChangedNotification
|
|
819
|
+
object:store
|
|
820
|
+
queue:nil
|
|
821
|
+
usingBlock:^(NSNotification*) { gChanged.NonBlockingCall(); }];
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// --- the natives ------------------------------------------------------------
|
|
825
|
+
|
|
826
|
+
static bool ThrowType(Napi::Env env, const std::string& msg) {
|
|
827
|
+
Napi::TypeError::New(env, msg).ThrowAsJavaScriptException();
|
|
828
|
+
return false;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
// o[k] as finite epoch ms; a Date is the wrapper's job, not the bridge's.
|
|
832
|
+
static bool QueryMillis(Napi::Env env, Napi::Object o, const char* k,
|
|
833
|
+
double* out) {
|
|
834
|
+
Napi::Value v = o.Get(k);
|
|
835
|
+
if (!v.IsNumber() || !std::isfinite(v.As<Napi::Number>().DoubleValue())) {
|
|
836
|
+
return ThrowType(env, std::string("eventsBetween: '") + k +
|
|
837
|
+
"' must be a time in epoch milliseconds");
|
|
838
|
+
}
|
|
839
|
+
*out = v.As<Napi::Number>().DoubleValue();
|
|
840
|
+
return true;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
static bool ParseEventsQuery(Napi::Env env, const Napi::CallbackInfo& info,
|
|
844
|
+
EventsQuery* q) {
|
|
845
|
+
if (info.Length() < 1 || !info[0].IsObject() || info[0].IsFunction()) {
|
|
846
|
+
return ThrowType(env,
|
|
847
|
+
"eventsBetween: expected ({ start, end, calendars? }, cb)");
|
|
848
|
+
}
|
|
849
|
+
Napi::Object o = info[0].As<Napi::Object>();
|
|
850
|
+
if (!QueryMillis(env, o, "start", &q->start)) return false;
|
|
851
|
+
if (!QueryMillis(env, o, "end", &q->end)) return false;
|
|
852
|
+
if (q->end < q->start) {
|
|
853
|
+
return ThrowType(env, "eventsBetween: 'end' is before 'start'");
|
|
854
|
+
}
|
|
855
|
+
if (q->end - q->start > kMaxSpanMs) {
|
|
856
|
+
return ThrowType(env,
|
|
857
|
+
"eventsBetween: the predicate is limited to a four-year "
|
|
858
|
+
"span (1461 days); ask for the range in chunks");
|
|
859
|
+
}
|
|
860
|
+
Napi::Value cals = o.Get("calendars");
|
|
861
|
+
if (cals.IsUndefined() || cals.IsNull()) return true;
|
|
862
|
+
if (!cals.IsArray()) {
|
|
863
|
+
return ThrowType(env,
|
|
864
|
+
"eventsBetween: 'calendars' must be an array of calendar "
|
|
865
|
+
"ids");
|
|
866
|
+
}
|
|
867
|
+
Napi::Array a = cals.As<Napi::Array>();
|
|
868
|
+
if (a.Length() == 0) {
|
|
869
|
+
// an empty list would reach the predicate as nil, i.e. every calendar
|
|
870
|
+
return ThrowType(env,
|
|
871
|
+
"eventsBetween: 'calendars' must name at least one "
|
|
872
|
+
"calendar; leave it out for all of them");
|
|
873
|
+
}
|
|
874
|
+
for (uint32_t i = 0; i < a.Length(); i++) {
|
|
875
|
+
Napi::Value v = a.Get(i);
|
|
876
|
+
if (!v.IsString()) {
|
|
877
|
+
return ThrowType(env,
|
|
878
|
+
"eventsBetween: 'calendars' must be an array of "
|
|
879
|
+
"calendar ids (strings)");
|
|
880
|
+
}
|
|
881
|
+
q->calendarIds.push_back(v.As<Napi::String>().Utf8Value());
|
|
882
|
+
}
|
|
883
|
+
return true;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
// calendars(cb) — cb(err, [calendar]): every EKCalendar that holds events,
|
|
887
|
+
// across every source. Never prompts.
|
|
888
|
+
static Napi::Value Calendars(const Napi::CallbackInfo& info) {
|
|
889
|
+
Napi::Env env = info.Env();
|
|
890
|
+
if (info.Length() < 1 || !info[0].IsFunction()) {
|
|
891
|
+
ThrowType(env, "calendars: expected a callback (cb)");
|
|
892
|
+
return env.Undefined();
|
|
893
|
+
}
|
|
894
|
+
@autoreleasepool {
|
|
895
|
+
EKEventStore* store = CALEventStore(); // JS thread: it is a singleton
|
|
896
|
+
Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
|
|
897
|
+
env, info[0].As<Napi::Function>(), "appkit:calendars", 0, 1);
|
|
898
|
+
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
|
|
899
|
+
@autoreleasepool {
|
|
900
|
+
CalAnswer* a = new CalAnswer;
|
|
901
|
+
if (Authorized("calendars", a)) FetchCalendars(store, a);
|
|
902
|
+
Deliver(tsfn, a);
|
|
903
|
+
}
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
return env.Undefined();
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// eventsBetween({ start, end, calendars? }, cb) — cb(err, [event]): the
|
|
910
|
+
// occurrences the predicate answers, recurrences expanded by the framework,
|
|
911
|
+
// sorted by start. Never prompts.
|
|
912
|
+
static Napi::Value EventsBetween(const Napi::CallbackInfo& info) {
|
|
913
|
+
Napi::Env env = info.Env();
|
|
914
|
+
EventsQuery q;
|
|
915
|
+
if (!ParseEventsQuery(env, info, &q)) return env.Undefined();
|
|
916
|
+
if (info.Length() < 2 || !info[1].IsFunction()) {
|
|
917
|
+
ThrowType(env, "eventsBetween: expected ({ start, end, calendars? }, cb)");
|
|
918
|
+
return env.Undefined();
|
|
919
|
+
}
|
|
920
|
+
@autoreleasepool {
|
|
921
|
+
EKEventStore* store = CALEventStore();
|
|
922
|
+
Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
|
|
923
|
+
env, info[1].As<Napi::Function>(), "appkit:eventsBetween", 0, 1);
|
|
924
|
+
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
|
|
925
|
+
@autoreleasepool {
|
|
926
|
+
CalAnswer* a = new CalAnswer;
|
|
927
|
+
a->kind = Answer::Events;
|
|
928
|
+
if (Authorized("eventsBetween", a)) FetchEvents(store, q, a);
|
|
929
|
+
Deliver(tsfn, a);
|
|
930
|
+
}
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
return env.Undefined();
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
// --- the writes: what to save, parsed on the JS thread ----------------------
|
|
938
|
+
|
|
939
|
+
// One field of a save: absent (unchanged, or the default for a new event),
|
|
940
|
+
// null (cleared), or a value. undefined counts as absent, so a wrapper that
|
|
941
|
+
// spreads { start: toMs(undefined) } says nothing about start.
|
|
942
|
+
template <typename T>
|
|
943
|
+
struct Field {
|
|
944
|
+
bool given = false, null = false;
|
|
945
|
+
T value{};
|
|
946
|
+
bool set() const { return given && !null; }
|
|
947
|
+
};
|
|
948
|
+
|
|
949
|
+
struct EventProps {
|
|
950
|
+
std::optional<std::string> id; // absent: create
|
|
951
|
+
std::optional<double> occurrenceDate; // with id: which occurrence
|
|
952
|
+
std::optional<std::string> calendar; // create: the default when absent
|
|
953
|
+
Field<std::string> title, location, notes, url, timeZone;
|
|
954
|
+
std::optional<double> start, end; // both required to create
|
|
955
|
+
std::optional<bool> allDay;
|
|
956
|
+
std::optional<EKEventAvailability> availability;
|
|
957
|
+
Field<RuleInfo> recurrence;
|
|
958
|
+
Field<std::vector<AlarmInfo>> alarms; // null or []: none
|
|
959
|
+
};
|
|
960
|
+
|
|
961
|
+
struct WriteOpts {
|
|
962
|
+
EKSpan span = EKSpanThisEvent;
|
|
963
|
+
bool commit = true;
|
|
964
|
+
std::optional<double> occurrenceDate; // removeEvent: which occurrence
|
|
965
|
+
};
|
|
966
|
+
|
|
967
|
+
// o[k], or empty when absent or undefined.
|
|
968
|
+
static Napi::Value Given(Napi::Object o, const char* k) {
|
|
969
|
+
Napi::Value v = o.Get(k);
|
|
970
|
+
return v.IsUndefined() ? Napi::Value() : v;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
static bool ParseMillis(Napi::Env env, Napi::Value v, const std::string& what,
|
|
974
|
+
double* out) {
|
|
975
|
+
if (!v.IsNumber() || !std::isfinite(v.As<Napi::Number>().DoubleValue())) {
|
|
976
|
+
return ThrowType(env, what + " must be a time in epoch milliseconds");
|
|
977
|
+
}
|
|
978
|
+
*out = v.As<Napi::Number>().DoubleValue();
|
|
979
|
+
return true;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// An integer in [lo, hi], never zero: the framework's arrays count from one,
|
|
983
|
+
// negatives from the end.
|
|
984
|
+
static bool ParseInt(Napi::Env env, Napi::Value v, const std::string& what,
|
|
985
|
+
int lo, int hi, int* out) {
|
|
986
|
+
double d = v.IsNumber() ? v.As<Napi::Number>().DoubleValue() : NAN;
|
|
987
|
+
if (!(d == std::floor(d)) || d < lo || d > hi || d == 0) {
|
|
988
|
+
return ThrowType(env, what + " must be an integer from " +
|
|
989
|
+
std::to_string(lo) + " to " +
|
|
990
|
+
std::to_string(hi) + (lo < 0 ? ", never zero" : ""));
|
|
991
|
+
}
|
|
992
|
+
*out = (int)d;
|
|
993
|
+
return true;
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
static bool ParseInts(Napi::Env env, Napi::Object rule, const char* k, int lo,
|
|
997
|
+
int hi, std::optional<std::vector<int>>* out) {
|
|
998
|
+
Napi::Value v = Given(rule, k);
|
|
999
|
+
if (v.IsEmpty() || v.IsNull()) return true;
|
|
1000
|
+
std::string what = std::string("saveEvent: recurrence.") + k;
|
|
1001
|
+
if (!v.IsArray()) return ThrowType(env, what + " must be an array of integers");
|
|
1002
|
+
Napi::Array a = v.As<Napi::Array>();
|
|
1003
|
+
std::vector<int> ints;
|
|
1004
|
+
for (uint32_t i = 0; i < a.Length(); i++) {
|
|
1005
|
+
int n;
|
|
1006
|
+
if (!ParseInt(env, a.Get(i), what, lo, hi, &n)) return false;
|
|
1007
|
+
ints.push_back(n);
|
|
1008
|
+
}
|
|
1009
|
+
if (!ints.empty()) *out = std::move(ints); // []: none, as nil is
|
|
1010
|
+
return true;
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
static bool ParseRule(Napi::Env env, Napi::Value v, RuleInfo* r) {
|
|
1014
|
+
if (!v.IsObject() || v.IsArray() || v.IsFunction()) {
|
|
1015
|
+
return ThrowType(env,
|
|
1016
|
+
"saveEvent: 'recurrence' must be { frequency, interval?, "
|
|
1017
|
+
"until? | count?, daysOfWeek?, daysOfMonth?, "
|
|
1018
|
+
"monthsOfYear?, weeksOfYear?, daysOfYear?, "
|
|
1019
|
+
"setPositions? } or null");
|
|
1020
|
+
}
|
|
1021
|
+
Napi::Object o = v.As<Napi::Object>();
|
|
1022
|
+
Napi::Value f = Given(o, "frequency");
|
|
1023
|
+
if (f.IsEmpty() || !f.IsString() ||
|
|
1024
|
+
!ParseFrequency(f.As<Napi::String>().Utf8Value(), &r->frequency)) {
|
|
1025
|
+
return ThrowType(env,
|
|
1026
|
+
"saveEvent: recurrence.frequency must be 'daily', "
|
|
1027
|
+
"'weekly', 'monthly' or 'yearly'");
|
|
1028
|
+
}
|
|
1029
|
+
Napi::Value iv = Given(o, "interval");
|
|
1030
|
+
if (!iv.IsEmpty() && !iv.IsNull()) {
|
|
1031
|
+
if (!ParseInt(env, iv, "saveEvent: recurrence.interval", 1, INT32_MAX,
|
|
1032
|
+
&r->interval)) {
|
|
1033
|
+
return false;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
Napi::Value until = Given(o, "until"), count = Given(o, "count");
|
|
1037
|
+
bool hasUntil = !until.IsEmpty() && !until.IsNull();
|
|
1038
|
+
bool hasCount = !count.IsEmpty() && !count.IsNull();
|
|
1039
|
+
if (hasUntil && hasCount) {
|
|
1040
|
+
return ThrowType(env,
|
|
1041
|
+
"saveEvent: a recurrence ends at 'until' or after "
|
|
1042
|
+
"'count' occurrences, not both");
|
|
1043
|
+
}
|
|
1044
|
+
if (hasUntil) {
|
|
1045
|
+
double ms;
|
|
1046
|
+
if (!ParseMillis(env, until, "saveEvent: recurrence.until", &ms)) return false;
|
|
1047
|
+
r->until = ms;
|
|
1048
|
+
}
|
|
1049
|
+
if (hasCount) {
|
|
1050
|
+
int n;
|
|
1051
|
+
if (!ParseInt(env, count, "saveEvent: recurrence.count", 1, INT32_MAX, &n)) {
|
|
1052
|
+
return false;
|
|
1053
|
+
}
|
|
1054
|
+
r->count = (uint32_t)n;
|
|
1055
|
+
}
|
|
1056
|
+
Napi::Value days = Given(o, "daysOfWeek");
|
|
1057
|
+
if (!days.IsEmpty() && !days.IsNull()) {
|
|
1058
|
+
if (!days.IsArray()) {
|
|
1059
|
+
return ThrowType(env,
|
|
1060
|
+
"saveEvent: recurrence.daysOfWeek must be an array of "
|
|
1061
|
+
"{ day: 1..7 (Sunday = 1), week? }");
|
|
1062
|
+
}
|
|
1063
|
+
// the framework raises for a week number its frequency has no place
|
|
1064
|
+
// for: none on a daily or weekly rule, ±1..5 in a month, ±1..53 in a year
|
|
1065
|
+
int maxWeek = r->frequency == EKRecurrenceFrequencyMonthly ? 5
|
|
1066
|
+
: r->frequency == EKRecurrenceFrequencyYearly ? 53
|
|
1067
|
+
: 0;
|
|
1068
|
+
Napi::Array a = days.As<Napi::Array>();
|
|
1069
|
+
std::vector<DayOfWeek> ds;
|
|
1070
|
+
for (uint32_t i = 0; i < a.Length(); i++) {
|
|
1071
|
+
Napi::Value e = a.Get(i);
|
|
1072
|
+
if (!e.IsObject() || e.IsArray() || e.IsFunction()) {
|
|
1073
|
+
return ThrowType(env,
|
|
1074
|
+
"saveEvent: recurrence.daysOfWeek must be an array "
|
|
1075
|
+
"of { day: 1..7 (Sunday = 1), week? }");
|
|
1076
|
+
}
|
|
1077
|
+
Napi::Object d = e.As<Napi::Object>();
|
|
1078
|
+
DayOfWeek dw;
|
|
1079
|
+
Napi::Value day = Given(d, "day");
|
|
1080
|
+
if (day.IsEmpty() ||
|
|
1081
|
+
!ParseInt(env, day, "saveEvent: recurrence.daysOfWeek[].day", 1, 7,
|
|
1082
|
+
&dw.day)) {
|
|
1083
|
+
if (day.IsEmpty()) {
|
|
1084
|
+
ThrowType(env, "saveEvent: recurrence.daysOfWeek[].day must be an "
|
|
1085
|
+
"integer from 1 to 7 (Sunday = 1)");
|
|
1086
|
+
}
|
|
1087
|
+
return false;
|
|
1088
|
+
}
|
|
1089
|
+
Napi::Value week = Given(d, "week");
|
|
1090
|
+
if (!week.IsEmpty() && !week.IsNull()) {
|
|
1091
|
+
double w = week.IsNumber() ? week.As<Napi::Number>().DoubleValue() : NAN;
|
|
1092
|
+
if (!(w == std::floor(w)) || std::fabs(w) > maxWeek) {
|
|
1093
|
+
if (maxWeek == 0) {
|
|
1094
|
+
return ThrowType(env,
|
|
1095
|
+
"saveEvent: recurrence.daysOfWeek[].week has no "
|
|
1096
|
+
"meaning on a daily or weekly rule (the "
|
|
1097
|
+
"framework raises for one); leave it out");
|
|
1098
|
+
}
|
|
1099
|
+
return ThrowType(env, "saveEvent: recurrence.daysOfWeek[].week must "
|
|
1100
|
+
"be an integer from -" +
|
|
1101
|
+
std::to_string(maxWeek) + " to " +
|
|
1102
|
+
std::to_string(maxWeek) + " for a " +
|
|
1103
|
+
FrequencyName(r->frequency) + " rule");
|
|
1104
|
+
}
|
|
1105
|
+
dw.week = (int)w;
|
|
1106
|
+
}
|
|
1107
|
+
ds.push_back(dw);
|
|
1108
|
+
}
|
|
1109
|
+
if (!ds.empty()) r->daysOfWeek = std::move(ds);
|
|
1110
|
+
}
|
|
1111
|
+
return ParseInts(env, o, "daysOfMonth", -31, 31, &r->daysOfMonth) &&
|
|
1112
|
+
ParseInts(env, o, "monthsOfYear", 1, 12, &r->monthsOfYear) &&
|
|
1113
|
+
ParseInts(env, o, "weeksOfYear", -53, 53, &r->weeksOfYear) &&
|
|
1114
|
+
ParseInts(env, o, "daysOfYear", -366, 366, &r->daysOfYear) &&
|
|
1115
|
+
ParseInts(env, o, "setPositions", -366, 366, &r->setPositions);
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
static bool ParseAlarms(Napi::Env env, Napi::Value v,
|
|
1119
|
+
std::vector<AlarmInfo>* out) {
|
|
1120
|
+
const char* shape =
|
|
1121
|
+
"saveEvent: 'alarms' must be an array of { offset: seconds from the "
|
|
1122
|
+
"start } or { at: epoch ms }, or null";
|
|
1123
|
+
if (!v.IsArray()) return ThrowType(env, shape);
|
|
1124
|
+
Napi::Array a = v.As<Napi::Array>();
|
|
1125
|
+
for (uint32_t i = 0; i < a.Length(); i++) {
|
|
1126
|
+
Napi::Value e = a.Get(i);
|
|
1127
|
+
if (!e.IsObject() || e.IsArray() || e.IsFunction()) return ThrowType(env, shape);
|
|
1128
|
+
Napi::Object o = e.As<Napi::Object>();
|
|
1129
|
+
Napi::Value offset = Given(o, "offset"), at = Given(o, "at");
|
|
1130
|
+
bool hasOffset = !offset.IsEmpty() && !offset.IsNull();
|
|
1131
|
+
bool hasAt = !at.IsEmpty() && !at.IsNull();
|
|
1132
|
+
if (hasOffset == hasAt) return ThrowType(env, shape);
|
|
1133
|
+
AlarmInfo al;
|
|
1134
|
+
if (hasAt) {
|
|
1135
|
+
al.absolute = true;
|
|
1136
|
+
if (!ParseMillis(env, at, "saveEvent: alarms[].at", &al.value)) return false;
|
|
1137
|
+
} else if (!offset.IsNumber() ||
|
|
1138
|
+
!std::isfinite(offset.As<Napi::Number>().DoubleValue())) {
|
|
1139
|
+
return ThrowType(env,
|
|
1140
|
+
"saveEvent: alarms[].offset must be a number of seconds "
|
|
1141
|
+
"from the start (negative before it)");
|
|
1142
|
+
} else {
|
|
1143
|
+
al.value = offset.As<Napi::Number>().DoubleValue();
|
|
1144
|
+
}
|
|
1145
|
+
out->push_back(al);
|
|
1146
|
+
}
|
|
1147
|
+
return true;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
// An absolute URL, as the string says it: macOS 14's URLWithString: would
|
|
1151
|
+
// percent-encode a space itself and accept a bare word as a relative
|
|
1152
|
+
// reference, neither of which is what an event's URL is.
|
|
1153
|
+
static NSURL* ParseURL(const std::string& s) {
|
|
1154
|
+
NSString* str = [NSString stringWithUTF8String:s.c_str()];
|
|
1155
|
+
NSURL* u = nil;
|
|
1156
|
+
if (@available(macOS 14.0, *)) {
|
|
1157
|
+
u = [NSURL URLWithString:str encodingInvalidCharacters:NO];
|
|
1158
|
+
} else {
|
|
1159
|
+
u = [NSURL URLWithString:str];
|
|
1160
|
+
}
|
|
1161
|
+
return u && u.scheme.length ? u : nil;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
static bool ParseStringField(Napi::Env env, Napi::Object o, const char* k,
|
|
1165
|
+
Field<std::string>* f) {
|
|
1166
|
+
Napi::Value v = Given(o, k);
|
|
1167
|
+
if (v.IsEmpty()) return true;
|
|
1168
|
+
f->given = true;
|
|
1169
|
+
if (v.IsNull()) {
|
|
1170
|
+
f->null = true;
|
|
1171
|
+
return true;
|
|
1172
|
+
}
|
|
1173
|
+
if (!v.IsString()) {
|
|
1174
|
+
return ThrowType(env, std::string("saveEvent: '") + k +
|
|
1175
|
+
"' must be a string or null");
|
|
1176
|
+
}
|
|
1177
|
+
f->value = v.As<Napi::String>().Utf8Value();
|
|
1178
|
+
return true;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
static bool ParseEventProps(Napi::Env env, Napi::Value v, EventProps* p) {
|
|
1182
|
+
if (!v.IsObject() || v.IsFunction() || v.IsArray()) {
|
|
1183
|
+
return ThrowType(env, "saveEvent: expected (props, opts?, cb)");
|
|
1184
|
+
}
|
|
1185
|
+
Napi::Object o = v.As<Napi::Object>();
|
|
1186
|
+
Napi::Value id = Given(o, "id");
|
|
1187
|
+
if (!id.IsEmpty()) {
|
|
1188
|
+
if (!id.IsString() || id.As<Napi::String>().Utf8Value().empty()) {
|
|
1189
|
+
return ThrowType(env,
|
|
1190
|
+
"saveEvent: 'id' must be the identifier of an existing "
|
|
1191
|
+
"event (a string); leave it out to create one");
|
|
1192
|
+
}
|
|
1193
|
+
p->id = id.As<Napi::String>().Utf8Value();
|
|
1194
|
+
}
|
|
1195
|
+
Napi::Value occ = Given(o, "occurrenceDate");
|
|
1196
|
+
if (!occ.IsEmpty() && !occ.IsNull()) {
|
|
1197
|
+
double ms;
|
|
1198
|
+
if (!ParseMillis(env, occ, "saveEvent: 'occurrenceDate'", &ms)) return false;
|
|
1199
|
+
if (!p->id) {
|
|
1200
|
+
return ThrowType(env,
|
|
1201
|
+
"saveEvent: 'occurrenceDate' picks an occurrence of an "
|
|
1202
|
+
"existing event; pass its 'id' as well");
|
|
1203
|
+
}
|
|
1204
|
+
p->occurrenceDate = ms;
|
|
1205
|
+
}
|
|
1206
|
+
Napi::Value cal = Given(o, "calendar");
|
|
1207
|
+
if (!cal.IsEmpty()) {
|
|
1208
|
+
if (!cal.IsString() || cal.As<Napi::String>().Utf8Value().empty()) {
|
|
1209
|
+
return ThrowType(env,
|
|
1210
|
+
"saveEvent: 'calendar' must be a calendar id (string); "
|
|
1211
|
+
"leave it out for the default calendar");
|
|
1212
|
+
}
|
|
1213
|
+
p->calendar = cal.As<Napi::String>().Utf8Value();
|
|
1214
|
+
}
|
|
1215
|
+
if (!ParseStringField(env, o, "title", &p->title) ||
|
|
1216
|
+
!ParseStringField(env, o, "location", &p->location) ||
|
|
1217
|
+
!ParseStringField(env, o, "notes", &p->notes) ||
|
|
1218
|
+
!ParseStringField(env, o, "url", &p->url) ||
|
|
1219
|
+
!ParseStringField(env, o, "timeZone", &p->timeZone)) {
|
|
1220
|
+
return false;
|
|
1221
|
+
}
|
|
1222
|
+
@autoreleasepool {
|
|
1223
|
+
// validated here, where a refusal can be a TypeError; made again on
|
|
1224
|
+
// the write queue from the string
|
|
1225
|
+
if (p->url.set() && !ParseURL(p->url.value)) {
|
|
1226
|
+
return ThrowType(env,
|
|
1227
|
+
"saveEvent: 'url' is not an absolute URL "
|
|
1228
|
+
"('https://example.com/…')");
|
|
1229
|
+
}
|
|
1230
|
+
if (p->timeZone.set() &&
|
|
1231
|
+
![NSTimeZone timeZoneWithName:[NSString stringWithUTF8String:
|
|
1232
|
+
p->timeZone.value.c_str()]]) {
|
|
1233
|
+
return ThrowType(env,
|
|
1234
|
+
"saveEvent: 'timeZone' is not a time zone identifier "
|
|
1235
|
+
"('Europe/London'); null makes the event floating");
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
for (const char* k : {"start", "end"}) {
|
|
1239
|
+
Napi::Value t = Given(o, k);
|
|
1240
|
+
if (t.IsEmpty()) continue;
|
|
1241
|
+
double ms;
|
|
1242
|
+
if (!ParseMillis(env, t, std::string("saveEvent: '") + k + "'", &ms)) return false;
|
|
1243
|
+
(strcmp(k, "start") == 0 ? p->start : p->end) = ms;
|
|
1244
|
+
}
|
|
1245
|
+
if (!p->id && (!p->start || !p->end)) {
|
|
1246
|
+
return ThrowType(env,
|
|
1247
|
+
"saveEvent: 'start' and 'end' (epoch ms) are required to "
|
|
1248
|
+
"create an event");
|
|
1249
|
+
}
|
|
1250
|
+
Napi::Value allDay = Given(o, "allDay");
|
|
1251
|
+
if (!allDay.IsEmpty()) {
|
|
1252
|
+
if (!allDay.IsBoolean()) return ThrowType(env, "saveEvent: 'allDay' must be a boolean");
|
|
1253
|
+
p->allDay = allDay.As<Napi::Boolean>().Value();
|
|
1254
|
+
}
|
|
1255
|
+
Napi::Value av = Given(o, "availability");
|
|
1256
|
+
if (!av.IsEmpty()) {
|
|
1257
|
+
EKEventAvailability a;
|
|
1258
|
+
if (!av.IsString() || !ParseAvailability(av.As<Napi::String>().Utf8Value(), &a)) {
|
|
1259
|
+
return ThrowType(env,
|
|
1260
|
+
"saveEvent: 'availability' must be 'busy', 'free', "
|
|
1261
|
+
"'tentative' or 'unavailable'");
|
|
1262
|
+
}
|
|
1263
|
+
p->availability = a;
|
|
1264
|
+
}
|
|
1265
|
+
Napi::Value rec = Given(o, "recurrence");
|
|
1266
|
+
if (!rec.IsEmpty()) {
|
|
1267
|
+
p->recurrence.given = true;
|
|
1268
|
+
if (rec.IsNull()) p->recurrence.null = true;
|
|
1269
|
+
else if (!ParseRule(env, rec, &p->recurrence.value)) return false;
|
|
1270
|
+
}
|
|
1271
|
+
Napi::Value alarms = Given(o, "alarms");
|
|
1272
|
+
if (!alarms.IsEmpty()) {
|
|
1273
|
+
p->alarms.given = true;
|
|
1274
|
+
if (alarms.IsNull()) p->alarms.null = true;
|
|
1275
|
+
else if (!ParseAlarms(env, alarms, &p->alarms.value)) return false;
|
|
1276
|
+
if (p->alarms.value.empty()) p->alarms.null = true;
|
|
1277
|
+
}
|
|
1278
|
+
return true;
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
static bool ParseWriteOpts(Napi::Env env, const char* fn, Napi::Value v,
|
|
1282
|
+
bool forRemove, WriteOpts* o) {
|
|
1283
|
+
if (v.IsEmpty() || v.IsUndefined() || v.IsNull()) return true;
|
|
1284
|
+
std::string shape = std::string(fn) + ": options must be { span?: 'this' | "
|
|
1285
|
+
"'future', commit?: boolean" +
|
|
1286
|
+
(forRemove ? ", occurrenceDate? }" : " }");
|
|
1287
|
+
if (!v.IsObject() || v.IsFunction() || v.IsArray()) return ThrowType(env, shape);
|
|
1288
|
+
Napi::Object opts = v.As<Napi::Object>();
|
|
1289
|
+
Napi::Value span = Given(opts, "span");
|
|
1290
|
+
if (!span.IsEmpty() && !span.IsNull()) {
|
|
1291
|
+
std::string s = span.IsString() ? span.As<Napi::String>().Utf8Value() : "";
|
|
1292
|
+
if (s == "this") o->span = EKSpanThisEvent;
|
|
1293
|
+
else if (s == "future") o->span = EKSpanFutureEvents;
|
|
1294
|
+
else return ThrowType(env, std::string(fn) + ": span must be 'this' (the default) or 'future'");
|
|
1295
|
+
}
|
|
1296
|
+
Napi::Value commit = Given(opts, "commit");
|
|
1297
|
+
if (!commit.IsEmpty() && !commit.IsNull()) {
|
|
1298
|
+
if (!commit.IsBoolean()) return ThrowType(env, std::string(fn) + ": commit must be a boolean");
|
|
1299
|
+
o->commit = commit.As<Napi::Boolean>().Value();
|
|
1300
|
+
}
|
|
1301
|
+
Napi::Value occ = Given(opts, "occurrenceDate");
|
|
1302
|
+
if (!occ.IsEmpty() && !occ.IsNull()) {
|
|
1303
|
+
if (!forRemove) return ThrowType(env, shape + " — 'occurrenceDate' goes in the props, with the 'id'");
|
|
1304
|
+
double ms;
|
|
1305
|
+
if (!ParseMillis(env, occ, std::string(fn) + ": occurrenceDate", &ms)) return false;
|
|
1306
|
+
o->occurrenceDate = ms;
|
|
1307
|
+
}
|
|
1308
|
+
return true;
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// --- the writes (the write queue) --------------------------------------------
|
|
1312
|
+
|
|
1313
|
+
// Serial, at the reads' QoS: writes go one after another, in the order they
|
|
1314
|
+
// were asked, which is what makes a batch (commit: false, …, commit) mean
|
|
1315
|
+
// something.
|
|
1316
|
+
static dispatch_queue_t WriteQueue() {
|
|
1317
|
+
static dispatch_queue_t q = dispatch_queue_create(
|
|
1318
|
+
"dev.windowkit.appkit.calendars.write",
|
|
1319
|
+
dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL,
|
|
1320
|
+
QOS_CLASS_USER_INITIATED, 0));
|
|
1321
|
+
return q;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
static NSString* NS(const std::string& s) {
|
|
1325
|
+
return [NSString stringWithUTF8String:s.c_str()];
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
static NSDate* DateMs(double ms) {
|
|
1329
|
+
return [NSDate dateWithTimeIntervalSince1970:ms / 1000.0];
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
static NSArray<NSNumber*>* Numbers(const std::optional<std::vector<int>>& v) {
|
|
1333
|
+
if (!v) return nil;
|
|
1334
|
+
NSMutableArray<NSNumber*>* a = [NSMutableArray arrayWithCapacity:v->size()];
|
|
1335
|
+
for (int n : *v) [a addObject:@(n)];
|
|
1336
|
+
return a;
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
static EKRecurrenceRule* MakeRule(const RuleInfo& r) {
|
|
1340
|
+
NSMutableArray<EKRecurrenceDayOfWeek*>* days = nil;
|
|
1341
|
+
if (r.daysOfWeek) {
|
|
1342
|
+
days = [NSMutableArray arrayWithCapacity:r.daysOfWeek->size()];
|
|
1343
|
+
for (const DayOfWeek& d : *r.daysOfWeek) {
|
|
1344
|
+
[days addObject:[EKRecurrenceDayOfWeek dayOfWeek:(EKWeekday)d.day
|
|
1345
|
+
weekNumber:d.week]];
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
EKRecurrenceEnd* end = nil;
|
|
1349
|
+
if (r.until) end = [EKRecurrenceEnd recurrenceEndWithEndDate:DateMs(*r.until)];
|
|
1350
|
+
else if (r.count) end = [EKRecurrenceEnd recurrenceEndWithOccurrenceCount:*r.count];
|
|
1351
|
+
return [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:r.frequency
|
|
1352
|
+
interval:r.interval
|
|
1353
|
+
daysOfTheWeek:days
|
|
1354
|
+
daysOfTheMonth:Numbers(r.daysOfMonth)
|
|
1355
|
+
monthsOfTheYear:Numbers(r.monthsOfYear)
|
|
1356
|
+
weeksOfTheYear:Numbers(r.weeksOfYear)
|
|
1357
|
+
daysOfTheYear:Numbers(r.daysOfYear)
|
|
1358
|
+
setPositions:Numbers(r.setPositions)
|
|
1359
|
+
end:end];
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
static EKAlarm* MakeAlarm(const AlarmInfo& a) {
|
|
1363
|
+
return a.absolute ? [EKAlarm alarmWithAbsoluteDate:DateMs(a.value)]
|
|
1364
|
+
: [EKAlarm alarmWithRelativeOffset:a.value];
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
// Anything the framework raises rather than reports comes back as text, so
|
|
1368
|
+
// it can cross as an error instead of ending the process.
|
|
1369
|
+
static NSString* Guarded(void (^body)(void)) {
|
|
1370
|
+
@try {
|
|
1371
|
+
body();
|
|
1372
|
+
return nil;
|
|
1373
|
+
} @catch (NSException* ex) {
|
|
1374
|
+
return [NSString stringWithFormat:@"%@: %@", ex.name, ex.reason];
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// The occurrence of `id` whose place in the series is `occMs`, through the
|
|
1379
|
+
// reads' predicate over the widest window it takes, on the event's own
|
|
1380
|
+
// calendar. nil when no occurrence sits there.
|
|
1381
|
+
static EKEvent* FindOccurrence(EKEventStore* store, EKEvent* first,
|
|
1382
|
+
const std::string& id, double occMs) {
|
|
1383
|
+
NSDate* at = DateMs(occMs);
|
|
1384
|
+
NSArray<EKCalendar*>* cals = first.calendar ? @[ first.calendar ] : nil;
|
|
1385
|
+
NSPredicate* p = [store
|
|
1386
|
+
predicateForEventsWithStartDate:[at dateByAddingTimeInterval:-kOccurrenceWindowS]
|
|
1387
|
+
endDate:[at dateByAddingTimeInterval:kOccurrenceWindowS]
|
|
1388
|
+
calendars:cals];
|
|
1389
|
+
NSString* wanted = NS(id);
|
|
1390
|
+
for (EKEvent* e in [store eventsMatchingPredicate:p]) {
|
|
1391
|
+
if (![e.eventIdentifier isEqualToString:wanted] || !e.occurrenceDate) continue;
|
|
1392
|
+
if (std::fabs(Millis(e.occurrenceDate) - occMs) < 1.0) return e;
|
|
1393
|
+
}
|
|
1394
|
+
return nil;
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
// The event a write names: by id, then by occurrence when one is named. Sets
|
|
1398
|
+
// the answer's error and returns nil when there is no such event — under the
|
|
1399
|
+
// write-only grant that is the framework refusing to read it back, and it
|
|
1400
|
+
// crosses as the EKError it is.
|
|
1401
|
+
static EKEvent* ResolveEvent(EKEventStore* store, const char* fn,
|
|
1402
|
+
const std::string& id,
|
|
1403
|
+
const std::optional<double>& occ, CalAnswer* a) {
|
|
1404
|
+
EKEvent* e = [store eventWithIdentifier:NS(id)];
|
|
1405
|
+
if (!e) {
|
|
1406
|
+
if (WriteOnly()) {
|
|
1407
|
+
a->error = std::string(fn) + ": no event with identifier '" + id +
|
|
1408
|
+
"' — macOS 14's write-only grant saves events but cannot "
|
|
1409
|
+
"read one back to change or remove it "
|
|
1410
|
+
"(EKErrorEventStoreNotAuthorized)";
|
|
1411
|
+
a->fromFramework = true;
|
|
1412
|
+
a->code = (double)EKErrorEventStoreNotAuthorized;
|
|
1413
|
+
a->domain = CopyRequired(EKErrorDomain);
|
|
1414
|
+
a->reason = std::string("EKErrorEventStoreNotAuthorized");
|
|
1415
|
+
} else {
|
|
1416
|
+
a->error = std::string(fn) + ": no event with identifier '" + id +
|
|
1417
|
+
"' (it may have been removed; query again)";
|
|
1418
|
+
}
|
|
1419
|
+
return nil;
|
|
1420
|
+
}
|
|
1421
|
+
if (!occ) return e;
|
|
1422
|
+
EKEvent* o = FindOccurrence(store, e, id, *occ);
|
|
1423
|
+
if (!o) {
|
|
1424
|
+
a->error = std::string(fn) + ": no occurrence of '" + id + "' at " +
|
|
1425
|
+
std::to_string((long long)*occ) +
|
|
1426
|
+
" (pass the occurrenceDate eventsBetween reported for it)";
|
|
1427
|
+
}
|
|
1428
|
+
return o;
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
static bool ResolveCalendar(EKEventStore* store, const std::string& id,
|
|
1432
|
+
EKCalendar** out, CalAnswer* a) {
|
|
1433
|
+
*out = [store calendarWithIdentifier:NS(id)];
|
|
1434
|
+
if (*out) return true;
|
|
1435
|
+
a->error = "saveEvent: no calendar with identifier '" + id + "'" +
|
|
1436
|
+
(WriteOnly() ? " — under macOS 14's write-only grant the "
|
|
1437
|
+
"calendars may not be readable; leave it out for "
|
|
1438
|
+
"the default calendar"
|
|
1439
|
+
: " (it may have been removed; list them again)");
|
|
1440
|
+
return false;
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
static void DoDefaultCalendar(EKEventStore* store, CalAnswer* a) {
|
|
1444
|
+
EKCalendar* c = store.defaultCalendarForNewEvents;
|
|
1445
|
+
if (c) a->calendar = CopyCalendar(c);
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
static void DoSave(EKEventStore* store, const EventProps& p,
|
|
1449
|
+
const WriteOpts& o, CalAnswer* a) {
|
|
1450
|
+
NSString* raised = Guarded(^{
|
|
1451
|
+
EKEvent* e = nil;
|
|
1452
|
+
if (p.id) {
|
|
1453
|
+
e = ResolveEvent(store, "saveEvent", *p.id, p.occurrenceDate, a);
|
|
1454
|
+
if (!e) return;
|
|
1455
|
+
} else {
|
|
1456
|
+
e = [EKEvent eventWithEventStore:store];
|
|
1457
|
+
// nil here is the framework's to refuse (EKErrorNoCalendar)
|
|
1458
|
+
if (!p.calendar) e.calendar = store.defaultCalendarForNewEvents;
|
|
1459
|
+
}
|
|
1460
|
+
if (p.calendar) {
|
|
1461
|
+
EKCalendar* c;
|
|
1462
|
+
if (!ResolveCalendar(store, *p.calendar, &c, a)) return;
|
|
1463
|
+
e.calendar = c;
|
|
1464
|
+
}
|
|
1465
|
+
if (p.title.given) e.title = p.title.null ? nil : NS(p.title.value);
|
|
1466
|
+
if (p.location.given) e.location = p.location.null ? nil : NS(p.location.value);
|
|
1467
|
+
if (p.notes.given) e.notes = p.notes.null ? nil : NS(p.notes.value);
|
|
1468
|
+
if (p.url.given) e.URL = p.url.null ? nil : ParseURL(p.url.value);
|
|
1469
|
+
if (p.timeZone.given) {
|
|
1470
|
+
e.timeZone = p.timeZone.null ? nil : [NSTimeZone timeZoneWithName:NS(p.timeZone.value)];
|
|
1471
|
+
}
|
|
1472
|
+
if (p.allDay) e.allDay = *p.allDay;
|
|
1473
|
+
if (p.start) e.startDate = DateMs(*p.start);
|
|
1474
|
+
if (p.end) e.endDate = DateMs(*p.end);
|
|
1475
|
+
if (p.availability) e.availability = *p.availability;
|
|
1476
|
+
if (p.recurrence.given) {
|
|
1477
|
+
e.recurrenceRules = p.recurrence.null ? nil : @[ MakeRule(p.recurrence.value) ];
|
|
1478
|
+
}
|
|
1479
|
+
if (p.alarms.given) {
|
|
1480
|
+
NSMutableArray<EKAlarm*>* alarms = nil;
|
|
1481
|
+
if (!p.alarms.null) {
|
|
1482
|
+
alarms = [NSMutableArray arrayWithCapacity:p.alarms.value.size()];
|
|
1483
|
+
for (const AlarmInfo& al : p.alarms.value) [alarms addObject:MakeAlarm(al)];
|
|
1484
|
+
}
|
|
1485
|
+
e.alarms = alarms;
|
|
1486
|
+
}
|
|
1487
|
+
// NO with no error is "nothing was dirty", which is not a failure
|
|
1488
|
+
NSError* err = nil;
|
|
1489
|
+
BOOL ok = [store saveEvent:e span:o.span commit:o.commit error:&err];
|
|
1490
|
+
if (!ok && err) {
|
|
1491
|
+
SetFrameworkError(a, "saveEvent", err);
|
|
1492
|
+
return;
|
|
1493
|
+
}
|
|
1494
|
+
a->id = Copy(e.eventIdentifier);
|
|
1495
|
+
});
|
|
1496
|
+
if (raised) a->error = "saveEvent: EventKit raised " + CopyRequired(raised);
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
static void DoRemove(EKEventStore* store, const std::string& id,
|
|
1500
|
+
const WriteOpts& o, CalAnswer* a) {
|
|
1501
|
+
NSString* raised = Guarded(^{
|
|
1502
|
+
EKEvent* e = ResolveEvent(store, "removeEvent", id, o.occurrenceDate, a);
|
|
1503
|
+
if (!e) return;
|
|
1504
|
+
NSError* err = nil;
|
|
1505
|
+
BOOL ok = [store removeEvent:e span:o.span commit:o.commit error:&err];
|
|
1506
|
+
if (!ok && err) SetFrameworkError(a, "removeEvent", err);
|
|
1507
|
+
});
|
|
1508
|
+
if (raised) a->error = "removeEvent: EventKit raised " + CopyRequired(raised);
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
static void DoCommit(EKEventStore* store, CalAnswer* a) {
|
|
1512
|
+
NSString* raised = Guarded(^{
|
|
1513
|
+
NSError* err = nil;
|
|
1514
|
+
if (![store commit:&err] && err) SetFrameworkError(a, "commitCalendarStore", err);
|
|
1515
|
+
});
|
|
1516
|
+
if (raised) a->error = "commitCalendarStore: EventKit raised " + CopyRequired(raised);
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
// --- the write natives ------------------------------------------------------
|
|
1520
|
+
|
|
1521
|
+
// The callback of a (…, opts?, cb) call: at 1 when there are no options.
|
|
1522
|
+
static bool CallbackAt(Napi::Env env, const Napi::CallbackInfo& info,
|
|
1523
|
+
size_t first, const char* shape, size_t* at) {
|
|
1524
|
+
*at = info.Length() > first && info[first].IsFunction() ? first : first + 1;
|
|
1525
|
+
if (info.Length() <= *at || !info[*at].IsFunction()) return ThrowType(env, shape);
|
|
1526
|
+
return true;
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
// defaultCalendar(cb) — cb(err, calendar | null): defaultCalendarForNewEvents,
|
|
1530
|
+
// where a save with no calendar goes. Either grant; never prompts.
|
|
1531
|
+
static Napi::Value DefaultCalendar(const Napi::CallbackInfo& info) {
|
|
1532
|
+
Napi::Env env = info.Env();
|
|
1533
|
+
if (info.Length() < 1 || !info[0].IsFunction()) {
|
|
1534
|
+
ThrowType(env, "defaultCalendar: expected a callback (cb)");
|
|
1535
|
+
return env.Undefined();
|
|
1536
|
+
}
|
|
1537
|
+
@autoreleasepool {
|
|
1538
|
+
EKEventStore* store = CALEventStore();
|
|
1539
|
+
Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
|
|
1540
|
+
env, info[0].As<Napi::Function>(), "appkit:defaultCalendar", 0, 1);
|
|
1541
|
+
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
|
|
1542
|
+
@autoreleasepool {
|
|
1543
|
+
CalAnswer* a = new CalAnswer;
|
|
1544
|
+
a->kind = Answer::Calendar;
|
|
1545
|
+
if (Writable("defaultCalendar", a)) DoDefaultCalendar(store, a);
|
|
1546
|
+
Deliver(tsfn, a);
|
|
1547
|
+
}
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
return env.Undefined();
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
// saveEvent(props, opts?, cb) — cb(err, id): a new event when props has no
|
|
1554
|
+
// id, a change to the one it names otherwise (the occurrence at
|
|
1555
|
+
// props.occurrenceDate of a recurring one). opts.span says how far a change
|
|
1556
|
+
// to a recurring event reaches; opts.commit false leaves it for
|
|
1557
|
+
// commitCalendarStore. Either grant; never prompts.
|
|
1558
|
+
static Napi::Value SaveEvent(const Napi::CallbackInfo& info) {
|
|
1559
|
+
Napi::Env env = info.Env();
|
|
1560
|
+
const char* shape = "saveEvent: expected (props, opts?, cb)";
|
|
1561
|
+
size_t cbAt;
|
|
1562
|
+
if (info.Length() < 1 || !CallbackAt(env, info, 1, shape, &cbAt)) {
|
|
1563
|
+
if (info.Length() < 1) ThrowType(env, shape);
|
|
1564
|
+
return env.Undefined();
|
|
1565
|
+
}
|
|
1566
|
+
EventProps props;
|
|
1567
|
+
WriteOpts opts;
|
|
1568
|
+
if (!ParseEventProps(env, info[0], &props)) return env.Undefined();
|
|
1569
|
+
if (cbAt == 2 && !ParseWriteOpts(env, "saveEvent", info[1], false, &opts)) {
|
|
1570
|
+
return env.Undefined();
|
|
1571
|
+
}
|
|
1572
|
+
@autoreleasepool {
|
|
1573
|
+
EKEventStore* store = CALEventStore();
|
|
1574
|
+
Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
|
|
1575
|
+
env, info[cbAt].As<Napi::Function>(), "appkit:saveEvent", 0, 1);
|
|
1576
|
+
dispatch_async(WriteQueue(), ^{
|
|
1577
|
+
@autoreleasepool {
|
|
1578
|
+
CalAnswer* a = new CalAnswer;
|
|
1579
|
+
a->kind = Answer::Id;
|
|
1580
|
+
if (Writable("saveEvent", a)) DoSave(store, props, opts, a);
|
|
1581
|
+
Deliver(tsfn, a);
|
|
1582
|
+
}
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
return env.Undefined();
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
// removeEvent(id, opts?, cb) — cb(err): the event, or with opts.span
|
|
1589
|
+
// 'future' this and every later occurrence, or with opts.occurrenceDate the
|
|
1590
|
+
// one occurrence (and what follows it). Either grant; never prompts.
|
|
1591
|
+
static Napi::Value RemoveEvent(const Napi::CallbackInfo& info) {
|
|
1592
|
+
Napi::Env env = info.Env();
|
|
1593
|
+
const char* shape = "removeEvent: expected (id, opts?, cb)";
|
|
1594
|
+
size_t cbAt;
|
|
1595
|
+
if (info.Length() < 1 || !CallbackAt(env, info, 1, shape, &cbAt)) {
|
|
1596
|
+
if (info.Length() < 1) ThrowType(env, shape);
|
|
1597
|
+
return env.Undefined();
|
|
1598
|
+
}
|
|
1599
|
+
if (!info[0].IsString() || info[0].As<Napi::String>().Utf8Value().empty()) {
|
|
1600
|
+
ThrowType(env, "removeEvent: 'id' must be the identifier of an event (a string)");
|
|
1601
|
+
return env.Undefined();
|
|
1602
|
+
}
|
|
1603
|
+
std::string id = info[0].As<Napi::String>().Utf8Value();
|
|
1604
|
+
WriteOpts opts;
|
|
1605
|
+
if (cbAt == 2 && !ParseWriteOpts(env, "removeEvent", info[1], true, &opts)) {
|
|
1606
|
+
return env.Undefined();
|
|
1607
|
+
}
|
|
1608
|
+
@autoreleasepool {
|
|
1609
|
+
EKEventStore* store = CALEventStore();
|
|
1610
|
+
Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
|
|
1611
|
+
env, info[cbAt].As<Napi::Function>(), "appkit:removeEvent", 0, 1);
|
|
1612
|
+
dispatch_async(WriteQueue(), ^{
|
|
1613
|
+
@autoreleasepool {
|
|
1614
|
+
CalAnswer* a = new CalAnswer;
|
|
1615
|
+
a->kind = Answer::Done;
|
|
1616
|
+
if (Writable("removeEvent", a)) DoRemove(store, id, opts, a);
|
|
1617
|
+
Deliver(tsfn, a);
|
|
1618
|
+
}
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
return env.Undefined();
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
// commitCalendarStore(cb) — cb(err): commits what saves and removes with
|
|
1625
|
+
// commit: false left pending, in the order they were asked.
|
|
1626
|
+
static Napi::Value CommitCalendarStore(const Napi::CallbackInfo& info) {
|
|
1627
|
+
Napi::Env env = info.Env();
|
|
1628
|
+
if (info.Length() < 1 || !info[0].IsFunction()) {
|
|
1629
|
+
ThrowType(env, "commitCalendarStore: expected a callback (cb)");
|
|
1630
|
+
return env.Undefined();
|
|
1631
|
+
}
|
|
1632
|
+
@autoreleasepool {
|
|
1633
|
+
EKEventStore* store = CALEventStore();
|
|
1634
|
+
Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
|
|
1635
|
+
env, info[0].As<Napi::Function>(), "appkit:commitCalendarStore", 0, 1);
|
|
1636
|
+
dispatch_async(WriteQueue(), ^{
|
|
1637
|
+
@autoreleasepool {
|
|
1638
|
+
CalAnswer* a = new CalAnswer;
|
|
1639
|
+
a->kind = Answer::Done;
|
|
1640
|
+
if (Writable("commitCalendarStore", a)) DoCommit(store, a);
|
|
1641
|
+
Deliver(tsfn, a);
|
|
1642
|
+
}
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
return env.Undefined();
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
// resetCalendarStore(cb) — cb(null): forgets a pending batch, [EKEventStore
|
|
1649
|
+
// reset]; the store is back to the database's state. Needs no grant.
|
|
1650
|
+
static Napi::Value ResetCalendarStore(const Napi::CallbackInfo& info) {
|
|
1651
|
+
Napi::Env env = info.Env();
|
|
1652
|
+
if (info.Length() < 1 || !info[0].IsFunction()) {
|
|
1653
|
+
ThrowType(env, "resetCalendarStore: expected a callback (cb)");
|
|
1654
|
+
return env.Undefined();
|
|
1655
|
+
}
|
|
1656
|
+
@autoreleasepool {
|
|
1657
|
+
EKEventStore* store = CALEventStore();
|
|
1658
|
+
Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
|
|
1659
|
+
env, info[0].As<Napi::Function>(), "appkit:resetCalendarStore", 0, 1);
|
|
1660
|
+
dispatch_async(WriteQueue(), ^{
|
|
1661
|
+
@autoreleasepool {
|
|
1662
|
+
CalAnswer* a = new CalAnswer;
|
|
1663
|
+
a->kind = Answer::Done;
|
|
1664
|
+
[store reset];
|
|
1665
|
+
Deliver(tsfn, a);
|
|
1666
|
+
}
|
|
1667
|
+
});
|
|
1668
|
+
}
|
|
1669
|
+
return env.Undefined();
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
// --- test seam ---------------------------------------------------------------
|
|
1673
|
+
|
|
1674
|
+
// postCalendarStoreChanged() — the notification EventKit posts when anything
|
|
1675
|
+
// in the store changed, posted from here through the same centre, so the
|
|
1676
|
+
// observer path can be exercised without touching the user's calendars.
|
|
1677
|
+
// Test-only, like postAccessibilityDisplayChange; it creates the store (and
|
|
1678
|
+
// with it the observer) if no verb has yet, which never prompts.
|
|
1679
|
+
static Napi::Value PostCalendarStoreChanged(const Napi::CallbackInfo& info) {
|
|
1680
|
+
@autoreleasepool {
|
|
1681
|
+
[NSNotificationCenter.defaultCenter
|
|
1682
|
+
postNotificationName:EKEventStoreChangedNotification
|
|
1683
|
+
object:CALEventStore()];
|
|
1684
|
+
}
|
|
1685
|
+
return info.Env().Undefined();
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
// ---------------------------------------------------------------------------
|
|
1689
|
+
// registration (called from addon.mm's Init)
|
|
1690
|
+
// ---------------------------------------------------------------------------
|
|
1691
|
+
|
|
1692
|
+
void InitCalendars(Napi::Env env, Napi::Object exports) {
|
|
1693
|
+
gChanged = ChangedTsfn::New(env, "appkit:calendars-changed", 0, 1);
|
|
1694
|
+
gChanged.Unref(env); // a change never holds the loop open by itself
|
|
1695
|
+
exports.Set("calendars", Napi::Function::New(env, Calendars));
|
|
1696
|
+
exports.Set("eventsBetween", Napi::Function::New(env, EventsBetween));
|
|
1697
|
+
exports.Set("defaultCalendar", Napi::Function::New(env, DefaultCalendar));
|
|
1698
|
+
exports.Set("saveEvent", Napi::Function::New(env, SaveEvent));
|
|
1699
|
+
exports.Set("removeEvent", Napi::Function::New(env, RemoveEvent));
|
|
1700
|
+
exports.Set("commitCalendarStore",
|
|
1701
|
+
Napi::Function::New(env, CommitCalendarStore));
|
|
1702
|
+
exports.Set("resetCalendarStore",
|
|
1703
|
+
Napi::Function::New(env, ResetCalendarStore));
|
|
1704
|
+
exports.Set("postCalendarStoreChanged",
|
|
1705
|
+
Napi::Function::New(env, PostCalendarStoreChanged));
|
|
1706
|
+
}
|