2017-12-04 11:29:23 +08:00
|
|
|
"use strict";
|
|
|
|
|
2018-04-03 09:25:20 +08:00
|
|
|
const sqlInit = require('../../services/sql_init');
|
2018-07-23 01:56:20 +08:00
|
|
|
const sql = require('../../services/sql');
|
|
|
|
const cls = require('../../services/cls');
|
|
|
|
const tmp = require('tmp-promise');
|
|
|
|
const http = require('http');
|
|
|
|
const fs = require('fs');
|
|
|
|
const log = require('../../services/log');
|
|
|
|
const DOCUMENT_PATH = require('../../services/data_dir').DOCUMENT_PATH;
|
|
|
|
const sourceIdService = require('../../services/source_id');
|
|
|
|
const url = require('url');
|
2017-12-04 11:29:23 +08:00
|
|
|
|
2018-07-23 01:56:20 +08:00
|
|
|
async function setupNewDocument(req) {
|
2017-12-04 11:29:23 +08:00
|
|
|
const { username, password } = req.body;
|
|
|
|
|
2018-07-21 14:55:24 +08:00
|
|
|
await sqlInit.createInitialDatabase(username, password);
|
2018-03-31 05:07:41 +08:00
|
|
|
}
|
2017-12-04 11:29:23 +08:00
|
|
|
|
2018-07-23 01:56:20 +08:00
|
|
|
async function setupSyncFromServer(req) {
|
|
|
|
const { serverAddress, username, password } = req.body;
|
|
|
|
|
|
|
|
const tempFile = await tmp.file();
|
|
|
|
|
|
|
|
await new Promise((resolve, reject) => {
|
|
|
|
const file = fs.createWriteStream(tempFile.path);
|
|
|
|
const parsedAddress = url.parse(serverAddress);
|
|
|
|
|
|
|
|
const options = {
|
|
|
|
method: 'GET',
|
|
|
|
protocol: parsedAddress.protocol,
|
|
|
|
host: parsedAddress.hostname,
|
|
|
|
port: parsedAddress.port,
|
|
|
|
path: '/api/sync/document',
|
|
|
|
auth: username + ':' + password
|
|
|
|
};
|
|
|
|
|
|
|
|
log.info("Getting document from: " + serverAddress + JSON.stringify(options));
|
|
|
|
|
|
|
|
http.request(options, function(response) {
|
|
|
|
response.pipe(file);
|
|
|
|
|
|
|
|
file.on('finish', function() {
|
|
|
|
log.info("Document download finished, closing & renaming.");
|
|
|
|
|
|
|
|
file.close(() => { // close() is async, call after close completes.
|
|
|
|
fs.rename(tempFile.path, DOCUMENT_PATH, async () => {
|
|
|
|
cls.reset();
|
|
|
|
|
|
|
|
await sqlInit.initDbConnection();
|
|
|
|
|
|
|
|
// we need to generate new source ID for this instance, otherwise it will
|
|
|
|
// match the original server one
|
|
|
|
await sql.transactional(async () => {
|
|
|
|
await sourceIdService.generateSourceId();
|
|
|
|
});
|
|
|
|
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}).on('error', function(err) { // Handle errors
|
|
|
|
fs.unlink(tempFile.path); // Delete the file async. (But we don't check the result)
|
|
|
|
|
|
|
|
reject(err.message);
|
|
|
|
log.error(err.message);
|
|
|
|
}).end();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2018-03-31 05:07:41 +08:00
|
|
|
module.exports = {
|
2018-07-23 01:56:20 +08:00
|
|
|
setupNewDocument,
|
|
|
|
setupSyncFromServer
|
2018-03-31 05:07:41 +08:00
|
|
|
};
|