2017-10-22 09:10:33 +08:00
|
|
|
"use strict";
|
|
|
|
|
2017-10-15 11:31:44 +08:00
|
|
|
const utils = require('./utils');
|
2017-11-03 08:48:02 +08:00
|
|
|
const options = require('./options');
|
2017-10-15 11:31:44 +08:00
|
|
|
const fs = require('fs-extra');
|
2017-10-24 11:30:23 +08:00
|
|
|
const dataDir = require('./data_dir');
|
2017-10-25 10:17:48 +08:00
|
|
|
const log = require('./log');
|
2017-11-30 09:47:01 +08:00
|
|
|
const sql = require('./sql');
|
2017-10-15 11:31:44 +08:00
|
|
|
|
|
|
|
async function regularBackup() {
|
2017-12-11 01:56:59 +08:00
|
|
|
const now = new Date();
|
|
|
|
const lastBackupDate = utils.parseDate(await options.getOption('last_backup_date'));
|
2017-10-15 11:31:44 +08:00
|
|
|
|
2017-12-11 01:56:59 +08:00
|
|
|
console.log(lastBackupDate);
|
|
|
|
|
|
|
|
if (now.getTime() - lastBackupDate.getTime() > 43200 * 1000) {
|
2017-10-15 11:31:44 +08:00
|
|
|
await backupNow();
|
|
|
|
}
|
|
|
|
|
|
|
|
await cleanupOldBackups();
|
|
|
|
}
|
|
|
|
|
|
|
|
async function backupNow() {
|
2017-12-11 01:56:59 +08:00
|
|
|
const now = utils.nowDate();
|
2017-10-15 11:31:44 +08:00
|
|
|
|
2017-12-16 13:05:37 +08:00
|
|
|
const backupFile = dataDir.BACKUP_DIR + "/" + "backup-" + utils.getDateTimeForFile() + ".db";
|
2017-10-25 10:17:48 +08:00
|
|
|
|
|
|
|
fs.copySync(dataDir.DOCUMENT_PATH, backupFile);
|
|
|
|
|
|
|
|
log.info("Created backup at " + backupFile);
|
2017-10-15 11:31:44 +08:00
|
|
|
|
2017-11-29 06:24:08 +08:00
|
|
|
await sql.doInTransaction(async () => {
|
|
|
|
await options.setOption('last_backup_date', now);
|
2017-11-29 06:04:47 +08:00
|
|
|
});
|
2017-10-15 11:31:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
async function cleanupOldBackups() {
|
|
|
|
const now = new Date();
|
|
|
|
|
2017-10-24 11:30:23 +08:00
|
|
|
fs.readdirSync(dataDir.BACKUP_DIR).forEach(file => {
|
2017-10-15 11:31:44 +08:00
|
|
|
const match = file.match(/backup-([0-9 -:]+)\.db/);
|
|
|
|
|
|
|
|
if (match) {
|
2017-10-23 08:22:09 +08:00
|
|
|
const date_str = match[1];
|
2017-10-15 11:31:44 +08:00
|
|
|
|
|
|
|
const date = Date.parse(date_str);
|
|
|
|
|
|
|
|
if (now.getTime() - date.getTime() > 30 * 24 * 3600 * 1000) {
|
2017-10-25 10:17:48 +08:00
|
|
|
log.info("Removing old backup - " + file);
|
2017-10-15 11:31:44 +08:00
|
|
|
|
2017-10-24 11:30:23 +08:00
|
|
|
fs.unlink(dataDir.BACKUP_DIR + "/" + file);
|
2017-10-15 11:31:44 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-10-29 00:23:11 +08:00
|
|
|
if (!fs.existsSync(dataDir.BACKUP_DIR)) {
|
|
|
|
fs.mkdirSync(dataDir.BACKUP_DIR, 0o700);
|
|
|
|
}
|
|
|
|
|
2017-12-04 08:18:33 +08:00
|
|
|
sql.dbReady.then(() => {
|
|
|
|
setInterval(regularBackup, 60 * 60 * 1000);
|
2017-10-29 00:23:11 +08:00
|
|
|
|
2017-12-04 08:18:33 +08:00
|
|
|
// kickoff backup immediately
|
|
|
|
setTimeout(regularBackup, 1000);
|
|
|
|
});
|
2017-10-29 00:23:11 +08:00
|
|
|
|
2017-10-15 11:31:44 +08:00
|
|
|
module.exports = {
|
|
|
|
backupNow
|
|
|
|
};
|