Add calendar configuration and message builders
This commit is contained in:
1 parent
765f5dbbf1
commit
6e663710a7
3 files changed
+301
-31
No files matched your search
@@ -0,0 +1,72 @@
|
||||
import { CALENDAR_ACTOR } from './calendar';
|
||||
|
||||
export const CALDAV_TYPE = 'calendar-caldav';
|
||||
|
||||
// A CalDAV URL keeps its path (servers live under paths like `/remote.php/dav/`),
|
||||
// so only the scheme is added when missing.
|
||||
export function normalizeCaldavUrl(input) {
|
||||
let value = (input ?? '').trim();
|
||||
|
||||
if (!value || /\s/.test(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!/^https?:\/\//i.test(value)) {
|
||||
value = `https://${value}`;
|
||||
}
|
||||
|
||||
try {
|
||||
return new URL(value).href;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Keys a connected account by host and username so several accounts on the
|
||||
// same CalDAV server can coexist.
|
||||
export function caldavInstanceKey(url, username) {
|
||||
const normalized = normalizeCaldavUrl(url);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const host = new URL(normalized).host;
|
||||
const user = (username ?? '').trim().toLowerCase().replace(/\s+/g, '-');
|
||||
return user ? `${CALDAV_TYPE}-${host}-${user}` : `${CALDAV_TYPE}-${host}`;
|
||||
}
|
||||
|
||||
export function credentialsMessage(context, { url, username, password }) {
|
||||
return {
|
||||
'@context': context,
|
||||
type: 'credentials',
|
||||
actor: CALENDAR_ACTOR,
|
||||
object: { type: 'credentials', url, username, password },
|
||||
};
|
||||
}
|
||||
|
||||
export function fetchMessage(context) {
|
||||
return { '@context': context, type: 'fetch', actor: CALENDAR_ACTOR };
|
||||
}
|
||||
|
||||
export function queryMessage(context, calendarId, { startTime, endTime }) {
|
||||
return {
|
||||
'@context': context,
|
||||
type: 'query',
|
||||
actor: CALENDAR_ACTOR,
|
||||
target: { id: calendarId, type: 'calendar' },
|
||||
object: { type: 'event', startTime, endTime },
|
||||
};
|
||||
}
|
||||
|
||||
// Keeps only the fields the UI needs from a discovered calendar.
|
||||
export function normalizeCalendar(item) {
|
||||
if (!item || item.type !== 'calendar' || !item.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.name ?? item.id,
|
||||
components: Array.isArray(item.components) ? item.components : [],
|
||||
};
|
||||
}
|
||||
+169
-31
@@ -1,38 +1,176 @@
|
||||
// Calendar integration configuration. The integration is a non-tile widget
|
||||
// (like Bitcoin): it owns its own service and form and does not appear as a
|
||||
// dashboard site.
|
||||
// Shared configuration for the calendar integrations and their event cache.
|
||||
|
||||
// Storage key for the single calendar instance in the `integrations`
|
||||
// namespace. Calendar supports one connection (an account or a public feed).
|
||||
export const CALENDAR_INTEGRATION_KEY = 'calendar';
|
||||
// Persistent cache namespace for fetched events.
|
||||
export const CALENDAR_EVENTS_NAMESPACE = 'events';
|
||||
|
||||
// How the calendar is sourced. `account` uses CalDAV credentials and a
|
||||
// calendar selection; `public` reads a read-only `.ics`/`webcal:` feed.
|
||||
export const CALENDAR_MODE_ACCOUNT = 'account';
|
||||
export const CALENDAR_MODE_PUBLIC = 'public';
|
||||
|
||||
export const CALENDAR_MODES = [
|
||||
{
|
||||
value: CALENDAR_MODE_ACCOUNT,
|
||||
label: 'CalDAV account',
|
||||
description: 'Connect with a username and app password.',
|
||||
},
|
||||
{
|
||||
value: CALENDAR_MODE_PUBLIC,
|
||||
label: 'Public calendar link',
|
||||
description: 'Read a read-only .ics or webcal:// feed.',
|
||||
},
|
||||
];
|
||||
|
||||
// The Sockethub actor used for the calendar session. It must be stable across
|
||||
// The Sockethub actor used for calendar sessions. It must stay stable across
|
||||
// the credentials, fetch, and query messages so they share one session.
|
||||
export const CALENDAR_ACTOR = { id: 'caldav:dashtab', type: 'person' };
|
||||
|
||||
// The dashboard shows today plus the next two days.
|
||||
export const CALENDAR_WINDOW_DAYS = 3;
|
||||
// Fetch a week ahead; the dashboard shows today plus the next two days that
|
||||
// have events (empty days are skipped).
|
||||
export const CALENDAR_FETCH_DAYS = 7;
|
||||
export const CALENDAR_VISIBLE_DAYS = 2;
|
||||
|
||||
// Poll interval for refreshing events, in milliseconds.
|
||||
export const CALENDAR_REFRESH_INTERVAL = 300000;
|
||||
// Background refresh interval for the events cache.
|
||||
export const CALENDAR_REFRESH_INTERVAL = 900000;
|
||||
|
||||
// Upper bound on rendered events, to keep the widget compact.
|
||||
export const CALENDAR_MAX_EVENTS = 10;
|
||||
// The Sockethub caldav platform id (used for context and messages).
|
||||
export const CALDAV_PLATFORM = 'caldav';
|
||||
|
||||
// The fetch window: from now through local midnight plus CALENDAR_FETCH_DAYS.
|
||||
// Returned as ISO (UTC) strings, which is what the caldav range filter wants.
|
||||
export function fetchWindow(now = new Date()) {
|
||||
const end = new Date(now);
|
||||
end.setHours(0, 0, 0, 0);
|
||||
end.setDate(end.getDate() + CALENDAR_FETCH_DAYS);
|
||||
|
||||
return { startTime: now.toISOString(), endTime: end.toISOString() };
|
||||
}
|
||||
|
||||
// Parses a Sockethub item time into a Date. All-day values (`YYYY-MM-DD`) and
|
||||
// values flagged `allDay` are read as local dates so they do not drift a day
|
||||
// when interpreted as UTC.
|
||||
export function parseEventDate(value, allDay = false) {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (allDay || /^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||
const [year, month, day] = value.split('-').map(Number);
|
||||
return new Date(year, month - 1, day);
|
||||
}
|
||||
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
// Normalizes a Sockethub event item. Only `event` items are kept; recurring
|
||||
// items are dropped for now (recurrences are not expanded).
|
||||
export function normalizeEvent(item) {
|
||||
if (!item || item.type !== 'event' || item.recurrence) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const startTime = item.startTime;
|
||||
if (!startTime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: item.id ?? item.uid ?? startTime,
|
||||
name: item.name ?? 'Untitled event',
|
||||
startTime,
|
||||
endTime: item.endTime ?? null,
|
||||
allDay: Boolean(item.allDay),
|
||||
location: item.location ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function startOfDay(date) {
|
||||
const day = new Date(date);
|
||||
day.setHours(0, 0, 0, 0);
|
||||
return day;
|
||||
}
|
||||
|
||||
function dayKey(date) {
|
||||
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
|
||||
}
|
||||
|
||||
function eventStart(event) {
|
||||
return parseEventDate(event.startTime, event.allDay);
|
||||
}
|
||||
|
||||
function eventEnd(event) {
|
||||
const end = parseEventDate(event.endTime, event.allDay);
|
||||
if (end) {
|
||||
return end;
|
||||
}
|
||||
|
||||
const start = eventStart(event);
|
||||
if (event.allDay && start) {
|
||||
const next = new Date(start);
|
||||
next.setDate(next.getDate() + 1);
|
||||
return next;
|
||||
}
|
||||
|
||||
return start;
|
||||
}
|
||||
|
||||
function compareEvents(a, b) {
|
||||
if (a.allDay !== b.allDay) {
|
||||
return a.allDay ? -1 : 1;
|
||||
}
|
||||
|
||||
const aStart = eventStart(a)?.getTime() ?? 0;
|
||||
const bStart = eventStart(b)?.getTime() ?? 0;
|
||||
return aStart - bStart;
|
||||
}
|
||||
|
||||
// Splits events into a prominent "today" list (now through local midnight) and
|
||||
// up to `visibleDays` future days that have events, skipping empty ones.
|
||||
export function groupEvents(
|
||||
events,
|
||||
now = new Date(),
|
||||
visibleDays = CALENDAR_VISIBLE_DAYS
|
||||
) {
|
||||
const today = startOfDay(now);
|
||||
const tomorrow = new Date(today);
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
|
||||
const todayEvents = [];
|
||||
const futureByDay = new Map();
|
||||
|
||||
for (const event of events) {
|
||||
const start = eventStart(event);
|
||||
if (!start) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (start < tomorrow && (eventEnd(event) ?? start) >= now) {
|
||||
todayEvents.push(event);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (start >= tomorrow) {
|
||||
const key = dayKey(start);
|
||||
const bucket = futureByDay.get(key) ?? {
|
||||
key,
|
||||
date: startOfDay(start),
|
||||
events: [],
|
||||
};
|
||||
bucket.events.push(event);
|
||||
futureByDay.set(key, bucket);
|
||||
}
|
||||
}
|
||||
|
||||
const days = [...futureByDay.values()]
|
||||
.sort((a, b) => a.date - b.date)
|
||||
.slice(0, visibleDays)
|
||||
.map((day) => ({ ...day, events: day.events.sort(compareEvents) }));
|
||||
|
||||
return { today: todayEvents.sort(compareEvents), days };
|
||||
}
|
||||
|
||||
// Maps a Sockethub / Sockethub client failure to a user-facing message.
|
||||
export function classifyCalendarError(err) {
|
||||
if (err?.name === 'SockethubConnectionError') {
|
||||
return 'Unable to reach the Sockethub server';
|
||||
}
|
||||
|
||||
if (err?.name === 'SockethubPlatformError') {
|
||||
switch (err.message) {
|
||||
case 'caldav:authentication-failed':
|
||||
return 'Invalid username or password';
|
||||
case 'caldav:connection-failed':
|
||||
return 'Unable to reach the calendar server';
|
||||
case 'caldav:invalid-feed':
|
||||
case 'caldav:feed-failed':
|
||||
return 'Unable to read that calendar link';
|
||||
default:
|
||||
return err.message;
|
||||
}
|
||||
}
|
||||
|
||||
return 'Unable to load calendar events';
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { CALENDAR_ACTOR } from './calendar';
|
||||
|
||||
export const ICS_TYPE = 'calendar-ics';
|
||||
|
||||
// A published feed is either an http(s) URL or a webcal:// link. Sockethub
|
||||
// fetches webcal links over HTTPS, so both are accepted as-is.
|
||||
export function normalizeFeedUrl(input) {
|
||||
const value = (input ?? '').trim();
|
||||
|
||||
if (!value || /\s/.test(value) || !/^(https?|webcal):\/\//i.test(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new URL(value).href;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Short, stable hash so a feed's storage key stays tidy.
|
||||
function hash(value) {
|
||||
let result = 5381;
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
result = ((result << 5) + result + value.charCodeAt(index)) >>> 0;
|
||||
}
|
||||
return result.toString(36);
|
||||
}
|
||||
|
||||
export function icsInstanceKey(url) {
|
||||
const normalized = normalizeFeedUrl(url);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return `${ICS_TYPE}-${new URL(normalized).host}-${hash(normalized)}`;
|
||||
}
|
||||
|
||||
export function readMessage(context, url, { startTime, endTime }) {
|
||||
return {
|
||||
'@context': context,
|
||||
type: 'read',
|
||||
actor: CALENDAR_ACTOR,
|
||||
target: { id: url, type: 'feed' },
|
||||
object: { type: 'event', startTime, endTime },
|
||||
};
|
||||
}
|
||||
|
||||
// The feed's display name, from X-WR-CALNAME (`summary`) with a host fallback.
|
||||
export function feedName(response, url) {
|
||||
if (typeof response?.summary === 'string' && response.summary.trim()) {
|
||||
return response.summary.trim();
|
||||
}
|
||||
|
||||
try {
|
||||
return new URL(url).hostname;
|
||||
} catch {
|
||||
return 'Calendar';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user