1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-11-24 08:12:24 +02:00
joplin/ReactNativeClient/src/synchronizer.js

298 lines
8.9 KiB
JavaScript
Raw Normal View History

2017-06-15 23:46:53 +02:00
require('babel-plugin-transform-runtime');
2017-06-15 20:18:48 +02:00
import { BaseItem } from 'src/models/base-item.js';
2017-06-19 21:18:22 +02:00
import { Folder } from 'src/models/folder.js';
import { Note } from 'src/models/note.js';
2017-06-19 20:58:49 +02:00
import { BaseModel } from 'src/base-model.js';
2017-06-16 00:12:00 +02:00
import { sprintf } from 'sprintf-js';
2017-06-19 00:06:10 +02:00
import { time } from 'src/time-utils.js';
2017-06-23 23:32:24 +02:00
import { Logger } from 'src/logger.js'
import moment from 'moment';
2017-05-18 21:58:01 +02:00
class Synchronizer {
2017-05-19 21:12:09 +02:00
constructor(db, api) {
2017-06-24 19:40:03 +02:00
this.state_ = 'idle';
2017-05-19 21:12:09 +02:00
this.db_ = db;
this.api_ = api;
this.syncDirName_ = '.sync';
2017-06-23 23:32:24 +02:00
this.logger_ = new Logger();
2017-05-18 21:58:01 +02:00
}
2017-06-24 19:40:03 +02:00
state() {
return this.state_;
}
2017-05-18 21:58:01 +02:00
db() {
2017-05-19 21:12:09 +02:00
return this.db_;
2017-05-18 21:58:01 +02:00
}
api() {
2017-05-19 21:12:09 +02:00
return this.api_;
2017-05-18 21:58:01 +02:00
}
2017-06-23 23:32:24 +02:00
setLogger(l) {
this.logger_ = l;
}
logger() {
return this.logger_;
}
2017-06-24 19:40:03 +02:00
logSyncOperation(action, local, remote, reason) {
let line = ['Sync'];
line.push(action);
line.push(reason);
if (local) {
let s = [];
s.push(local.id);
if ('title' in local) s.push('"' + local.title + '"');
line.push('(Local ' + s.join(', ') + ')');
}
if (remote) {
let s = [];
s.push(remote.id);
if ('title' in remote) s.push('"' + remote.title + '"');
line.push('(Remote ' + s.join(', ') + ')');
}
this.logger().debug(line.join(': '));
}
async logSyncSummary(report) {
for (let n in report) {
this.logger().info(n + ': ' + (report[n] ? report[n] : '-'));
}
let folderCount = await Folder.count();
let noteCount = await Note.count();
this.logger().info('Total folders: ' + folderCount);
this.logger().info('Total notes: ' + noteCount);
}
async createWorkDir() {
if (this.syncWorkDir_) return this.syncWorkDir_;
let dir = await this.api().mkdir(this.syncDirName_);
return this.syncDirName_;
}
2017-06-19 00:06:10 +02:00
async start() {
2017-06-24 19:40:03 +02:00
if (this.state() != 'idle') {
this.logger().warn('Synchronization is already in progress. State: ' + this.state());
return;
}
2017-06-19 00:06:10 +02:00
// ------------------------------------------------------------------------
// First, find all the items that have been changed since the
// last sync and apply the changes to remote.
// ------------------------------------------------------------------------
2017-06-15 20:18:48 +02:00
2017-06-24 19:40:03 +02:00
let synchronizationId = time.unixMs().toString();
this.logger().info('Starting synchronization... [' + synchronizationId + ']');
this.state_ = 'started';
let report = {
createLocal: 0,
updateLocal: 0,
deleteLocal: 0,
createRemote: 0,
updateRemote: 0,
deleteRemote: 0,
folderConflict: 0,
noteConflict: 0,
};
2017-06-23 23:32:24 +02:00
await this.createWorkDir();
2017-06-14 00:39:45 +02:00
let donePaths = [];
2017-06-19 00:06:10 +02:00
while (true) {
let result = await BaseItem.itemsThatNeedSync();
let locals = result.items;
2017-06-13 22:58:17 +02:00
2017-06-19 00:06:10 +02:00
for (let i = 0; i < locals.length; i++) {
let local = locals[i];
let ItemClass = BaseItem.itemClass(local);
let path = BaseItem.systemPath(local);
2017-06-15 20:18:48 +02:00
2017-06-19 00:06:10 +02:00
// Safety check to avoid infinite loops:
if (donePaths.indexOf(path) > 0) throw new Error(sprintf('Processing a path that has already been done: %s. sync_time was not updated?', path));
2017-06-14 00:39:45 +02:00
2017-06-19 00:06:10 +02:00
let remote = await this.api().stat(path);
let content = ItemClass.serialize(local);
let action = null;
2017-06-19 20:58:49 +02:00
let updateSyncTimeOnly = true;
2017-06-24 19:40:03 +02:00
let reason = '';
2017-06-14 00:39:45 +02:00
2017-06-19 00:06:10 +02:00
if (!remote) {
2017-06-20 00:18:24 +02:00
if (!local.sync_time) {
action = 'createRemote';
2017-06-24 19:40:03 +02:00
reason = 'remote does not exist, and local is new and has never been synced';
2017-06-20 00:18:24 +02:00
} else {
// Note or folder was modified after having been deleted remotely
action = local.type_ == BaseModel.MODEL_TYPE_NOTE ? 'noteConflict' : 'folderConflict';
2017-06-24 19:40:03 +02:00
reason = 'remote has been deleted, but local has changes';
2017-06-20 00:18:24 +02:00
}
2017-06-14 00:39:45 +02:00
} else {
2017-06-19 21:18:22 +02:00
if (remote.updated_time > local.sync_time) {
// Since, in this loop, we are only dealing with notes that require sync, if the
// remote has been modified after the sync time, it means both notes have been
// modified and so there's a conflict.
2017-06-19 21:26:27 +02:00
action = local.type_ == BaseModel.MODEL_TYPE_NOTE ? 'noteConflict' : 'folderConflict';
2017-06-24 19:40:03 +02:00
reason = 'both remote and local have changes';
2017-06-14 00:39:45 +02:00
} else {
2017-06-19 00:06:10 +02:00
action = 'updateRemote';
2017-06-24 19:40:03 +02:00
reason = 'local has changes';
2017-06-14 00:39:45 +02:00
}
}
2017-06-24 19:40:03 +02:00
this.logSyncOperation(action, local, remote, reason);
2017-06-19 21:18:22 +02:00
2017-06-19 00:06:10 +02:00
if (action == 'createRemote' || action == 'updateRemote') {
2017-06-20 21:18:19 +02:00
// Make the operation atomic by doing the work on a copy of the file
// and then copying it back to the original location.
2017-06-24 19:40:03 +02:00
let tempPath = this.syncDirName_ + '/' + path + '_' + time.unixMs();
2017-06-24 00:19:59 +02:00
await this.api().put(tempPath, content);
await this.api().setTimestamp(tempPath, local.updated_time);
await this.api().move(tempPath, path);
2017-06-24 00:19:59 +02:00
2017-06-20 21:18:19 +02:00
await ItemClass.save({ id: local.id, sync_time: time.unixMs(), type_: local.type_ }, { autoTimestamp: false });
2017-06-19 21:18:22 +02:00
} else if (action == 'folderConflict') {
2017-06-20 21:18:19 +02:00
2017-06-21 00:16:41 +02:00
if (remote) {
let remoteContent = await this.api().get(path);
local = BaseItem.unserialize(remoteContent);
2017-06-20 21:25:01 +02:00
2017-06-21 00:16:41 +02:00
local.sync_time = time.unixMs();
await ItemClass.save(local, { autoTimestamp: false });
} else {
await ItemClass.delete(local.id);
}
2017-06-20 21:18:19 +02:00
2017-06-19 20:58:49 +02:00
} else if (action == 'noteConflict') {
2017-06-20 21:18:19 +02:00
2017-06-19 20:58:49 +02:00
// - Create a duplicate of local note into Conflicts folder (to preserve the user's changes)
// - Overwrite local note with remote note
let conflictedNote = Object.assign({}, local);
delete conflictedNote.id;
2017-06-20 21:18:19 +02:00
conflictedNote.is_conflict = 1;
2017-06-19 21:18:22 +02:00
await Note.save(conflictedNote, { autoTimestamp: false });
2017-06-19 20:58:49 +02:00
2017-06-20 21:25:01 +02:00
if (remote) {
let remoteContent = await this.api().get(path);
local = BaseItem.unserialize(remoteContent);
2017-06-19 20:58:49 +02:00
2017-06-20 21:25:01 +02:00
local.sync_time = time.unixMs();
await ItemClass.save(local, { autoTimestamp: false });
}
2017-06-18 01:49:52 +02:00
2017-06-20 21:18:19 +02:00
}
2017-06-03 18:20:17 +02:00
2017-06-24 19:40:03 +02:00
report[action]++;
2017-06-19 00:06:10 +02:00
donePaths.push(path);
}
2017-06-03 18:20:17 +02:00
2017-06-19 00:06:10 +02:00
if (!result.hasMore) break;
2017-05-18 21:58:01 +02:00
}
2017-06-16 00:12:00 +02:00
2017-06-19 00:06:10 +02:00
// ------------------------------------------------------------------------
2017-06-20 21:18:19 +02:00
// Delete the remote items that have been deleted locally.
// ------------------------------------------------------------------------
let deletedItems = await BaseModel.deletedItems();
for (let i = 0; i < deletedItems.length; i++) {
let item = deletedItems[i];
let path = BaseItem.systemPath(item.item_id)
2017-06-24 19:40:03 +02:00
this.logSyncOperation('deleteRemote', null, { id: item.item_id }, 'local has been deleted');
2017-06-20 21:18:19 +02:00
await this.api().delete(path);
await BaseModel.remoteDeletedItem(item.item_id);
2017-06-24 19:40:03 +02:00
report['deleteRemote']++;
2017-06-20 21:18:19 +02:00
}
// ------------------------------------------------------------------------
// Loop through all the remote items, find those that
2017-06-19 00:06:10 +02:00
// have been updated, and apply the changes to local.
// ------------------------------------------------------------------------
2017-06-15 01:14:15 +02:00
2017-06-19 00:06:10 +02:00
// At this point all the local items that have changed have been pushed to remote
// or handled as conflicts, so no conflict is possible after this.
2017-06-15 01:14:15 +02:00
2017-06-20 00:18:24 +02:00
let remoteIds = [];
2017-06-19 00:06:10 +02:00
let remotes = await this.api().list();
for (let i = 0; i < remotes.length; i++) {
let remote = remotes[i];
let path = remote.path;
2017-06-20 00:18:24 +02:00
remoteIds.push(BaseItem.pathToId(path));
2017-06-19 00:06:10 +02:00
if (donePaths.indexOf(path) > 0) continue;
2017-06-15 20:18:48 +02:00
2017-06-19 00:06:10 +02:00
let action = null;
2017-06-23 23:32:24 +02:00
let reason = '';
2017-06-19 00:06:10 +02:00
let local = await BaseItem.loadItemByPath(path);
if (!local) {
action = 'createLocal';
2017-06-24 19:40:03 +02:00
reason = 'remote exists but local does not';
2017-06-19 00:06:10 +02:00
} else {
if (remote.updated_time > local.updated_time) {
action = 'updateLocal';
2017-06-24 19:40:03 +02:00
reason = sprintf('remote is more recent than local'); // , time.unixMsToIso(remote.updated_time), time.unixMsToIso(local.updated_time)
2017-06-15 20:18:48 +02:00
}
}
2017-06-14 21:59:46 +02:00
2017-06-19 00:06:10 +02:00
if (!action) continue;
2017-06-15 01:14:15 +02:00
2017-06-19 00:06:10 +02:00
if (action == 'createLocal' || action == 'updateLocal') {
let content = await this.api().get(path);
if (!content) {
2017-06-24 19:40:03 +02:00
this.logger().warn('Remote has been deleted between now and the list() call? In that case it will be handled during the next sync: ' + path);
2017-06-19 00:06:10 +02:00
continue;
}
content = BaseItem.unserialize(content);
let ItemClass = BaseItem.itemClass(content);
2017-06-15 20:18:48 +02:00
2017-06-24 19:40:03 +02:00
let newContent = Object.assign({}, content);
newContent.sync_time = time.unixMs();
2017-06-19 00:06:10 +02:00
let options = { autoTimestamp: false };
if (action == 'createLocal') options.isNew = true;
2017-06-24 19:40:03 +02:00
await ItemClass.save(newContent, options);
this.logSyncOperation(action, local, content, reason);
} else {
this.logSyncOperation(action, local, remote, reason);
2017-06-15 20:18:48 +02:00
}
2017-06-24 19:40:03 +02:00
report[action]++;
2017-06-15 20:18:48 +02:00
}
2017-06-20 00:18:24 +02:00
// ------------------------------------------------------------------------
// Search, among the local IDs, those that don't exist remotely, which
// means the item has been deleted.
// ------------------------------------------------------------------------
2017-06-20 21:18:19 +02:00
let noteIds = await Folder.syncedNoteIds();
for (let i = 0; i < noteIds.length; i++) {
2017-06-24 19:40:03 +02:00
let noteId = noteIds[i];
if (remoteIds.indexOf(noteId) < 0) {
this.logSyncOperation('deleteLocal', { id: noteId }, null, 'remote has been deleted');
await Note.delete(noteId, { trackDeleted: false });
report['deleteLocal']++;
2017-06-20 21:18:19 +02:00
}
}
2017-05-18 21:58:01 +02:00
2017-06-24 19:40:03 +02:00
this.logger().info('Synchronization complete [' + synchronizationId + ']:');
await this.logSyncSummary(report);
this.state_ = 'idle';
2017-06-23 23:32:24 +02:00
2017-06-19 00:06:10 +02:00
return Promise.resolve();
2017-05-18 21:58:01 +02:00
}
}
export { Synchronizer };