forked from GitHubMirrors/silverbullet-icalendar
All checks were successful
Build SilverBullet Plug / build (push) Successful in 26s
200 lines
6.4 KiB
TypeScript
200 lines
6.4 KiB
TypeScript
import { clientStore, config, datastore, editor, index } from "@silverbulletmd/silverbullet/syscalls";
|
|
import { convertIcsCalendar, type IcsCalendar, type IcsEvent, type IcsDateObjects } from "ts-ics";
|
|
|
|
const VERSION = "0.2.14";
|
|
const CACHE_KEY = "icalendar:lastSync";
|
|
const DEFAULT_CACHE_DURATION_SECONDS = 21600; // 6 hours
|
|
|
|
console.log(`[iCalendar] Plug loading (Version ${VERSION})...`);
|
|
|
|
// ============================================================================
|
|
// Types
|
|
// ============================================================================
|
|
|
|
type DateToString<T> = T extends Date ? string
|
|
: T extends IcsDateObjects ? string
|
|
: T extends object ? { [K in keyof T]: DateToString<T[K]> }
|
|
: T extends Array<infer U> ? Array<DateToString<U>>
|
|
: T;
|
|
|
|
interface Source {
|
|
url: string;
|
|
name: string | undefined;
|
|
}
|
|
|
|
interface PlugConfig {
|
|
sources: Source[];
|
|
cacheDuration: number | undefined;
|
|
tzShift: number | undefined;
|
|
}
|
|
|
|
interface CalendarEvent extends DateToString<IcsEvent> {
|
|
ref: string;
|
|
tag: "ical-event";
|
|
sourceName: string | undefined;
|
|
}
|
|
|
|
// ============================================================================
|
|
// Utility Functions
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Standard SilverBullet local date string formatter
|
|
*/
|
|
function toLocalISO(d: Date): string {
|
|
const pad = (n: number) => String(n).padStart(2, "0");
|
|
return d.getFullYear() +
|
|
"-" + pad(d.getMonth() + 1) +
|
|
"-" + pad(d.getDate()) +
|
|
"T" + pad(d.getHours()) +
|
|
":" + pad(d.getMinutes()) +
|
|
":" + pad(d.getSeconds()) +
|
|
"." + String(d.getMilliseconds()).padStart(3, "0");
|
|
}
|
|
|
|
/**
|
|
* Simplified date processor that trusts the parsed Date object
|
|
*/
|
|
function processIcsDate(obj: any, manualShift = 0): string {
|
|
if (!obj) return "";
|
|
|
|
// The 'date' property from ts-ics is already a native JS Date object
|
|
// which has been parsed with the correct TZID context if available.
|
|
const d = obj.date instanceof Date ? obj.date : (obj instanceof Date ? obj : null);
|
|
|
|
if (!d) return "";
|
|
|
|
// Apply ONLY the user requested shift
|
|
const shiftedDate = new Date(d.getTime() + (manualShift * 3600000));
|
|
|
|
return toLocalISO(shiftedDate);
|
|
}
|
|
|
|
function isIcsDateObjects(obj: any): obj is IcsDateObjects {
|
|
return obj && typeof obj === 'object' && ('date' in obj && 'type' in obj);
|
|
}
|
|
|
|
async function sha256Hash(str: string): Promise<string> {
|
|
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 convertDatesToStrings<T>(obj: T, hourShift = 0): DateToString<T> {
|
|
if (obj === null || obj === undefined) return obj as DateToString<T>;
|
|
|
|
if (isIcsDateObjects(obj)) {
|
|
return processIcsDate(obj, hourShift) as DateToString<T>;
|
|
}
|
|
|
|
if (obj instanceof Date) {
|
|
return toLocalISO(new Date(obj.getTime() + (hourShift * 3600000))) as DateToString<T>;
|
|
}
|
|
|
|
if (Array.isArray(obj)) {
|
|
return obj.map(item => convertDatesToStrings(item, hourShift)) as DateToString<T>;
|
|
}
|
|
|
|
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], hourShift);
|
|
}
|
|
}
|
|
return result as DateToString<T>;
|
|
}
|
|
|
|
return obj as DateToString<T>;
|
|
}
|
|
|
|
// ============================================================================
|
|
// Configuration & Commands
|
|
// ============================================================================
|
|
|
|
async function getSources(): Promise<Source[]> {
|
|
const plugConfig = await config.get<PlugConfig>("icalendar", { sources: [] });
|
|
if (!plugConfig.sources) return [];
|
|
let sources = plugConfig.sources;
|
|
if (!Array.isArray(sources)) sources = [sources as unknown as Source];
|
|
return sources.filter(s => typeof s.url === "string");
|
|
}
|
|
|
|
async function fetchAndParseCalendar(source: Source, hourShift = 0): Promise<CalendarEvent[]> {
|
|
let url = source.url.trim();
|
|
if (url.includes(" ")) url = encodeURI(url);
|
|
|
|
const response = await fetch(url, {
|
|
headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" }
|
|
});
|
|
|
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
|
|
const icsData = await response.text();
|
|
const calendar: IcsCalendar = convertIcsCalendar(undefined, icsData);
|
|
|
|
if (!calendar.events) return [];
|
|
|
|
return await Promise.all(calendar.events.map(async (icsEvent: IcsEvent): Promise<CalendarEvent> => {
|
|
const uniqueKey = `${icsEvent.start?.date || ''}${icsEvent.uid || icsEvent.summary || ''}`;
|
|
const ref = await sha256Hash(uniqueKey);
|
|
|
|
return convertDatesToStrings({
|
|
...icsEvent,
|
|
ref,
|
|
tag: "ical-event" as const,
|
|
sourceName: source.name,
|
|
}, hourShift);
|
|
}));
|
|
}
|
|
|
|
export async function syncCalendars() {
|
|
try {
|
|
const plugConfig = await config.get<PlugConfig>("icalendar", { sources: [] });
|
|
const hourShift = plugConfig.tzShift ?? 0;
|
|
const sources = await getSources();
|
|
if (sources.length === 0) return;
|
|
|
|
await editor.flashNotification("Syncing calendars...", "info");
|
|
|
|
const allEvents: CalendarEvent[] = [];
|
|
for (const source of sources) {
|
|
try {
|
|
const events = await fetchAndParseCalendar(source, hourShift);
|
|
allEvents.push(...events);
|
|
} catch (err) {
|
|
console.error(`[iCalendar] Failed to sync ${source.name}:`, err);
|
|
}
|
|
}
|
|
|
|
await index.indexObjects("$icalendar", allEvents);
|
|
await editor.flashNotification(`Synced ${allEvents.length} events`, "info");
|
|
} catch (err) {
|
|
console.error("[iCalendar] Sync 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");
|
|
}
|