trilium/services/sync.js

335 lines
9.6 KiB
JavaScript
Raw Normal View History

2017-10-22 09:10:33 +08:00
"use strict";
2017-10-26 10:39:21 +08:00
const log = require('./log');
const rp = require('request-promise');
const sql = require('./sql');
2017-11-03 08:48:02 +08:00
const options = require('./options');
2017-10-26 10:39:21 +08:00
const migration = require('./migration');
2017-10-27 09:16:21 +08:00
const utils = require('./utils');
const config = require('./config');
const source_id = require('./source_id');
const notes = require('./notes');
2017-11-10 09:52:47 +08:00
const syncUpdate = require('./sync_update');
2017-11-22 11:11:27 +08:00
const content_hash = require('./content_hash');
const event_log = require('./event_log');
const fs = require('fs');
2017-12-04 11:29:23 +08:00
const app_info = require('./app_info');
const SYNC_SERVER = config['Sync']['syncServerHost'];
const isSyncSetup = !!SYNC_SERVER;
2017-11-10 09:06:33 +08:00
const SYNC_TIMEOUT = config['Sync']['syncServerTimeout'] || 5000;
2017-11-14 08:45:13 +08:00
const SYNC_PROXY = config['Sync']['syncProxy'];
2017-10-26 10:39:21 +08:00
let syncInProgress = false;
let proxyToggle = true;
let syncServerCertificate = null;
2017-10-26 10:39:21 +08:00
2017-11-10 09:52:47 +08:00
async function sync() {
if (syncInProgress) {
log.info("Sync already in progress");
2017-11-10 09:52:47 +08:00
return {
success: false,
message: "Sync already in progress"
};
}
syncInProgress = true;
2017-10-30 02:55:48 +08:00
try {
if (!await sql.isDbUpToDate()) {
2017-11-10 09:52:47 +08:00
return {
success: false,
message: "DB not up to date"
};
}
2017-11-01 07:34:58 +08:00
2017-11-10 09:52:47 +08:00
const syncContext = await login();
await pushSync(syncContext);
await pullSync(syncContext);
await pushSync(syncContext);
2017-11-22 11:11:27 +08:00
await checkContentHash(syncContext);
2017-11-10 09:52:47 +08:00
return {
success: true
};
2017-10-30 02:55:48 +08:00
}
catch (e) {
proxyToggle = !proxyToggle;
2017-11-10 09:52:47 +08:00
if (e.message.indexOf('ECONNREFUSED') !== -1) {
log.info("No connection to sync server.");
2017-11-10 09:52:47 +08:00
return {
success: false,
message: "No connection to sync server."
};
2017-11-01 07:34:58 +08:00
}
2017-11-10 09:52:47 +08:00
else {
log.info("sync failed: " + e.stack);
return {
success: false,
message: e.message
}
2017-11-01 07:34:58 +08:00
}
2017-11-10 09:52:47 +08:00
}
finally {
syncInProgress = false;
}
}
async function login() {
2017-12-11 04:45:17 +08:00
const timestamp = utils.nowDate();
2017-11-10 09:52:47 +08:00
const documentSecret = await options.getOption('document_secret');
const hash = utils.hmac(documentSecret, timestamp);
const syncContext = { cookieJar: rp.jar() };
const resp = await syncRequest(syncContext, 'POST', '/api/login/sync', {
2017-11-10 09:52:47 +08:00
timestamp: timestamp,
2017-12-04 11:29:23 +08:00
dbVersion: app_info.db_version,
2017-11-10 09:52:47 +08:00
hash: hash
});
syncContext.sourceId = resp.sourceId;
return syncContext;
}
2017-11-22 11:11:27 +08:00
async function getLastSyncedPull() {
return parseInt(await options.getOption('last_synced_pull'));
}
async function setLastSyncedPull(syncId) {
await sql.doInTransaction(async () => {
await options.setOption('last_synced_pull', syncId);
});
}
2017-11-10 09:52:47 +08:00
async function pullSync(syncContext) {
2017-11-22 11:11:27 +08:00
const lastSyncedPull = await getLastSyncedPull();
2017-11-10 09:52:47 +08:00
const changesUri = '/api/sync/changed?lastSyncId=' + lastSyncedPull;
2017-11-10 09:52:47 +08:00
const syncRows = await syncRequest(syncContext, 'GET', changesUri);
log.info("Pulled " + syncRows.length + " changes from " + changesUri);
for (const sync of syncRows) {
if (source_id.isLocalSourceId(sync.source_id)) {
log.info("Skipping " + sync.entity_name + " " + sync.entity_id + " because it has local source id.");
await setLastSyncedPull(sync.id);
continue;
}
const resp = await syncRequest(syncContext, 'GET', "/api/sync/" + sync.entity_name + "/" + encodeURIComponent(sync.entity_id));
2017-11-01 07:34:58 +08:00
2017-11-24 12:54:54 +08:00
if (!resp) {
log.error("Empty response to pull for " + sync.entity_name + ", id=" + sync.entity_id);
}
2017-12-11 04:45:17 +08:00
else if (sync.entity_name === 'notes') {
await syncUpdate.updateNote(resp.entity, syncContext.sourceId);
2017-11-01 08:09:07 +08:00
}
else if (sync.entity_name === 'notes_tree') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateNoteTree(resp, syncContext.sourceId);
2017-11-01 08:09:07 +08:00
}
else if (sync.entity_name === 'notes_history') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateNoteHistory(resp, syncContext.sourceId);
2017-11-01 08:09:07 +08:00
}
2017-11-03 10:55:22 +08:00
else if (sync.entity_name === 'notes_reordering') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateNoteReordering(resp, syncContext.sourceId);
2017-11-03 10:55:22 +08:00
}
2017-11-03 08:48:02 +08:00
else if (sync.entity_name === 'options') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateOptions(resp, syncContext.sourceId);
2017-11-03 08:48:02 +08:00
}
2017-11-05 12:16:02 +08:00
else if (sync.entity_name === 'recent_notes') {
2017-11-10 09:52:47 +08:00
await syncUpdate.updateRecentNotes(resp, syncContext.sourceId);
2017-11-05 12:16:02 +08:00
}
2017-11-01 08:09:07 +08:00
else {
2017-12-07 09:58:59 +08:00
throw new Error("Unrecognized entity type " + sync.entity_name);
2017-11-01 08:09:07 +08:00
}
await setLastSyncedPull(sync.id);
}
2017-11-01 07:34:58 +08:00
2017-11-10 09:52:47 +08:00
log.info("Finished pull");
}
2017-10-26 10:39:21 +08:00
2017-11-22 11:11:27 +08:00
async function getLastSyncedPush() {
return parseInt(await options.getOption('last_synced_push'));
}
async function setLastSyncedPush(lastSyncedPush) {
await sql.doInTransaction(async () => {
await options.setOption('last_synced_push', lastSyncedPush);
});
}
2017-11-10 09:52:47 +08:00
async function pushSync(syncContext) {
2017-11-22 11:11:27 +08:00
let lastSyncedPush = await getLastSyncedPush();
2017-10-26 10:39:21 +08:00
2017-11-10 09:52:47 +08:00
while (true) {
const sync = await sql.getSingleResultOrNull('SELECT * FROM sync WHERE id > ? LIMIT 1', [lastSyncedPush]);
if (sync === null) {
// nothing to sync
log.info("Nothing to push");
break;
2017-10-30 02:55:48 +08:00
}
2017-10-30 10:22:30 +08:00
2017-11-10 09:52:47 +08:00
if (sync.source_id === syncContext.sourceId) {
log.info("Skipping sync " + sync.entity_name + " " + sync.entity_id + " because it originates from sync target");
}
else {
await readAndPushEntity(sync, syncContext);
}
lastSyncedPush = sync.id;
await setLastSyncedPush(lastSyncedPush);
2017-10-27 09:16:21 +08:00
}
2017-10-30 10:22:30 +08:00
}
async function readAndPushEntity(sync, syncContext) {
let entity;
if (sync.entity_name === 'notes') {
entity = await sql.getSingleResult('SELECT * FROM notes WHERE note_id = ?', [sync.entity_id]);
}
else if (sync.entity_name === 'notes_tree') {
entity = await sql.getSingleResult('SELECT * FROM notes_tree WHERE note_tree_id = ?', [sync.entity_id]);
}
else if (sync.entity_name === 'notes_history') {
entity = await sql.getSingleResult('SELECT * FROM notes_history WHERE note_history_id = ?', [sync.entity_id]);
}
2017-11-03 10:55:22 +08:00
else if (sync.entity_name === 'notes_reordering') {
entity = {
note_pid: sync.entity_id,
ordering: await sql.getMap('SELECT note_tree_id, note_pos FROM notes_tree WHERE note_pid = ?', [sync.entity_id])
2017-11-03 10:55:22 +08:00
};
}
2017-11-03 08:48:02 +08:00
else if (sync.entity_name === 'options') {
entity = await sql.getSingleResult('SELECT * FROM options WHERE opt_name = ?', [sync.entity_id]);
}
2017-11-05 12:16:02 +08:00
else if (sync.entity_name === 'recent_notes') {
entity = await sql.getSingleResult('SELECT * FROM recent_notes WHERE note_tree_id = ?', [sync.entity_id]);
2017-11-05 12:16:02 +08:00
}
else {
2017-12-07 09:58:59 +08:00
throw new Error("Unrecognized entity type " + sync.entity_name);
}
2017-11-05 10:10:41 +08:00
if (!entity) {
2017-11-10 09:52:47 +08:00
log.info("Sync entity for " + sync.entity_name + " " + sync.entity_id + " doesn't exist. Skipping.");
2017-11-05 10:10:41 +08:00
return;
}
2017-11-10 09:52:47 +08:00
log.info("Pushing changes in " + sync.entity_name + " " + sync.entity_id);
2017-11-10 09:52:47 +08:00
await sendEntity(syncContext, entity, sync.entity_name);
}
2017-11-10 09:52:47 +08:00
async function sendEntity(syncContext, entity, entityName) {
const payload = {
sourceId: source_id.currentSourceId,
2017-11-10 09:52:47 +08:00
entity: entity
};
2017-10-30 10:22:30 +08:00
2017-11-10 09:52:47 +08:00
await syncRequest(syncContext, 'PUT', '/api/sync/' + entityName, payload);
}
2017-10-29 10:17:00 +08:00
2017-11-22 11:11:27 +08:00
async function checkContentHash(syncContext) {
const lastSyncedPush = await getLastSyncedPush();
const notPushedSyncs = await sql.getSingleValue("SELECT COUNT(*) FROM sync WHERE id > ?", [lastSyncedPush]);
if (notPushedSyncs > 0) {
log.info("There's " + notPushedSyncs + " outstanding pushes, skipping content check.");
return;
}
const resp = await syncRequest(syncContext, 'GET', '/api/sync/check');
// if (await getLastSyncedPull() < resp.max_sync_id) {
// log.info("There are some outstanding pulls, skipping content check.");
//
// return;
// }
const localContentHash = await content_hash.getContentHash();
if (resp.content_hash === localContentHash) {
log.info("Content hash check PASSED with value: " + localContentHash);
2017-11-22 11:11:27 +08:00
}
else {
await event_log.addEvent("Content hash check FAILED. Local is " + localContentHash + ", remote is " + resp.content_hash);
2017-11-22 11:11:27 +08:00
}
}
2017-11-10 09:52:47 +08:00
async function syncRequest(syncContext, method, uri, body) {
const fullUri = SYNC_SERVER + uri;
2017-10-29 10:17:00 +08:00
2017-10-30 02:55:48 +08:00
try {
2017-11-14 08:45:13 +08:00
const options = {
2017-11-10 09:52:47 +08:00
method: method,
uri: fullUri,
jar: syncContext.cookieJar,
2017-10-30 02:55:48 +08:00
json: true,
2017-11-10 09:52:47 +08:00
body: body,
timeout: SYNC_TIMEOUT
2017-11-14 08:45:13 +08:00
};
if (syncServerCertificate) {
options.ca = syncServerCertificate;
}
if (SYNC_PROXY && proxyToggle) {
2017-11-14 08:45:13 +08:00
options.proxy = SYNC_PROXY;
}
return await rp(options);
2017-10-26 10:39:21 +08:00
}
catch (e) {
2017-12-07 09:58:59 +08:00
throw new Error("Request to " + method + " " + fullUri + " failed, inner exception: " + e.stack);
2017-11-05 12:16:02 +08:00
}
}
sql.dbReady.then(() => {
if (isSyncSetup) {
log.info("Setting up sync to " + SYNC_SERVER + " with timeout " + SYNC_TIMEOUT);
2017-10-26 10:39:21 +08:00
if (SYNC_PROXY) {
log.info("Sync proxy: " + SYNC_PROXY);
}
const syncCertPath = config['Sync']['syncServerCertificate'];
if (syncCertPath) {
log.info('Sync certificate: ' + syncCertPath);
syncServerCertificate = fs.readFileSync(syncCertPath);
}
setInterval(sync, 60000);
// kickoff initial sync immediately
setTimeout(sync, 1000);
}
else {
log.info("Sync server not configured, sync timer not running.")
}
});
2017-10-27 09:16:21 +08:00
module.exports = {
2017-10-29 23:22:41 +08:00
sync,
isSyncSetup
2017-10-27 09:16:21 +08:00
};