Skip to content

Instantly share code, notes, and snippets.

@jmandel jmandel/Code.gs
Created Oct 16, 2016

Embed
What would you like to do?
var calsToSynchronize = [
"address-one@gmail.com",
"address-two@gmail.com",
];
var BUSY = "Busy",
COPIED_FROM_CALENDAR = "copied-from-calendar",
COPIED_FROM_EVENT = "copied-from-event",
TIME_HORIZON = 365 / 2; // scan for 6 months
function synchronize() {
var today = new Date();
today.setHours(0, 0, 0, 0);
// Scan the year in one-day chunks because...
// it avoids collapsing of recurring events
for (var day = 0; day < TIME_HORIZON; day++) {
var eventsByCalId = {};
calsToSynchronize.forEach(function(sourceCalId) { // no [].map available here :(
var sourceCal = CalendarApp.getCalendarById(sourceCalId);
var oneDay = new Date(today.getTime() + (day * 24 * 60 * 60 * 1000));
var nextDay = new Date(today.getTime() + ((day + 1) * 24 * 60 * 60 * 1000));
eventsByCalId[sourceCalId] = sourceCal.getEvents(oneDay, nextDay);
});
calsToSynchronize.forEach(function(sourceCalId) { // no [].map available here :(
eventsByCalId[sourceCalId].forEach(function(sourceEvent) {
if (sourceEvent.getTag(COPIED_FROM_CALENDAR) || sourceEvent.getTitle() === BUSY) {
// we created this from an existing event. See if it still exists!
var stillExists = false;
var possibleMatches = eventsByCalId[sourceEvent.getTag(COPIED_FROM_CALENDAR)];
possibleMatches && possibleMatches.forEach(function(possibleMatch) {
if (possibleMatch.getId() === sourceEvent.getTag(COPIED_FROM_EVENT)) {
stillExists = true;
}
});
if (!stillExists) {
sourceEvent.deleteEvent();
}
return;
}
calsToSynchronize.forEach(function(targetCalId) {
if (targetCalId === sourceCalId) { // no [].filter available here :(
return;
}
var alreadyExists = false;
eventsByCalId[targetCalId].forEach(function(possibleMatch) {
if (possibleMatch.getTag(COPIED_FROM_CALENDAR) === sourceCalId &&
possibleMatch.getTag(COPIED_FROM_EVENT) === sourceEvent.getId()) {
alreadyExists = true;
}
});
if (alreadyExists) {
return;
}
CalendarApp.getCalendarById(targetCalId)
.createEvent(BUSY, sourceEvent.getStartTime(), sourceEvent.getEndTime())
.setDescription("Busy status propagated from " + sourceCalId)
.setTag(COPIED_FROM_CALENDAR, sourceCalId)
.setTag(COPIED_FROM_EVENT, sourceEvent.getId());
})
})
});
}
}
function debugListCalendars() {
var cals = CalendarApp.getAllCalendars();
Logger.log("You have " + cals.length + " cals");
var c = cals[0];
cals.forEach(function(c) {
Logger.log(c.getId() + ": Name=" + c.getName() + "; Description: " + c.getDescription());
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.