642 lines
30 KiB
JavaScript
642 lines
30 KiB
JavaScript
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog } = require('electron');
|
|
const path = require('node:path');
|
|
const fs = require('node:fs/promises');
|
|
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:-//Eternity Project//ep-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();
|
|
const password = String(input?.password || '');
|
|
const imapHost = String(input?.imapHost || '').trim();
|
|
const smtpHost = String(input?.smtpHost || '').trim();
|
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) {
|
|
throw new Error('Enter a valid email, password, and both mail server names.');
|
|
}
|
|
return { email, password, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
|
|
}
|
|
|
|
function imapClient(account) {
|
|
return new ImapFlow({
|
|
host: account.imapHost,
|
|
port: account.imapPort,
|
|
secure: false,
|
|
doSTARTTLS: true,
|
|
auth: { user: account.email, pass: account.password },
|
|
tls: { rejectUnauthorized: true },
|
|
logger: false,
|
|
connectionTimeout: 15000,
|
|
greetingTimeout: 10000,
|
|
socketTimeout: 20000
|
|
});
|
|
}
|
|
|
|
function smtpTransport(account) {
|
|
return nodemailer.createTransport({
|
|
host: account.smtpHost,
|
|
port: account.smtpPort,
|
|
secure: false,
|
|
requireTLS: true,
|
|
auth: { user: account.email, pass: account.password },
|
|
tls: { rejectUnauthorized: true, servername: account.smtpHost },
|
|
connectionTimeout: 15000,
|
|
greetingTimeout: 10000,
|
|
socketTimeout: 20000
|
|
});
|
|
}
|
|
|
|
async function readAccountStore() {
|
|
try {
|
|
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
|
|
const encrypted = await fs.readFile(credentialsPath());
|
|
const { result } = await safeStorage.decryptStringAsync(encrypted);
|
|
const stored = JSON.parse(result);
|
|
if (Array.isArray(stored.accounts)) return stored;
|
|
if (stored.email) {
|
|
const account = { ...stored, id: stored.id || randomUUID() };
|
|
const migrated = { accounts: [account], activeId: account.id };
|
|
await saveAccountStore(migrated);
|
|
return migrated;
|
|
}
|
|
return { accounts: [], activeId: null };
|
|
} catch (error) {
|
|
if (error.code === 'ENOENT') return null;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function saveAccountStore(store) {
|
|
if (!await safeStorage.isAsyncEncryptionAvailable()) {
|
|
throw new Error('Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.');
|
|
}
|
|
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store));
|
|
const file = credentialsPath();
|
|
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
await fs.writeFile(`${file}.tmp`, encrypted, { mode: 0o600 });
|
|
await fs.rename(`${file}.tmp`, file);
|
|
}
|
|
|
|
async function readAccount(accountId = null) {
|
|
const store = await readAccountStore();
|
|
if (!store?.accounts.length) return null;
|
|
return store.accounts.find(account => account.id === (accountId || store.activeId)) || null;
|
|
}
|
|
|
|
function publicAccount(account) {
|
|
return { id: account.id, email: account.email, imapHost: account.imapHost, smtpHost: account.smtpHost };
|
|
}
|
|
|
|
async function saveAccount(account) {
|
|
const store = (await readAccountStore()) || { accounts: [], activeId: null };
|
|
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
|
|
const saved = { ...account, id: existing?.id || randomUUID() };
|
|
store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved];
|
|
store.activeId = saved.id;
|
|
await saveAccountStore(store);
|
|
return saved;
|
|
}
|
|
|
|
async function connectMail(account) {
|
|
const client = imapClient(account);
|
|
let transport;
|
|
try {
|
|
await client.connect();
|
|
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
|
|
transport = smtpTransport(account);
|
|
await transport.verify();
|
|
return { mailbox: mailbox.name, messages: mailbox.exists };
|
|
} finally {
|
|
if (transport) transport.close();
|
|
if (client.usable) await client.logout().catch(() => {});
|
|
}
|
|
}
|
|
|
|
async function findSpecialMailbox(client, specialUse, fallbackNames, createName = null) {
|
|
const mailboxes = await client.list();
|
|
const match = mailboxes.find(mailbox => mailbox.specialUse?.toLowerCase() === specialUse.toLowerCase()) ||
|
|
mailboxes.find(mailbox => fallbackNames.includes(mailbox.path.toLowerCase().split(/[./]/).pop()));
|
|
if (match) return match.path;
|
|
if (!createName) return null;
|
|
return (await client.mailboxCreate(createName)).path;
|
|
}
|
|
|
|
async function findSentMailbox(client, createIfMissing = false) {
|
|
return findSpecialMailbox(client, '\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], createIfMissing ? 'Sent' : null);
|
|
}
|
|
|
|
async function folderPath(client, folder, createIfMissing = false) {
|
|
if (folder === 'Inbox' || folder === 'Starred' || folder === 'Snoozed') return 'INBOX';
|
|
const definitions = {
|
|
Sent: ['\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], 'Sent'],
|
|
Archive: ['\\Archive', ['archive', 'archives', 'all mail'], 'Archive'],
|
|
Trash: ['\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash']
|
|
};
|
|
const definition = definitions[folder];
|
|
if (!definition) throw new Error('This folder is not available on the mail server.');
|
|
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
|
|
}
|
|
|
|
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
|
const client = imapClient(account);
|
|
try {
|
|
await client.connect();
|
|
const mailboxPath = await folderPath(client, folder);
|
|
if (!mailboxPath) return { messages: [], total: 0 };
|
|
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
|
|
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
|
|
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
|
|
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
|
|
const fetched = await client.fetchAll(`${first}:${end}`, {
|
|
uid: true,
|
|
envelope: true,
|
|
flags: true,
|
|
internalDate: true,
|
|
source: true
|
|
});
|
|
const messages = [];
|
|
for (const item of fetched.reverse()) {
|
|
if (!item.source) continue;
|
|
const parsed = await simpleParser(item.source);
|
|
const sender = parsed.from?.value?.[0];
|
|
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim();
|
|
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
|
|
const date = parsed.date || item.internalDate || new Date();
|
|
messages.push({
|
|
id: Number(item.uid),
|
|
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
|
|
color: '#dce6df',
|
|
sender: sender?.name || sender?.address || 'Unknown sender',
|
|
email: sender?.address || '',
|
|
subject: parsed.subject || '(no subject)',
|
|
snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
|
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
|
|
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
|
|
unread: !item.flags?.has('\\Seen'),
|
|
star: item.flags?.has('\\Flagged') || false,
|
|
tags: [folder],
|
|
sent: folder === 'Sent',
|
|
archived: folder === 'Archive',
|
|
deleted: folder === 'Trash',
|
|
body,
|
|
uid: Number(item.uid),
|
|
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
|
|
attachment: parsed.attachments?.[0]?.filename || null,
|
|
size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : ''
|
|
});
|
|
}
|
|
return { messages, total: mailbox.exists, start: first, end: Math.min(end, mailbox.exists), folder };
|
|
} finally {
|
|
if (client.usable) await client.logout().catch(() => {});
|
|
}
|
|
}
|
|
|
|
ipcMain.handle('mail:get-account', async () => {
|
|
const account = await readAccount();
|
|
return account ? publicAccount(account) : null;
|
|
});
|
|
|
|
ipcMain.handle('mail:list-accounts', async () => {
|
|
const store = (await readAccountStore()) || { accounts: [], activeId: null };
|
|
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
|
});
|
|
|
|
ipcMain.handle('mail:select-account', async (_event, accountId) => {
|
|
const store = await readAccountStore();
|
|
const account = store?.accounts.find(item => item.id === accountId);
|
|
if (!account) throw new Error('That mail account is no longer available.');
|
|
store.activeId = account.id;
|
|
await saveAccountStore(store);
|
|
return publicAccount(account);
|
|
});
|
|
|
|
ipcMain.handle('mail:remove-account', async (_event, accountId) => {
|
|
const store = await readAccountStore();
|
|
if (!store) return { accounts: [], activeId: null };
|
|
store.accounts = store.accounts.filter(account => account.id !== accountId);
|
|
if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null;
|
|
if (store.accounts.length) await saveAccountStore(store);
|
|
else await fs.rm(credentialsPath(), { force: true });
|
|
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
|
});
|
|
|
|
ipcMain.handle('mail:update-account', async (_event, accountId, input) => {
|
|
const store = await readAccountStore();
|
|
const existing = store?.accounts.find(account => account.id === accountId);
|
|
if (!existing) throw new Error('That mail account is no longer available.');
|
|
const account = normalizeAccount({ ...existing, ...input, password: String(input?.password || '') || existing.password });
|
|
account.id = existing.id;
|
|
try {
|
|
const status = await connectMail(account);
|
|
store.accounts = store.accounts.map(item => item.id === existing.id ? account : item);
|
|
await saveAccountStore(store);
|
|
return { ...publicAccount(account), ...status };
|
|
} catch (error) {
|
|
throw new Error(`Could not update the mailbox: ${error.message}`);
|
|
}
|
|
});
|
|
|
|
ipcMain.handle('mail:connect', async (_event, input) => {
|
|
const account = normalizeAccount(input);
|
|
try {
|
|
const status = await connectMail(account);
|
|
const saved = await saveAccount(account);
|
|
return { ok: true, ...publicAccount(saved), ...status };
|
|
} catch (error) {
|
|
throw new Error(`Could not connect to the mailbox: ${error.message}`);
|
|
}
|
|
});
|
|
|
|
ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0) => {
|
|
const account = await readAccount();
|
|
if (!account) throw new Error('Add a mail account before syncing.');
|
|
const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']);
|
|
const folder = allowedFolders.has(requestedFolder) ? requestedFolder : 'Inbox';
|
|
return fetchMailbox(account, folder, offset);
|
|
});
|
|
|
|
ipcMain.handle('mail:update-message', async (_event, input) => {
|
|
const account = await readAccount();
|
|
if (!account) throw new Error('Add a mail account before changing messages.');
|
|
const uid = Number(input?.uid);
|
|
const folder = String(input?.folder || 'Inbox');
|
|
const action = String(input?.action || '');
|
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
|
if (!['star', 'unread', 'archive', 'delete'].includes(action)) throw new Error('That mail action is not supported.');
|
|
const client = imapClient(account);
|
|
try {
|
|
await client.connect();
|
|
const sourcePath = await folderPath(client, folder);
|
|
if (!sourcePath) throw new Error('That mail folder could not be found.');
|
|
const lock = await client.getMailboxLock(sourcePath);
|
|
try {
|
|
if (action === 'star') {
|
|
if (input.enabled) await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
|
|
else await client.messageFlagsRemove(uid, ['\\Flagged'], { uid: true });
|
|
} else if (action === 'unread') {
|
|
if (input.enabled) await client.messageFlagsRemove(uid, ['\\Seen'], { uid: true });
|
|
else await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true });
|
|
} else {
|
|
const target = action === 'archive'
|
|
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
|
|
: await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash');
|
|
if (action === 'delete' && sourcePath === target) await client.messageDelete(uid, { uid: true });
|
|
else await client.messageMove(uid, target, { uid: true });
|
|
}
|
|
} finally {
|
|
lock.release();
|
|
}
|
|
return { ok: true };
|
|
} finally {
|
|
if (client.usable) await client.logout().catch(() => {});
|
|
}
|
|
});
|
|
|
|
ipcMain.handle('mail:save-attachment', async (event, input) => {
|
|
const account = await readAccount();
|
|
if (!account) throw new Error('Add a mail account before downloading attachments.');
|
|
const uid = Number(input?.uid);
|
|
const folder = String(input?.folder || 'Inbox');
|
|
const filename = String(input?.filename || 'attachment');
|
|
const safeFilename = filename.replace(/[\\/:*?"<>|]/g, '_');
|
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
|
const client = imapClient(account);
|
|
try {
|
|
await client.connect();
|
|
const mailboxPath = await folderPath(client, folder);
|
|
if (!mailboxPath) throw new Error('That mail folder could not be found.');
|
|
const lock = await client.getMailboxLock(mailboxPath);
|
|
try {
|
|
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
|
|
if (!item?.source) throw new Error('The message is no longer available.');
|
|
const parsed = await simpleParser(item.source);
|
|
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename) || parsed.attachments?.[0];
|
|
if (!attachment) throw new Error('No attachment was found in this message.');
|
|
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_') });
|
|
if (result.canceled || !result.filePath) return { canceled: true };
|
|
await fs.writeFile(result.filePath, attachment.content);
|
|
return { saved: true };
|
|
} finally {
|
|
lock.release();
|
|
}
|
|
} finally {
|
|
if (client.usable) await client.logout().catch(() => {});
|
|
}
|
|
});
|
|
|
|
ipcMain.handle('mail:sync-inbox', async () => {
|
|
const account = await readAccount();
|
|
if (!account) throw new Error('Add a mail account before syncing.');
|
|
return fetchMailbox(account, 'Inbox');
|
|
});
|
|
|
|
ipcMain.handle('mail:send', async (_event, message) => {
|
|
const account = await readAccount();
|
|
if (!account) throw new Error('Add a mail account before sending.');
|
|
const to = String(message?.to || '').trim();
|
|
if (!to) throw new Error('Add at least one recipient.');
|
|
const transport = smtpTransport(account);
|
|
const sentMessageId = `<${require('node:crypto').randomUUID()}@ep-mail.local>`;
|
|
const fromName = String(message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
|
const messageOptions = {
|
|
from: { name: fromName, address: account.email },
|
|
to,
|
|
cc: String(message.cc || '').trim() || undefined,
|
|
subject: String(message.subject || '(no subject)').slice(0, 998),
|
|
text: String(message.text || '').slice(0, 500000),
|
|
messageId: sentMessageId
|
|
};
|
|
try {
|
|
await transport.sendMail(messageOptions);
|
|
} finally {
|
|
transport.close();
|
|
}
|
|
let savedToSent = false;
|
|
const copy = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
|
|
try {
|
|
const rendered = await copy.sendMail(messageOptions);
|
|
const client = imapClient(account);
|
|
try {
|
|
await client.connect();
|
|
const sentPath = await findSentMailbox(client, true);
|
|
const lock = await client.getMailboxLock(sentPath);
|
|
try {
|
|
const existing = await client.search({ header: { 'message-id': sentMessageId } }, { uid: true });
|
|
if (!existing.length) await client.append(sentPath, rendered.message, ['\\Seen'], new Date());
|
|
savedToSent = true;
|
|
} finally {
|
|
lock.release();
|
|
}
|
|
} finally {
|
|
if (client.usable) await client.logout().catch(() => {});
|
|
}
|
|
} catch {
|
|
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
|
|
}
|
|
return { ok: true, savedToSent };
|
|
});
|
|
|
|
ipcMain.handle('mail:disconnect', async (_event, accountId) => {
|
|
const store = await readAccountStore();
|
|
if (!store) return { accounts: [], activeId: null };
|
|
if (accountId) {
|
|
store.accounts = store.accounts.filter(account => account.id !== accountId);
|
|
} else {
|
|
store.accounts = [];
|
|
}
|
|
if (!store.accounts.length) await fs.rm(credentialsPath(), { force: true });
|
|
else {
|
|
if (!store.accounts.some(account => account.id === store.activeId)) store.activeId = store.accounts[0].id;
|
|
await saveAccountStore(store);
|
|
}
|
|
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,
|
|
height: 920,
|
|
minWidth: 920,
|
|
minHeight: 680,
|
|
title: 'ep-mail',
|
|
backgroundColor: '#f4f5f1',
|
|
show: false,
|
|
autoHideMenuBar: true,
|
|
icon: path.join(__dirname, '..', 'icon.svg'),
|
|
webPreferences: {
|
|
preload: path.join(__dirname, 'preload.cjs'),
|
|
contextIsolation: true,
|
|
nodeIntegration: false,
|
|
sandbox: true
|
|
}
|
|
});
|
|
|
|
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);
|
|
return { action: 'deny' };
|
|
});
|
|
window.webContents.on('will-navigate', (event, url) => {
|
|
if (!url.startsWith('file:')) event.preventDefault();
|
|
});
|
|
}
|
|
|
|
app.whenReady().then(() => {
|
|
app.setAppUserModelId('studio.daybreak.mail');
|
|
createWindow();
|
|
app.on('activate', () => {
|
|
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
|
});
|
|
});
|
|
|
|
app.on('window-all-closed', () => {
|
|
if (process.platform !== 'darwin') app.quit();
|
|
});
|