import ICAL from "ical.js"; import type { CalendarTone } from "./store"; export type CalendarEvent = { id: string; calendar: string; title: string; location?: string; start: string; end: string; allDay: boolean; tone: CalendarTone; }; const maxFeedBytes = 5 * 1024 * 1024; const maxOccurrencesPerEvent = 10_000; function cleanText(value: unknown, fallback: string, maxLength: number) { return String(value ?? fallback).replace(/\s+/g, " ").trim().slice(0, maxLength) || fallback; } function calendarDate(value: ICAL.Time) { return `${String(value.year).padStart(4, "0")}-${String(value.month).padStart(2, "0")}-${String(value.day).padStart(2, "0")}`; } export function organizerDate(date: Date) { const parts = new Intl.DateTimeFormat("en-US", { timeZone: process.env.ORGANIZER_TIMEZONE || "America/Chicago", year: "numeric", month: "2-digit", day: "2-digit", }).formatToParts(date); const value = (part: string) => parts.find((entry) => entry.type === part)?.value ?? ""; return `${value("year")}-${value("month")}-${value("day")}`; } export function addCalendarDays(isoDate: string, days: number) { const [year, month, day] = isoDate.split("-").map(Number); const value = new Date(Date.UTC(year, month - 1, day + days)); return value.toISOString().slice(0, 10); } function hashId(value: string) { let hash = 0x811c9dc5; for (let index = 0; index < value.length; index += 1) { hash ^= value.charCodeAt(index); hash = Math.imul(hash, 0x01000193); } return (hash >>> 0).toString(36); } async function readLimitedText(response: Response) { const declaredLength = Number(response.headers.get("content-length") ?? 0); if (declaredLength > maxFeedBytes) throw new Error("Calendar feed is too large"); if (!response.body) return ""; const reader = response.body.getReader(); const decoder = new TextDecoder(); let total = 0; let text = ""; while (true) { const chunk = await reader.read(); if (chunk.done) break; total += chunk.value.byteLength; if (total > maxFeedBytes) { await reader.cancel(); throw new Error("Calendar feed is too large"); } text += decoder.decode(chunk.value, { stream: true }); } return text + decoder.decode(); } function componentString(component: ICAL.Component, name: string) { const value = component.getFirstPropertyValue(name); return typeof value === "string" ? value : ""; } function isCancelled(event: ICAL.Event) { return componentString(event.component, "status").toUpperCase() === "CANCELLED"; } function detach(component: ICAL.Component) { return new ICAL.Component(structuredClone(component.toJSON())); } function eventIsInWindow( start: ICAL.Time, end: ICAL.Time, windowStart: number, horizon: number, windowStartDate: string, horizonDate: string, ) { if (start.isDate) { return calendarDate(end) > windowStartDate && calendarDate(start) <= horizonDate; } return end.toJSDate().getTime() > windowStart && start.toJSDate().getTime() <= horizon; } function occurrenceIsPastHorizon(start: ICAL.Time, horizon: number, horizonDate: string) { return start.isDate ? calendarDate(start) > horizonDate : start.toJSDate().getTime() > horizon; } function serializeOccurrence( event: ICAL.Event, start: ICAL.Time, end: ICAL.Time, calendar: string, tone: CalendarTone, feedIndex: number, ) { const allDay = start.isDate; const startValue = allDay ? calendarDate(start) : start.toJSDate().toISOString(); const endValue = allDay ? calendarDate(end) : end.toJSDate().toISOString(); const uid = cleanText(event.uid, "event", 180); const location = cleanText(event.location, "", 120); return { id: hashId(`${feedIndex}|${uid}|${startValue}`), calendar, title: cleanText(event.summary, "Busy", 140), ...(location ? { location } : {}), start: startValue, end: endValue, allDay, tone, } satisfies CalendarEvent; } export type FeedOptions = { feedIndex: number; tone: CalendarTone; nameOverride: string }; function expandCalendar( ics: string, { feedIndex, tone, nameOverride }: FeedOptions, windowStart: number, horizon: number, windowStartDate: string, horizonDate: string, ) { const root = new ICAL.Component(ICAL.parse(ics)); for (const timezone of root.getAllSubcomponents("vtimezone")) { try { ICAL.TimezoneService.register(timezone); } catch { // A feed may repeat a timezone that was already registered. } } const sourceName = cleanText(root.getFirstPropertyValue("x-wr-calname"), `Calendar ${feedIndex + 1}`, 50); const calendar = nameOverride || (sourceName.includes("@") ? "Personal" : sourceName); const components = root.getAllSubcomponents("vevent"); const exceptions = new Map(); for (const component of components) { if (!component.hasProperty("recurrence-id")) continue; const uid = componentString(component, "uid"); if (!uid) continue; exceptions.set(uid, [...(exceptions.get(uid) ?? []), component]); } const items: CalendarEvent[] = []; for (const component of components) { if (component.hasProperty("recurrence-id")) continue; try { const event = new ICAL.Event(detach(component)); for (const exception of exceptions.get(event.uid) ?? []) { event.relateException(detach(exception)); } if (isCancelled(event)) continue; if (!event.isRecurring()) { if (eventIsInWindow(event.startDate, event.endDate, windowStart, horizon, windowStartDate, horizonDate)) { items.push(serializeOccurrence(event, event.startDate, event.endDate, calendar, tone, feedIndex)); } continue; } const iterator = event.iterator(); for (let count = 0; count < maxOccurrencesPerEvent; count += 1) { const occurrence = iterator.next(); if (!occurrence) break; if (occurrenceIsPastHorizon(occurrence, horizon, horizonDate)) break; const details = event.getOccurrenceDetails(occurrence); if (isCancelled(details.item)) continue; if (eventIsInWindow(details.startDate, details.endDate, windowStart, horizon, windowStartDate, horizonDate)) { items.push(serializeOccurrence(details.item, details.startDate, details.endDate, calendar, tone, feedIndex)); } } } catch { // Ignore a malformed event while keeping the rest of the calendar usable. } } return { calendar, sourceName, eventCount: components.length, items }; } export async function readCalendar( url: string, options: FeedOptions, windowStart: number, horizon: number, windowStartDate: string, horizonDate: string, ) { let currentUrl = url; let response: Response | undefined; for (let redirectCount = 0; redirectCount <= 3; redirectCount += 1) { const validatedUrl = new URL(currentUrl); if (validatedUrl.protocol !== "https:" || validatedUrl.hostname !== "calendar.google.com" || !validatedUrl.pathname.endsWith("/basic.ics")) { throw new Error("Calendar redirect host is not allowed"); } response = await fetch(validatedUrl, { headers: { Accept: "text/calendar" }, redirect: "manual", signal: AbortSignal.timeout(10_000), }); if (![301, 302, 303, 307, 308].includes(response.status)) break; const location = response.headers.get("location"); if (!location || redirectCount === 3) throw new Error("Calendar feed redirected too many times"); currentUrl = new URL(location, validatedUrl).toString(); } if (!response) throw new Error("Calendar feed request failed"); if (!response.ok) throw new Error("Calendar feed request failed"); return expandCalendar(await readLimitedText(response), options, windowStart, horizon, windowStartDate, horizonDate); }