Created
October 28, 2020 03:50
-
-
Save quad/258b31c3c65db0397da5d15c8756fd7c to your computer and use it in GitHub Desktop.
Block out my work calendar with my personal events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function hashify(hash, [key, value]) { | |
hash[key] = value; | |
return hash; | |
} | |
function eventId(event) { | |
if (event.isRecurringEvent()) { | |
return event.getId() + "-" + event.getStartTime().toISOString() + "-" + event.getEndTime(); | |
} | |
return event.getId(); | |
} | |
function sync() { | |
const srcId = "scott@quadhome.com"; | |
const syncWindowInDays = 7; | |
const today = new Date(); | |
const startDate = new Date(); | |
startDate.setDate(today.getDate() - syncWindowInDays); | |
const endDate = new Date(); | |
endDate.setDate(today.getDate() + syncWindowInDays); | |
const sourceCal = CalendarApp.getCalendarById(srcId); | |
const destCal = CalendarApp.getDefaultCalendar(); | |
const sourceEvents = sourceCal.getEvents(startDate, endDate); | |
const sourceEventsById = sourceEvents | |
.map(function(e) { return [eventId(e), e] }) | |
.reduce(hashify, {}); | |
const TAG_ID = "block.id"; | |
const destEvents = destCal.getEvents(startDate, endDate); | |
const destEventsAndSourceId = destEvents | |
.map(function(e) { return [e.getTag(TAG_ID), e] }) | |
.filter(function([id, e]) { return id != null }) | |
// Delete stale block events | |
const existingEvents = destEventsAndSourceId | |
.filter(function([id, e]) { | |
if (sourceEventsById[id]) return true; | |
Logger.log("Deleting stale event: %s [id=%s]", e.getTitle(), id) | |
e.deleteEvent(); | |
}) | |
.reduce(hashify, {}); | |
sourceEvents | |
.filter(function(e) { return !e.isAllDayEvent() }) | |
.map(function(e) { return [e, existingEvents[eventId(e)]] }) | |
.forEach(function([sourceEvent, destEvent]) { | |
if (!destEvent) { | |
Logger.log("Creating new event: %s [id=%s]", sourceEvent.getTitle(), eventId(sourceEvent)) | |
destEvent = destCal | |
.createEvent("Blocked", sourceEvent.getStartTime(), sourceEvent.getEndTime()) | |
.setTag(TAG_ID, eventId(sourceEvent)) | |
.setVisibility(CalendarApp.Visibility.PRIVATE) | |
.removeAllReminders(); | |
} | |
if ((destEvent.getStartTime().valueOf() != sourceEvent.getStartTime().valueOf()) || (destEvent.getEndTime().valueOf() != sourceEvent.getEndTime().valueOf())) { | |
Logger.log("Correcting event: %s [sourceId=%s destId=%s]", sourceEvent.getTitle(), eventId(sourceEvent), eventId(destEvent)) | |
destEvent.setTime(sourceEvent.getStartTime(), sourceEvent.getEndTime()) | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment