Add a 'days with events' preference (default 3, range 1-7) that drives the upcoming events widget, and extend the fetch window to 8 days so the largest window can populate. Add a Calendar settings pane (moved under Integrations) that lists the connected CalDAV/ICS sources in a two-column grid with add/edit/remove, and remove calendars from Manage Integrations. Turn the modal service into a stack so add/edit forms open on top of the settings dialog, with one dialog per level, per-entry title ids, and a softened stacked backdrop. Move CALENDAR_ACTOR into its own config module to break the calendar/caldav/ics import cycle.
471 lines
12 KiB
JavaScript
471 lines
12 KiB
JavaScript
import Service, { service } from '@ember/service';
|
|
import { tracked } from '@glimmer/tracking';
|
|
import {
|
|
CALDAV_PLATFORM,
|
|
CALENDAR_REFRESH_INTERVAL,
|
|
CALENDAR_TYPES,
|
|
CALENDAR_VISIBLE_DAYS,
|
|
CALENDAR_VISIBLE_DAYS_KEY,
|
|
classifyCalendarError,
|
|
fetchWindow,
|
|
groupEvents,
|
|
normalizeEvent,
|
|
normalizeVisibleDays,
|
|
} from '../config/calendar';
|
|
import {
|
|
CALDAV_TYPE,
|
|
caldavInstanceKey,
|
|
credentialsMessage,
|
|
fetchMessage,
|
|
normalizeCalendar,
|
|
queryMessage,
|
|
} from '../config/caldav';
|
|
import { ICS_TYPE, feedName, icsInstanceKey, readMessage } from '../config/ics';
|
|
import { isCancellation } from './http';
|
|
|
|
const CALENDAR_CONSUMER = 'calendar';
|
|
|
|
function hostOf(url) {
|
|
try {
|
|
return new URL(url).host;
|
|
} catch {
|
|
return url;
|
|
}
|
|
}
|
|
|
|
function cacheKey(type, instanceKey, calendarId) {
|
|
return `${type}:${instanceKey}:${calendarId}`;
|
|
}
|
|
|
|
// Owns every calendar source (CalDAV accounts and ICS feeds), keeps the events
|
|
// cache fresh, and exposes the combined upcoming view the dashboard renders.
|
|
export default class CalendarService extends Service {
|
|
@service storage;
|
|
@service sockethub;
|
|
@service calendarCache;
|
|
@service pageLifecycle;
|
|
|
|
@tracked instances = [];
|
|
@tracked error = null;
|
|
@tracked visibleDays = CALENDAR_VISIBLE_DAYS;
|
|
|
|
intervalId = null;
|
|
refreshPromise = null;
|
|
ready = null;
|
|
loadFailed = false;
|
|
removeRestoreHandler = null;
|
|
|
|
constructor() {
|
|
super(...arguments);
|
|
this.ready = Promise.all([this.load(), this.loadVisibleDays()]);
|
|
this.removeRestoreHandler = this.pageLifecycle.onRestore(() =>
|
|
this.handleRestore()
|
|
);
|
|
}
|
|
|
|
// A bfcache restore leaves the Sockethub socket dropped and the last refresh
|
|
// may have stored an error. Reconnect, clear the stale message, and refresh
|
|
// immediately rather than waiting for the next interval. If the initial load
|
|
// itself was interrupted, retry it first so the instances are populated.
|
|
async handleRestore() {
|
|
if (this.loadFailed) {
|
|
await this.load();
|
|
return;
|
|
}
|
|
|
|
if (!this.enabled) {
|
|
return;
|
|
}
|
|
|
|
await this.syncConnection();
|
|
await this.refreshAll();
|
|
}
|
|
|
|
async load() {
|
|
try {
|
|
const keys = await this.storage.keys('integrations');
|
|
const records = await Promise.all(
|
|
keys.map(async (key) => ({
|
|
key,
|
|
data: await this.storage.get('integrations', key),
|
|
}))
|
|
);
|
|
|
|
this.instances = records
|
|
.filter(
|
|
({ data }) =>
|
|
data?.status === 'active' && CALENDAR_TYPES.includes(data.type)
|
|
)
|
|
.map(({ key, data }) => this.buildInstance(key, data));
|
|
|
|
this.loadFailed = false;
|
|
await this.syncConnection();
|
|
this.startPolling();
|
|
} catch (err) {
|
|
// An interrupted storage read (navigation or bfcache freeze) must not be
|
|
// reported as a calendar failure; `handleRestore` retries the load.
|
|
if (isCancellation(err) || this.pageLifecycle.leaving) {
|
|
this.loadFailed = true;
|
|
return;
|
|
}
|
|
|
|
console.error('Error loading calendar integrations:', err);
|
|
this.loadFailed = true;
|
|
this.error = 'Unable to load calendars';
|
|
}
|
|
}
|
|
|
|
// The visible day count is a preference, loaded separately so a storage
|
|
// failure here does not fail the calendar load itself.
|
|
async loadVisibleDays() {
|
|
try {
|
|
const stored = await this.storage.get(
|
|
'preferences',
|
|
CALENDAR_VISIBLE_DAYS_KEY
|
|
);
|
|
|
|
if (stored != null) {
|
|
this.visibleDays = normalizeVisibleDays(stored);
|
|
}
|
|
} catch (err) {
|
|
console.error('Error loading the calendar visible days:', err);
|
|
}
|
|
}
|
|
|
|
async setVisibleDays(days) {
|
|
this.visibleDays = normalizeVisibleDays(days);
|
|
await this.storage.set(
|
|
'preferences',
|
|
CALENDAR_VISIBLE_DAYS_KEY,
|
|
this.visibleDays
|
|
);
|
|
}
|
|
|
|
buildInstance(key, data) {
|
|
return {
|
|
id: key,
|
|
type: data.type,
|
|
label: data.name?.trim() || hostOf(data.url),
|
|
url: data.url,
|
|
username: data.username,
|
|
password: data.password,
|
|
calendars: data.calendars ?? [],
|
|
selectedCalendarIds: data.selectedCalendarIds ?? [],
|
|
createdAt: data.createdAt,
|
|
};
|
|
}
|
|
|
|
get enabled() {
|
|
return this.instances.length > 0;
|
|
}
|
|
|
|
get sources() {
|
|
return this.instances;
|
|
}
|
|
|
|
instancesFor(type) {
|
|
return this.instances.filter((instance) => instance.type === type);
|
|
}
|
|
|
|
// The connection stays open only while at least one calendar is configured.
|
|
async syncConnection() {
|
|
if (!this.enabled) {
|
|
this.sockethub.release(CALENDAR_CONSUMER);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await this.sockethub.acquire(CALENDAR_CONSUMER);
|
|
this.error = null;
|
|
} catch (err) {
|
|
// A navigation that tears down the socket is not a connection failure.
|
|
if (isCancellation(err) || this.pageLifecycle.leaving) {
|
|
return;
|
|
}
|
|
|
|
console.error('Error connecting to Sockethub for calendars:', err);
|
|
this.error = classifyCalendarError(err);
|
|
}
|
|
}
|
|
|
|
async reload() {
|
|
await this.load();
|
|
}
|
|
|
|
// --- Setup helpers (used by the wizards) ---------------------------------
|
|
|
|
async fetchCalendars({ url, username, password }) {
|
|
await this.sockethub.acquire(CALENDAR_CONSUMER);
|
|
|
|
try {
|
|
const context = this.sockethub.contextFor(CALDAV_PLATFORM);
|
|
await this.sockethub.sendCredentials(
|
|
credentialsMessage(context, { url, username, password })
|
|
);
|
|
|
|
const response = await this.sockethub.send(fetchMessage(context));
|
|
|
|
return (response.items ?? []).map(normalizeCalendar).filter(Boolean);
|
|
} finally {
|
|
this.releaseIfIdle();
|
|
}
|
|
}
|
|
|
|
async verifyFeed(url) {
|
|
await this.sockethub.acquire(CALENDAR_CONSUMER);
|
|
|
|
try {
|
|
const context = this.sockethub.contextFor(CALDAV_PLATFORM);
|
|
const response = await this.sockethub.send(
|
|
readMessage(context, url, fetchWindow())
|
|
);
|
|
|
|
return { name: feedName(response, url) };
|
|
} finally {
|
|
this.releaseIfIdle();
|
|
}
|
|
}
|
|
|
|
// A wizard that is abandoned should not leave a connection open; only keep it
|
|
// when the integration is actually enabled.
|
|
releaseIfIdle() {
|
|
if (!this.enabled) {
|
|
this.sockethub.release(CALENDAR_CONSUMER);
|
|
}
|
|
}
|
|
|
|
// --- Configure / remove --------------------------------------------------
|
|
|
|
async configureCaldav(
|
|
{ url, username, password, calendars, selectedCalendarIds },
|
|
key = null
|
|
) {
|
|
const instanceKey = key ?? caldavInstanceKey(url, username);
|
|
const existing = await this.storage.get('integrations', instanceKey);
|
|
|
|
await this.storage.set('integrations', instanceKey, {
|
|
type: CALDAV_TYPE,
|
|
status: 'active',
|
|
url,
|
|
username,
|
|
password,
|
|
calendars,
|
|
selectedCalendarIds,
|
|
createdAt: existing?.createdAt ?? Date.now(),
|
|
});
|
|
|
|
await this.reload();
|
|
await this.pruneUnselectedCalendars(instanceKey);
|
|
}
|
|
|
|
// A calendar the user deselected should not keep showing cached events.
|
|
async pruneUnselectedCalendars(instanceKey) {
|
|
const instance = this.instances.find(
|
|
(candidate) => candidate.id === instanceKey
|
|
);
|
|
|
|
if (!instance || instance.type !== CALDAV_TYPE) {
|
|
return;
|
|
}
|
|
|
|
const selected = new Set(instance.selectedCalendarIds);
|
|
const stale = this.calendarCache
|
|
.forSource(CALDAV_TYPE, instanceKey)
|
|
.filter((entry) => !selected.has(entry.source.calendarId));
|
|
|
|
await Promise.all(
|
|
stale.map((entry) => this.calendarCache.remove(entry.key))
|
|
);
|
|
}
|
|
|
|
async configureIcs({ url, name }, key = null) {
|
|
const instanceKey = key ?? icsInstanceKey(url);
|
|
const existing = await this.storage.get('integrations', instanceKey);
|
|
|
|
await this.storage.set('integrations', instanceKey, {
|
|
type: ICS_TYPE,
|
|
status: 'active',
|
|
url,
|
|
name,
|
|
createdAt: existing?.createdAt ?? Date.now(),
|
|
});
|
|
|
|
await this.reload();
|
|
}
|
|
|
|
async remove(instance) {
|
|
await this.storage.remove('integrations', instance.id);
|
|
await this.calendarCache.removeSource(instance.type, instance.id);
|
|
await this.reload();
|
|
}
|
|
|
|
// --- Refresh -------------------------------------------------------------
|
|
|
|
async refreshInstance(instance) {
|
|
if (!instance || !this.sockethub.connected) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const context = this.sockethub.contextFor(CALDAV_PLATFORM);
|
|
const window = fetchWindow();
|
|
|
|
if (instance.type === CALDAV_TYPE) {
|
|
await this.refreshCaldav(instance, context, window);
|
|
} else {
|
|
await this.refreshIcs(instance, context, window);
|
|
}
|
|
} catch (err) {
|
|
// The Sockethub socket drops when the tab is navigated away from or
|
|
// frozen; that cancellation should not surface as a calendar error.
|
|
if (isCancellation(err) || this.pageLifecycle.leaving) {
|
|
return;
|
|
}
|
|
|
|
console.error(`Error refreshing calendar ${instance.id}:`, err);
|
|
this.error = classifyCalendarError(err);
|
|
}
|
|
}
|
|
|
|
async refreshCaldav(instance, context, window) {
|
|
await this.sockethub.sendCredentials(
|
|
credentialsMessage(context, {
|
|
url: instance.url,
|
|
username: instance.username,
|
|
password: instance.password,
|
|
})
|
|
);
|
|
|
|
for (const calendarId of instance.selectedCalendarIds) {
|
|
const response = await this.sockethub.send(
|
|
queryMessage(context, calendarId, window)
|
|
);
|
|
|
|
await this.calendarCache.put({
|
|
key: cacheKey(instance.type, instance.id, calendarId),
|
|
source: {
|
|
type: instance.type,
|
|
instanceKey: instance.id,
|
|
calendarId,
|
|
name: this.calendarName(instance, calendarId),
|
|
},
|
|
fetchedAt: Date.now(),
|
|
events: this.normalizeItems(response),
|
|
});
|
|
}
|
|
}
|
|
|
|
async refreshIcs(instance, context, window) {
|
|
const response = await this.sockethub.send(
|
|
readMessage(context, instance.url, window)
|
|
);
|
|
|
|
await this.calendarCache.put({
|
|
key: cacheKey(instance.type, instance.id, instance.url),
|
|
source: {
|
|
type: instance.type,
|
|
instanceKey: instance.id,
|
|
calendarId: instance.url,
|
|
name: instance.label,
|
|
},
|
|
fetchedAt: Date.now(),
|
|
events: this.normalizeItems(response),
|
|
});
|
|
}
|
|
|
|
normalizeItems(response) {
|
|
return (response?.items ?? []).map(normalizeEvent).filter(Boolean);
|
|
}
|
|
|
|
calendarName(instance, calendarId) {
|
|
const calendar = instance.calendars.find(
|
|
(entry) => entry.id === calendarId
|
|
);
|
|
return calendar?.name ?? instance.label;
|
|
}
|
|
|
|
async refreshAll() {
|
|
if (this.refreshPromise) {
|
|
return this.refreshPromise;
|
|
}
|
|
|
|
if (!this.sockethub.connected) {
|
|
return;
|
|
}
|
|
|
|
// A fresh cycle clears a stale error; failures set it again below.
|
|
this.error = null;
|
|
|
|
this.refreshPromise = Promise.all(
|
|
this.instances.map((instance) => this.refreshInstance(instance))
|
|
).finally(() => {
|
|
this.refreshPromise = null;
|
|
});
|
|
|
|
return this.refreshPromise;
|
|
}
|
|
|
|
startPolling() {
|
|
this.stopPolling();
|
|
|
|
if (!this.enabled) {
|
|
return;
|
|
}
|
|
|
|
this.refreshAll();
|
|
this.intervalId = setInterval(() => {
|
|
this.refreshAll();
|
|
}, CALENDAR_REFRESH_INTERVAL);
|
|
}
|
|
|
|
stopPolling() {
|
|
if (this.intervalId) {
|
|
clearInterval(this.intervalId);
|
|
this.intervalId = null;
|
|
}
|
|
}
|
|
|
|
// --- View ----------------------------------------------------------------
|
|
|
|
// Combined upcoming events from every enabled source, split into today and
|
|
// the next few days that have events. Only calendars still selected on their
|
|
// instance are shown.
|
|
get events() {
|
|
const instancesById = new Map(
|
|
this.instances.map((instance) => [instance.id, instance])
|
|
);
|
|
|
|
const events = this.calendarCache
|
|
.all()
|
|
.filter((entry) => this.isEntryVisible(entry, instancesById))
|
|
.flatMap((entry) =>
|
|
entry.events.map((event) => ({ ...event, source: entry.source }))
|
|
);
|
|
|
|
return groupEvents(events, new Date(), this.visibleDays);
|
|
}
|
|
|
|
isEntryVisible(entry, instancesById) {
|
|
const instance = instancesById.get(entry.source.instanceKey);
|
|
|
|
if (!instance) {
|
|
return false;
|
|
}
|
|
|
|
// A CalDAV account can hold several calendars; an ICS instance owns one
|
|
// feed, so its single entry is visible whenever the instance is.
|
|
if (instance.type === CALDAV_TYPE) {
|
|
return instance.selectedCalendarIds.includes(entry.source.calendarId);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
willDestroy() {
|
|
this.removeRestoreHandler?.();
|
|
this.stopPolling();
|
|
this.sockethub.release(CALENDAR_CONSUMER);
|
|
super.willDestroy();
|
|
}
|
|
}
|