opt-cc/api/cron-job/cron.js

74 lines
2.2 KiB
JavaScript

'use strict';
const cron = require('cron');
const async = require('async');
const {exec} = require('child_process');
const UserModel = require('../models/user');
const signatureTool = require('../tools/signature-tool');
const debug = require('debug');
const error = debug('cc:cronjob:err');
const logger = debug('cc:cronjob');
logger.log = console.log.bind(console);
const createAllSignatures = () => {
logger('\x1b[35m%s\x1b[0m', new Date().toLocaleString()
+ ': cron job started - UPDATE SIGNATURES');
// mock response
const res = {
locals: {
items: {},
},
};
// re-create signature image for each active user
UserModel.find({}, (err, users) => {
async.eachSeries(users, (user, callback) => {
// mock next to execute callback
const next = (err) => {
if (!err || (err && err.message.startsWith('Fraction not defined'))) {
callback();
} else {
error('\x1b[41m%s\x1b[0m', new Date().toLocaleString()
+ ': Error in execution - UPDATE SIGNATURES: ' + err.message);
}
};
signatureTool(user._id, res, next);
}, () => {
if (err) {
error('\x1b[41m%s\x1b[0m', new Date().toLocaleString()
+ ': Error in execution - UPDATE SIGNATURES: ' + err.message);
}
logger('\x1b[35m%s\x1b[0m', new Date().toLocaleString()
+ ': finished successful - UPDATE SIGNATURES');
});
});
};
const createBackup = () => {
logger('\x1b[35m%s\x1b[0m', new Date().toLocaleString()
+ ': cron job started - CREATE BACKUP');
exec(__dirname + '/../../backup/backup.sh', (err, stdout, stderr) => {
if (err) {
error(err.message);
}
logger('\x1b[32m%s\x1b[0m', stderr);
logger('\x1b[35m%s\x1b[0m', new Date().toLocaleString()
+ ': cron job finished - CREATE BACKUP');
});
};
// Execute daily @ 02:30 AM
const cronJobSignature = cron.job('00 30 02 * * *', createAllSignatures);
// Execute on Mon, Thu and Sat @ 04:00 AM
const cronJobBackup = cron.job('00 00 04 * * mon,thu,sat', createBackup);
module.exports = {
cronJobSignature: cronJobSignature,
cronJobBackup: cronJobBackup,
createAllSignatures: createAllSignatures,
};