Recv/lib/workers/notification.js

132 lines
3.3 KiB
JavaScript

const async = require('async');
const nodemailer = require('nodemailer');
const Email = require('email-templates');
const fs = require('mz/fs');
const path = require('path');
const getPaths = require('get-paths');
const AbstractIntervalWorker = require('./abstractintervalworker');
class NotificationWorker extends AbstractIntervalWorker
{
constructor(repository)
{
super();
this.repository = repository;
}
async tick()
{
var self = this;
var notifications = await self.repository.notifications.list();
return new Promise((resolve, reject) =>
{
async.eachOfSeries(notifications,
async (item) => { await self.sendNotification(item) },
(err) =>
{
if (err)
reject(err);
else
resolve();
});
})
}
async sendNotification(notification)
{
let self = this;
let user = await self.repository.users.get(notification.userId);
if (user === null || !user.email)
return;
let upload = await self.repository.uploads.get(notification.uploadId);
if (upload === null)
return;
return new Promise((resolve, reject) =>
{
const email = new Email({
message: {
from: config.notifications.mail.from
},
send: true,
preview: false,
transport: nodemailer.createTransport(config.notifications.mail.transport),
views: {
options: {
extension: 'ejs'
}
}
});
// Override the default template locator with one that checks
// the custom folder first, then falls back to the configured folder
let getTemplatePathFromRoot = function(root, view, ext)
{
return new Promise(async (resolve, reject) => {
try {
const paths = await getPaths(
root,
view,
ext
);
const filePath = path.resolve(root, paths.rel);
resolve({ filePath, paths });
} catch (err) {
reject(err);
}
});
};
email.getTemplatePath = async function(view)
{
try
{
return await getTemplatePathFromRoot(path.resolve('custom/emails'), view, this.config.views.options.extension);
}
catch (err)
{
return await getTemplatePathFromRoot(this.config.views.root, view, this.config.views.options.extension);
}
};
email
.send({
template: 'uploadnotification',
message: {
to: user.email
},
locals: {
user: user,
upload: upload,
adminUrl: config.notifications.adminUrl
}
})
.then(async () =>
{
await self.repository.notifications.delete(notification.id);
console.log('Notification sent to: ' + user.email + ' for upload ID: ' + upload.id);
resolve();
})
.catch(async (error) =>
{
notification.attempt++;
if (notification.attempt > config.notifications.maxAttempts)
await self.repository.notifications.delete(notification.id);
else
await self.repository.notifications.update(notification);
resolve();
});
});
}
}
module.exports = NotificationWorker;