-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalBlock.gs
More file actions
1157 lines (1026 loc) · 41.1 KB
/
Copy pathCalBlock.gs
File metadata and controls
1157 lines (1026 loc) · 41.1 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// CalBlock — Clockwise Replacement
// Google Apps Script — runs under your work Google account
// ============================================================================
// ---------------------------------------------------------------------------
// CONFIGURATION — Update these values during setup
// ---------------------------------------------------------------------------
const CONFIG = {
// Calendar IDs
personalCalendarId: 'your-personal-email@gmail.com', // Shared TO work account (read-only)
workCalendarId: 'primary', // Native work calendar
// Travel time
homeAddress: '', // TODO: Set your home address
mapsApiKey: '', // TODO: Set your Google Maps API key
travelTimeBufferMin: 10, // Extra buffer on top of Maps estimate
defaultTravelMinutes: 30, // Fallback if Maps API fails or location is vague
maxDriveTravelMinutes: 180, // Skip travel blocks if drive time exceeds this (interstate/overseas — you'd fly)
// Sync behaviour
syncWindowDays: 14, // How far ahead to sync
syncAllDayEvents: false, // Whether to sync all-day personal events
syncTentativeEvents: true, // Whether to sync tentative/maybe personal events
// Event identification tags
syncTagPrefix: '[CalBlock]',
travelTagPrefix: '[Travel]',
// Error notification
errorNotifyEmail: 'your-email@gmail.com',
// Maps API cache duration (hours)
mapsCacheDurationHours: 24,
};
// ---------------------------------------------------------------------------
// ADAPTIVE THROTTLE — Slows down API calls when rate limits are encountered
// ---------------------------------------------------------------------------
var _throttleMs = 250; // Current delay between Calendar API writes (ms)
var _rateLimitHitCount = 0; // Number of rate limit errors this execution
/** Pause between Calendar API writes to stay within quotas. */
function calendarThrottle_() {
Utilities.sleep(_throttleMs);
}
/** Escalate throttle after a rate limit hit — doubles the inter-call delay. */
function escalateThrottle_() {
_rateLimitHitCount++;
_throttleMs = Math.min(3000, 250 * Math.pow(2, _rateLimitHitCount));
Logger.log('CalBlock: Throttle escalated to ' + _throttleMs + 'ms (rate limit hit #' + _rateLimitHitCount + ')');
}
/**
* Set all metadata on a newly created calendar block with throttling between
* each API call to avoid triggering Google's rate limits.
*
* @param {CalendarEvent} block - The event to configure.
* @param {string} description - The description text.
* @param {Object} tags - Key-value pairs to set as tags.
*/
function setBlockMetadata_(block, description, tags) {
block.setVisibility(CalendarApp.Visibility.PRIVATE);
calendarThrottle_();
block.removeAllReminders();
calendarThrottle_();
block.setDescription(description);
calendarThrottle_();
var keys = Object.keys(tags);
for (var i = 0; i < keys.length; i++) {
block.setTag(keys[i], tags[keys[i]]);
if (i < keys.length - 1) calendarThrottle_();
}
}
// ---------------------------------------------------------------------------
// MAIN ENTRY POINT — Called by the 10-minute trigger
// ---------------------------------------------------------------------------
function syncAll() {
// Prevent concurrent runs — if a previous trigger is still executing, skip
var lock = LockService.getScriptLock();
if (!lock.tryLock(30000)) {
Logger.log('CalBlock: Another sync is already running — skipping this run');
return;
}
const stats = {
personalSynced: 0,
personalUpdated: 0,
personalDeleted: 0,
travelCreated: 0,
travelUpdated: 0,
travelDeleted: 0,
errors: [],
};
try {
Logger.log('CalBlock: Starting sync run...');
syncPersonalToWork_(stats);
syncTravelBlocks_(stats);
cleanupOrphans_(stats);
// Store stats for debugging
PropertiesService.getScriptProperties().setProperty(
'lastSync',
JSON.stringify({
timestamp: new Date().toISOString(),
stats: stats,
})
);
Logger.log('CalBlock: Sync complete. Stats: ' + JSON.stringify(stats));
// Send alert if there were non-fatal errors
if (stats.errors.length > 0) {
MailApp.sendEmail(
CONFIG.errorNotifyEmail,
'[CalBlock] Sync completed with errors',
'CalBlock ran but encountered errors:\n\n' +
stats.errors.join('\n\n') +
'\n\nStats: ' +
JSON.stringify(stats, null, 2)
);
}
} catch (e) {
Logger.log('CalBlock: CRITICAL ERROR — ' + e.message);
try {
MailApp.sendEmail(
CONFIG.errorNotifyEmail,
'[CalBlock] CRITICAL: Sync failed',
'CalBlock failed entirely.\n\nError: ' +
e.message +
'\nStack: ' +
e.stack +
'\n\nPartial stats: ' +
JSON.stringify(stats, null, 2)
);
} catch (mailErr) {
Logger.log('CalBlock: Could not send error email — ' + mailErr.message);
}
} finally {
lock.releaseLock();
}
}
// ---------------------------------------------------------------------------
// FEATURE 1: Personal Calendar → Work Calendar Sync
// ---------------------------------------------------------------------------
function syncPersonalToWork_(stats) {
const now = new Date();
const endDate = new Date(now.getTime() + CONFIG.syncWindowDays * 24 * 60 * 60 * 1000);
// 1. Fetch personal events using CalendarApp (reliable for shared calendars)
var personalCal;
try {
personalCal = CalendarApp.getCalendarById(CONFIG.personalCalendarId);
} catch (e) {
stats.errors.push(
'Cannot access personal calendar (' +
CONFIG.personalCalendarId +
'). Is it shared with this account? Error: ' + e.message
);
return;
}
if (!personalCal) {
stats.errors.push(
'Personal calendar not found: ' +
CONFIG.personalCalendarId +
'. Make sure it is shared with this work account.'
);
return;
}
var personalEvents = personalCal.getEvents(now, endDate);
Logger.log('CalBlock: Found ' + personalEvents.length + ' personal events in window');
// 2. Build transparency lookup using Advanced Calendar Service (best-effort)
// CalendarApp doesn't expose transparency (free/busy). We attempt the
// Calendar API v3 to get it. If it fails (common with cross-account shared
// calendars), we degrade gracefully — all non-declined events get synced.
var transparencyMap = {}; // eventId → 'transparent' | 'opaque'
var hasTransparencyData = false;
try {
var apiEvents = fetchPersonalEventsAdvanced_(CONFIG.personalCalendarId, now, endDate);
if (apiEvents && apiEvents.length > 0) {
apiEvents.forEach(function (ae) {
if (ae.id && ae.transparency) {
transparencyMap[ae.id] = ae.transparency;
}
});
hasTransparencyData = true;
Logger.log('CalBlock: Advanced Calendar API succeeded — transparency data for ' +
Object.keys(transparencyMap).length + ' events');
}
} catch (e) {
Logger.log('CalBlock: Advanced Calendar API unavailable (' + e.message +
'). Free/busy filtering disabled — all non-declined events will sync.');
}
// 3. Get existing CalBlock blocks from work calendar
var workCal = CalendarApp.getCalendarById(CONFIG.workCalendarId);
var existingBlocks = getTaggedEvents_(workCal, CONFIG.syncTagPrefix, now, endDate);
Logger.log('CalBlock: Found ' + existingBlocks.length + ' existing sync blocks');
// Build lookup of existing blocks by source event ID (normalized)
// Uses tag first, then falls back to parsing the description (tags can be
// unreliable in CalendarApp across runs). Also deduplicates — if multiple
// blocks share the same sourceId, keep the first and delete the rest.
var blocksBySourceId = {};
existingBlocks.forEach(function (block) {
var sourceId = block.getTag('sourceEventId');
if (!sourceId) {
sourceId = extractIdFromDescription_(block.getDescription(), 'sourceId');
}
if (sourceId) {
var normId = normalizeEventId_(sourceId);
if (blocksBySourceId[normId]) {
// Duplicate detected — delete this one, keep the first
try {
block.deleteEvent();
stats.personalDeleted++;
Logger.log('CalBlock: Deleted duplicate sync block for: ' + normId);
} catch (e) {
stats.errors.push('Error deleting duplicate sync block: ' + e.message);
}
} else {
blocksBySourceId[normId] = block;
}
}
});
// 4. Process personal events
var processedSourceIds = {};
personalEvents.forEach(function (personalEvent) {
try {
// Skip all-day events unless configured to sync them
if (personalEvent.isAllDayEvent() && !CONFIG.syncAllDayEvents) {
return;
}
// Skip declined events
if (personalEvent.getMyStatus() === CalendarApp.GuestStatus.NO) {
return;
}
// Skip tentative events if configured
if (
!CONFIG.syncTentativeEvents &&
personalEvent.getMyStatus() === CalendarApp.GuestStatus.MAYBE
) {
return;
}
// Skip events marked as "free" (if transparency data is available)
var rawId = personalEvent.getId();
var baseId = normalizeEventId_(rawId);
// Create a unique instance ID for recurring events by appending the start time.
// CalendarApp.getId() returns the same base ID for every instance of a
// recurring event, so without this, all instances would collide on the same key.
var eventId = baseId;
if (!personalEvent.isAllDayEvent()) {
eventId = baseId + '_' + personalEvent.getStartTime().getTime();
} else {
eventId = baseId + '_' + personalEvent.getAllDayStartDate().getTime();
}
if (hasTransparencyData) {
var transparency = transparencyMap[rawId] || transparencyMap[baseId];
if (transparency === 'transparent') {
Logger.log('CalBlock: Skipping free/transparent personal event');
return;
}
}
processedSourceIds[eventId] = true;
// Check if this personal event has a physical address for travel blocking
var personalLocation = personalEvent.getLocation();
var hasPhysicalAddress =
personalLocation &&
personalLocation.trim().length > 0 &&
isPhysicalAddress_(personalLocation.trim());
var eventHash = hashEventCalApp_(personalEvent);
if (blocksBySourceId[eventId]) {
// Existing block — check if it needs updating
var existingBlock = blocksBySourceId[eventId];
var existingHash = existingBlock.getTag('lastSyncHash');
if (existingHash !== eventHash) {
// Update times
if (personalEvent.isAllDayEvent()) {
existingBlock.setAllDayDate(personalEvent.getAllDayStartDate());
} else {
existingBlock.setTime(
personalEvent.getStartTime(),
personalEvent.getEndTime()
);
}
// Update hidden location tag (for travel blocking)
if (hasPhysicalAddress) {
existingBlock.setTag('physicalAddress', personalLocation.trim());
} else {
existingBlock.setTag('physicalAddress', '');
}
existingBlock.setTag('lastSyncHash', eventHash);
stats.personalUpdated++;
Logger.log('CalBlock: Updated block for: ' + eventId);
}
} else {
// New event — create a block (with rate-limit retry)
var newBlock = withCalendarRetry_(function () {
if (personalEvent.isAllDayEvent()) {
return workCal.createAllDayEvent('Busy', personalEvent.getAllDayStartDate());
} else {
return workCal.createEvent(
'Busy',
personalEvent.getStartTime(),
personalEvent.getEndTime()
);
}
});
var blockTags = {
sourceEventId: eventId,
sourceCalendar: CONFIG.personalCalendarId,
lastSyncHash: eventHash,
managedBy: CONFIG.syncTagPrefix,
};
if (hasPhysicalAddress) {
blockTags.physicalAddress = personalLocation.trim();
}
setBlockMetadata_(
newBlock,
CONFIG.syncTagPrefix + ' Auto-synced — do not edit manually\n[sourceId:' + eventId + ']',
blockTags
);
// Add to lookup so recurring instances don't create duplicate blocks
blocksBySourceId[eventId] = newBlock;
stats.personalSynced++;
Logger.log('CalBlock: Created block for personal event: ' + eventId);
}
} catch (e) {
stats.errors.push('Error processing personal event: ' + e.message);
}
});
// 5. Delete blocks for personal events that no longer exist
Object.keys(blocksBySourceId).forEach(function (sourceId) {
if (!processedSourceIds[sourceId]) {
try {
withCalendarRetry_(function () {
blocksBySourceId[sourceId].deleteEvent();
});
stats.personalDeleted++;
Logger.log('CalBlock: Deleted orphaned block for: ' + sourceId);
} catch (e) {
stats.errors.push('Error deleting orphaned block: ' + e.message);
}
}
});
}
// ---------------------------------------------------------------------------
// FEATURE 2: Travel Time Blocking
// ---------------------------------------------------------------------------
function syncTravelBlocks_(stats) {
if (!CONFIG.mapsApiKey || !CONFIG.homeAddress) {
Logger.log('CalBlock: Skipping travel blocks — Maps API key or home address not configured');
return;
}
const now = new Date();
const endDate = new Date(now.getTime() + CONFIG.syncWindowDays * 24 * 60 * 60 * 1000);
const workCal = CalendarApp.getCalendarById(CONFIG.workCalendarId);
// 1. Get ALL work calendar events (real + synced) that have a physical address
// For regular work events: check the visible location field
// For [CalBlock] blocks: check the hidden 'physicalAddress' tag
// (personal events don't have a visible location — it's stored as a tag to preserve privacy)
const allWorkEvents = workCal.getEvents(now, endDate);
const eventsWithLocation = allWorkEvents.filter(function (event) {
// Skip travel blocks themselves
if (isTaggedEvent_(event, CONFIG.travelTagPrefix)) return false;
// Get the effective physical address (visible location or hidden tag)
var addr = getEffectiveAddress_(event);
if (!addr) return false;
// Skip events AT the home address — no travel needed
if (normalizeAddress_(addr) === normalizeAddress_(CONFIG.homeAddress)) {
Logger.log('CalBlock: Skipping travel for event at home address');
return false;
}
return true;
});
Logger.log(
'CalBlock: Found ' + eventsWithLocation.length + ' events with physical addresses for travel blocking'
);
// 2. Get existing travel blocks — build lookup with normalized IDs
// CalendarApp.getId() returns IDs in inconsistent formats:
// - "abc123" or "abc123@google.com" for regular events
// - "abc123_20260325T060000Z" for recurring instances
// We normalize to avoid duplicate blocks on each sync cycle.
const existingTravelBlocks = getTaggedEvents_(workCal, CONFIG.travelTagPrefix, now, endDate);
const travelBlocksByLinkedId = {};
existingTravelBlocks.forEach(function (block) {
var linkedId = block.getTag('linkedEventId');
if (!linkedId) {
linkedId = extractIdFromDescription_(block.getDescription(), 'linkedId');
}
var direction = block.getTag('travelDirection');
if (!direction) {
direction = extractIdFromDescription_(block.getDescription(), 'direction');
}
if (!direction) {
direction = 'to';
}
if (linkedId) {
var normKey = normalizeEventId_(linkedId) + '_' + direction;
if (travelBlocksByLinkedId[normKey]) {
// Duplicate detected — delete this one, keep the first
try {
block.deleteEvent();
stats.travelDeleted++;
Logger.log('CalBlock: Deleted duplicate travel block: ' + normKey);
} catch (e) {
stats.errors.push('Error deleting duplicate travel block: ' + e.message);
}
} else {
travelBlocksByLinkedId[normKey] = block;
}
}
});
Logger.log('CalBlock: Found ' + existingTravelBlocks.length + ' existing travel blocks');
// Sort events by start time for chaining
eventsWithLocation.sort(function (a, b) {
return a.getStartTime().getTime() - b.getStartTime().getTime();
});
const processedKeys = {};
// 3. Create/update travel blocks
for (var i = 0; i < eventsWithLocation.length; i++) {
var event = eventsWithLocation[i];
var rawEventId = event.getId();
var eventId = normalizeEventId_(rawEventId); // Normalized for consistent matching
var eventLocation = getEffectiveAddress_(event); // reads visible location or hidden tag
var eventTitle = event.getTitle();
// For [CalBlock] blocks, the title is "Busy" — use a more descriptive travel block title
var travelLabel = isTaggedEvent_(event, CONFIG.syncTagPrefix) ? 'Personal event' : eventTitle;
try {
// --- TRAVEL TO EVENT ---
var origin;
if (i > 0) {
var prevEvent = eventsWithLocation[i - 1];
var prevLoc = getEffectiveAddress_(prevEvent);
// Only chain from previous event if it ends within 4 hours of this one starting
var gap = event.getStartTime().getTime() - prevEvent.getEndTime().getTime();
if (prevLoc && gap < 4 * 60 * 60 * 1000) {
origin = prevLoc;
} else {
origin = CONFIG.homeAddress;
}
} else {
origin = CONFIG.homeAddress;
}
var travelMinutes = getCachedTravelTime_(origin, eventLocation);
// Skip travel blocks for long-distance trips (interstate/overseas — you'd fly, not drive)
if (CONFIG.maxDriveTravelMinutes && travelMinutes > CONFIG.maxDriveTravelMinutes) {
Logger.log(
'CalBlock: Skipping travel block — drive time ' +
travelMinutes +
' min exceeds threshold (' +
CONFIG.maxDriveTravelMinutes +
' min)'
);
continue;
}
var totalMinutes = travelMinutes + CONFIG.travelTimeBufferMin;
var travelHash = hashString_(
event.getStartTime().getTime() + '|' + eventLocation + '|' + origin + '|to'
);
var toKey = eventId + '_to';
processedKeys[toKey] = true;
if (travelBlocksByLinkedId[toKey]) {
// Update existing travel block if needed
var existingBlock = travelBlocksByLinkedId[toKey];
var existingHash = existingBlock.getTag('lastSyncHash');
if (existingHash !== travelHash) {
var toStart = new Date(event.getStartTime().getTime() - totalMinutes * 60 * 1000);
existingBlock.setTime(toStart, event.getStartTime());
existingBlock.setTitle(CONFIG.travelTagPrefix + ' → ' + travelLabel);
existingBlock.setTag('lastSyncHash', travelHash);
existingBlock.setTag('travelMinutes', String(totalMinutes));
stats.travelUpdated++;
}
} else {
// Create new travel-to block (with rate-limit retry)
var toStart = new Date(event.getStartTime().getTime() - totalMinutes * 60 * 1000);
var toBlock = withCalendarRetry_(function () {
return workCal.createEvent(
CONFIG.travelTagPrefix + ' → ' + travelLabel,
toStart,
event.getStartTime()
);
});
setBlockMetadata_(
toBlock,
CONFIG.travelTagPrefix +
' Auto-generated travel time — do not edit manually\n' +
'[linkedId:' + eventId + '][direction:to]\n' +
'From: ' + origin + '\n' +
'To: ' + eventLocation + '\n' +
'Estimated: ' + travelMinutes + ' min + ' + CONFIG.travelTimeBufferMin + ' min buffer',
{
linkedEventId: eventId,
travelDirection: 'to',
travelMinutes: String(totalMinutes),
lastSyncHash: travelHash,
managedBy: CONFIG.travelTagPrefix,
}
);
stats.travelCreated++;
Logger.log('CalBlock: Created travel-to block for event ' + redactIdentifier_(eventId));
}
// --- RETURN TRAVEL (from event → home) ---
// Only create return travel if next event is far away or doesn't have a location
var needsReturn = true;
if (i < eventsWithLocation.length - 1) {
var nextEvent = eventsWithLocation[i + 1];
var nextGap = nextEvent.getStartTime().getTime() - event.getEndTime().getTime();
// If the next event with a location is within 4 hours, we'll chain to it instead
if (nextGap < 4 * 60 * 60 * 1000) {
needsReturn = false;
}
}
if (needsReturn) {
var returnMinutes = getCachedTravelTime_(eventLocation, CONFIG.homeAddress);
var returnTotal = returnMinutes + CONFIG.travelTimeBufferMin;
var returnHash = hashString_(
event.getEndTime().getTime() + '|' + eventLocation + '|' + CONFIG.homeAddress + '|from'
);
var fromKey = eventId + '_from';
processedKeys[fromKey] = true;
if (travelBlocksByLinkedId[fromKey]) {
var existingReturn = travelBlocksByLinkedId[fromKey];
var existingReturnHash = existingReturn.getTag('lastSyncHash');
if (existingReturnHash !== returnHash) {
var fromEnd = new Date(event.getEndTime().getTime() + returnTotal * 60 * 1000);
existingReturn.setTime(event.getEndTime(), fromEnd);
existingReturn.setTitle(CONFIG.travelTagPrefix + ' ← ' + travelLabel);
existingReturn.setTag('lastSyncHash', returnHash);
existingReturn.setTag('travelMinutes', String(returnTotal));
stats.travelUpdated++;
}
} else {
// Create new return travel block (with rate-limit retry)
var fromEnd = new Date(event.getEndTime().getTime() + returnTotal * 60 * 1000);
var fromBlock = withCalendarRetry_(function () {
return workCal.createEvent(
CONFIG.travelTagPrefix + ' ← ' + travelLabel,
event.getEndTime(),
fromEnd
);
});
setBlockMetadata_(
fromBlock,
CONFIG.travelTagPrefix +
' Auto-generated return travel time — do not edit manually\n' +
'[linkedId:' + eventId + '][direction:from]\n' +
'From: ' + eventLocation + '\n' +
'To: ' + CONFIG.homeAddress + '\n' +
'Estimated: ' + returnMinutes + ' min + ' + CONFIG.travelTimeBufferMin + ' min buffer',
{
linkedEventId: eventId,
travelDirection: 'from',
travelMinutes: String(returnTotal),
lastSyncHash: returnHash,
managedBy: CONFIG.travelTagPrefix,
}
);
stats.travelCreated++;
Logger.log('CalBlock: Created return travel block for event ' + redactIdentifier_(eventId));
}
}
} catch (e) {
stats.errors.push(
'Error processing travel for event ' + redactIdentifier_(eventId) + ': ' + e.message
);
}
}
// 4. Delete orphaned travel blocks
Object.keys(travelBlocksByLinkedId).forEach(function (key) {
if (!processedKeys[key]) {
try {
withCalendarRetry_(function () {
travelBlocksByLinkedId[key].deleteEvent();
});
stats.travelDeleted++;
Logger.log('CalBlock: Deleted orphaned travel block: ' + key);
} catch (e) {
stats.errors.push('Error deleting orphaned travel block: ' + e.message);
}
}
});
}
// ---------------------------------------------------------------------------
// CLEANUP — Remove any orphaned managed events
// ---------------------------------------------------------------------------
function cleanupOrphans_(stats) {
// This is handled within each sync function above.
// This function exists as a hook for any additional cleanup logic.
Logger.log('CalBlock: Cleanup pass complete');
}
// ---------------------------------------------------------------------------
// GOOGLE MAPS API — Travel Time Calculation with Caching
// ---------------------------------------------------------------------------
function getCachedTravelTime_(origin, destination) {
var cache = CacheService.getScriptCache();
var cacheKey = 'travel_' + hashString_(origin + '|' + destination);
var cached = cache.get(cacheKey);
if (cached) {
Logger.log('CalBlock: Cache hit for travel route ' + redactIdentifier_(cacheKey));
return parseInt(cached, 10);
}
var minutes = fetchTravelTime_(origin, destination);
// Cache for configured duration (max 6 hours — Apps Script cache limit)
var cacheSecs = Math.min(CONFIG.mapsCacheDurationHours * 3600, 21600);
cache.put(cacheKey, String(minutes), cacheSecs);
return minutes;
}
function fetchTravelTime_(origin, destination) {
try {
var url =
'https://maps.googleapis.com/maps/api/directions/json' +
'?origin=' + encodeURIComponent(origin) +
'&destination=' + encodeURIComponent(destination) +
'&mode=driving' +
'&traffic_model=pessimistic' +
'&departure_time=now' +
'&key=' + CONFIG.mapsApiKey;
var response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
var data = JSON.parse(response.getContentText());
if (data.status === 'OK' && data.routes && data.routes.length > 0) {
var leg = data.routes[0].legs[0];
// Prefer duration_in_traffic if available (pessimistic)
var seconds = leg.duration_in_traffic
? leg.duration_in_traffic.value
: leg.duration.value;
var minutes = Math.ceil(seconds / 60);
Logger.log(
'CalBlock: Maps API returned ' + minutes + ' min for route ' + redactIdentifier_(origin + '|' + destination)
);
return minutes;
} else {
Logger.log('CalBlock: Maps API returned status: ' + data.status + ' — using default');
return CONFIG.defaultTravelMinutes;
}
} catch (e) {
Logger.log('CalBlock: Maps API error — ' + e.message + ' — using default');
return CONFIG.defaultTravelMinutes;
}
}
// ---------------------------------------------------------------------------
// ADVANCED CALENDAR SERVICE — Fetch events with full API fields
// ---------------------------------------------------------------------------
/**
* Fetch events from a calendar using the Advanced Calendar Service (Calendar API v3).
* This gives us access to fields not available in the basic CalendarApp, including:
* - transparency ('transparent' = free, 'opaque' = busy)
* - location
* - full attendee details with response status
*
* Requires the Advanced Calendar Service to be enabled in the Apps Script project:
* Services → Calendar API → Add
*
* Returns an array of raw event objects from the API.
*/
function fetchPersonalEventsAdvanced_(calendarId, startDate, endDate) {
var allEvents = [];
var pageToken = null;
do {
var options = {
timeMin: startDate.toISOString(),
timeMax: endDate.toISOString(),
singleEvents: true, // Expand recurring events into instances
orderBy: 'startTime',
maxResults: 250,
};
if (pageToken) {
options.pageToken = pageToken;
}
var response = Calendar.Events.list(calendarId, options);
if (response.items) {
allEvents = allEvents.concat(response.items);
}
pageToken = response.nextPageToken;
} while (pageToken);
return allEvents;
}
// ---------------------------------------------------------------------------
// HELPER FUNCTIONS
// ---------------------------------------------------------------------------
/**
* Get the effective physical address for an event.
* - For regular work events: checks the visible location field
* - For [CalBlock] blocks (synced personal events): checks the hidden
* 'physicalAddress' tag (location is not set on the visible event to
* preserve privacy — the block just shows "Busy")
*
* Returns the address string if it's a valid physical address, or null if not.
*/
function getEffectiveAddress_(event) {
// First check the visible location field
var loc = event.getLocation();
if (loc && loc.trim().length > 0 && isPhysicalAddress_(loc.trim())) {
return loc.trim();
}
// For CalBlock blocks, check the hidden tag
var taggedAddress = event.getTag('physicalAddress');
if (taggedAddress && taggedAddress.trim().length > 0) {
// Already validated as physical when it was stored — but re-check
// in case the validation logic has been updated
if (isPhysicalAddress_(taggedAddress.trim())) {
return taggedAddress.trim();
}
}
return null;
}
/**
* Get all events in a range that are managed by CalBlock (identified by tag).
*/
function getTaggedEvents_(calendar, tagPrefix, startDate, endDate) {
var allEvents = calendar.getEvents(startDate, endDate);
return allEvents.filter(function (event) {
return isTaggedEvent_(event, tagPrefix);
});
}
/**
* Check if an event is managed by CalBlock.
*/
function isTaggedEvent_(event, tagPrefix) {
var managedBy = event.getTag('managedBy');
if (managedBy === tagPrefix) return true;
// Fallback: check description for tag prefix
var desc = event.getDescription() || '';
return desc.indexOf(tagPrefix) === 0;
}
/**
* Determine if a location string is a real physical address (not a URL,
* video call link, or generic label like "Office" or "TBD").
*
* Uses a two-layer approach:
* 1. Heuristic reject — instantly filter out obvious non-addresses
* 2. Google Maps Geocoding API — confirm the location resolves to a
* physical place (street address, establishment, point of interest)
*
* Results are cached to avoid redundant API calls.
*/
function isPhysicalAddress_(location) {
// --- Layer 1: Heuristic reject ---
var loc = location.toLowerCase().trim();
// Reject URLs and video call links
if (/^https?:\/\//.test(loc)) return false;
if (/^meet\.google\.com/.test(loc)) return false;
if (/^zoom\.us/.test(loc)) return false;
if (/^teams\.microsoft\.com/.test(loc)) return false;
// Reject known virtual / non-place keywords (exact match or starts with)
var rejectExact = [
'zoom', 'google meet', 'microsoft teams', 'teams', 'webex', 'slack',
'slack huddle', 'skype', 'facetime', 'discord', 'phone', 'call',
'online', 'virtual', 'remote', 'wfh', 'work from home', 'home office',
'tbd', 'tba', 'tbc', 'n/a', 'none', 'anywhere',
];
if (rejectExact.indexOf(loc) !== -1) return false;
// Reject if it looks like a phone number (digits, spaces, dashes, plus, parens)
if (/^[\d\s\-\+\(\)]{7,}$/.test(loc)) return false;
// Reject very short generic strings (1-3 chars) — unlikely to be addresses
if (loc.length <= 3) return false;
// --- Layer 2: Google Maps Geocoding API validation ---
if (!CONFIG.mapsApiKey) return false;
return isGeocodableAddress_(location);
}
/**
* Use the Google Maps Geocoding API to check if a location string resolves
* to a physical place. Returns true only if the result type indicates a
* real-world location you could drive to.
*
* Results are cached for mapsCacheDurationHours to avoid repeat API calls.
*/
function isGeocodableAddress_(location) {
var cache = CacheService.getScriptCache();
var cacheKey = 'geo_' + hashString_(location.toLowerCase().trim());
var cached = cache.get(cacheKey);
if (cached !== null) {
return cached === 'true';
}
try {
var url =
'https://maps.googleapis.com/maps/api/geocode/json' +
'?address=' + encodeURIComponent(location) +
'&key=' + CONFIG.mapsApiKey;
var response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
var data = JSON.parse(response.getContentText());
var isPhysical = false;
if (data.status === 'OK' && data.results && data.results.length > 0) {
var result = data.results[0];
var types = result.types || [];
// These result types indicate a real physical place
var physicalTypes = [
'street_address', // "123 Collins St, Melbourne"
'premise', // A named building or complex
'subpremise', // A unit/suite within a building
'establishment', // A business / named place
'point_of_interest', // A landmark or POI
'route', // A street name (partial address)
'intersection', // A street intersection
'airport', // An airport
'park', // A park
'train_station', // A station
'transit_station', // A transit hub
'bus_station', // A bus station
];
for (var i = 0; i < types.length; i++) {
if (physicalTypes.indexOf(types[i]) !== -1) {
isPhysical = true;
break;
}
}
// Also accept if the result has a geometry location_type of ROOFTOP or
// RANGE_INTERPOLATED — these indicate precise street-level geocoding
if (!isPhysical && result.geometry) {
var locationType = result.geometry.location_type;
if (locationType === 'ROOFTOP' || locationType === 'RANGE_INTERPOLATED') {
isPhysical = true;
}
}
Logger.log(
'CalBlock: Geocode ' +
redactIdentifier_(location) +
' → ' +
(isPhysical ? 'PHYSICAL' : 'NOT PHYSICAL') +
' (types: ' +
types.join(', ') +
')'
);
} else {
Logger.log(
'CalBlock: Geocode ' +
redactIdentifier_(location) +
' → NO RESULTS (status: ' +
data.status +
')'
);
}
// Cache the result
var cacheSecs = Math.min(CONFIG.mapsCacheDurationHours * 3600, 21600);
cache.put(cacheKey, String(isPhysical), cacheSecs);
return isPhysical;
} catch (e) {
Logger.log('CalBlock: Geocoding error for ' + redactIdentifier_(location) + ': ' + e.message);
// On error, assume it's NOT a physical address (safe default — don't create wrong blocks)
return false;
}
}
/**
* Extract an embedded ID from an event description.
* Descriptions contain fallback IDs in the format [key:value] because
* CalendarApp.getTag() can be unreliable across script executions.
* e.g. extractIdFromDescription_("[CalBlock]...\n[sourceId:abc123]", "sourceId") → "abc123"
*/
function extractIdFromDescription_(description, keyName) {
if (!description) return null;
var pattern = new RegExp('\\[' + keyName + ':([^\\]]+)\\]');
var match = description.match(pattern);
return match ? match[1] : null;
}
/**
* Normalize a Google Calendar event ID for consistent matching.
* CalendarApp.getId() returns IDs in inconsistent formats:
* - "abc123" (short form)
* - "abc123@google.com" (with domain suffix)
* - "abc123_20260325T060000Z" (recurring instance with timestamp)
* We strip the @domain suffix to get a stable base ID.
*/
function normalizeEventId_(eventId) {
if (!eventId) return '';
return eventId.replace(/@.*$/, '');
}
/**
* Normalize an address string for comparison (e.g. checking if event is at home).
* Lowercases, strips extra whitespace, removes common punctuation.
*/
function normalizeAddress_(address) {
if (!address) return '';
return address
.toLowerCase()
.replace(/[,.\-\/\\]/g, ' ') // Replace punctuation with spaces
.replace(/\s+/g, ' ') // Collapse multiple spaces
.trim();
}
/**
* Create a hash of a CalendarApp event's time, status, and location for change detection.
*/
function hashEventCalApp_(event) {
var str;
if (event.isAllDayEvent()) {
str = 'allday|' + event.getAllDayStartDate().getTime();
} else {
str = event.getStartTime().getTime() + '|' + event.getEndTime().getTime();
}
str += '|' + (event.getMyStatus() || 'owner');
str += '|' + (event.getLocation() || '');
return hashString_(str);
}
/**
* Simple string hash (djb2).
*/
function hashString_(str) {
var hash = 5381;
for (var i = 0; i < str.length; i++) {
hash = (hash * 33) ^ str.charCodeAt(i);
}
return (hash >>> 0).toString(36);
}
/**