2017-10-22 09:10:33 +08:00
|
|
|
"use strict";
|
|
|
|
|
2017-10-15 11:31:44 +08:00
|
|
|
const utils = require('./utils');
|
|
|
|
const sql = require('./sql');
|
|
|
|
const config = require('./config');
|
|
|
|
const fs = require('fs-extra');
|
2017-10-24 11:30:23 +08:00
|
|
|
const dataDir = require('./data_dir');
|
2017-10-15 11:31:44 +08:00
|
|
|
|
|
|
|
async function regularBackup() {
|
|
|
|
const now = utils.nowTimestamp();
|
|
|
|
const last_backup_date = parseInt(await sql.getOption('last_backup_date'));
|
|
|
|
|
|
|
|
if (now - last_backup_date > 43200) {
|
|
|
|
await backupNow();
|
|
|
|
}
|
|
|
|
|
|
|
|
await cleanupOldBackups();
|
|
|
|
}
|
|
|
|
|
|
|
|
async function backupNow() {
|
|
|
|
const now = utils.nowTimestamp();
|
|
|
|
|
|
|
|
const backup_directory = config.Backup.backupDirectory;
|
|
|
|
|
|
|
|
const date_str = new Date().toISOString().substr(0, 19);
|
|
|
|
|
2017-10-24 11:30:23 +08:00
|
|
|
if (!fs.existsSync(dataDir.BACKUP_DIR)) {
|
|
|
|
fs.mkdirSync(dataDir.BACKUP_DIR, 0o700);
|
|
|
|
}
|
|
|
|
|
|
|
|
fs.copySync(dataDir.DOCUMENT_PATH, dataDir.BACKUP_DIR + "/" + "backup-" + date_str + ".db");
|
2017-10-15 11:31:44 +08:00
|
|
|
|
|
|
|
await sql.setOption('last_backup_date', now);
|
|
|
|
//await sql.commit();
|
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
|
|
|
console.log("Removing old backup - " + file);
|
|
|
|
|
2017-10-24 11:30:23 +08:00
|
|
|
fs.unlink(dataDir.BACKUP_DIR + "/" + file);
|
2017-10-15 11:31:44 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
regularBackup,
|
|
|
|
backupNow
|
|
|
|
};
|