Compare commits

..

No commits in common. "7d956f7d8914a49505298abd03e1d8825754a3ad" and "f42fbd4e74f58eef1b81c3c3b6f6616d89e8bb51" have entirely different histories.

6 changed files with 236 additions and 226 deletions

13
app.js
View file

@ -1,5 +1,4 @@
#!/usr/bin/env node
/* eslint unicorn/no-process-exit: 0 */
const config = require('./application/config')
@ -7,7 +6,7 @@ const config = require('./application/config')
// Until node 11 adds flatmap, we use this:
require('array.prototype.flatmap').shim()
const { app, io, server } = require('./infrastructure/web/web')
const {app, io, server} = require('./infrastructure/web/web')
const ClientNotification = require('./infrastructure/web/client-notification')
const ImapService = require('./application/imap-service')
const MailProcessingService = require('./application/mail-processing-service')
@ -36,25 +35,25 @@ imapService.on(ImapService.EVENT_DELETED_MAIL, mail =>
)
mailProcessingService.on('error', err => {
console.error('Error from mailProcessingService, stopping.', err)
console.error('error from mailProcessingService, stopping.', err)
process.exit(1)
})
imapService.on(ImapService.EVENT_ERROR, error => {
console.error('Fatal error from IMAP service', error)
console.error('fatal error from imap service', error)
process.exit(1)
})
app.set('mailProcessingService', mailProcessingService)
imapService.connectAndLoadMessages().catch(error => {
console.error('Fatal error from IMAP service', error)
console.error('fatal error from imap service', error)
process.exit(1)
})
server.on('error', error => {
if (error.syscall !== 'listen') {
console.error('Fatal web server error', error)
console.error('fatal web server error', error)
return
}
@ -69,7 +68,7 @@ server.on('error', error => {
console.error('Port ' + config.http.port + ' is already in use')
process.exit(1)
default:
console.error('Fatal web server error', error)
console.error('fatal web server error', error)
process.exit(1)
}
})

View file

@ -127,18 +127,21 @@ class ImapService extends EventEmitter {
this.connection.on('error', err => {
// We assume that the app will be restarted after a crash.
console.error('Got fatal error during imap operation, stop app.', err)
console.error(
'got fatal error during imap operation, stop app.',
err
)
this.emit('error', err)
})
await this.connection.openBox('INBOX')
debug('Connected to imap')
debug('connected to imap')
}, {
retries: 5
}
)
} catch (error) {
console.error('Cant connect, even after retrying, stopping app', error)
console.error('can not connect, even with retry, stop app', error)
throw error
}
}
@ -199,11 +202,13 @@ class ImapService extends EventEmitter {
let uids = []
//fetch mails from date +1day (calculated in MS) to avoid wasting resources and to fix imaps missing time-awareness
if (helper.moreThanOneDay(moment(), deleteMailsBefore)) {
console.log("Deleting mails older than one day");
uids = await this._searchWithoutFetch([
['!DELETED'],
['BEFORE', deleteMailsBefore]
])
} else {
console.log("Deleting mails without date filter");
uids = await this._searchWithoutFetch([
['!DELETED'],
])
@ -215,15 +220,18 @@ class ImapService extends EventEmitter {
const DeleteOlderThan = helper.purgeTimeStamp()
const uidsWithHeaders = await this._getMailHeaders(uids)
console.log(`Fetched ${uidsWithHeaders.length} mails for deletion check.`);
uidsWithHeaders.forEach(mail => {
if (mail['attributes'].date > DeleteOlderThan || this.config.email.examples.uids.includes(parseInt(mail['attributes'].uid))) {
uids = uids.filter(uid => uid !== mail['attributes'].uid)
console.log(mail['attributes'].date > DeleteOlderThan ? `Mail UID: ${mail['attributes'].uid} is newer than purge time.` : `Mail UID: ${mail['attributes'].uid} is an example mail.`);
}
})
if (uids.length === 0) {
debug('No mails to delete.')
console.log("Length 0")
debug('no mails to delete.')
return
}
@ -231,8 +239,9 @@ class ImapService extends EventEmitter {
await this.connection.deleteMessage(uids)
uids.forEach(uid => {
this.emit(ImapService.EVENT_DELETED_MAIL, uid)
console.log(`UID deleted: ${uid}`);
})
console.log(`Deleted ${uids.length} old messages.`)
console.log(`deleted ${uids.length} old messages.`)
}
/**
@ -240,10 +249,10 @@ class ImapService extends EventEmitter {
* @param uid delete specific mail per UID
*/
async deleteSpecificEmail(uid) {
debug(`Deleting mails ${uid}`)
debug(`deleting mails ${uid}`)
if (!this.config.email.examples.uids.includes(parseInt(uid))) {
await this.connection.deleteMessage(uid)
debug(`Deleted mail with UID: ${uid}.`)
console.log(`deleted mail with UID: ${uid}.`)
this.emit(ImapService.EVENT_DELETED_MAIL, uid)
}
}
@ -294,10 +303,10 @@ class ImapService extends EventEmitter {
async fetchOneFullMail(to, uid, raw = false) {
if (!this.connection) {
// Here we 'fail fast' instead of waiting for the connection.
throw new Error('IMAP connection not ready')
throw new Error('imap connection not ready')
}
debug(`Fetching full message ${uid}`)
debug(`fetching full message ${uid}`)
// For security we also filter TO, so it is harder to just enumerate all messages.
const searchCriteria = [
@ -341,7 +350,7 @@ class ImapService extends EventEmitter {
}
})
} catch (error) {
debug('Cant fetch', error)
debug('can not fetch', error)
throw error
}
}

View file

@ -1,9 +1,9 @@
const EventEmitter = require('events')
const debug = require('debug')('48hr-email:imap-manager')
const mem = require('mem')
const moment = require('moment')
const ImapService = require('./imap-service')
const Helper = require('./helper')
const config = require('./config')
const helper = new(Helper)
@ -26,12 +26,9 @@ class MailProcessingService extends EventEmitter {
this.imapService.once(ImapService.EVENT_INITIAL_LOAD_DONE, () =>
this._deleteOldMails()
)
console.log(`Fetching and deleting mails every ${this.config.imap.refreshIntervalSeconds} seconds`)
setInterval(() => {
this._deleteOldMails()
}, this.config.imap.refreshIntervalSeconds * 1000)
}, 60 * 1000)
}
getMailSummaries(address) {
@ -54,13 +51,15 @@ class MailProcessingService extends EventEmitter {
onInitialLoadDone() {
this.initialLoadDone = true
console.log(`Initial load done, got ${this.mailRepository.mailCount()} mails`)
console.log(
`initial load done, got ${this.mailRepository.mailCount()} mails`
)
}
onNewMail(mail) {
if (this.initialLoadDone) {
// For now, only log messages if they arrive after the initial load
debug('New mail for', mail.to[0])
debug('new mail for', mail.to[0])
}
mail.to.forEach(to => {
@ -70,7 +69,7 @@ class MailProcessingService extends EventEmitter {
}
onMailDeleted(uid) {
debug('Mail deleted with uid', uid)
debug('mail deleted with uid', uid)
this.mailRepository.removeUid(uid)
}
@ -78,7 +77,7 @@ class MailProcessingService extends EventEmitter {
try {
await this.imapService.deleteOldMails(helper.purgeTimeStamp())
} catch (error) {
console.log('Cant delete old messages', error)
console.log('can not delete old messages', error)
}
}
@ -86,7 +85,7 @@ class MailProcessingService extends EventEmitter {
const fs = require('fs')
fs.writeFile(filename, JSON.stringify(mails), err => {
if (err) {
console.error('Cant save mails to file', err)
console.error('can not save mails to file', err)
}
})
}

View file

@ -15,7 +15,7 @@ class MailRepository {
mails.forEach(mail => {
if (mail.to == this.config.email.examples.account && !this.config.email.examples.uids.includes(parseInt(mail.uid))) {
mails = mails.filter(m => m.uid != mail.uid)
debug('Prevented non-example email from being shown in example inbox', mail.uid)
console.log('prevented non-example email from being shown in example inbox', mail.uid)
}
})
return _.orderBy(mails, mail => Date.parse(mail.date), ['desc'])
@ -43,7 +43,7 @@ class MailRepository {
.filter(mail => mail.uid === parseInt(uid) && (address ? to == address : true))
.forEach(mail => {
this.mailSummaries.remove(to, mail)
debug('Removed ', mail.date, to, mail.subject)
debug('removed ', mail.date, to, mail.subject)
deleted = true
})
})

View file

@ -1,6 +1,6 @@
const express = require('express')
const router = new express.Router()
const { param } = require('express-validator')
const {param} = require('express-validator')
const config = require('../../../application/config')
const Helper = require('../../../application/helper')
@ -9,7 +9,7 @@ const helper = new(Helper)
const purgeTime = helper.purgeTimeElemetBuilder()
const sanitizeAddress = param('address').customSanitizer(
(value, { req }) => {
(value, {req}) => {
return req.params.address
.replace(/[^A-Za-z0-9_.+@-]/g, '') // Remove special characters
.toLowerCase()
@ -30,7 +30,7 @@ router.get('^/:address([^@/]+@[^@/]+)', sanitizeAddress, (req, res, _next) => {
router.get(
'^/:address/:uid([0-9]+)',
sanitizeAddress,
async(req, res, next) => {
async (req, res, next) => {
try {
const mailProcessingService = req.app.get('mailProcessingService')
const mail = await mailProcessingService.getOneFullMail(
@ -55,7 +55,8 @@ router.get(
})
} else {
res.render(
'error', {
'error',
{
purgeTime: purgeTime,
address: req.params.address,
message: 'This mail could not be found. It either does not exist or has been deleted from our servers!',
@ -65,7 +66,7 @@ router.get(
)
}
} catch (error) {
console.error('Error while fetching email', error)
console.error('error while fetching one email', error)
next(error)
}
}
@ -74,7 +75,7 @@ router.get(
router.get(
'^/:address/delete-all',
sanitizeAddress,
async(req, res, next) => {
async (req, res, next) => {
try {
const mailProcessingService = req.app.get('mailProcessingService')
const mailSummaries = await mailProcessingService.getMailSummaries(req.params.address)
@ -83,7 +84,7 @@ router.get(
}
res.redirect(`/inbox/${req.params.address}`)
} catch (error) {
console.error('Error while deleting email', error)
console.error('error while deleting email', error)
next(error)
}
}
@ -93,13 +94,13 @@ router.get(
router.get(
'^/:address/:uid/delete',
sanitizeAddress,
async(req, res, next) => {
async (req, res, next) => {
try {
const mailProcessingService = req.app.get('mailProcessingService')
await mailProcessingService.deleteSpecificEmail(req.params.address, req.params.uid)
res.redirect(`/inbox/${req.params.address}`)
} catch (error) {
console.error('Error while deleting email', error)
console.error('error while deleting email', error)
next(error)
}
}
@ -108,7 +109,7 @@ router.get(
router.get(
'^/:address/:uid/:checksum([a-f0-9]+)',
sanitizeAddress,
async(req, res, next) => {
async (req, res, next) => {
try {
const mailProcessingService = req.app.get('mailProcessingService')
const mail = await mailProcessingService.getOneFullMail(
@ -124,12 +125,13 @@ router.get(
res.send(attachment.content);
return;
} catch (error) {
console.error('Error while fetching attachment', error);
console.error('error while fetching attachment', error);
next(error);
}
} else {
res.render(
'error', {
'error',
{
purgeTime: purgeTime,
address: req.params.address,
message: 'This attachment could not be found. It either does not exist or has been deleted from our servers!',
@ -139,7 +141,7 @@ router.get(
}
res.redirect(`/inbox/${req.params.address}`)
} catch (error) {
console.error('Error while deleting email', error)
console.error('error while deleting email', error)
next(error)
}
}
@ -150,7 +152,7 @@ router.get(
router.get(
'^/:address/:uid/raw',
sanitizeAddress,
async(req, res, next) => {
async (req, res, next) => {
try {
const mailProcessingService = req.app.get('mailProcessingService')
mail = await mailProcessingService.getOneFullMail(
@ -168,7 +170,8 @@ router.get(
})
} else {
res.render(
'error', {
'error',
{
purgeTime: purgeTime,
address: req.params.address,
message: 'This mail could not be found. It either does not exist or has been deleted from our servers!',
@ -177,7 +180,7 @@ router.get(
)
}
} catch (error) {
console.error('Error while fetching raw email', error)
console.error('error while fetching one email', error)
next(error)
}
}

View file

@ -11,7 +11,7 @@ const socketio = require('socket.io')
const config = require('../../application/config')
const inboxRouter = require('./routes/inbox')
const loginRouter = require('./routes/login')
const { sanitizeHtmlTwigFilter } = require('./views/twig-filters')
const {sanitizeHtmlTwigFilter} = require('./views/twig-filters')
// Init express middleware
const app = express()
@ -24,8 +24,8 @@ const io = socketio(server)
app.set('socketio', io)
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
// View engine setup
app.use(express.urlencoded({extended: false}))
// View engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'twig')
app.set('twig options', {
@ -52,7 +52,7 @@ app.use('/inbox', inboxRouter)
// Catch 404 and forward to error handler
app.use((req, res, next) => {
next({ message: 'Page not found', status: 404 })
next({message: 'page not found', status: 404})
})
// Error handler
@ -82,4 +82,4 @@ server.on('listening', () => {
debug('Listening on ' + bind)
})
module.exports = { app, io, server }
module.exports = {app, io, server}