Add the calendar service
This commit is contained in:
1 parent
a257eafafc
commit
c5de63d473
1 file changed
+350
@@ -0,0 +1,350 @@
|
||||
import Service, { service } from '@ember/service';
|
||||
import { tracked } from '@glimmer/tracking';
|
||||
import {
|
||||
CALDAV_PLATFORM,
|
||||
CALENDAR_REFRESH_INTERVAL,
|
||||
classifyCalendarError,
|
||||
fetchWindow,
|
||||
groupEvents,
|
||||
normalizeEvent,
|
||||
} from '../config/calendar';
|
||||
import {
|
||||
CALDAV_TYPE,
|
||||
caldavInstanceKey,
|
||||
credentialsMessage,
|
||||
fetchMessage,
|
||||
normalizeCalendar,
|
||||
queryMessage,
|
||||
} from '../config/caldav';
|
||||
import { ICS_TYPE, feedName, icsInstanceKey, readMessage } from '../config/ics';
|
||||
|
||||
const CALENDAR_CONSUMER = 'calendar';
|
||||
const CALENDAR_TYPES = [CALDAV_TYPE, ICS_TYPE];
|
||||
|
||||
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;
|
||||
|
||||
@tracked instances = [];
|
||||
@tracked error = null;
|
||||
|
||||
intervalId = null;
|
||||
refreshPromise = null;
|
||||
ready = null;
|
||||
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.ready = this.load();
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
await this.syncConnection();
|
||||
this.startPolling();
|
||||
} catch (err) {
|
||||
console.error('Error loading calendar integrations:', err);
|
||||
this.error = 'Unable to load calendars';
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
} catch (err) {
|
||||
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();
|
||||
}
|
||||
|
||||
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) {
|
||||
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;
|
||||
}
|
||||
|
||||
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.
|
||||
get events() {
|
||||
const enabledIds = new Set(this.instances.map((instance) => instance.id));
|
||||
|
||||
const events = this.calendarCache
|
||||
.all()
|
||||
.filter((entry) => enabledIds.has(entry.source.instanceKey))
|
||||
.flatMap((entry) =>
|
||||
entry.events.map((event) => ({ ...event, source: entry.source }))
|
||||
);
|
||||
|
||||
return groupEvents(events);
|
||||
}
|
||||
|
||||
willDestroy() {
|
||||
this.stopPolling();
|
||||
this.sockethub.release(CALENDAR_CONSUMER);
|
||||
super.willDestroy();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user