import { clientStore, config, datastore, editor, index } from "@silverbulletmd/silverbullet/syscalls"; import { convertIcsCalendar } from "https://esm.sh/ts-ics@2.4.0"; const VERSION = "0.3.25"; const CACHE_KEY = "icalendar:lastSync"; console.log(`[iCalendar] Plug script executing at top level (Version ${VERSION})`); const TIMEZONE_OFFSETS: Record = { "GMT Standard Time": 0, "W. Europe Standard Time": 1, "Central Europe Standard Time": 1, "Romance Standard Time": 1, "Central European Standard Time": 1, "Eastern Standard Time": -5, "Central Standard Time": -6, "Mountain Standard Time": -7, "Pacific Standard Time": -8, "UTC": 0, "None": 0 }; // ============================================================================ // Utility Functions // ============================================================================ /** * Creates a SHA-256 hash of a string (hex encoded) */ async function sha256Hash(str: string): Promise { const encoder = new TextEncoder(); const data = encoder.encode(str); const hashBuffer = await crypto.subtle.digest("SHA-256", data); const hashArray = Array.from(new Uint8Array(hashBuffer)); return hashArray.map(b => b.toString(16).padStart(2, "0")).join(""); } function localDateString(date: Date): string { const pad = (n: number) => String(n).padStart(2, "0"); return date.getFullYear() + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate()) + "T" + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds()); } /** * Recursively converts all Date objects and ISO date strings to strings * Handles nested objects like {date: Date, local: {date: Date, timezone: string}} */ function convertDatesToStrings(obj: T): any { if (obj === null || obj === undefined) { return obj; } if (obj instanceof Date) { return localDateString(obj); } if (typeof obj === 'object' && 'date' in obj && (obj as any).date instanceof Date) { return localDateString((obj as any).date); } if (typeof obj === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(obj)) { try { return localDateString(new Date(obj)); } catch { return obj; } } if (Array.isArray(obj)) { return obj.map(item => convertDatesToStrings(item)); } if (typeof obj === 'object') { const result: any = {}; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { result[key] = convertDatesToStrings((obj as any)[key]); } } return result; } return obj; } // ============================================================================ // Configuration Functions // ============================================================================ async function getSources(): Promise<{ sources: any[], tzShift: number }> { try { const rawConfig = await config.get("icalendar", { sources: [] }); console.log("[iCalendar] Raw config retrieved:", JSON.stringify(rawConfig)); let sources = rawConfig.sources || []; let tzShift = rawConfig.tzShift || 0; if (sources && typeof sources === "object" && !Array.isArray(sources)) { if (sources.tzShift !== undefined && tzShift === 0) { tzShift = sources.tzShift; } const sourceArray = []; for (const key in sources) { if (sources[key] && typeof sources[key].url === "string") { sourceArray.push(sources[key]); } } sources = sourceArray; } return { sources, tzShift }; } catch (e) { console.error("[iCalendar] Error in getSources:", e); return { sources: [], tzShift: 0 }; } } // ============================================================================ // Calendar Fetching & Parsing // ============================================================================ async function fetchAndParseCalendar(source: any, hourShift = 0): Promise { console.log(`[iCalendar] Fetching from: ${source.url}`); try { const response = await fetch(source.url); if (!response.ok) { console.error(`[iCalendar] Fetch failed for ${source.name}: ${response.status} ${response.statusText}`); return []; } const text = await response.text(); const calendar = convertIcsCalendar(undefined, text); if (!calendar || !calendar.events) { return []; } const events: any[] = []; for (const icsEvent of calendar.events) { const obj = icsEvent.start; if (!obj) continue; let wallTimeStr = ""; if (obj.local && obj.local.date) { wallTimeStr = typeof obj.local.date === "string" ? obj.local.date : (obj.local.date instanceof Date ? obj.local.date.toISOString() : String(obj.local.date)); } else if (obj.date) { wallTimeStr = typeof obj.date === "string" ? obj.date : (obj.date instanceof Date ? obj.date.toISOString() : String(obj.date)); } if (!wallTimeStr) continue; const baseDate = new Date(wallTimeStr.replace("Z", "") + "Z"); const tzName = obj.local?.timezone || obj.timezone || "UTC"; const sourceOffset = TIMEZONE_OFFSETS[tzName] ?? 0; const utcMillis = baseDate.getTime() - (sourceOffset * 3600000); const finalDate = new Date(utcMillis + (hourShift * 3600000)); const localIso = localDateString(finalDate); const uniqueKey = `${localIso}${icsEvent.uid || icsEvent.summary || ''}`; const ref = await sha256Hash(uniqueKey); events.push(convertDatesToStrings({ ...icsEvent, name: icsEvent.summary || "Untitled Event", start: localIso, ref, tag: "ical-event", sourceName: source.name })); } return events; } catch (err) { console.error(`[iCalendar] Error fetching/parsing ${source.name}:`, err); return []; } } export async function syncCalendars() { try { const { sources, tzShift } = await getSources(); if (sources.length === 0) return; await editor.flashNotification("Syncing calendars...", "info"); const allEvents: any[] = []; for (const source of sources) { const events = await fetchAndParseCalendar(source, tzShift); allEvents.push(...events); } await index.indexObjects("$icalendar", allEvents); await editor.flashNotification(`Synced ${allEvents.length} events`, "info"); } catch (err) { console.error("[iCalendar] syncCalendars failed:", err); } } export async function forceSync() { await clientStore.del(CACHE_KEY); await syncCalendars(); } export async function clearCache() { if (!await editor.confirm("Clear all calendar events?")) return; const pageKeys = await datastore.query({ prefix: ["ridx", "$icalendar"] }); const allKeys: any[] = []; for (const { key } of pageKeys) { allKeys.push(key); allKeys.push(["idx", ...key.slice(2), "$icalendar"]); } if (allKeys.length > 0) await datastore.batchDel(allKeys); await clientStore.del(CACHE_KEY); await editor.flashNotification("Calendar index cleared", "info"); } export async function showVersion() { await editor.flashNotification(`iCalendar Plug ${VERSION}`, "info"); }