Add caldav and cardav support remove old test account and contacts

This commit is contained in:
2026-10-05 00:09:15 +03:00
parent 12730e4f7e
commit 64667495fa
10 changed files with 326 additions and 45 deletions
+206
View File
@@ -5,8 +5,60 @@ const { ImapFlow } = require('imapflow');
const nodemailer = require('nodemailer');
const { simpleParser } = require('mailparser');
const { randomUUID } = require('node:crypto');
const { createDAVClient } = require('tsdav');
const ICAL = require('ical.js');
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
async function readDavStore() {
try {
const encrypted = await fs.readFile(davCredentialsPath());
const { result } = await safeStorage.decryptStringAsync(encrypted);
return JSON.parse(result);
} catch (error) {
if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null };
throw error;
}
}
async function saveDavStore(store) {
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure credential storage is unavailable.');
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store));
await fs.mkdir(path.dirname(davCredentialsPath()), { recursive: true });
await fs.writeFile(`${davCredentialsPath()}.tmp`, encrypted, { mode: 0o600 });
await fs.rename(`${davCredentialsPath()}.tmp`, davCredentialsPath());
}
function davPublicConfig(config) {
return { id: config.id, serverUrl: config.serverUrl, username: config.username, collections: config.collections || [] };
}
async function openDavClient(config, type) {
return createDAVClient({ serverUrl: config.serverUrl, credentials: { username: config.username, password: config.password }, authMethod: 'Basic', defaultAccountType: type });
}
function activeDavConfig(store, type, id = null) {
const key = type === 'caldav' ? 'caldav' : 'carddav';
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
return store[key].find(item => item.id === (id || store[activeKey])) || null;
}
function escapeIcal(value = '') { return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;'); }
function escapeVcard(value = '') { return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;'); }
function makeCalendarData(event) {
const uid = event._dav?.uid || randomUUID();
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
const start = event.time ? new Date(`${event.date}T${event.time}:00`).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '') : event.date.replace(/-/g, '');
const endDate = event.time ? new Date(new Date(`${event.date}T${event.time}:00`).getTime() + 3600000).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '') : null;
return `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Daybreak Mail//CalDAV\r\nBEGIN:VEVENT\r\nUID:${uid}\r\nDTSTAMP:${stamp}\r\n${event.time ? `DTSTART:${start}\r\nDTEND:${endDate}\r\n` : `DTSTART;VALUE=DATE:${start}\r\n` }SUMMARY:${escapeIcal(event.title)}\r\n${event.place ? `LOCATION:${escapeIcal(event.place)}\r\n` : ''}${event.notes ? `DESCRIPTION:${escapeIcal(event.notes)}\r\n` : ''}END:VEVENT\r\nEND:VCALENDAR\r\n`;
}
function makeVcard(contact) {
const name = String(contact.name || '').trim().split(/\s+/);
const first = name.shift() || '';
const last = name.join(' ');
return `BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${contact._dav?.uid || randomUUID()}\r\nFN:${escapeVcard(contact.name)}\r\nN:${escapeVcard(last)};${escapeVcard(first)};;;\r\nEMAIL:${escapeVcard(contact.email)}\r\n${contact.note ? `NOTE:${escapeVcard(contact.note)}\r\n` : ''}END:VCARD\r\n`;
}
function normalizeAccount(input) {
const email = String(input?.email || '').trim();
@@ -377,6 +429,157 @@ ipcMain.handle('mail:disconnect', async (_event, accountId) => {
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
});
ipcMain.handle('dav:list', async () => {
const store = await readDavStore();
return { caldav: store.caldav.map(davPublicConfig), carddav: store.carddav.map(davPublicConfig), activeCaldavId: store.activeCaldavId, activeCarddavId: store.activeCarddavId };
});
ipcMain.handle('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.protocol === 'http:' && !['localhost','127.0.0.1','::1'].includes(parsedUrl.hostname))) throw new Error('DAV server URLs must use HTTPS.');
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 } };
});
ipcMain.handle('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 };
});
ipcMain.handle('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] };
});
ipcMain.handle('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) };
});
ipcMain.handle('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 = calendars.find(item => item.url === remote?.collectionUrl) || calendars[0];
if (!calendar) throw new Error('No writable calendar was found.');
const uid = remote?.uid || randomUUID();
const data = makeCalendarData({ ...input, _dav: { ...remote, uid } });
if (remote?.objectUrl) {
const response = await client.updateCalendarObject({ calendarObject: { url: remote.objectUrl, data, etag: remote.etag } });
return { accountId: config.id, collectionUrl: calendar.url, objectUrl: remote.objectUrl, etag: response.headers.get('etag') || remote.etag, uid };
}
const filename = `${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 };
});
ipcMain.handle('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');
await client.deleteCalendarObject({ calendarObject: { url: remote.objectUrl, etag: remote.etag } });
});
ipcMain.handle('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 = books.find(item => item.url === remote?.collectionUrl) || books[0];
if (!book) throw new Error('No writable address book was found.');
const uid = remote?.uid || randomUUID();
const data = makeVcard({ ...input, _dav: { ...remote, uid } });
if (remote?.objectUrl) {
const response = await client.updateVCard({ vCard: { url: remote.objectUrl, data, etag: remote.etag } });
return { accountId: config.id, collectionUrl: book.url, objectUrl: remote.objectUrl, etag: response.headers.get('etag') || remote.etag, uid };
}
const filename = `${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 };
});
ipcMain.handle('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');
await client.deleteVCard({ vCard: { url: remote.objectUrl, etag: remote.etag } });
});
function createWindow() {
const window = new BrowserWindow({
width: 1440,
@@ -385,6 +588,7 @@ function createWindow() {
minHeight: 680,
title: 'Daybreak Mail',
backgroundColor: '#f4f5f1',
show: false,
autoHideMenuBar: true,
icon: path.join(__dirname, '..', 'icon.svg'),
webPreferences: {
@@ -395,6 +599,8 @@ function createWindow() {
}
});
window.once('ready-to-show', () => window.show());
window.loadFile(path.join(__dirname, '..', 'index.html'));
window.webContents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('https://') || url.startsWith('mailto:')) shell.openExternal(url);
+10 -1
View File
@@ -11,5 +11,14 @@ contextBridge.exposeInMainWorld('daybreakMail', {
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
send: message => ipcRenderer.invoke('mail:send', message),
disconnect: id => ipcRenderer.invoke('mail:disconnect', id)
disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
davList: () => ipcRenderer.invoke('dav:list'),
davConnect: config => ipcRenderer.invoke('dav:connect', config),
davActivate: (type, id) => ipcRenderer.invoke('dav:activate', { type, id }),
davRemove: (type, id) => ipcRenderer.invoke('dav:remove', { type, id }),
davSync: type => ipcRenderer.invoke('dav:sync', type),
davSaveEvent: event => ipcRenderer.invoke('dav:save-event', event),
davDeleteEvent: remote => ipcRenderer.invoke('dav:delete-event', remote),
davSaveContact: contact => ipcRenderer.invoke('dav:save-contact', contact),
davDeleteContact: remote => ipcRenderer.invoke('dav:delete-contact', remote)
});