66 lines
3.0 KiB
JavaScript
66 lines
3.0 KiB
JavaScript
function createMailReader({
|
|
imapClient,
|
|
folderPath,
|
|
toUiMessage,
|
|
cacheMailboxMessages,
|
|
fetchSnoozedMailbox,
|
|
filterMailboxMessages
|
|
}) {
|
|
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
|
|
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
|
|
const client = await 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 snoozed = new Set((account.snoozedMessages || [])
|
|
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
|
|
.map(item => Number(item.uid)));
|
|
if (Object.values(filters).some(value => value && value !== false)) {
|
|
const searchStart = Math.max(1, mailbox.exists - 4999);
|
|
const fetched = mailbox.exists ? await client.fetchAll(`${searchStart}:${mailbox.exists}`, {
|
|
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
|
}) : [];
|
|
const all = [];
|
|
for (const item of fetched) {
|
|
if (!item.source || snoozed.has(Number(item.uid))) continue;
|
|
const message = await toUiMessage(item, folder);
|
|
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
|
|
all.push(message);
|
|
}
|
|
await cacheMailboxMessages(account.id, folder, all);
|
|
const matches = filterMailboxMessages(all, filters).sort((a, b) => Number(b.timestamp) - Number(a.timestamp));
|
|
const start = Math.max(0, Number(offset) || 0);
|
|
const messages = matches.slice(start, start + Math.max(1, Math.min(50, Number(limit) || 20)));
|
|
return { messages, total: matches.length, start: matches.length ? start + 1 : 0, end: start + messages.length, folder };
|
|
}
|
|
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 || snoozed.has(Number(item.uid))) continue;
|
|
const message = await toUiMessage(item, folder);
|
|
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
|
|
messages.push(message);
|
|
}
|
|
await cacheMailboxMessages(account.id, folder, messages);
|
|
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
|
|
} finally {
|
|
if (client.usable) await client.logout().catch(() => {});
|
|
}
|
|
}
|
|
|
|
return { fetchMailbox };
|
|
}
|
|
|
|
module.exports = { createMailReader };
|