chorus/index.ts

82 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-12-24 14:43:23 +00:00
import { config } from "./src/config.ts";
2024-12-31 02:36:12 +00:00
import {ImapFlow, type MailboxLockObject} from "imapflow";
import { extract } from 'letterparser'
import {ReplyParser} from "./src/mail/replies.ts";
import type {Message} from "./src/types.ts";
import type {Awaitable} from "./src/bones";
import {AsyncCollection} from "./src/bones/collection/AsyncCollection.ts";
import {AsyncGeneratorIterable} from "./src/bones/collection/AsyncGeneratorIterable.ts";
export async function withMessageClient<TReturn>(cb: (c: ImapFlow) => Awaitable<TReturn>): Promise<TReturn> {
const client = new ImapFlow(config.mail.imap)
await client.connect()
try {
return cb(client)
} finally {
await client.logout()
}
}
export async function getFolders(): Promise<string[]> {
return withMessageClient(async client => {
const list = await client.list()
return list.map(l => l.name)
})
}
export const getMessagesForMailbox = (box: string): AsyncCollection<Message> => {
return new AsyncCollection(
new AsyncGeneratorIterable(
() => getMessagesForMailboxOld(box)))
}
export async function* getMessagesForMailboxOld(box: string): AsyncGenerator<Message, void, unknown> {
const client = new ImapFlow(config.mail.imap)
await client.connect()
try {
let lock: MailboxLockObject
try {
lock = await client.getMailboxLock(box)
} catch (e: unknown) {
// This is usually because the mailbox does not exist, so yield nothing
console.warn(`Error when opening mailbox lock for mailbox "${box}":\n`, e)
return
}
try {
await client.mailboxOpen(box)
const messages = client.fetch('1:*', {
envelope: true,
source: true,
uid: true,
bodyParts: ['text'],
})
for await ( const message of messages ) {
const source = message.source.toString('utf-8')
const content = ReplyParser.parseReply(extract(source).text || '')
const msg: Message = {
id: message.envelope.messageId,
date: message.envelope.date,
recipients: message.envelope.to.map(x => x.address || '').filter(Boolean),
from: message.envelope.from[0],
subject: message.envelope.subject,
content,
}
yield msg
}
} finally {
lock.release()
}
} finally {
await client.logout()
}
}
2024-12-24 14:43:23 +00:00
2024-12-31 02:36:12 +00:00
const c = getMessagesForMailbox('e12a')
console.log(await c.all())