Add Android security Phase 0
This commit is contained in:
+332
-332
@@ -10,47 +10,47 @@ function traceStartup(message) {
|
||||
traceStartup('main process entered');
|
||||
|
||||
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor, Menu, Tray, nativeImage } = require('electron');
|
||||
const fsSync = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const fs = require('node:fs/promises');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
|
||||
let tsdavPromise = null;
|
||||
function getTsdav() {
|
||||
if (!tsdavPromise) tsdavPromise = import('tsdav');
|
||||
return tsdavPromise;
|
||||
}
|
||||
|
||||
let icalPromise = null;
|
||||
function getICAL() {
|
||||
if (!icalPromise) icalPromise = import('ical.js');
|
||||
return icalPromise;
|
||||
}
|
||||
|
||||
let openpgpPromise = null;
|
||||
function getOpenPGP() {
|
||||
if (!openpgpPromise) openpgpPromise = import('openpgp');
|
||||
return openpgpPromise;
|
||||
}
|
||||
|
||||
let imapFlowPromise = null;
|
||||
function getImapFlow() {
|
||||
if (!imapFlowPromise) imapFlowPromise = import('imapflow');
|
||||
return imapFlowPromise;
|
||||
}
|
||||
|
||||
let nodemailerPromise = null;
|
||||
function getNodemailer() {
|
||||
if (!nodemailerPromise) nodemailerPromise = import('nodemailer');
|
||||
return nodemailerPromise;
|
||||
}
|
||||
|
||||
let mailparserPromise = null;
|
||||
function getMailparser() {
|
||||
if (!mailparserPromise) mailparserPromise = import('mailparser');
|
||||
return mailparserPromise;
|
||||
}
|
||||
|
||||
const fsSync = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const fs = require('node:fs/promises');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
|
||||
let tsdavPromise = null;
|
||||
function getTsdav() {
|
||||
if (!tsdavPromise) tsdavPromise = import('tsdav');
|
||||
return tsdavPromise;
|
||||
}
|
||||
|
||||
let icalPromise = null;
|
||||
function getICAL() {
|
||||
if (!icalPromise) icalPromise = import('ical.js');
|
||||
return icalPromise;
|
||||
}
|
||||
|
||||
let openpgpPromise = null;
|
||||
function getOpenPGP() {
|
||||
if (!openpgpPromise) openpgpPromise = import('openpgp');
|
||||
return openpgpPromise;
|
||||
}
|
||||
|
||||
let imapFlowPromise = null;
|
||||
function getImapFlow() {
|
||||
if (!imapFlowPromise) imapFlowPromise = import('imapflow');
|
||||
return imapFlowPromise;
|
||||
}
|
||||
|
||||
let nodemailerPromise = null;
|
||||
function getNodemailer() {
|
||||
if (!nodemailerPromise) nodemailerPromise = import('nodemailer');
|
||||
return nodemailerPromise;
|
||||
}
|
||||
|
||||
let mailparserPromise = null;
|
||||
function getMailparser() {
|
||||
if (!mailparserPromise) mailparserPromise = import('mailparser');
|
||||
return mailparserPromise;
|
||||
}
|
||||
|
||||
const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs');
|
||||
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs');
|
||||
const {
|
||||
@@ -109,11 +109,11 @@ const pgpJsonStore = createSecureJsonStore({
|
||||
assertSecureStorage,
|
||||
unavailableMessage: 'Secure key storage is unavailable.'
|
||||
});
|
||||
const backgroundSyncIntervalMs = 30 * 1000;
|
||||
const backgroundRetryIntervalMs = 2 * 60 * 1000;
|
||||
const backgroundSyncConcurrency = 2;
|
||||
const backgroundIdleConcurrency = 2;
|
||||
const snoozeCheckIntervalMs = 30 * 1000;
|
||||
const backgroundSyncIntervalMs = 30 * 1000;
|
||||
const backgroundRetryIntervalMs = 2 * 60 * 1000;
|
||||
const backgroundSyncConcurrency = 2;
|
||||
const backgroundIdleConcurrency = 2;
|
||||
const snoozeCheckIntervalMs = 30 * 1000;
|
||||
const windowsAppUserModelId = 'studio.daybreak.mail';
|
||||
const applicationHtmlPath = path.join(__dirname, '..', 'index.html');
|
||||
const ipcMainHandle = ipcMain.handle.bind(ipcMain);
|
||||
@@ -122,7 +122,7 @@ const backgroundSyncGenerations = new Map();
|
||||
const backgroundSyncFailures = new Map();
|
||||
const flagSnapshots = new Map();
|
||||
const lastBackgroundSyncAt = new Map();
|
||||
let windowsAppIcon = null;
|
||||
let windowsAppIcon = null;
|
||||
let tray = null;
|
||||
|
||||
function registerIpcHandler(channel, handler) {
|
||||
@@ -140,16 +140,16 @@ function registerIpcHandler(channel, handler) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function updateAccountStore(update) {
|
||||
const operation = accountStoreQueue.then(async () => {
|
||||
const store = (await readAccountStore()) || { accounts: [], activeId: null };
|
||||
const result = await update(store);
|
||||
if (store.accounts.length) await saveAccountStore(store);
|
||||
else await fs.rm(credentialsPath(), { force: true });
|
||||
return result;
|
||||
});
|
||||
accountStoreQueue = operation.catch(() => {});
|
||||
const operation = accountStoreQueue.then(async () => {
|
||||
const store = (await readAccountStore()) || { accounts: [], activeId: null };
|
||||
const result = await update(store);
|
||||
if (store.accounts.length) await saveAccountStore(store);
|
||||
else await fs.rm(credentialsPath(), { force: true });
|
||||
return result;
|
||||
});
|
||||
accountStoreQueue = operation.catch(() => {});
|
||||
return operation;
|
||||
}
|
||||
|
||||
@@ -175,13 +175,13 @@ async function authorizeOAuthAccount(account) {
|
||||
function listOAuthProviders() {
|
||||
return oauth2Service.listProviders();
|
||||
}
|
||||
|
||||
|
||||
function sendMailSyncUpdate(update) {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed() && !window.webContents.isDestroyed()) {
|
||||
window.webContents.send('mail:sync-update', update);
|
||||
}
|
||||
}
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed() && !window.webContents.isDestroyed()) {
|
||||
window.webContents.send('mail:sync-update', update);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { checkSnoozeReminders } = createSnoozeReminderService({
|
||||
@@ -197,10 +197,10 @@ const { checkSnoozeReminders } = createSnoozeReminderService({
|
||||
},
|
||||
sendMailSyncUpdate
|
||||
});
|
||||
|
||||
|
||||
const { createKeyStore } = require('./pgp-keystore.cjs');
|
||||
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
|
||||
|
||||
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
|
||||
|
||||
const pgpKeys = createKeyStore({
|
||||
async load() {
|
||||
try {
|
||||
@@ -212,59 +212,59 @@ const pgpKeys = createKeyStore({
|
||||
},
|
||||
save(data) { return pgpJsonStore.save(data); }
|
||||
});
|
||||
|
||||
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
|
||||
|
||||
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
|
||||
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
|
||||
const pgpKeyServers = createKeyServerService();
|
||||
const { findSpecialMailbox, findSentMailbox, listCustomFolders, folderPath } = createFolderService({
|
||||
customFolderPrefix: CUSTOM_FOLDER_PREFIX,
|
||||
isReservedFolderName
|
||||
});
|
||||
|
||||
|
||||
async function readDavStore() {
|
||||
try {
|
||||
return await davJsonStore.load();
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveDavStore(store) {
|
||||
return davJsonStore.save(store);
|
||||
}
|
||||
|
||||
function davPublicConfig(config) {
|
||||
return { id: config.id, serverUrl: config.serverUrl, username: config.username, collections: config.collections || [] };
|
||||
}
|
||||
|
||||
async function openDavClient(config, type) {
|
||||
const { createDAVClient } = await getTsdav();
|
||||
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 davPublicConfig(config) {
|
||||
return { id: config.id, serverUrl: config.serverUrl, username: config.username, collections: config.collections || [] };
|
||||
}
|
||||
|
||||
async function openDavClient(config, type) {
|
||||
const { createDAVClient } = await getTsdav();
|
||||
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;
|
||||
}
|
||||
|
||||
const { imapClient, smtpTransport } = createMailConnections({
|
||||
getImapFlow,
|
||||
getNodemailer,
|
||||
oauthTokenManager
|
||||
});
|
||||
|
||||
function assertSecureStorage() {
|
||||
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
|
||||
const backend = safeStorage.getSelectedStorageBackend();
|
||||
if (backend === 'basic_text') {
|
||||
throw new Error('This Linux session is using the insecure basic_text password backend. Configure a secure secret store such as gnome-libsecret or kwallet before saving mail credentials or OpenPGP keys.');
|
||||
}
|
||||
}
|
||||
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
|
||||
}
|
||||
|
||||
|
||||
function assertSecureStorage() {
|
||||
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
|
||||
const backend = safeStorage.getSelectedStorageBackend();
|
||||
if (backend === 'basic_text') {
|
||||
throw new Error('This Linux session is using the insecure basic_text password backend. Configure a secure secret store such as gnome-libsecret or kwallet before saving mail credentials or OpenPGP keys.');
|
||||
}
|
||||
}
|
||||
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
|
||||
}
|
||||
|
||||
async function readAccountStore() {
|
||||
return accountRepository.load();
|
||||
}
|
||||
@@ -272,135 +272,135 @@ async function readAccountStore() {
|
||||
async function saveAccountStore(store) {
|
||||
return accountRepository.save(store);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
async function saveAccount(account) {
|
||||
return updateAccountStore(store => {
|
||||
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
|
||||
const saved = { ...existing, ...account, id: existing?.id || randomUUID() };
|
||||
store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved];
|
||||
store.activeId = saved.id;
|
||||
return saved;
|
||||
});
|
||||
}
|
||||
|
||||
return updateAccountStore(store => {
|
||||
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
|
||||
const saved = { ...existing, ...account, id: existing?.id || randomUUID() };
|
||||
store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved];
|
||||
store.activeId = saved.id;
|
||||
return saved;
|
||||
});
|
||||
}
|
||||
|
||||
async function connectMail(account) {
|
||||
const client = await imapClient(account);
|
||||
let transport;
|
||||
try {
|
||||
await client.connect();
|
||||
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
|
||||
let transport;
|
||||
try {
|
||||
await client.connect();
|
||||
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
|
||||
transport = await smtpTransport(account);
|
||||
await transport.verify();
|
||||
return { mailbox: mailbox.name, messages: mailbox.exists };
|
||||
} finally {
|
||||
if (transport) transport.close();
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
await transport.verify();
|
||||
return { mailbox: mailbox.name, messages: mailbox.exists };
|
||||
} finally {
|
||||
if (transport) transport.close();
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async function cacheMailboxMessages(accountId, folder, messages) {
|
||||
if (!messages.length) return;
|
||||
await updateAccountStore(store => {
|
||||
const account = store.accounts.find(item => item.id === accountId);
|
||||
if (!account) return;
|
||||
account.mailCache = account.mailCache || {};
|
||||
const previous = account.mailCache[folder] || [];
|
||||
const merged = new Map(previous.map(message => [String(message.uid || message.id), message]));
|
||||
for (const message of messages) merged.set(String(message.uid || message.id), message);
|
||||
account.mailCache[folder] = [...merged.values()].slice(-50);
|
||||
});
|
||||
}
|
||||
|
||||
function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
|
||||
const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters)
|
||||
.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
|
||||
const start = Math.max(0, Number(offset) || 0);
|
||||
const messages = all.slice(start, start + limit);
|
||||
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
|
||||
}
|
||||
|
||||
if (!messages.length) return;
|
||||
await updateAccountStore(store => {
|
||||
const account = store.accounts.find(item => item.id === accountId);
|
||||
if (!account) return;
|
||||
account.mailCache = account.mailCache || {};
|
||||
const previous = account.mailCache[folder] || [];
|
||||
const merged = new Map(previous.map(message => [String(message.uid || message.id), message]));
|
||||
for (const message of messages) merged.set(String(message.uid || message.id), message);
|
||||
account.mailCache[folder] = [...merged.values()].slice(-50);
|
||||
});
|
||||
}
|
||||
|
||||
function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
|
||||
const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters)
|
||||
.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
|
||||
const start = Math.max(0, Number(offset) || 0);
|
||||
const messages = all.slice(start, start + limit);
|
||||
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
|
||||
}
|
||||
|
||||
async function toUiMessage(item, folder) {
|
||||
const { simpleParser } = await getMailparser();
|
||||
const parsed = await simpleParser(item.source);
|
||||
const sender = parsed.from?.value?.[0];
|
||||
const pgpKind = pgpMail.detect(parsed);
|
||||
const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
|
||||
const content = encrypted
|
||||
? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' }
|
||||
const parsed = await simpleParser(item.source);
|
||||
const sender = parsed.from?.value?.[0];
|
||||
const pgpKind = pgpMail.detect(parsed);
|
||||
const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
|
||||
const content = encrypted
|
||||
? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' }
|
||||
: extractMailContent(parsed);
|
||||
const { bodyText, body, links } = content;
|
||||
const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null;
|
||||
const date = parsed.date || item.internalDate || new Date();
|
||||
return {
|
||||
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: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
||||
encrypted,
|
||||
pgpSignatures,
|
||||
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
|
||||
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
|
||||
timestamp: date.getTime(),
|
||||
unread: !item.flags?.has('\\Seen'),
|
||||
star: item.flags?.has('\\Flagged') || false,
|
||||
tags: [folder],
|
||||
sent: folder === 'Sent',
|
||||
archived: folder === 'Archive',
|
||||
deleted: folder === 'Trash',
|
||||
sourceFolder: folder,
|
||||
body,
|
||||
html: content.html,
|
||||
links,
|
||||
uid: Number(item.uid),
|
||||
attachments: content.attachments,
|
||||
attachment: content.attachment,
|
||||
size: content.size
|
||||
};
|
||||
}
|
||||
|
||||
const { bodyText, body, links } = content;
|
||||
const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null;
|
||||
const date = parsed.date || item.internalDate || new Date();
|
||||
return {
|
||||
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: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
||||
encrypted,
|
||||
pgpSignatures,
|
||||
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
|
||||
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
|
||||
timestamp: date.getTime(),
|
||||
unread: !item.flags?.has('\\Seen'),
|
||||
star: item.flags?.has('\\Flagged') || false,
|
||||
tags: [folder],
|
||||
sent: folder === 'Sent',
|
||||
archived: folder === 'Archive',
|
||||
deleted: folder === 'Trash',
|
||||
sourceFolder: folder,
|
||||
body,
|
||||
html: content.html,
|
||||
links,
|
||||
uid: Number(item.uid),
|
||||
attachments: content.attachments,
|
||||
attachment: content.attachment,
|
||||
size: content.size
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchSnoozedMailbox(account, offset, limit) {
|
||||
const now = Date.now();
|
||||
const pending = (account.snoozedMessages || [])
|
||||
.filter(item => Number(item.dueAt) > now)
|
||||
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
|
||||
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
|
||||
const now = Date.now();
|
||||
const pending = (account.snoozedMessages || [])
|
||||
.filter(item => Number(item.dueAt) > now)
|
||||
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
|
||||
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
|
||||
const client = await imapClient(account);
|
||||
const messages = [];
|
||||
try {
|
||||
await client.connect();
|
||||
for (const snooze of selected) {
|
||||
const sourceFolder = String(snooze.folder || 'Inbox');
|
||||
const mailboxPath = await folderPath(client, sourceFolder);
|
||||
if (!mailboxPath) continue;
|
||||
const lock = await client.getMailboxLock(mailboxPath);
|
||||
try {
|
||||
const item = await client.fetchOne(Number(snooze.uid), {
|
||||
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
||||
}, { uid: true });
|
||||
if (!item?.source) continue;
|
||||
const message = await toUiMessage(item, 'Snoozed');
|
||||
message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || []));
|
||||
messages.push({
|
||||
...message,
|
||||
sourceFolder,
|
||||
snoozedUntil: Number(snooze.dueAt)
|
||||
});
|
||||
} finally {
|
||||
lock.release();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
const messages = [];
|
||||
try {
|
||||
await client.connect();
|
||||
for (const snooze of selected) {
|
||||
const sourceFolder = String(snooze.folder || 'Inbox');
|
||||
const mailboxPath = await folderPath(client, sourceFolder);
|
||||
if (!mailboxPath) continue;
|
||||
const lock = await client.getMailboxLock(mailboxPath);
|
||||
try {
|
||||
const item = await client.fetchOne(Number(snooze.uid), {
|
||||
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
||||
}, { uid: true });
|
||||
if (!item?.source) continue;
|
||||
const message = await toUiMessage(item, 'Snoozed');
|
||||
message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || []));
|
||||
messages.push({
|
||||
...message,
|
||||
sourceFolder,
|
||||
snoozedUntil: Number(snooze.dueAt)
|
||||
});
|
||||
} finally {
|
||||
lock.release();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
|
||||
}
|
||||
|
||||
@@ -420,28 +420,28 @@ const { applyMessageAction } = createMessageActionService({
|
||||
});
|
||||
|
||||
async function saveAccountSyncState(accountId, generation, folders) {
|
||||
return updateAccountStore(store => {
|
||||
const account = store.accounts.find(item => item.id === accountId);
|
||||
if (!account || backgroundSyncGenerations.get(accountId) !== generation) return false;
|
||||
account.syncState = account.syncState || { folders: {} };
|
||||
account.syncState.folders = folders;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
return updateAccountStore(store => {
|
||||
const account = store.accounts.find(item => item.id === accountId);
|
||||
if (!account || backgroundSyncGenerations.get(accountId) !== generation) return false;
|
||||
account.syncState = account.syncState || { folders: {} };
|
||||
account.syncState.folders = folders;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function showNewMailNotification(account, count) {
|
||||
if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return;
|
||||
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
|
||||
if (focused) return;
|
||||
const notification = new Notification({
|
||||
title: count === 1 ? 'New mail' : `${count} new messages`,
|
||||
body: account.email
|
||||
});
|
||||
notification.show();
|
||||
}
|
||||
|
||||
if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return;
|
||||
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
|
||||
if (focused) return;
|
||||
const notification = new Notification({
|
||||
title: count === 1 ? 'New mail' : `${count} new messages`,
|
||||
body: account.email
|
||||
});
|
||||
notification.show();
|
||||
}
|
||||
|
||||
registerIpcHandler('app:get-version', () => app.getVersion());
|
||||
|
||||
|
||||
registerPgpIpcHandlers({
|
||||
registerIpcHandler,
|
||||
BrowserWindow,
|
||||
@@ -561,23 +561,23 @@ traceStartup('main services and IPC handlers initialized');
|
||||
function createWindow() {
|
||||
traceStartup('creating BrowserWindow');
|
||||
const window = new BrowserWindow({
|
||||
width: 1440,
|
||||
height: 920,
|
||||
minWidth: 920,
|
||||
minHeight: 680,
|
||||
title: `ep-mail v${app.getVersion()}`,
|
||||
backgroundColor: '#f4f5f1',
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
icon: windowsAppIcon || path.join(__dirname, '..', 'icon.svg'),
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.cjs'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true
|
||||
}
|
||||
});
|
||||
|
||||
width: 1440,
|
||||
height: 920,
|
||||
minWidth: 920,
|
||||
minHeight: 680,
|
||||
title: `ep-mail v${app.getVersion()}`,
|
||||
backgroundColor: '#f4f5f1',
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
icon: windowsAppIcon || path.join(__dirname, '..', 'icon.svg'),
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.cjs'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true
|
||||
}
|
||||
});
|
||||
|
||||
window.webContents.on('dom-ready', () => traceStartup('renderer DOM ready'));
|
||||
window.webContents.on('did-finish-load', () => traceStartup('renderer load complete'));
|
||||
window.once('ready-to-show', () => {
|
||||
@@ -595,70 +595,70 @@ function createWindow() {
|
||||
window.webContents.on('will-navigate', (event, url) => {
|
||||
if (!isTrustedApplicationUrl(url, applicationHtmlPath)) event.preventDefault();
|
||||
});
|
||||
return window;
|
||||
}
|
||||
|
||||
function showMainWindow() {
|
||||
let window = BrowserWindow.getAllWindows().find(item => !item.isDestroyed());
|
||||
if (!window) {
|
||||
window = createWindow();
|
||||
} else {
|
||||
if (window.isMinimized()) window.restore();
|
||||
window.show();
|
||||
window.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function createWindowsTray() {
|
||||
tray = new Tray(windowsAppIcon.resize({ width: 16, height: 16 }));
|
||||
tray.setToolTip('ep-mail');
|
||||
tray.setContextMenu(Menu.buildFromTemplate([
|
||||
{ label: 'Open ep-mail', click: showMainWindow },
|
||||
{ type: 'separator' },
|
||||
{ label: 'Quit ep-mail', click: () => app.quit() }
|
||||
]));
|
||||
tray.on('click', showMainWindow);
|
||||
tray.on('double-click', showMainWindow);
|
||||
}
|
||||
|
||||
function repairWindowsStartMenuShortcut() {
|
||||
if (!app.isPackaged) return;
|
||||
|
||||
const shortcutPath = path.join(
|
||||
app.getPath('appData'),
|
||||
'Microsoft',
|
||||
'Windows',
|
||||
'Start Menu',
|
||||
'Programs',
|
||||
'ep-mail.lnk'
|
||||
);
|
||||
if (!fsSync.existsSync(shortcutPath)) return;
|
||||
|
||||
try {
|
||||
const shortcut = shell.readShortcutLink(shortcutPath);
|
||||
const isEpMailShortcut = path.basename(shortcut.target).toLowerCase() === 'ep-mail.exe'
|
||||
|| shortcut.appUserModelId === windowsAppUserModelId;
|
||||
if (!isEpMailShortcut) return;
|
||||
if (shortcut.appUserModelId && shortcut.appUserModelId !== windowsAppUserModelId) return;
|
||||
|
||||
const portableExecutable = process.env.PORTABLE_EXECUTABLE_FILE;
|
||||
const executable = portableExecutable && fsSync.existsSync(portableExecutable)
|
||||
? portableExecutable
|
||||
: process.execPath;
|
||||
const updated = shell.writeShortcutLink(shortcutPath, 'update', {
|
||||
...shortcut,
|
||||
target: executable,
|
||||
cwd: path.dirname(executable),
|
||||
icon: executable,
|
||||
iconIndex: 0,
|
||||
appUserModelId: windowsAppUserModelId
|
||||
});
|
||||
if (!updated) throw new Error('Windows did not update the shortcut.');
|
||||
} catch (error) {
|
||||
console.error('Could not repair the ep-mail Start Menu shortcut:', error);
|
||||
}
|
||||
}
|
||||
|
||||
return window;
|
||||
}
|
||||
|
||||
function showMainWindow() {
|
||||
let window = BrowserWindow.getAllWindows().find(item => !item.isDestroyed());
|
||||
if (!window) {
|
||||
window = createWindow();
|
||||
} else {
|
||||
if (window.isMinimized()) window.restore();
|
||||
window.show();
|
||||
window.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function createWindowsTray() {
|
||||
tray = new Tray(windowsAppIcon.resize({ width: 16, height: 16 }));
|
||||
tray.setToolTip('ep-mail');
|
||||
tray.setContextMenu(Menu.buildFromTemplate([
|
||||
{ label: 'Open ep-mail', click: showMainWindow },
|
||||
{ type: 'separator' },
|
||||
{ label: 'Quit ep-mail', click: () => app.quit() }
|
||||
]));
|
||||
tray.on('click', showMainWindow);
|
||||
tray.on('double-click', showMainWindow);
|
||||
}
|
||||
|
||||
function repairWindowsStartMenuShortcut() {
|
||||
if (!app.isPackaged) return;
|
||||
|
||||
const shortcutPath = path.join(
|
||||
app.getPath('appData'),
|
||||
'Microsoft',
|
||||
'Windows',
|
||||
'Start Menu',
|
||||
'Programs',
|
||||
'ep-mail.lnk'
|
||||
);
|
||||
if (!fsSync.existsSync(shortcutPath)) return;
|
||||
|
||||
try {
|
||||
const shortcut = shell.readShortcutLink(shortcutPath);
|
||||
const isEpMailShortcut = path.basename(shortcut.target).toLowerCase() === 'ep-mail.exe'
|
||||
|| shortcut.appUserModelId === windowsAppUserModelId;
|
||||
if (!isEpMailShortcut) return;
|
||||
if (shortcut.appUserModelId && shortcut.appUserModelId !== windowsAppUserModelId) return;
|
||||
|
||||
const portableExecutable = process.env.PORTABLE_EXECUTABLE_FILE;
|
||||
const executable = portableExecutable && fsSync.existsSync(portableExecutable)
|
||||
? portableExecutable
|
||||
: process.execPath;
|
||||
const updated = shell.writeShortcutLink(shortcutPath, 'update', {
|
||||
...shortcut,
|
||||
target: executable,
|
||||
cwd: path.dirname(executable),
|
||||
icon: executable,
|
||||
iconIndex: 0,
|
||||
appUserModelId: windowsAppUserModelId
|
||||
});
|
||||
if (!updated) throw new Error('Windows did not update the shortcut.');
|
||||
} catch (error) {
|
||||
console.error('Could not repair the ep-mail Start Menu shortcut:', error);
|
||||
}
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
traceStartup('Electron app.whenReady');
|
||||
app.setAppUserModelId(windowsAppUserModelId);
|
||||
@@ -685,17 +685,17 @@ app.whenReady().then(() => {
|
||||
snoozeTimer.unref();
|
||||
powerMonitor.on('suspend', () => {
|
||||
idleWatcherManager.stopAll();
|
||||
});
|
||||
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
||||
});
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') app.quit();
|
||||
});
|
||||
|
||||
});
|
||||
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
||||
});
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') app.quit();
|
||||
});
|
||||
|
||||
app.on('before-quit', () => {
|
||||
idleWatcherManager.stopAll();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user