48hr.email/domain/mail-repository.js

61 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-11-01 11:48:19 +01:00
const debug = require('debug')('48hr-email:mail-summary-store')
const MultiMap = require('mnemonist/multi-map')
const _ = require('lodash')
2024-10-02 02:36:25 +02:00
const config = require('../application/config')
2023-11-01 11:48:19 +01:00
class MailRepository {
constructor() {
// MultiMap docs: https://yomguithereal.github.io/mnemonist/multi-map
this.mailSummaries = new MultiMap()
2024-10-02 02:36:25 +02:00
this.config = config
2023-11-01 11:48:19 +01:00
}
getForRecipient(address) {
2024-10-02 02:36:25 +02:00
let mails = this.mailSummaries.get(address) || []
mails.forEach(mail => {
2024-10-21 01:52:33 +02:00
if (mail.to == this.config.email.examples.account && !this.config.email.examples.uids.includes(parseInt(mail.uid))) {
2024-10-02 02:36:25 +02:00
mails = mails.filter(m => m.uid != mail.uid)
debug('prevented non-example email from being shown in example inbox', mail.uid)
2024-10-02 02:36:25 +02:00
}
})
2023-11-01 11:48:19 +01:00
return _.orderBy(mails, mail => Date.parse(mail.date), ['desc'])
}
getAll() {
const mails = [...this.mailSummaries.values()]
return _.orderBy(mails, mail => Date.parse(mail.date), ['desc'])
}
add(to, mailSummary) {
2024-12-03 07:57:12 +01:00
if (to !== undefined) {
this.mailSummaries.set(to.toLowerCase(), mailSummary)
} else {
debug('IMAP reported no recipient for mail, ignoring', mailSummary)
}
2023-11-01 11:48:19 +01:00
}
removeUid(uid, address) {
2024-10-21 01:52:33 +02:00
if (!this.config.email.examples.uids.includes(parseInt(uid))) {
var deleted = false
// TODO: make this more efficient, looping through each email is not cool.
this.mailSummaries.forEachAssociation((mails, to) => {
mails
.filter(mail => mail.uid === parseInt(uid) && (address ? to == address : true))
.forEach(mail => {
this.mailSummaries.remove(to, mail)
debug('removed ', mail.date, to, mail.subject)
deleted = true
})
})
return deleted
}
return false
2023-11-01 11:48:19 +01:00
}
mailCount() {
return this.mailSummaries.size
}
}
module.exports = MailRepository