Fix(timezone): Implement True UTC calculation and bump to v0.3.0
All checks were successful
Build SilverBullet Plug / build (push) Successful in 24s

This commit is contained in:
2026-02-17 10:06:41 -08:00
parent 8d66834a48
commit 070b10843e
6 changed files with 77 additions and 105 deletions

View File

@@ -3,6 +3,8 @@
# Build the plug using a Docker container with Deno # Build the plug using a Docker container with Deno
build: build:
docker run --rm -v $(PWD):/app -w /app denoland/deno:latest task build docker run --rm -v $(PWD):/app -w /app denoland/deno:latest task build
mkdir -p test_space/_plug
cp icalendar.plug.js test_space/_plug/icalendar.plug.js
# Start the SilverBullet test container # Start the SilverBullet test container
up: up:

View File

@@ -1,8 +1,6 @@
--- ---
name: Library/sstent/icalendar/PLUG name: Library/sstent/icalendar/PLUG
version: 0.2.14 version: 0.3.0
tags: meta/library tags: meta/library
files:
- icalendar.plug.js
--- ---
iCalendar sync plug for SilverBullet. iCalendar sync plug for SilverBullet.

View File

@@ -1,4 +1,5 @@
{ {
"nodeModulesDir": "auto",
"tasks": { "tasks": {
"build": "deno run -A https://github.com/silverbulletmd/silverbullet/releases/download/edge/plug-compile.js -c deno.json icalendar.plug.yaml", "build": "deno run -A https://github.com/silverbulletmd/silverbullet/releases/download/edge/plug-compile.js -c deno.json icalendar.plug.yaml",
"watch": "deno run -A https://github.com/silverbulletmd/silverbullet/releases/download/edge/plug-compile.js -c deno.json icalendar.plug.yaml -w", "watch": "deno run -A https://github.com/silverbulletmd/silverbullet/releases/download/edge/plug-compile.js -c deno.json icalendar.plug.yaml -w",

View File

@@ -5,6 +5,15 @@ services:
- "3000:3000" - "3000:3000"
volumes: volumes:
- ./test_space:/space - ./test_space:/space
- ./icalendar.plug.js:/space/_plug/icalendar.plug.js:ro
environment: environment:
- SB_USER=admin:admin # Default for easy local testing - SB_USER=admin:admin
- SB_LOG_PUSH=true
- SB_DEBUG=true
- SB_SPACE_LUA_TRUSTED=true
mock-ics:
image: nginx:alpine
ports:
- "8080:80"
volumes:
- ./mock_calendar.ics:/usr/share/nginx/html/calendar.ics:ro

View File

@@ -1,47 +1,15 @@
name: icalendar name: icalendar
requiredPermissions: version: 0.3.0
- fetch author: sstent
functions: functions:
syncCalendars: syncCalendars:
path: ./icalendar.ts:syncCalendars command: "iCalendar: Sync"
command:
name: "iCalendar: Sync"
priority: -1
events:
- editor:init
forceSync: forceSync:
path: ./icalendar.ts:forceSync command: "iCalendar: Force Sync"
command:
name: "iCalendar: Force Sync"
priority: -1
clearCache: clearCache:
path: ./icalendar.ts:clearCache command: "iCalendar: Clear Cache"
command:
name: "iCalendar: Clear All Events"
priority: -1
showVersion: showVersion:
path: ./icalendar.ts:showVersion command: "iCalendar: Show Version"
command: # Grant permissions to fetch from anywhere
name: "iCalendar: Version" permissions:
priority: -2 - http
config:
schema.config.properties.icalendar:
type: object
required:
- sources
properties:
sources:
type: array
minItems: 1
items:
type: object
required:
- url
properties:
url:
type: string
name:
type: string
cacheDuration:
type: number
description: "Interval between two calendar synchronizations (default: 21600 = 6 hours)"

View File

@@ -1,7 +1,7 @@
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.15"; const VERSION = "0.3.0";
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
@@ -20,8 +20,6 @@ const TIMEZONE_OFFSETS: Record<string, number> = {
"None": 0 "None": 0
}; };
console.log(`[iCalendar] Plug loading (Version ${VERSION})...`);
// ============================================================================ // ============================================================================
// Types // Types
// ============================================================================ // ============================================================================
@@ -38,7 +36,7 @@ interface Source {
} }
interface PlugConfig { interface PlugConfig {
sources: Source[]; sources: any;
cacheDuration: number | undefined; cacheDuration: number | undefined;
tzShift: number | undefined; tzShift: number | undefined;
} }
@@ -53,9 +51,6 @@ interface CalendarEvent extends DateToString<IcsEvent> {
// Utility Functions // Utility Functions
// ============================================================================ // ============================================================================
/**
* Standard SilverBullet local date string formatter
*/
function toLocalISO(d: Date): string { function toLocalISO(d: Date): string {
const pad = (n: number) => String(n).padStart(2, "0"); const pad = (n: number) => String(n).padStart(2, "0");
return d.getFullYear() + return d.getFullYear() +
@@ -67,43 +62,33 @@ function toLocalISO(d: Date): string {
"." + String(d.getMilliseconds()).padStart(3, "0"); "." + String(d.getMilliseconds()).padStart(3, "0");
} }
/**
* Robustly converts an ICS date object to a localized PST string
*/
function processIcsDate(obj: any, manualShift = 0): string { function processIcsDate(obj: any, manualShift = 0): string {
if (!obj) return ""; if (!obj) return "";
let wallTimeStr = "";
// 1. Get the "Wall Time" (the hour shown in the organizer's calendar) if (obj.local && typeof obj.local.date === "string") {
// ts-ics often puts this in obj.local.date but marks it with 'Z' wallTimeStr = obj.local.date;
let wallTimeStr = (obj.local && typeof obj.local.date === "string") } else if (typeof obj.date === "string") {
? obj.local.date wallTimeStr = obj.date;
: (typeof obj.date === "string" ? obj.date : ""); } else if (obj.date instanceof Date) {
wallTimeStr = obj.date.toISOString();
} else if (obj instanceof Date) {
wallTimeStr = obj.toISOString();
}
if (!wallTimeStr) return ""; if (!wallTimeStr) return "";
// Remove any 'Z' to treat it as a raw floating time initially // 1. Extract the "Wall Time" from the string (ignoring Z if present)
wallTimeStr = wallTimeStr.replace("Z", ""); const baseDate = new Date(wallTimeStr.replace("Z", "") + "Z");
// Parse as UTC so we have a stable starting point // 2. Determine Source Timezone Offset
const baseDate = new Date(wallTimeStr + "Z");
// 2. Identify the Source Timezone
const tzName = obj.local?.timezone || obj.timezone || "UTC"; const tzName = obj.local?.timezone || obj.timezone || "UTC";
const sourceOffset = TIMEZONE_OFFSETS[tzName] ?? 0; const sourceOffset = TIMEZONE_OFFSETS[tzName] ?? 0;
// 3. Calculate True UTC // 3. Calculate True UTC: WallTime - SourceOffset
// UTC = WallTime - SourceOffset
// Example: 16:00 WallTime in GMT+1 (+1) -> 15:00 UTC
const utcMillis = baseDate.getTime() - (sourceOffset * 3600000); const utcMillis = baseDate.getTime() - (sourceOffset * 3600000);
const envOffset = new Date().getTimezoneOffset(); // 4. Apply User's Manual Shift and Localize
console.log(`[iCalendar] Date Calc: Wall=${wallTimeStr}, TZ=${tzName}, SourceOffset=${sourceOffset}, EnvOffset=${envOffset}, UTC=${new Date(utcMillis).toISOString()}`); return toLocalISO(new Date(utcMillis + (manualShift * 3600000)));
// 4. Apply User's Manual Shift (if any)
const finalMillis = utcMillis + (manualShift * 3600000);
// 5. Localize to environment
return toLocalISO(new Date(finalMillis));
} }
function isIcsDateObjects(obj: any): obj is IcsDateObjects { function isIcsDateObjects(obj: any): obj is IcsDateObjects {
@@ -120,19 +105,9 @@ async function sha256Hash(str: string): Promise<string> {
function convertDatesToStrings<T>(obj: T, hourShift = 0): DateToString<T> { function convertDatesToStrings<T>(obj: T, hourShift = 0): DateToString<T> {
if (obj === null || obj === undefined) return obj as DateToString<T>; if (obj === null || obj === undefined) return obj as DateToString<T>;
if (isIcsDateObjects(obj)) return processIcsDate(obj, hourShift) as DateToString<T>;
if (isIcsDateObjects(obj)) { if (obj instanceof Date) return processIcsDate({ date: obj }, hourShift) as DateToString<T>;
return processIcsDate(obj, hourShift) as DateToString<T>; if (Array.isArray(obj)) return obj.map(item => convertDatesToStrings(item, 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') { if (typeof obj === 'object') {
const result: any = {}; const result: any = {};
for (const key in obj) { for (const key in obj) {
@@ -142,7 +117,6 @@ function convertDatesToStrings<T>(obj: T, hourShift = 0): DateToString<T> {
} }
return result as DateToString<T>; return result as DateToString<T>;
} }
return obj as DateToString<T>; return obj as DateToString<T>;
} }
@@ -150,12 +124,30 @@ function convertDatesToStrings<T>(obj: T, hourShift = 0): DateToString<T> {
// Configuration & Commands // Configuration & Commands
// ============================================================================ // ============================================================================
async function getSources(): Promise<Source[]> { async function getSources(): Promise<{ sources: Source[], tzShift: number }> {
const plugConfig = await config.get<PlugConfig>("icalendar", { sources: [] }); try {
if (!plugConfig.sources) return []; const rawConfig = await config.get<PlugConfig>("icalendar", { sources: [] });
let sources = plugConfig.sources; let sources: Source[] = [];
if (!Array.isArray(sources)) sources = [sources as unknown as Source]; let tzShift = rawConfig.tzShift ?? 0;
return sources.filter(s => typeof s.url === "string");
let rawSources = rawConfig.sources;
if (rawSources && typeof rawSources === "object") {
if (rawSources.tzShift !== undefined && tzShift === 0) tzShift = rawSources.tzShift;
if (Array.isArray(rawSources)) {
sources = rawSources.filter(s => s && typeof s.url === "string");
} else if (rawSources.url) {
sources = [rawSources];
} else {
for (const key in rawSources) {
if (rawSources[key] && typeof rawSources[key].url === "string") sources.push(rawSources[key]);
}
}
}
return { sources, tzShift };
} catch (e) {
console.error("Failed to load configuration", e);
return { sources: [], tzShift: 0 };
}
} }
async function fetchAndParseCalendar(source: Source, hourShift = 0): Promise<CalendarEvent[]> { async function fetchAndParseCalendar(source: Source, hourShift = 0): Promise<CalendarEvent[]> {
@@ -188,20 +180,22 @@ async function fetchAndParseCalendar(source: Source, hourShift = 0): Promise<Cal
export async function syncCalendars() { export async function syncCalendars() {
try { try {
const plugConfig = await config.get<PlugConfig>("icalendar", { sources: [] }); const { sources, tzShift } = await getSources();
const hourShift = plugConfig.tzShift ?? 0; if (sources.length === 0) {
const sources = await getSources(); console.log("[iCalendar] No sources configured.");
if (sources.length === 0) return; return;
}
await editor.flashNotification("Syncing calendars...", "info"); await editor.flashNotification("Syncing calendars...", "info");
const allEvents: CalendarEvent[] = []; const allEvents: CalendarEvent[] = [];
for (const source of sources) { for (const source of sources) {
try { try {
const events = await fetchAndParseCalendar(source, hourShift); const events = await fetchAndParseCalendar(source, tzShift);
allEvents.push(...events); allEvents.push(...events);
} catch (err) { } catch (err) {
console.error(`[iCalendar] Failed to sync ${source.name}:`, err); console.error(`[iCalendar] Failed to sync ${source.name}:`, err);
await editor.flashNotification(`Failed to sync ${source.name}`, "error");
} }
} }