Refractoring Stage 5 Moved the OpenPGP and DAV IPC handlers into desktop/ipc/pgp.cjs and desktop/ipc/dav.cjs.
This commit is contained in:
@@ -0,0 +1,257 @@
|
||||
function registerDavIpcHandlers({
|
||||
registerIpcHandler,
|
||||
readDavStore,
|
||||
saveDavStore,
|
||||
davPublicConfig,
|
||||
openDavClient,
|
||||
activeDavConfig,
|
||||
ICAL,
|
||||
makeCalendarData,
|
||||
makeVcard,
|
||||
randomUUID,
|
||||
assertDavObjectReference
|
||||
}) {
|
||||
registerIpcHandler('dav:list', async () => {
|
||||
const store = await readDavStore();
|
||||
return {
|
||||
caldav: store.caldav.map(davPublicConfig),
|
||||
carddav: store.carddav.map(davPublicConfig),
|
||||
activeCaldavId: store.activeCaldavId,
|
||||
activeCarddavId: store.activeCarddavId
|
||||
};
|
||||
});
|
||||
|
||||
registerIpcHandler('dav:connect', async (_event, input) => {
|
||||
const type = input?.type === 'carddav' ? 'carddav' : 'caldav';
|
||||
const serverUrl = String(input?.serverUrl || '').trim();
|
||||
const username = String(input?.username || '').trim();
|
||||
const password = String(input?.password || '');
|
||||
let parsedUrl;
|
||||
try { parsedUrl = new URL(serverUrl); } catch { throw new Error('Enter a valid CalDAV or CardDAV server URL.'); }
|
||||
if (!['https:', 'http:'].includes(parsedUrl.protocol) || parsedUrl.username || parsedUrl.password ||
|
||||
(parsedUrl.protocol === 'http:' && !['localhost', '127.0.0.1', '::1'].includes(parsedUrl.hostname))) {
|
||||
throw new Error('DAV server URLs must use HTTPS and must not contain embedded credentials.');
|
||||
}
|
||||
if (!username || !password) throw new Error('Enter the DAV username and password.');
|
||||
const config = { id: randomUUID(), type, serverUrl: parsedUrl.href, username, password };
|
||||
const client = await openDavClient(config, type);
|
||||
const collections = type === 'caldav' ? await client.fetchCalendars() : await client.fetchAddressBooks();
|
||||
if (!collections.length) throw new Error(`No ${type === 'caldav' ? 'calendars' : 'address books'} were found on this server.`);
|
||||
config.collections = collections.map(collection => ({
|
||||
url: collection.url,
|
||||
name: typeof collection.displayName === 'string' ? collection.displayName : collection.url
|
||||
}));
|
||||
const store = await readDavStore();
|
||||
const key = type;
|
||||
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
|
||||
const duplicate = store[key].find(account => account.serverUrl === config.serverUrl && account.username.toLowerCase() === username.toLowerCase());
|
||||
if (duplicate) config.id = duplicate.id;
|
||||
store[key] = [...store[key].filter(account => account.id !== config.id), config];
|
||||
store[activeKey] = config.id;
|
||||
await saveDavStore(store);
|
||||
return {
|
||||
config: davPublicConfig(config),
|
||||
collections: config.collections,
|
||||
accounts: {
|
||||
caldav: store.caldav.map(davPublicConfig),
|
||||
carddav: store.carddav.map(davPublicConfig),
|
||||
activeCaldavId: store.activeCaldavId,
|
||||
activeCarddavId: store.activeCarddavId
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
registerIpcHandler('dav:activate', async (_event, input) => {
|
||||
const type = input?.type === 'carddav' ? 'carddav' : 'caldav';
|
||||
const store = await readDavStore();
|
||||
const config = store[type].find(item => item.id === input?.id);
|
||||
if (!config) throw new Error('That DAV account could not be found.');
|
||||
store[type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId'] = config.id;
|
||||
await saveDavStore(store);
|
||||
return { id: config.id };
|
||||
});
|
||||
|
||||
registerIpcHandler('dav:remove', async (_event, input) => {
|
||||
const type = input?.type === 'carddav' ? 'carddav' : 'caldav';
|
||||
const store = await readDavStore();
|
||||
store[type] = store[type].filter(item => item.id !== input?.id);
|
||||
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
|
||||
if (store[activeKey] === input?.id) store[activeKey] = store[type][0]?.id || null;
|
||||
await saveDavStore(store);
|
||||
return { accounts: store[type].map(davPublicConfig), activeId: store[activeKey] };
|
||||
});
|
||||
|
||||
registerIpcHandler('dav:sync', async (_event, requestedType) => {
|
||||
const type = requestedType === 'carddav' ? 'carddav' : 'caldav';
|
||||
const store = await readDavStore();
|
||||
const config = activeDavConfig(store, type);
|
||||
if (!config) throw new Error(`Connect a ${type === 'caldav' ? 'CalDAV' : 'CardDAV'} server first.`);
|
||||
const client = await openDavClient(config, type);
|
||||
if (type === 'caldav') {
|
||||
const calendars = await client.fetchCalendars();
|
||||
const result = [];
|
||||
for (const calendar of calendars) {
|
||||
const objects = await client.fetchCalendarObjects({ calendar });
|
||||
for (const object of objects) {
|
||||
if (!object.data) continue;
|
||||
try {
|
||||
const component = new ICAL.Component(ICAL.parse(object.data));
|
||||
for (const part of component.getAllSubcomponents('vevent')) {
|
||||
const parsed = new ICAL.Event(part);
|
||||
if (!parsed.startDate) continue;
|
||||
const start = parsed.startDate.toJSDate();
|
||||
result.push({
|
||||
id: `dav:${config.id}:${encodeURIComponent(object.url)}:${encodeURIComponent(parsed.uid)}`,
|
||||
title: parsed.summary || '(no title)',
|
||||
date: `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')}`,
|
||||
time: parsed.startDate.isDate ? '' : `${String(start.getHours()).padStart(2, '0')}:${String(start.getMinutes()).padStart(2, '0')}`,
|
||||
with: part.getAllProperties('attendee').map(property => String(property.getFirstValue() || '').replace(/^mailto:/i, '')).join(', '),
|
||||
place: parsed.location || '',
|
||||
notes: parsed.description || '',
|
||||
_dav: { accountId: config.id, collectionUrl: calendar.url, objectUrl: object.url, etag: object.etag, uid: parsed.uid }
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
return { items: result, account: davPublicConfig(config) };
|
||||
}
|
||||
const books = await client.fetchAddressBooks();
|
||||
const result = [];
|
||||
for (const book of books) {
|
||||
const cards = await client.fetchVCards({ addressBook: book });
|
||||
for (const card of cards) {
|
||||
if (!card.data) continue;
|
||||
try {
|
||||
const parsed = new ICAL.Component(ICAL.parse(card.data));
|
||||
const name = String(parsed.getFirstPropertyValue('fn') || '').trim();
|
||||
if (!name) continue;
|
||||
const emails = parsed.getAllProperties('email').map(property => String(property.getFirstValue() || ''));
|
||||
const uid = String(parsed.getFirstPropertyValue('uid') || '');
|
||||
result.push({
|
||||
id: `dav:${config.id}:${encodeURIComponent(card.url)}:${encodeURIComponent(uid)}`,
|
||||
name,
|
||||
email: emails[0] || '',
|
||||
note: String(parsed.getFirstPropertyValue('note') || ''),
|
||||
initials: name.split(/\s+/).map(part => part[0]).join('').slice(0, 2).toUpperCase(),
|
||||
color: '#dce9dd',
|
||||
_dav: { accountId: config.id, collectionUrl: book.url, objectUrl: card.url, etag: card.etag, uid }
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
return { items: result, account: davPublicConfig(config) };
|
||||
});
|
||||
|
||||
registerIpcHandler('dav:save-event', async (_event, input) => {
|
||||
const store = await readDavStore();
|
||||
const remote = input?._dav;
|
||||
const config = activeDavConfig(store, 'caldav', remote?.accountId);
|
||||
if (!config) return null;
|
||||
const client = await openDavClient(config, 'caldav');
|
||||
const calendars = await client.fetchCalendars();
|
||||
const calendar = remote?.collectionUrl
|
||||
? calendars.find(item => item.url === remote.collectionUrl)
|
||||
: calendars[0];
|
||||
if (!calendar) throw new Error('No writable calendar was found.');
|
||||
let trustedObject = null;
|
||||
if (remote?.objectUrl) {
|
||||
const objects = await client.fetchCalendarObjects({ calendar });
|
||||
trustedObject = assertDavObjectReference({ config, remote, collections: calendars, objects });
|
||||
}
|
||||
const uid = remote?.uid || randomUUID();
|
||||
const data = makeCalendarData({ ...input, _dav: { ...remote, uid } });
|
||||
if (remote?.objectUrl) {
|
||||
const response = await client.updateCalendarObject({
|
||||
calendarObject: { url: trustedObject.objectUrl, data, etag: trustedObject.object.etag ?? remote.etag }
|
||||
});
|
||||
return {
|
||||
accountId: config.id,
|
||||
collectionUrl: calendar.url,
|
||||
objectUrl: trustedObject.objectUrl,
|
||||
etag: response.headers.get('etag') || remote.etag,
|
||||
uid
|
||||
};
|
||||
}
|
||||
const filename = `${encodeURIComponent(uid)}.ics`;
|
||||
const response = await client.createCalendarObject({ calendar, iCalString: data.replace(`UID:${uid}`, `UID:${uid}`), filename });
|
||||
return {
|
||||
accountId: config.id,
|
||||
collectionUrl: calendar.url,
|
||||
objectUrl: new URL(filename, calendar.url.endsWith('/') ? calendar.url : `${calendar.url}/`).href,
|
||||
etag: response.headers.get('etag'),
|
||||
uid
|
||||
};
|
||||
});
|
||||
|
||||
registerIpcHandler('dav:delete-event', async (_event, remote) => {
|
||||
const store = await readDavStore();
|
||||
const config = activeDavConfig(store, 'caldav', remote?.accountId);
|
||||
if (!config || !remote?.objectUrl) return;
|
||||
const client = await openDavClient(config, 'caldav');
|
||||
const calendars = await client.fetchCalendars();
|
||||
const calendar = calendars.find(item => item.url === remote.collectionUrl);
|
||||
if (!calendar) throw new Error('This DAV collection is not available on the selected server.');
|
||||
const objects = await client.fetchCalendarObjects({ calendar });
|
||||
const trustedObject = assertDavObjectReference({ config, remote, collections: calendars, objects });
|
||||
await client.deleteCalendarObject({
|
||||
calendarObject: { url: trustedObject.objectUrl, etag: trustedObject.object.etag ?? remote.etag }
|
||||
});
|
||||
});
|
||||
|
||||
registerIpcHandler('dav:save-contact', async (_event, input) => {
|
||||
const store = await readDavStore();
|
||||
const remote = input?._dav;
|
||||
const config = activeDavConfig(store, 'carddav', remote?.accountId);
|
||||
if (!config) return null;
|
||||
const client = await openDavClient(config, 'carddav');
|
||||
const books = await client.fetchAddressBooks();
|
||||
const book = remote?.collectionUrl
|
||||
? books.find(item => item.url === remote.collectionUrl)
|
||||
: books[0];
|
||||
if (!book) throw new Error('No writable address book was found.');
|
||||
let trustedObject = null;
|
||||
if (remote?.objectUrl) {
|
||||
const cards = await client.fetchVCards({ addressBook: book });
|
||||
trustedObject = assertDavObjectReference({ config, remote, collections: books, objects: cards });
|
||||
}
|
||||
const uid = remote?.uid || randomUUID();
|
||||
const data = makeVcard({ ...input, _dav: { ...remote, uid } });
|
||||
if (remote?.objectUrl) {
|
||||
const response = await client.updateVCard({
|
||||
vCard: { url: trustedObject.objectUrl, data, etag: trustedObject.object.etag ?? remote.etag }
|
||||
});
|
||||
return {
|
||||
accountId: config.id,
|
||||
collectionUrl: book.url,
|
||||
objectUrl: trustedObject.objectUrl,
|
||||
etag: response.headers.get('etag') || remote.etag,
|
||||
uid
|
||||
};
|
||||
}
|
||||
const filename = `${encodeURIComponent(uid)}.vcf`;
|
||||
const response = await client.createVCard({ addressBook: book, vCardString: data, filename });
|
||||
return {
|
||||
accountId: config.id,
|
||||
collectionUrl: book.url,
|
||||
objectUrl: new URL(filename, book.url.endsWith('/') ? book.url : `${book.url}/`).href,
|
||||
etag: response.headers.get('etag'),
|
||||
uid
|
||||
};
|
||||
});
|
||||
|
||||
registerIpcHandler('dav:delete-contact', async (_event, remote) => {
|
||||
const store = await readDavStore();
|
||||
const config = activeDavConfig(store, 'carddav', remote?.accountId);
|
||||
if (!config || !remote?.objectUrl) return;
|
||||
const client = await openDavClient(config, 'carddav');
|
||||
const books = await client.fetchAddressBooks();
|
||||
const book = books.find(item => item.url === remote.collectionUrl);
|
||||
if (!book) throw new Error('This DAV collection is not available on the selected server.');
|
||||
const cards = await client.fetchVCards({ addressBook: book });
|
||||
const trustedObject = assertDavObjectReference({ config, remote, collections: books, objects: cards });
|
||||
await client.deleteVCard({ vCard: { url: trustedObject.objectUrl, etag: trustedObject.object.etag ?? remote.etag } });
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { registerDavIpcHandlers };
|
||||
Reference in New Issue
Block a user