Skip to content

Instantly share code, notes, and snippets.

@jmandel
Created October 16, 2016 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmandel/a3d87e2cc9716b9deee9db8bdfac8890 to your computer and use it in GitHub Desktop.
Save jmandel/a3d87e2cc9716b9deee9db8bdfac8890 to your computer and use it in GitHub Desktop.
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