Last active
April 20, 2026 00:19
-
-
Save espinchi/ae0d09037f4c5eb72c642924addff48a to your computer and use it in GitHub Desktop.
Personal to Work Email Sync
This file contains hidden or 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
| /** | |
| * WHAT THIS IS | |
| * | |
| * Keeps your work calendar in sync with your personal calendar by creating "Busy" blocks | |
| * on the work calendar. A time-based trigger can run the sync every 15 minutes. | |
| * | |
| * HOW TO INSTALL | |
| * | |
| * - Share your personal calendar with your work account so it appears in Calendar (often | |
| * under "Other calendars"; "See all event details" helps guest status work correctly). | |
| * - Create a standalone Apps Script project in your work account: | |
| * https://script.google.com/home/ > New Project | |
| * - Set PERSONAL_CALENDAR_ID and the sync window (SYNC_WINDOW_PAST_HOURS, | |
| * SYNC_WINDOW_FUTURE_DAYS) below as needed. | |
| * - Paste this file as Code.gs. | |
| * - Run syncBusyBlocks() once from the editor to authorize Calendar access. | |
| * - Run installTrigger() once to schedule sync every 15 minutes. | |
| * | |
| * BELLS AND WHISTLES | |
| * | |
| * - Skips all-day personal events, events you declined or marked Maybe, and personal events | |
| * set to "Show as free" (transparent). | |
| * - Recurring series: each occurrence inside the sync window gets its own Busy block. | |
| * - Full lifecycle on work: create missing blocks, update time if the personal slot moves, | |
| * reset if the event changes. | |
| * - Remembers personal→work event ids in Script Properties (JSON sharded under 9 KB per key) | |
| * so reruns do not duplicate blocks; a single chunk larger than that limit is split across | |
| * multiple property keys so Script Properties size limits are not exceeded. | |
| * - Polite to Google's quotas: exponential backoff and retries on "too many events" style | |
| * errors, plus a short sleep after each successful calendar write; summary logs include | |
| * backoff/throttle totals for troubleshooting. | |
| * - Privacy-minded logs: mostly counts; long internal map keys are abbreviated in WARN lines. | |
| * - Creates without invitation email (sendInvites: false). Uses built-in Apps Script services only | |
| * (CalendarApp, PropertiesService, ScriptApp, Logger)—no external libraries. | |
| */ | |
| var PERSONAL_CALENDAR_ID = 'your.email.address@gmail.com'; | |
| var SYNC_WINDOW_PAST_HOURS = 48; | |
| var SYNC_WINDOW_FUTURE_DAYS = 60; | |
| // Internal constants | |
| var BUSY_TITLE = 'Busy'; | |
| var MAP_CHUNK_MAX_CHARS = 8000; | |
| var MAP_KEY_PREFIX = 'busy_map_'; | |
| var MAP_COUNT_KEY = 'busy_map_n'; | |
| var MAP_FRAG_COUNT_SUFFIX = '_fc'; | |
| var MAP_FRAG_PART_SUFFIX = '_p'; | |
| var CAL_WRITE_THROTTLE_MS = 150; | |
| var CAL_RATE_LIMIT_RETRIES = 5; | |
| var CAL_RATE_LIMIT_BASE_SLEEP_MS = 1500; | |
| var MS_PER_HOUR = 3600000; | |
| var MS_PER_DAY = 86400000; | |
| function syncBusyBlocks() { | |
| const stats = { | |
| fetched: 0, | |
| skipAllDay: 0, | |
| skipDeclined: 0, | |
| skipMaybe: 0, | |
| skipFree: 0, | |
| qualifying: 0, | |
| created: 0, | |
| updated: 0, | |
| deleted: 0, | |
| errors: 0, | |
| backoffRetries: 0, | |
| backoffSleepMs: 0, | |
| throttleSleepMs: 0, | |
| }; | |
| const personalCal = CalendarApp.getCalendarById(PERSONAL_CALENDAR_ID); | |
| if (!personalCal) { | |
| Logger.log( | |
| 'ERROR: cannot open calendar ' + PERSONAL_CALENDAR_ID + ' (share it with this account or fix id)' | |
| ); | |
| return; | |
| } | |
| const workCal = CalendarApp.getDefaultCalendar(); | |
| const now = Date.now(); | |
| const windowStart = new Date(now - SYNC_WINDOW_PAST_HOURS * MS_PER_HOUR); | |
| const windowEnd = new Date(now + SYNC_WINDOW_FUTURE_DAYS * MS_PER_DAY); | |
| const personalEvents = personalCal.getEvents(windowStart, windowEnd); | |
| stats.fetched = personalEvents.length; | |
| const qualifying = collectQualifyingPersonalEvents(personalEvents, stats); | |
| const map = loadMap(); | |
| removeObsoleteWorkBlocks(workCal, map, qualifying, stats); | |
| upsertWorkBlocksForQualifying(workCal, map, qualifying, stats); | |
| saveMap(map); | |
| Logger.log( | |
| [ | |
| 'done', | |
| 'fetched=' + stats.fetched, | |
| 'qualifying=' + stats.qualifying, | |
| 'skipAllDay=' + stats.skipAllDay, | |
| 'skipDeclined=' + stats.skipDeclined, | |
| 'skipMaybe=' + stats.skipMaybe, | |
| 'skipFree=' + stats.skipFree, | |
| 'created=' + stats.created, | |
| 'updated=' + stats.updated, | |
| 'deleted=' + stats.deleted, | |
| 'errors=' + stats.errors, | |
| 'mapSize=' + Object.keys(map).length, | |
| 'backoffRetries=' + stats.backoffRetries, | |
| 'backoffSleepMs=' + stats.backoffSleepMs, | |
| 'throttleSleepMs=' + stats.throttleSleepMs, | |
| ].join(' ') | |
| ); | |
| } | |
| function collectQualifyingPersonalEvents(personalEvents, stats) { | |
| const qualifying = {}; | |
| for (const ev of personalEvents) { | |
| try { | |
| if (ev.isAllDayEvent()) { | |
| stats.skipAllDay++; | |
| continue; | |
| } | |
| const status = ev.getMyStatus(); | |
| if (status === CalendarApp.GuestStatus.NO) { | |
| stats.skipDeclined++; | |
| continue; | |
| } | |
| if (status === CalendarApp.GuestStatus.MAYBE) { | |
| stats.skipMaybe++; | |
| continue; | |
| } | |
| if (ev.getTransparency() === CalendarApp.EventTransparency.TRANSPARENT) { | |
| stats.skipFree++; | |
| continue; | |
| } | |
| const key = personalEventMapKey(ev); | |
| qualifying[key] = { start: ev.getStartTime(), end: ev.getEndTime() }; | |
| stats.qualifying++; | |
| } catch (e) { | |
| stats.errors++; | |
| Logger.log('WARN: skip event (read): ' + errMsg(e)); | |
| } | |
| } | |
| return qualifying; | |
| } | |
| function removeObsoleteWorkBlocks(workCal, map, qualifying, stats) { | |
| for (const pid of Object.keys(map)) { | |
| if (qualifying[pid]) { | |
| continue; | |
| } | |
| const wid = map[pid]; | |
| try { | |
| const workEv = workCal.getEventById(wid); | |
| if (workEv) { | |
| withRateLimitRetry('delete', stats, function () { | |
| workEv.deleteEvent(); | |
| }); | |
| throttleCalendarWrite(stats); | |
| } | |
| delete map[pid]; | |
| stats.deleted++; | |
| } catch (e) { | |
| stats.errors++; | |
| Logger.log( | |
| 'WARN: delete failed mapKey=' + abbrevForLog(pid) + ' workId=' + wid + ' err=' + errMsg(e) | |
| ); | |
| // Keep map[pid] so a later run can retry deleting the work event. | |
| } | |
| } | |
| } | |
| function upsertWorkBlocksForQualifying(workCal, map, qualifying, stats) { | |
| for (const personalId of Object.keys(qualifying)) { | |
| const slot = qualifying[personalId]; | |
| const workId = map[personalId]; | |
| if (!workId) { | |
| createAndRecordBusy(workCal, map, personalId, slot, stats, 'create'); | |
| continue; | |
| } | |
| try { | |
| const existing = workCal.getEventById(workId); | |
| if (!existing) { | |
| createAndRecordBusy(workCal, map, personalId, slot, stats, 'create_repair'); | |
| continue; | |
| } | |
| let mutated = false; | |
| withRateLimitRetry('update', stats, function () { | |
| const ws = existing.getStartTime().getTime(); | |
| const we = existing.getEndTime().getTime(); | |
| if (ws !== slot.start.getTime() || we !== slot.end.getTime()) { | |
| existing.setTime(slot.start, slot.end); | |
| mutated = true; | |
| } | |
| if (existing.getTitle() !== BUSY_TITLE) { | |
| existing.setTitle(BUSY_TITLE); | |
| mutated = true; | |
| } | |
| if (existing.getTransparency() !== CalendarApp.EventTransparency.OPAQUE) { | |
| existing.setTransparency(CalendarApp.EventTransparency.OPAQUE); | |
| mutated = true; | |
| } | |
| }); | |
| if (mutated) { | |
| stats.updated++; | |
| throttleCalendarWrite(stats); | |
| } | |
| } catch (e) { | |
| stats.errors++; | |
| Logger.log( | |
| 'WARN: update failed mapKey=' + | |
| abbrevForLog(personalId) + | |
| ' workId=' + | |
| workId + | |
| ' err=' + | |
| errMsg(e) | |
| ); | |
| } | |
| } | |
| } | |
| function createAndRecordBusy(workCal, map, personalId, slot, stats, rateLimitContext) { | |
| try { | |
| map[personalId] = withRateLimitRetry(rateLimitContext, stats, function () { | |
| return createBusyEvent(workCal, slot.start, slot.end).getId(); | |
| }); | |
| stats.created++; | |
| throttleCalendarWrite(stats); | |
| } catch (e) { | |
| stats.errors++; | |
| Logger.log('WARN: create failed mapKey=' + abbrevForLog(personalId) + ' err=' + errMsg(e)); | |
| } | |
| } | |
| function installTrigger() { | |
| for (const t of ScriptApp.getProjectTriggers()) { | |
| if (t.getHandlerFunction() === 'syncBusyBlocks') { | |
| ScriptApp.deleteTrigger(t); | |
| } | |
| } | |
| ScriptApp.newTrigger('syncBusyBlocks').timeBased().everyMinutes(15).create(); | |
| Logger.log('Trigger: syncBusyBlocks every 15m'); | |
| } | |
| function loadMap() { | |
| const props = PropertiesService.getScriptProperties(); | |
| const n = parseInt(props.getProperty(MAP_COUNT_KEY) || '0', 10); | |
| const merged = {}; | |
| for (let i = 0; i < n; i++) { | |
| const base = MAP_KEY_PREFIX + i; | |
| const fc = parseInt(props.getProperty(base + MAP_FRAG_COUNT_SUFFIX) || '0', 10); | |
| let raw = ''; | |
| if (fc > 0) { | |
| for (let p = 0; p < fc; p++) { | |
| raw += props.getProperty(base + MAP_FRAG_PART_SUFFIX + p) || ''; | |
| } | |
| } else { | |
| raw = props.getProperty(base) || ''; | |
| } | |
| if (!raw) { | |
| continue; | |
| } | |
| try { | |
| Object.assign(merged, JSON.parse(raw)); | |
| } catch (e) { | |
| Logger.log('WARN: loadMap chunk ' + i + ': ' + errMsg(e)); | |
| } | |
| } | |
| return merged; | |
| } | |
| function clearChunkStorageAtIndex(props, index) { | |
| const base = MAP_KEY_PREFIX + index; | |
| const oldFc = parseInt(props.getProperty(base + MAP_FRAG_COUNT_SUFFIX) || '0', 10); | |
| props.deleteProperty(base + MAP_FRAG_COUNT_SUFFIX); | |
| for (let p = 0; p < oldFc; p++) { | |
| props.deleteProperty(base + MAP_FRAG_PART_SUFFIX + p); | |
| } | |
| props.deleteProperty(base); | |
| } | |
| function deleteMapChunkSlotRange(props, startInclusive, endExclusive) { | |
| for (let i = startInclusive; i < endExclusive; i++) { | |
| clearChunkStorageAtIndex(props, i); | |
| } | |
| } | |
| function writeMapChunk(props, index, obj) { | |
| const base = MAP_KEY_PREFIX + index; | |
| clearChunkStorageAtIndex(props, index); | |
| const s = JSON.stringify(obj); | |
| if (s.length <= MAP_CHUNK_MAX_CHARS) { | |
| props.setProperty(base, s); | |
| return; | |
| } | |
| const partSize = MAP_CHUNK_MAX_CHARS; | |
| const parts = Math.ceil(s.length / partSize); | |
| props.setProperty(base + MAP_FRAG_COUNT_SUFFIX, String(parts)); | |
| for (let p = 0; p < parts; p++) { | |
| props.setProperty(base + MAP_FRAG_PART_SUFFIX + p, s.substring(p * partSize, (p + 1) * partSize)); | |
| } | |
| if (parts > 1) { | |
| Logger.log('INFO: busy_map chunk ' + index + ' stored as ' + parts + ' property fragments (jsonChars=' + s.length + ').'); | |
| } | |
| } | |
| function saveMap(map) { | |
| const props = PropertiesService.getScriptProperties(); | |
| const keys = Object.keys(map).sort(); | |
| const oldN = parseInt(props.getProperty(MAP_COUNT_KEY) || '0', 10); | |
| if (keys.length === 0) { | |
| deleteMapChunkSlotRange(props, 0, oldN); | |
| props.setProperty(MAP_COUNT_KEY, '0'); | |
| return; | |
| } | |
| const chunks = []; | |
| let current = {}; | |
| for (const key of keys) { | |
| const candidate = Object.assign({}, current); | |
| candidate[key] = map[key]; | |
| const candidateJson = JSON.stringify(candidate); | |
| if (candidateJson.length <= MAP_CHUNK_MAX_CHARS) { | |
| current = candidate; | |
| } else { | |
| if (Object.keys(current).length) { | |
| chunks.push(current); | |
| current = {}; | |
| } | |
| current[key] = map[key]; | |
| const soloJson = JSON.stringify(current); | |
| if (soloJson.length > MAP_CHUNK_MAX_CHARS) { | |
| chunks.push(current); | |
| current = {}; | |
| } | |
| } | |
| } | |
| if (Object.keys(current).length) { | |
| chunks.push(current); | |
| } | |
| for (let j = 0; j < chunks.length; j++) { | |
| writeMapChunk(props, j, chunks[j]); | |
| } | |
| deleteMapChunkSlotRange(props, chunks.length, oldN); | |
| props.setProperty(MAP_COUNT_KEY, String(chunks.length)); | |
| } | |
| function createBusyEvent(cal, start, end) { | |
| const event = cal.createEvent(BUSY_TITLE, start, end, { sendInvites: false }); | |
| event.setTransparency(CalendarApp.EventTransparency.OPAQUE); | |
| return event; | |
| } | |
| function errMsg(e) { | |
| return e && e.message ? e.message : String(e); | |
| } | |
| function isCalendarRateLimitError(e) { | |
| const m = errMsg(e).toLowerCase(); | |
| return ( | |
| m.indexOf('too many') !== -1 || | |
| m.indexOf('try again later') !== -1 || | |
| m.indexOf('invoked too many times') !== -1 | |
| ); | |
| } | |
| function withRateLimitRetry(context, stats, fn) { | |
| let lastErr; | |
| for (let attempt = 0; attempt < CAL_RATE_LIMIT_RETRIES; attempt++) { | |
| try { | |
| const out = fn(); | |
| if (attempt > 0) { | |
| Logger.log('INFO: calendar write ok context=' + context + ' afterRetries=' + attempt); | |
| } | |
| return out; | |
| } catch (e) { | |
| lastErr = e; | |
| const last = attempt === CAL_RATE_LIMIT_RETRIES - 1; | |
| if (last || !isCalendarRateLimitError(e)) { | |
| throw e; | |
| } | |
| const sleepMs = CAL_RATE_LIMIT_BASE_SLEEP_MS * Math.pow(2, attempt); | |
| stats.backoffRetries++; | |
| stats.backoffSleepMs += sleepMs; | |
| Logger.log( | |
| 'WARN: calendar quota backoff context=' + | |
| context + | |
| ' attempt=' + | |
| (attempt + 1) + | |
| '/' + | |
| CAL_RATE_LIMIT_RETRIES + | |
| ' sleepMs=' + | |
| sleepMs + | |
| ' err=' + | |
| errMsg(e) | |
| ); | |
| Utilities.sleep(sleepMs); | |
| } | |
| } | |
| throw lastErr; | |
| } | |
| function throttleCalendarWrite(stats) { | |
| Utilities.sleep(CAL_WRITE_THROTTLE_MS); | |
| stats.throttleSleepMs += CAL_WRITE_THROTTLE_MS; | |
| } | |
| function abbrevForLog(s) { | |
| if (!s) { | |
| return ''; | |
| } | |
| const max = 96; | |
| if (s.length <= max) { | |
| return s; | |
| } | |
| return s.substring(0, max) + '…(len=' + s.length + ')'; | |
| } | |
| function personalEventMapKey(ev) { | |
| return [ev.getId(), ev.getStartTime().getTime(), ev.getEndTime().getTime()].join('\x1f'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment