-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsync.mjs
More file actions
388 lines (333 loc) · 13.2 KB
/
sync.mjs
File metadata and controls
388 lines (333 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import {
fetchIcalEvents,
extractTrips,
extractFlights,
extractLodging,
buildTimezoneSegments,
filterFutureSegments,
filterFutureTrips,
filterIgnoredTrips,
deduplicateSegments,
} from './lib/tripit.mjs';
import {
createClient,
listEntries,
clearAllEntries,
createEntry,
getPrimaryCalendar,
listReclaimEvents,
setEventPriority,
} from './lib/reclaim.mjs';
import {
createGCalClient,
listOooEvents,
createOooEvent,
deleteOooEvent,
OOO_PREFIX,
} from './lib/google-calendar.mjs';
import { entriesChanged, sendNotification, findOverlaps } from './lib/notify.mjs';
// Parse CLI arguments: mode (positional) and --output=json (flag)
const args = process.argv.slice(2);
const outputIdx = args.findIndex(a => a.startsWith('--output='));
const outputFormat = outputIdx >= 0 ? args.splice(outputIdx, 1)[0].split('=')[1] : 'text';
if (outputFormat !== 'text' && outputFormat !== 'json') {
console.error(`Unknown output format: ${outputFormat}`);
console.error('Supported: --output=text (default), --output=json');
process.exit(1);
}
const jsonOutput = outputFormat === 'json';
const mode = args[0] || 'dry-run';
const VALID_MODES = ['dry-run', 'sync'];
if (!VALID_MODES.includes(mode)) {
console.error(`Unknown mode: ${mode}`);
console.error(`Usage: node sync.mjs [${VALID_MODES.join('|')}] [--output=json]`);
process.exit(1);
}
// In JSON mode, suppress human-readable output and collect structured data instead
const _log = console.log;
const _error = console.error;
if (jsonOutput) {
console.log = () => {};
}
const result = {
mode,
noChanges: true,
timezoneChanges: [],
segments: [],
ooo: null,
conflicts: [],
errors: [],
};
const TRIPIT_ICAL_URL = process.env.TRIPIT_ICAL_URL;
const RECLAIM_API_TOKEN = process.env.RECLAIM_API_TOKEN;
if (!TRIPIT_ICAL_URL) {
if (jsonOutput) { result.errors.push('Missing TRIPIT_ICAL_URL environment variable'); _log(JSON.stringify(result)); }
_error('Missing TRIPIT_ICAL_URL environment variable');
process.exit(1);
}
if (!RECLAIM_API_TOKEN) {
if (jsonOutput) { result.errors.push('Missing RECLAIM_API_TOKEN environment variable'); _log(JSON.stringify(result)); }
_error('Missing RECLAIM_API_TOKEN environment variable');
process.exit(1);
}
// Google Calendar credentials (all optional — OOO feature skips if missing)
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
const GOOGLE_REFRESH_TOKEN = process.env.GOOGLE_REFRESH_TOKEN;
// Optional: comma-separated trip names to ignore (case-insensitive substring match)
const IGNORE_TRIPS = (process.env.TRIPIT_IGNORE_TRIPS || '')
.split(',')
.map(s => s.trim().toLowerCase())
.filter(Boolean);
// Optional: comma-separated keywords — any trip whose name contains one of these is ignored
const IGNORE_KEYWORDS = (process.env.TRIPIT_IGNORE_KEYWORDS || '')
.split(',')
.map(s => s.trim().toLowerCase())
.filter(Boolean);
console.log(`\n=== TripIt → Reclaim Travel Timezone Sync ===`);
console.log(`Mode: ${mode}\n`);
try {
// Step 1: Fetch and parse iCal feed
const events = await fetchIcalEvents(TRIPIT_ICAL_URL);
const allTrips = extractTrips(events);
const flights = extractFlights(events);
const stays = extractLodging(events);
// Filter out ignored trips (by exact name or keyword match)
const trips = filterIgnoredTrips(allTrips, IGNORE_TRIPS, IGNORE_KEYWORDS);
const skipped = allTrips.length - trips.length;
if (skipped > 0) {
console.log(` Ignored ${skipped} trip(s) matching TRIPIT_IGNORE_TRIPS/KEYWORDS`);
}
// Step 2: Build timezone segments
console.log('\nBuilding timezone segments...');
const allSegments = buildTimezoneSegments(trips, flights, stays);
console.log(` Built ${allSegments.length} segment(s)`);
// Step 3: Filter and deduplicate
const future = filterFutureSegments(allSegments);
console.log(` ${future.length} future segment(s) > 1 day`);
const segments = deduplicateSegments(future);
console.log(` ${segments.length} after deduplication`);
// Check for overlapping trips
const overlaps = findOverlaps(future);
if (overlaps.length > 0) {
console.log(`\n⚠️ OVERLAPPING TRIPS:`);
for (const o of overlaps) {
console.log(` ${o.labelA} (→ ${o.endA}) overlaps ${o.labelB} (${o.startB} →)`);
result.conflicts.push({ trip1: o.labelA, trip2: o.labelB, overlap: o.startB });
}
}
// Print summary
console.log(`\n── Timezone segments ──`);
for (const s of segments) {
console.log(` ${s.label}`);
console.log(` ${s.startDate} → ${s.endDate} [${s.timezone}]`);
}
// Populate result segments. `from` / `to` (date-only YYYY-MM-DD)
// preserve the JSON contract existing consumers depend on; the
// adjacent `from_dt` / `to_dt` (ISO 8601 UTC) carry the underlying
// wall-clock so a downstream walker can resolve at the actual
// flight-arrival / check-in moment instead of UTC midnight of the
// departure day. See jbaruch/nanoclaw-admin#229.
result.segments = segments.map(s => ({
timezone: s.timezone,
from: s.startDate,
to: s.endDate,
from_dt: s.startDateTime,
to_dt: s.endDateTime,
label: s.label,
}));
// Get future trips for OOO sync
const futureTrips = filterFutureTrips(trips);
if (mode === 'dry-run') {
console.log('\nDry run complete. No changes made to Reclaim.');
if (futureTrips.length > 0 && GOOGLE_CLIENT_ID && GOOGLE_CLIENT_SECRET && GOOGLE_REFRESH_TOKEN) {
console.log(`\n── OOO blocks (would create) ──`);
for (const t of futureTrips) {
console.log(` ${OOO_PREFIX}${t.summary} ${t.startDate} → ${t.endDate}`);
}
} else if (futureTrips.length > 0) {
console.log('\n OOO blocks: skipped (Google Calendar credentials not configured)');
}
if (jsonOutput) _log(JSON.stringify(result));
process.exit(0);
}
// Step 4: Sync to Reclaim
console.log('\n── Syncing to Reclaim ──');
const client = createClient(RECLAIM_API_TOKEN);
// Show current state
const current = await listEntries(client);
const previousEntries = current.entries || [];
console.log(` Current entries: ${previousEntries.length}`);
const defTz = typeof current.defaultTimezone === 'object'
? JSON.stringify(current.defaultTimezone)
: current.defaultTimezone || 'unknown';
console.log(` Default timezone: ${defTz}`);
let timezoneChanged = false;
// Skip timezone sync if nothing changed
if (!entriesChanged(previousEntries, segments)) {
console.log(' No timezone changes detected — skipping timezone sync.');
} else {
timezoneChanged = true;
result.noChanges = false;
// Clear existing (pass known entries to avoid redundant API call)
await clearAllEntries(client, previousEntries);
for (const e of previousEntries) {
result.timezoneChanges.push({
action: 'delete', timezone: e.timezone, from: e.startDate, to: e.endDate,
});
}
// Create new entries
if (segments.length === 0) {
console.log(' No segments to sync.');
} else {
for (const s of segments) {
console.log(` Creating: ${s.timezone} (${s.startDate} → ${s.endDate})`);
result.timezoneChanges.push({
action: 'create', timezone: s.timezone, from: s.startDate, to: s.endDate,
});
}
await Promise.all(segments.map(s => createEntry(client, {
startDate: s.startDate,
endDate: s.endDate,
timezone: s.timezone,
})));
console.log(` Created ${segments.length} ${segments.length === 1 ? 'entry' : 'entries'}`);
}
}
// Step 5: OOO calendar blocks
let oooStats = null;
const gcal = createGCalClient({
clientId: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
refreshToken: GOOGLE_REFRESH_TOKEN,
});
if (!gcal) {
console.log('\n OOO blocks: skipped (Google Calendar credentials not configured)');
} else {
console.log('\n── OOO Calendar Blocks ──');
oooStats = await syncOooEvents(client, gcal, futureTrips);
result.ooo = {
created: oooStats.created,
deleted: oooStats.deleted,
setToP2: oooStats.prioritySet,
};
if (oooStats.created > 0 || oooStats.deleted > 0) {
result.noChanges = false;
}
}
// Notify on changes (never throws)
if (timezoneChanged || (oooStats && (oooStats.created > 0 || oooStats.deleted > 0 || oooStats.prioritySet > 0))) {
await sendNotification(previousEntries, segments, future, oooStats);
}
console.log('\nSync complete!');
if (jsonOutput) _log(JSON.stringify(result));
} catch (err) {
if (jsonOutput) {
result.errors.push(err.message);
_log(JSON.stringify(result));
}
_error(`\nFATAL ERROR: ${err.message}`);
_error(err.stack);
process.exit(1);
}
/**
* Sync OOO events: create missing, delete stale, set Reclaim priority to P2.
*/
async function syncOooEvents(reclaimClient, gcal, futureTrips) {
const stats = { created: 0, deleted: 0, prioritySet: 0, createdNames: [], deletedNames: [] };
// Get Reclaim primary calendar for the Google Calendar ID and Reclaim calendar ID
const { calendarId, googleCalendarId } = await getPrimaryCalendar(reclaimClient);
if (!googleCalendarId) {
console.log(' WARNING: Could not determine Google Calendar ID from Reclaim');
return stats;
}
console.log(` Reclaim calendar: ${calendarId}, Google Calendar: ${googleCalendarId}`);
// List existing OOO events in Google Calendar
const existingOoo = await listOooEvents(gcal, googleCalendarId);
console.log(` Existing OOO events: ${existingOoo.length}`);
// Build a map of desired OOO events keyed by trip summary
const desiredByName = new Map();
for (const trip of futureTrips) {
desiredByName.set(trip.summary, trip);
}
// Build a map of existing OOO events keyed by trip summary (strip prefix)
const existingByName = new Map();
for (const ev of existingOoo) {
const name = ev.summary.replace(OOO_PREFIX, '');
existingByName.set(name, ev);
}
// Delete stale OOO events (exist in GCal but no matching future trip, or dates changed)
for (const [name, ev] of existingByName) {
const desired = desiredByName.get(name);
if (!desired || desired.startDate !== ev.startDate || desired.endDate !== ev.endDate) {
console.log(` Deleting stale: ${ev.summary}`);
await deleteOooEvent(gcal, googleCalendarId, ev.id);
stats.deleted++;
stats.deletedNames.push(name);
existingByName.delete(name);
}
}
// Create missing OOO events
const createdEventIds = [];
for (const [name, trip] of desiredByName) {
if (existingByName.has(name)) continue;
console.log(` Creating: ${OOO_PREFIX}${name} ${trip.startDate} → ${trip.endDate}`);
const eventId = await createOooEvent(gcal, googleCalendarId, {
summary: name,
startDate: trip.startDate,
endDate: trip.endDate,
});
createdEventIds.push(eventId);
stats.created++;
stats.createdNames.push(name);
}
// Set Reclaim priority to P2 for OOO events
// Search Reclaim for our OOO events and set priority
const pendingPriority = await setOooPriorities(reclaimClient, calendarId, futureTrips, stats);
// If we just created events and Reclaim hasn't synced them yet, retry in 10 minutes
if (stats.created > 0 && pendingPriority > 0) {
const RETRY_DELAY_MS = parseInt(process.env.OOO_RETRY_DELAY_MS, 10) || 60 * 1000;
console.log(` ${pendingPriority} new event(s) not yet in Reclaim — retrying priority in ${RETRY_DELAY_MS / 1000}s...`);
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
await setOooPriorities(reclaimClient, calendarId, futureTrips, stats);
}
console.log(` OOO sync: ${stats.created} created, ${stats.deleted} deleted, ${stats.prioritySet} set to P2`);
return stats;
}
/**
* Find OOO events in Reclaim and set their priority to P2.
* Returns the number of expected events that weren't found (still pending Reclaim sync).
*/
async function setOooPriorities(reclaimClient, calendarId, futureTrips, stats) {
if (futureTrips.length === 0) return 0;
const earliest = futureTrips.reduce((min, t) => t.startDate < min ? t.startDate : min, futureTrips[0].startDate);
const latest = futureTrips.reduce((max, t) => t.endDate > max ? t.endDate : max, futureTrips[0].endDate);
try {
const reclaimEvents = await listReclaimEvents(
reclaimClient,
calendarId,
earliest,
latest,
);
const oooEvents = (reclaimEvents || []).filter(e =>
e.title?.startsWith(OOO_PREFIX)
);
const needsPriority = oooEvents.filter(e => e.priority !== 'P2');
for (const ev of needsPriority) {
console.log(` Setting P2 priority: ${ev.title}`);
try {
await setEventPriority(reclaimClient, calendarId, ev.eventId, 'P2');
stats.prioritySet++;
} catch (err) {
console.log(` WARNING: Failed to set priority for "${ev.title}": ${err.message}`);
}
}
// How many trips don't have a matching Reclaim event yet?
const foundNames = new Set(oooEvents.map(e => e.title));
const missing = futureTrips.filter(t => !foundNames.has(`${OOO_PREFIX}${t.summary}`));
return missing.length;
} catch (err) {
console.log(` WARNING: Could not list Reclaim events for priority update: ${err.message}`);
return futureTrips.length;
}
}