123 lines
2.6 KiB
JavaScript
123 lines
2.6 KiB
JavaScript
const config = require('../../config');
|
|
const async = require('async');
|
|
const nodemailer = require('nodemailer');
|
|
const Email = require('email-templates');
|
|
|
|
|
|
class NotificationWorker
|
|
{
|
|
constructor(repository)
|
|
{
|
|
this.repository = repository;
|
|
}
|
|
|
|
|
|
start(interval)
|
|
{
|
|
var self = this;
|
|
|
|
self.stop();
|
|
self.timer = setInterval(async () =>
|
|
{
|
|
if (self.ticking)
|
|
return;
|
|
|
|
self.ticking = true;
|
|
await self.tick();
|
|
self.ticking = false;
|
|
}, interval);
|
|
}
|
|
|
|
|
|
stop()
|
|
{
|
|
var self = this;
|
|
if (self.timer)
|
|
{
|
|
clearInterval(self.timer);
|
|
self.timer = null;
|
|
}
|
|
}
|
|
|
|
|
|
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'
|
|
}
|
|
}
|
|
});
|
|
|
|
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; |