forked from GitHubMirrors/silverbullet-icalendar
Bump version to 0.2.12 and fix Outlook timezone logic
All checks were successful
Build SilverBullet Plug / build (push) Successful in 24s
All checks were successful
Build SilverBullet Plug / build (push) Successful in 24s
This commit is contained in:
2
PLUG.md
2
PLUG.md
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: Library/sstent/icalendar/PLUG
|
name: Library/sstent/icalendar/PLUG
|
||||||
version: 0.2.11
|
version: 0.2.12
|
||||||
tags: meta/library
|
tags: meta/library
|
||||||
files:
|
files:
|
||||||
- icalendar.plug.js
|
- icalendar.plug.js
|
||||||
|
|||||||
146
icalendar.ts
146
icalendar.ts
@@ -1,45 +1,47 @@
|
|||||||
import { clientStore, config, datastore, editor, index } from "@silverbulletmd/silverbullet/syscalls";
|
import { clientStore, config, datastore, editor, index } from "@silverbulletmd/silverbullet/syscalls";
|
||||||
import { convertIcsCalendar, type IcsCalendar, type IcsEvent, type IcsDateObjects } from "ts-ics";
|
import { convertIcsCalendar, type IcsCalendar, type IcsEvent, type IcsDateObjects } from "ts-ics";
|
||||||
|
|
||||||
const VERSION = "0.2.11";
|
const VERSION = "0.2.12";
|
||||||
const CACHE_KEY = "icalendar:lastSync";
|
const CACHE_KEY = "icalendar:lastSync";
|
||||||
const DEFAULT_CACHE_DURATION_SECONDS = 21600; // 6 hours
|
const DEFAULT_CACHE_DURATION_SECONDS = 21600; // 6 hours
|
||||||
|
|
||||||
|
// Mapping of common Windows/Outlook timezones to their standard offsets
|
||||||
|
const TIMEZONE_OFFSETS: Record<string, number> = {
|
||||||
|
"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
|
||||||
|
};
|
||||||
|
|
||||||
console.log(`[iCalendar] Plug loading (Version ${VERSION})...`);
|
console.log(`[iCalendar] Plug loading (Version ${VERSION})...`);
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Types
|
// Types
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
/**
|
|
||||||
* Recursively converts all Date objects to strings in a type
|
|
||||||
*/
|
|
||||||
type DateToString<T> = T extends Date ? string
|
type DateToString<T> = T extends Date ? string
|
||||||
: T extends IcsDateObjects ? string
|
: T extends IcsDateObjects ? string
|
||||||
: T extends object ? { [K in keyof T]: DateToString<T[K]> }
|
: T extends object ? { [K in keyof T]: DateToString<T[K]> }
|
||||||
: T extends Array<infer U> ? Array<DateToString<U>>
|
: T extends Array<infer U> ? Array<DateToString<U>>
|
||||||
: T;
|
: T;
|
||||||
|
|
||||||
/**
|
|
||||||
* Configuration for a calendar source
|
|
||||||
*/
|
|
||||||
interface Source {
|
interface Source {
|
||||||
url: string;
|
url: string;
|
||||||
name: string | undefined;
|
name: string | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Plugin configuration structure
|
|
||||||
*/
|
|
||||||
interface PlugConfig {
|
interface PlugConfig {
|
||||||
sources: Source[];
|
sources: Source[];
|
||||||
cacheDuration: number | undefined;
|
cacheDuration: number | undefined;
|
||||||
tzShift: number | undefined; // Manual hour shift override
|
tzShift: number | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Calendar event object indexed in SilverBullet
|
|
||||||
*/
|
|
||||||
interface CalendarEvent extends DateToString<IcsEvent> {
|
interface CalendarEvent extends DateToString<IcsEvent> {
|
||||||
ref: string;
|
ref: string;
|
||||||
tag: "ical-event";
|
tag: "ical-event";
|
||||||
@@ -51,15 +53,36 @@ interface CalendarEvent extends DateToString<IcsEvent> {
|
|||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Custom date formatter that handles the local timezone shift correctly
|
* Robustly converts an ICS date object to a localized PST string
|
||||||
*/
|
*/
|
||||||
function localizeDate(d: Date, hourShift = 0): string {
|
function processIcsDate(obj: any, manualShift = 0): string {
|
||||||
// Apply any manual shift requested by the user
|
// 1. Get the "Wall Time" (e.g., 16:00)
|
||||||
if (hourShift !== 0) {
|
// If ts-ics provides a 'local' date string, it's usually the wall time but incorrectly marked as UTC
|
||||||
d = new Date(d.getTime() + (hourShift * 3600000));
|
const wallTimeStr = (obj.local && typeof obj.local.date === "string")
|
||||||
|
? obj.local.date
|
||||||
|
: (typeof obj.date === "string" ? obj.date : "");
|
||||||
|
|
||||||
|
if (!wallTimeStr) return "";
|
||||||
|
|
||||||
|
// 2. Parse it as if it were UTC to get a base date object
|
||||||
|
// We remove the 'Z' if it exists to ensure we control the parsing
|
||||||
|
const baseDate = new Date(wallTimeStr.replace("Z", "") + "Z");
|
||||||
|
|
||||||
|
// 3. Determine the Source Offset (e.g., W. Europe = +1)
|
||||||
|
const tzName = obj.local?.timezone || obj.timezone || "UTC";
|
||||||
|
const sourceOffset = TIMEZONE_OFFSETS[tzName] || 0;
|
||||||
|
|
||||||
|
// 4. Calculate the TRUE UTC time
|
||||||
|
// UTC = WallTime - SourceOffset
|
||||||
|
let utcTime = baseDate.getTime() - (sourceOffset * 3600000);
|
||||||
|
|
||||||
|
// 5. Apply User's Manual Shift (if any)
|
||||||
|
if (manualShift !== 0) {
|
||||||
|
utcTime += (manualShift * 3600000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get local parts based on the environment's timezone
|
// 6. Localize to the browser's current timezone (PST)
|
||||||
|
const d = new Date(utcTime);
|
||||||
const pad = (n: number) => String(n).padStart(2, "0");
|
const pad = (n: number) => String(n).padStart(2, "0");
|
||||||
|
|
||||||
return d.getFullYear() +
|
return d.getFullYear() +
|
||||||
@@ -71,16 +94,10 @@ function localizeDate(d: Date, hourShift = 0): string {
|
|||||||
"." + String(d.getMilliseconds()).padStart(3, "0");
|
"." + String(d.getMilliseconds()).padStart(3, "0");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Type guard for IcsDateObjects
|
|
||||||
*/
|
|
||||||
function isIcsDateObjects(obj: any): obj is IcsDateObjects {
|
function isIcsDateObjects(obj: any): obj is IcsDateObjects {
|
||||||
return obj && typeof obj === 'object' && ('date' in obj && 'type' in obj);
|
return obj && typeof obj === 'object' && ('date' in obj && 'type' in obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a SHA-256 hash of a string (hex encoded)
|
|
||||||
*/
|
|
||||||
async function sha256Hash(str: string): Promise<string> {
|
async function sha256Hash(str: string): Promise<string> {
|
||||||
const encoder = new TextEncoder();
|
const encoder = new TextEncoder();
|
||||||
const data = encoder.encode(str);
|
const data = encoder.encode(str);
|
||||||
@@ -89,28 +106,18 @@ async function sha256Hash(str: string): Promise<string> {
|
|||||||
return hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
|
return hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Recursively converts all Date objects and ISO date strings to strings
|
|
||||||
*/
|
|
||||||
function convertDatesToStrings<T>(obj: T, hourShift = 0): DateToString<T> {
|
function convertDatesToStrings<T>(obj: T, hourShift = 0): DateToString<T> {
|
||||||
if (obj === null || obj === undefined) {
|
if (obj === null || obj === undefined) return obj as DateToString<T>;
|
||||||
return obj as DateToString<T>;
|
|
||||||
|
if (isIcsDateObjects(obj)) {
|
||||||
|
return processIcsDate(obj, hourShift) as DateToString<T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (obj instanceof Date) {
|
if (obj instanceof Date) {
|
||||||
return localizeDate(obj, hourShift) as DateToString<T>;
|
// Fallback for raw Date objects
|
||||||
}
|
const d = new Date(obj.getTime() + (hourShift * 3600000));
|
||||||
|
const pad = (n: number) => String(n).padStart(2, "0");
|
||||||
if (isIcsDateObjects(obj) && obj.date instanceof Date) {
|
return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()) + "T" + pad(d.getHours()) + ":" + pad(d.getMinutes()) + ":" + pad(d.getSeconds()) + ".000" as DateToString<T>;
|
||||||
// If ts-ics gave us a nested 'local' object, prioritize it but treat it as the base time
|
|
||||||
const baseDate = (obj as any).local?.date instanceof Date ? (obj as any).local.date : obj.date;
|
|
||||||
return localizeDate(baseDate, hourShift) as DateToString<T>;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof obj === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(obj)) {
|
|
||||||
// Ensure it's treated as UTC if it doesn't have a timezone marking
|
|
||||||
const forcedUTC = obj.endsWith("Z") ? obj : obj + "Z";
|
|
||||||
return localizeDate(new Date(forcedUTC), hourShift) as DateToString<T>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Array.isArray(obj)) {
|
if (Array.isArray(obj)) {
|
||||||
@@ -131,7 +138,7 @@ function convertDatesToStrings<T>(obj: T, hourShift = 0): DateToString<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Configuration Functions
|
// Configuration & Commands
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
async function getSources(): Promise<Source[]> {
|
async function getSources(): Promise<Source[]> {
|
||||||
@@ -139,27 +146,15 @@ async function getSources(): Promise<Source[]> {
|
|||||||
if (!plugConfig.sources) return [];
|
if (!plugConfig.sources) return [];
|
||||||
let sources = plugConfig.sources;
|
let sources = plugConfig.sources;
|
||||||
if (!Array.isArray(sources)) sources = [sources as unknown as Source];
|
if (!Array.isArray(sources)) sources = [sources as unknown as Source];
|
||||||
const validated: Source[] = [];
|
return sources.filter(s => typeof s.url === "string");
|
||||||
for (const src of sources) {
|
|
||||||
if (typeof src.url === "string") {
|
|
||||||
validated.push({ url: src.url, name: src.name });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return validated;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Calendar Fetching & Parsing
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
async function fetchAndParseCalendar(source: Source, hourShift = 0): Promise<CalendarEvent[]> {
|
async function fetchAndParseCalendar(source: Source, hourShift = 0): Promise<CalendarEvent[]> {
|
||||||
let url = source.url.trim();
|
let url = source.url.trim();
|
||||||
if (url.includes(" ")) url = encodeURI(url);
|
if (url.includes(" ")) url = encodeURI(url);
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
headers: {
|
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" }
|
||||||
"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}`);
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||||
@@ -182,24 +177,13 @@ async function fetchAndParseCalendar(source: Source, hourShift = 0): Promise<Cal
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Exported Commands
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
export async function syncCalendars() {
|
export async function syncCalendars() {
|
||||||
try {
|
try {
|
||||||
const plugConfig = await config.get<PlugConfig>("icalendar", { sources: [] });
|
const plugConfig = await config.get<PlugConfig>("icalendar", { sources: [] });
|
||||||
const hourShift = plugConfig.tzShift ?? 0;
|
const hourShift = plugConfig.tzShift ?? 0;
|
||||||
const cacheDurationMs = (plugConfig.cacheDuration ?? DEFAULT_CACHE_DURATION_SECONDS) * 1000;
|
|
||||||
|
|
||||||
const sources = await getSources();
|
const sources = await getSources();
|
||||||
if (sources.length === 0) return;
|
if (sources.length === 0) return;
|
||||||
|
|
||||||
const lastSync = await clientStore.get(CACHE_KEY);
|
|
||||||
const now = Date.now();
|
|
||||||
|
|
||||||
if (lastSync && (now - lastSync) < cacheDurationMs) return;
|
|
||||||
|
|
||||||
await editor.flashNotification("Syncing calendars...", "info");
|
await editor.flashNotification("Syncing calendars...", "info");
|
||||||
|
|
||||||
const allEvents: CalendarEvent[] = [];
|
const allEvents: CalendarEvent[] = [];
|
||||||
@@ -213,7 +197,6 @@ export async function syncCalendars() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await index.indexObjects("$icalendar", allEvents);
|
await index.indexObjects("$icalendar", allEvents);
|
||||||
await clientStore.set(CACHE_KEY, now);
|
|
||||||
await editor.flashNotification(`Synced ${allEvents.length} events`, "info");
|
await editor.flashNotification(`Synced ${allEvents.length} events`, "info");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("[iCalendar] Sync failed:", err);
|
console.error("[iCalendar] Sync failed:", err);
|
||||||
@@ -226,20 +209,15 @@ export async function forceSync() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function clearCache() {
|
export async function clearCache() {
|
||||||
if (!await editor.confirm("Clear all calendar events and cache?")) return;
|
if (!await editor.confirm("Clear all calendar events?")) return;
|
||||||
try {
|
const pageKeys = await datastore.query({ prefix: ["ridx", "$icalendar"] });
|
||||||
const pageKeys = await datastore.query({ prefix: ["ridx", "$icalendar"] });
|
const allKeys: any[] = [];
|
||||||
const allKeys: any[] = [];
|
for (const { key } of pageKeys) {
|
||||||
for (const { key } of pageKeys) {
|
allKeys.push(key);
|
||||||
allKeys.push(key);
|
allKeys.push(["idx", ...key.slice(2), "$icalendar"]);
|
||||||
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");
|
|
||||||
} catch (err) {
|
|
||||||
console.error("[iCalendar] Failed to clear cache:", err);
|
|
||||||
}
|
}
|
||||||
|
if (allKeys.length > 0) await datastore.batchDel(allKeys);
|
||||||
|
await editor.flashNotification("Calendar index cleared", "info");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function showVersion() {
|
export async function showVersion() {
|
||||||
|
|||||||
Reference in New Issue
Block a user