1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-24 10:27:10 +02:00

All: Started moving sync glue logic to SyncTarget classes

This commit is contained in:
Laurent Cozic 2017-11-23 23:10:55 +00:00
parent a2ae2c766a
commit d7f3cfd778
15 changed files with 329 additions and 138 deletions

View File

@ -16,7 +16,7 @@ class Command extends BaseCommand {
constructor() { constructor() {
super(); super();
this.syncTarget_ = null; this.syncTargetId_ = null;
this.releaseLockFn_ = null; this.releaseLockFn_ = null;
this.oneDriveApiUtils_ = null; this.oneDriveApiUtils_ = null;
} }
@ -62,6 +62,27 @@ class Command extends BaseCommand {
}); });
} }
async doAuth(syncTargetId) {
const syncTarget = reg.syncTarget(this.syncTargetId_);
this.oneDriveApiUtils_ = new OneDriveApiNodeUtils(syncTarget.oneDriveApi());
const auth = await this.oneDriveApiUtils_.oauthDance({
log: (...s) => { return this.stdout(...s); }
});
this.oneDriveApiUtils_ = null;
return auth;
}
cancelAuth() {
if (this.oneDriveApiUtils_) {
this.oneDriveApiUtils_.cancelOAuthDance();
return;
}
}
doingAuth() {
return !!this.oneDriveApiUtils_;
}
async action(args) { async action(args) {
this.releaseLockFn_ = null; this.releaseLockFn_ = null;
@ -91,25 +112,24 @@ class Command extends BaseCommand {
}; };
try { try {
this.syncTarget_ = Setting.value('sync.target'); this.syncTargetId_ = Setting.value('sync.target');
if (args.options.target) this.syncTarget_ = args.options.target; if (args.options.target) this.syncTargetId_ = args.options.target;
if (this.syncTarget_ == Setting.SYNC_TARGET_ONEDRIVE && !reg.syncHasAuth(this.syncTarget_)) { const syncTarget = reg.syncTarget(this.syncTargetId_);
if (syncTarget.isAuthenticated()) {
app().gui().showConsole(); app().gui().showConsole();
app().gui().maximizeConsole(); app().gui().maximizeConsole();
this.oneDriveApiUtils_ = new OneDriveApiNodeUtils(reg.oneDriveApi());
const auth = await this.oneDriveApiUtils_.oauthDance({ const auth = await this.doAuth(this.syncTargetId_);
log: (...s) => { return this.stdout(...s); } Setting.setValue('sync.' + this.syncTargetId_ + '.auth', auth ? JSON.stringify(auth) : null);
});
this.oneDriveApiUtils_ = null;
Setting.setValue('sync.3.auth', auth ? JSON.stringify(auth) : null);
if (!auth) { if (!auth) {
this.stdout(_('Authentication was not completed (did not receive an authentication token).')); this.stdout(_('Authentication was not completed (did not receive an authentication token).'));
return cleanUp(); return cleanUp();
} }
} }
let sync = await reg.synchronizer(this.syncTarget_); const sync = await syncTarget.synchronizer();
let options = { let options = {
onProgress: (report) => { onProgress: (report) => {
@ -123,13 +143,13 @@ class Command extends BaseCommand {
randomFailures: args.options['random-failures'] === true, randomFailures: args.options['random-failures'] === true,
}; };
this.stdout(_('Synchronisation target: %s (%s)', Setting.enumOptionLabel('sync.target', this.syncTarget_), this.syncTarget_)); this.stdout(_('Synchronisation target: %s (%s)', Setting.enumOptionLabel('sync.target', this.syncTargetId_), this.syncTargetId_));
if (!sync) throw new Error(_('Cannot initialize synchroniser.')); if (!sync) throw new Error(_('Cannot initialize synchroniser.'));
this.stdout(_('Starting synchronisation...')); this.stdout(_('Starting synchronisation...'));
const contextKey = 'sync.' + this.syncTarget_ + '.context'; const contextKey = 'sync.' + this.syncTargetId_ + '.context';
let context = Setting.value(contextKey); let context = Setting.value(contextKey);
context = context ? JSON.parse(context) : {}; context = context ? JSON.parse(context) : {};
@ -156,26 +176,28 @@ class Command extends BaseCommand {
} }
async cancel() { async cancel() {
if (this.oneDriveApiUtils_) { if (this.doingAuth()) {
this.oneDriveApiUtils_.cancelOAuthDance(); this.cancelAuth();
return; return;
} }
const target = this.syncTarget_ ? this.syncTarget_ : Setting.value('sync.target'); const syncTargetId = this.syncTargetId_ ? this.syncTargetId_ : Setting.value('sync.target');
cliUtils.redrawDone(); cliUtils.redrawDone();
this.stdout(_('Cancelling... Please wait.')); this.stdout(_('Cancelling... Please wait.'));
if (reg.syncHasAuth(target)) { const syncTarget = reg.syncTarget(syncTargetId);
let sync = await reg.synchronizer(target);
if (syncTarget.isAuthenticated()) {
const sync = await syncTarget.synchronizer();
if (sync) await sync.cancel(); if (sync) await sync.cancel();
} else { } else {
if (this.releaseLockFn_) this.releaseLockFn_(); if (this.releaseLockFn_) this.releaseLockFn_();
this.releaseLockFn_ = null; this.releaseLockFn_ = null;
} }
this.syncTarget_ = null; this.syncTargetId_ = null;
} }
cancellable() { cancellable() {

View File

@ -568,12 +568,15 @@ msgstr ""
msgid "Add or remove tags" msgid "Add or remove tags"
msgstr "" msgstr ""
msgid "Switch between note and to-do" msgid "Switch between note and to-do type"
msgstr "" msgstr ""
msgid "Delete" msgid "Delete"
msgstr "" msgstr ""
msgid "Delete notes?"
msgstr ""
msgid "No notes in here. Create one by clicking on \"New note\"." msgid "No notes in here. Create one by clicking on \"New note\"."
msgstr "" msgstr ""
@ -628,6 +631,9 @@ msgstr ""
msgid "Unknown flag: %s" msgid "Unknown flag: %s"
msgstr "" msgstr ""
msgid "OneDrive"
msgstr ""
#, javascript-format #, javascript-format
msgid "Unknown log level: %s" msgid "Unknown log level: %s"
msgstr "" msgstr ""
@ -641,11 +647,6 @@ msgid ""
"synchronisation again may fix the problem." "synchronisation again may fix the problem."
msgstr "" msgstr ""
msgid ""
"Please set the \"sync.2.path\" config value to the desired synchronisation "
"destination."
msgstr ""
#, javascript-format #, javascript-format
msgid "Cannot access %s" msgid "Cannot access %s"
msgstr "" msgstr ""
@ -737,9 +738,6 @@ msgstr ""
msgid "File system" msgid "File system"
msgstr "" msgstr ""
msgid "OneDrive"
msgstr ""
msgid "Text editor" msgid "Text editor"
msgstr "" msgstr ""
@ -784,10 +782,10 @@ msgstr ""
msgid "%d hours" msgid "%d hours"
msgstr "" msgstr ""
msgid "Show advanced options" msgid "Automatically update the application"
msgstr "" msgstr ""
msgid "Automatically update the application" msgid "Show advanced options"
msgstr "" msgstr ""
msgid "Sync status (synced items / total items)" msgid "Sync status (synced items / total items)"
@ -819,6 +817,9 @@ msgstr ""
msgid "There are currently no notes. Create one by clicking on the (+) button." msgid "There are currently no notes. Create one by clicking on the (+) button."
msgstr "" msgstr ""
msgid "Delete these notes?"
msgstr ""
msgid "Log" msgid "Log"
msgstr "" msgstr ""
@ -828,6 +829,13 @@ msgstr ""
msgid "Export Debug Report" msgid "Export Debug Report"
msgstr "" msgstr ""
msgid "Move to notebook..."
msgstr ""
#, javascript-format
msgid "Move %d notes to notebook \"%s\"?"
msgstr ""
msgid "Cancel synchronisation" msgid "Cancel synchronisation"
msgstr "" msgstr ""

View File

@ -620,12 +620,17 @@ msgstr "Disposition"
msgid "Add or remove tags" msgid "Add or remove tags"
msgstr "Gérer les étiquettes" msgstr "Gérer les étiquettes"
msgid "Switch between note and to-do" #, fuzzy
msgid "Switch between note and to-do type"
msgstr "Alterner entre note et tâche" msgstr "Alterner entre note et tâche"
msgid "Delete" msgid "Delete"
msgstr "Supprimer" msgstr "Supprimer"
#, fuzzy
msgid "Delete notes?"
msgstr "Supprimer la note ?"
msgid "No notes in here. Create one by clicking on \"New note\"." msgid "No notes in here. Create one by clicking on \"New note\"."
msgstr "" msgstr ""
"Pas de notes ici. Créez-en une en pressant le bouton \"Nouvelle note\"." "Pas de notes ici. Créez-en une en pressant le bouton \"Nouvelle note\"."
@ -681,6 +686,9 @@ msgstr "Utilisation : %s"
msgid "Unknown flag: %s" msgid "Unknown flag: %s"
msgstr "Paramètre inconnu : %s" msgstr "Paramètre inconnu : %s"
msgid "OneDrive"
msgstr "OneDrive"
#, javascript-format #, javascript-format
msgid "Unknown log level: %s" msgid "Unknown log level: %s"
msgstr "Paramètre inconnu : %s" msgstr "Paramètre inconnu : %s"
@ -696,13 +704,6 @@ msgstr ""
"Impossible de rafraîchir la connexion à OneDrive. Démarrez la " "Impossible de rafraîchir la connexion à OneDrive. Démarrez la "
"synchronisation à nouveau pour corriger le problème." "synchronisation à nouveau pour corriger le problème."
msgid ""
"Please set the \"sync.2.path\" config value to the desired synchronisation "
"destination."
msgstr ""
"Veuillez attribuer une valeur au paramètre de configuration \"sync.2.path\" "
"pour indiquer le dossier où devra se faire la synchronisation."
#, javascript-format #, javascript-format
msgid "Cannot access %s" msgid "Cannot access %s"
msgstr "Impossible d'accéder à %s" msgstr "Impossible d'accéder à %s"
@ -798,9 +799,6 @@ msgstr ""
msgid "File system" msgid "File system"
msgstr "Système de fichier" msgstr "Système de fichier"
msgid "OneDrive"
msgstr "OneDrive"
msgid "Text editor" msgid "Text editor"
msgstr "Éditeur de texte" msgstr "Éditeur de texte"
@ -847,13 +845,13 @@ msgstr "%d heure"
msgid "%d hours" msgid "%d hours"
msgstr "%d heures" msgstr "%d heures"
msgid "Show advanced options"
msgstr "Montrer les options avancées"
#, fuzzy #, fuzzy
msgid "Automatically update the application" msgid "Automatically update the application"
msgstr "Quitter le logiciel." msgstr "Quitter le logiciel."
msgid "Show advanced options"
msgstr "Montrer les options avancées"
msgid "Sync status (synced items / total items)" msgid "Sync status (synced items / total items)"
msgstr "Status de la synchronisation (objets synchro. / total)" msgstr "Status de la synchronisation (objets synchro. / total)"
@ -885,6 +883,10 @@ msgstr ""
"Ce carnet ne contient aucune note. Créez-en une en appuyant sur le bouton " "Ce carnet ne contient aucune note. Créez-en une en appuyant sur le bouton "
"(+)." "(+)."
#, fuzzy
msgid "Delete these notes?"
msgstr "Supprimer la note ?"
msgid "Log" msgid "Log"
msgstr "Journal" msgstr "Journal"
@ -894,6 +896,14 @@ msgstr "État"
msgid "Export Debug Report" msgid "Export Debug Report"
msgstr "Exporter rapport de débogage" msgstr "Exporter rapport de débogage"
#, fuzzy
msgid "Move to notebook..."
msgstr "Déplacer la note vers un carnet."
#, fuzzy, javascript-format
msgid "Move %d notes to notebook \"%s\"?"
msgstr "Déplacer la note vers un carnet."
msgid "Cancel synchronisation" msgid "Cancel synchronisation"
msgstr "Annuler synchronisation" msgstr "Annuler synchronisation"
@ -962,6 +972,13 @@ msgstr ""
msgid "Welcome" msgid "Welcome"
msgstr "Bienvenue" msgstr "Bienvenue"
#~ msgid ""
#~ "Please set the \"sync.2.path\" config value to the desired "
#~ "synchronisation destination."
#~ msgstr ""
#~ "Veuillez attribuer une valeur au paramètre de configuration \"sync.2.path"
#~ "\" pour indiquer le dossier où devra se faire la synchronisation."
#~ msgid "Seach:" #~ msgid "Seach:"
#~ msgstr "Chercher :" #~ msgstr "Chercher :"

View File

@ -568,12 +568,15 @@ msgstr ""
msgid "Add or remove tags" msgid "Add or remove tags"
msgstr "" msgstr ""
msgid "Switch between note and to-do" msgid "Switch between note and to-do type"
msgstr "" msgstr ""
msgid "Delete" msgid "Delete"
msgstr "" msgstr ""
msgid "Delete notes?"
msgstr ""
msgid "No notes in here. Create one by clicking on \"New note\"." msgid "No notes in here. Create one by clicking on \"New note\"."
msgstr "" msgstr ""
@ -628,6 +631,9 @@ msgstr ""
msgid "Unknown flag: %s" msgid "Unknown flag: %s"
msgstr "" msgstr ""
msgid "OneDrive"
msgstr ""
#, javascript-format #, javascript-format
msgid "Unknown log level: %s" msgid "Unknown log level: %s"
msgstr "" msgstr ""
@ -641,11 +647,6 @@ msgid ""
"synchronisation again may fix the problem." "synchronisation again may fix the problem."
msgstr "" msgstr ""
msgid ""
"Please set the \"sync.2.path\" config value to the desired synchronisation "
"destination."
msgstr ""
#, javascript-format #, javascript-format
msgid "Cannot access %s" msgid "Cannot access %s"
msgstr "" msgstr ""
@ -737,9 +738,6 @@ msgstr ""
msgid "File system" msgid "File system"
msgstr "" msgstr ""
msgid "OneDrive"
msgstr ""
msgid "Text editor" msgid "Text editor"
msgstr "" msgstr ""
@ -784,10 +782,10 @@ msgstr ""
msgid "%d hours" msgid "%d hours"
msgstr "" msgstr ""
msgid "Show advanced options" msgid "Automatically update the application"
msgstr "" msgstr ""
msgid "Automatically update the application" msgid "Show advanced options"
msgstr "" msgstr ""
msgid "Sync status (synced items / total items)" msgid "Sync status (synced items / total items)"
@ -819,6 +817,9 @@ msgstr ""
msgid "There are currently no notes. Create one by clicking on the (+) button." msgid "There are currently no notes. Create one by clicking on the (+) button."
msgstr "" msgstr ""
msgid "Delete these notes?"
msgstr ""
msgid "Log" msgid "Log"
msgstr "" msgstr ""
@ -828,6 +829,13 @@ msgstr ""
msgid "Export Debug Report" msgid "Export Debug Report"
msgstr "" msgstr ""
msgid "Move to notebook..."
msgstr ""
#, javascript-format
msgid "Move %d notes to notebook \"%s\"?"
msgstr ""
msgid "Cancel synchronisation" msgid "Cancel synchronisation"
msgstr "" msgstr ""

View File

@ -30,8 +30,6 @@ const logDir = __dirname + '/../tests/logs';
fs.mkdirpSync(logDir, 0o755); fs.mkdirpSync(logDir, 0o755);
const syncTargetId_ = Setting.SYNC_TARGET_MEMORY; const syncTargetId_ = Setting.SYNC_TARGET_MEMORY;
//const syncTargetId_ = Setting.SYNC_TARGET_FILESYSTEM;
//const syncTargetId_ = Setting.SYNC_TARGET_ONEDRIVE;
const syncDir = __dirname + '/../tests/sync'; const syncDir = __dirname + '/../tests/sync';
const sleepTime = syncTargetId_ == Setting.SYNC_TARGET_FILESYSTEM ? 1001 : 400; const sleepTime = syncTargetId_ == Setting.SYNC_TARGET_FILESYSTEM ? 1001 : 400;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -14,6 +14,7 @@ const { Logger } = require('lib/logger.js');
const { splitCommandString } = require('lib/string-utils.js'); const { splitCommandString } = require('lib/string-utils.js');
const { sprintf } = require('sprintf-js'); const { sprintf } = require('sprintf-js');
const { reg } = require('lib/registry.js'); const { reg } = require('lib/registry.js');
const BaseSyncTarget = require('lib/BaseSyncTarget.js');
const { fileExtension } = require('lib/path-utils.js'); const { fileExtension } = require('lib/path-utils.js');
const { shim } = require('lib/shim.js'); const { shim } = require('lib/shim.js');
const { _, setLocale, defaultLocale, closestSupportedLocale } = require('lib/locale.js'); const { _, setLocale, defaultLocale, closestSupportedLocale } = require('lib/locale.js');
@ -276,6 +277,7 @@ class BaseApplication {
BaseModel.dispatch = this.store().dispatch; BaseModel.dispatch = this.store().dispatch;
FoldersScreenUtils.dispatch = this.store().dispatch; FoldersScreenUtils.dispatch = this.store().dispatch;
reg.dispatch = this.store().dispatch; reg.dispatch = this.store().dispatch;
BaseSyncTarget.dispatch = this.store().dispatch;
} }
async readFlagsFromFile(flagPath) { async readFlagsFromFile(flagPath) {

View File

@ -0,0 +1,82 @@
const { reg } = require('lib/registry.js');
class BaseSyncTarget {
constructor(db) {
this.db_ = db;
this.synchronizer_ = null;
this.initState_ = null;
this.logger_ = null;
}
logger() {
return this.logger_;
}
setLogger(v) {
this.logger_ = v;
}
db() {
return this.db_;
}
isAuthenticated() {
return false;
}
name() {
throw new Error('Not implemented');
}
label() {
throw new Error('Not implemented');
}
async initSynchronizer() {
throw new Error('Not implemented');
}
async synchronizer() {
if (this.synchronizer_) return this.synchronizer_;
if (this.initState_ == 'started') {
// Synchronizer is already being initialized, so wait here till it's done.
return new Promise((resolve, reject) => {
const iid = setInterval(() => {
if (this.initState_ == 'ready') {
clearInterval(iid);
resolve(this.synchronizer_);
}
if (this.initState_ == 'error') {
clearInterval(iid);
reject(new Error('Could not initialise synchroniser'));
}
}, 1000);
});
} else {
this.initState_ = 'started';
try {
this.synchronizer_ = await this.initSynchronizer();
this.synchronizer_.setLogger(this.logger());
this.synchronizer_.dispatch = BaseSyncTarget.dispatch;
this.initState_ = 'ready';
return this.synchronizer_;
} catch (error) {
this.initState_ = 'error';
throw error;
}
}
}
async syncStarted() {
if (!this.synchronizer_) return false;
if (!this.isAuthenticated()) return false;
const sync = await this.synchronizer();
return sync.state() != 'idle';
}
}
module.exports = BaseSyncTarget;

View File

@ -0,0 +1,23 @@
const BaseSyncTarget = require('lib/BaseSyncTarget.js');
class SyncTarget1 extends BaseSyncTarget {
id() {
return 1;
}
name() {
return 'Memory';
}
label() {
return 'Memory';
}
isAuthenticated() {
return true;
}
}
module.exports = SyncTarget1;

View File

@ -0,0 +1,80 @@
const BaseSyncTarget = require('lib/BaseSyncTarget.js');
const { _ } = require('lib/locale.js');
const { OneDriveApi } = require('lib/onedrive-api.js');
const { Setting } = require('lib/models/setting.js');
const { parameters } = require('lib/parameters.js');
const { FileApi } = require('lib/file-api.js');
const { Synchronizer } = require('lib/synchronizer.js');
const { FileApiDriverOneDrive } = require('lib/file-api-driver-onedrive.js');
class SyncTarget3 extends BaseSyncTarget {
constructor(db) {
super();
this.oneDriveApi_ = null;
}
id() {
return 3;
}
name() {
return 'OneDrive';
}
label() {
return _('OneDrive');
}
isAuthenticated() {
return this.oneDriveApi_ && this.oneDriveApi_.auth();
}
oneDriveApi() {
if (this.oneDriveApi_) return this.oneDriveApi_;
const isPublic = Setting.value('appType') != 'cli';
this.oneDriveApi_ = new OneDriveApi(parameters().oneDrive.id, parameters().oneDrive.secret, isPublic);
this.oneDriveApi_.setLogger(this.logger());
this.oneDriveApi_.on('authRefreshed', (a) => {
this.logger().info('Saving updated OneDrive auth.');
Setting.setValue('sync.' + this.id() + '.auth', a ? JSON.stringify(a) : null);
});
let auth = Setting.value('sync.' + this.id() + '.auth');
if (auth) {
try {
auth = JSON.parse(auth);
} catch (error) {
this.logger().warn('Could not parse OneDrive auth token');
this.logger().warn(error);
auth = null;
}
this.oneDriveApi_.setAuth(auth);
}
return this.oneDriveApi_;
}
async initSynchronizer() {
let fileApi = null;
if (!this.oneDriveApi().auth()) throw new Error('User is not authentified');
const appDir = await this.oneDriveApi().appDirectory();
fileApi = new FileApi(appDir, new FileApiDriverOneDrive(this.oneDriveApi()));
fileApi.setSyncTargetId(this.id());
fileApi.setLogger(this.logger());
return new Synchronizer(this.db(), fileApi, Setting.value('appType'));
}
isAuthenticated() {
return true;
}
}
module.exports = SyncTarget3;

View File

@ -72,16 +72,19 @@ class Setting extends BaseModel {
}); });
} }
static dispatchUpdateAll() { static toPlainObject() {
const keys = this.keys(); const keys = this.keys();
let keyToValues = {}; let keyToValues = {};
for (let i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
keyToValues[keys[i]] = this.value(keys[i]); keyToValues[keys[i]] = this.value(keys[i]);
} }
return keyToValues;
}
static dispatchUpdateAll() {
this.dispatch({ this.dispatch({
type: 'SETTING_UPDATE_ALL', type: 'SETTING_UPDATE_ALL',
settings: keyToValues, settings: this.toPlainObject(),
}); });
} }
@ -326,6 +329,7 @@ class Setting extends BaseModel {
Setting.SYNC_TARGET_MEMORY = 1; Setting.SYNC_TARGET_MEMORY = 1;
Setting.SYNC_TARGET_FILESYSTEM = 2; Setting.SYNC_TARGET_FILESYSTEM = 2;
Setting.SYNC_TARGET_ONEDRIVE = 3; Setting.SYNC_TARGET_ONEDRIVE = 3;
//Setting.SYNC_TARGET_ONEDRIVE_DEV = 4;
Setting.TYPE_INT = 1; Setting.TYPE_INT = 1;
Setting.TYPE_STRING = 2; Setting.TYPE_STRING = 2;
@ -341,11 +345,13 @@ Setting.metadata_ = {
'firstStart': { value: true, type: Setting.TYPE_BOOL, public: false }, 'firstStart': { value: true, type: Setting.TYPE_BOOL, public: false },
'sync.2.path': { value: '', type: Setting.TYPE_STRING, public: true, appTypes: ['cli'], label: () => _('File system synchronisation target directory'), description: () => _('The path to synchronise with when file system synchronisation is enabled. See `sync.target`.') }, 'sync.2.path': { value: '', type: Setting.TYPE_STRING, public: true, appTypes: ['cli'], label: () => _('File system synchronisation target directory'), description: () => _('The path to synchronise with when file system synchronisation is enabled. See `sync.target`.') },
'sync.3.auth': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.3.auth': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.4.auth': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.target': { value: Setting.SYNC_TARGET_ONEDRIVE, type: Setting.TYPE_INT, isEnum: true, public: true, label: () => _('Synchronisation target'), description: () => _('The target to synchonise to. If synchronising with the file system, set `sync.2.path` to specify the target directory.'), options: () => { 'sync.target': { value: Setting.SYNC_TARGET_ONEDRIVE, type: Setting.TYPE_INT, isEnum: true, public: true, label: () => _('Synchronisation target'), description: () => _('The target to synchonise to. If synchronising with the file system, set `sync.2.path` to specify the target directory.'), options: () => {
let output = {}; let output = {};
output[Setting.SYNC_TARGET_MEMORY] = 'Memory'; output[Setting.SYNC_TARGET_MEMORY] = 'Memory';
output[Setting.SYNC_TARGET_FILESYSTEM] = _('File system'); output[Setting.SYNC_TARGET_FILESYSTEM] = _('File system');
output[Setting.SYNC_TARGET_ONEDRIVE] = _('OneDrive'); output[Setting.SYNC_TARGET_ONEDRIVE] = _('OneDrive');
//output[Setting.SYNC_TARGET_ONEDRIVE_DEV] = _('OneDrive (Testing Only)');
return output; return output;
}}, }},
'sync.1.context': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.1.context': { value: '', type: Setting.TYPE_STRING, public: false },

View File

@ -1,10 +1,11 @@
const { Logger } = require('lib/logger.js'); const { Logger } = require('lib/logger.js');
const { Setting } = require('lib/models/setting.js'); const { Setting } = require('lib/models/setting.js');
const { OneDriveApi } = require('lib/onedrive-api.js');
const { parameters } = require('lib/parameters.js'); const { parameters } = require('lib/parameters.js');
const { FileApi } = require('lib/file-api.js'); const { FileApi } = require('lib/file-api.js');
const { Database } = require('lib/database.js'); const { Database } = require('lib/database.js');
const { Synchronizer } = require('lib/synchronizer.js'); const { Synchronizer } = require('lib/synchronizer.js');
const SyncTarget1 = require('lib/SyncTarget1.js');
const SyncTarget3 = require('lib/SyncTarget3.js');
const { FileApiDriverOneDrive } = require('lib/file-api-driver-onedrive.js'); const { FileApiDriverOneDrive } = require('lib/file-api-driver-onedrive.js');
const { shim } = require('lib/shim.js'); const { shim } = require('lib/shim.js');
const { time } = require('lib/time-utils.js'); const { time } = require('lib/time-utils.js');
@ -14,6 +15,12 @@ const { _ } = require('lib/locale.js');
const reg = {}; const reg = {};
reg.initSynchronizerStates_ = {}; reg.initSynchronizerStates_ = {};
reg.syncTargetClasses_ = {
1: SyncTarget1,
// 2: SyncTarget2,
3: SyncTarget3,
};
reg.syncTargets_ = {};
reg.synchronizers_ = {}; reg.synchronizers_ = {};
reg.logger = () => { reg.logger = () => {
@ -29,71 +36,17 @@ reg.setLogger = (l) => {
reg.logger_ = l; reg.logger_ = l;
} }
reg.oneDriveApi = () => { reg.syncTarget = (syncTargetId = null) => {
if (reg.oneDriveApi_) return reg.oneDriveApi_; if (syncTargetId === null) syncTargetId = Setting.value('sync.target');
if (reg.syncTargets_[syncTargetId]) return reg.syncTargets_[syncTargetId];
const isPublic = Setting.value('appType') != 'cli'; const SyncTargetClass = reg.syncTargetClasses_[syncTargetId];
if (!reg.db()) throw new Error('Cannot initialize sync without a db');
reg.oneDriveApi_ = new OneDriveApi(parameters().oneDrive.id, parameters().oneDrive.secret, isPublic); const target = new SyncTargetClass(reg.db());
reg.oneDriveApi_.setLogger(reg.logger()); target.setLogger(reg.logger());
reg.syncTargets_[syncTargetId] = target;
reg.oneDriveApi_.on('authRefreshed', (a) => { return target;
reg.logger().info('Saving updated OneDrive auth.');
Setting.setValue('sync.3.auth', a ? JSON.stringify(a) : null);
});
let auth = Setting.value('sync.3.auth');
if (auth) {
try {
auth = JSON.parse(auth);
} catch (error) {
reg.logger().warn('Could not parse OneDrive auth token');
reg.logger().warn(error);
auth = null;
}
reg.oneDriveApi_.setAuth(auth);
}
return reg.oneDriveApi_;
}
reg.initSynchronizer_ = async (syncTargetId) => {
if (!reg.db()) throw new Error('Cannot initialize synchronizer: db not initialized');
let fileApi = null;
if (syncTargetId == Setting.SYNC_TARGET_ONEDRIVE) {
if (!reg.oneDriveApi().auth()) throw new Error('User is not authentified');
let appDir = await reg.oneDriveApi().appDirectory();
fileApi = new FileApi(appDir, new FileApiDriverOneDrive(reg.oneDriveApi()));
} else if (syncTargetId == Setting.SYNC_TARGET_MEMORY) {
fileApi = new FileApi('joplin', new FileApiDriverMemory());
} else if (syncTargetId == Setting.SYNC_TARGET_FILESYSTEM) {
let syncDir = Setting.value('sync.2.path');
if (!syncDir) throw new Error(_('Please set the "sync.2.path" config value to the desired synchronisation destination.'));
await shim.fs.mkdirp(syncDir, 0o755);
fileApi = new FileApi(syncDir, new shim.FileApiDriverLocal());
} else {
throw new Error('Unknown sync target: ' + syncTargetId);
}
fileApi.setSyncTargetId(syncTargetId);
fileApi.setLogger(reg.logger());
let sync = new Synchronizer(reg.db(), fileApi, Setting.value('appType'));
sync.setLogger(reg.logger());
sync.dispatch = reg.dispatch;
return sync;
} }
reg.synchronizer = async (syncTargetId) => { reg.synchronizer = async (syncTargetId) => {
@ -130,11 +83,7 @@ reg.synchronizer = async (syncTargetId) => {
} }
reg.syncHasAuth = (syncTargetId) => { reg.syncHasAuth = (syncTargetId) => {
if (syncTargetId == Setting.SYNC_TARGET_ONEDRIVE && !reg.oneDriveApi().auth()) { return reg.syncTargets(syncTargetId).isAuthenticated();
return false;
}
return true;
} }
reg.scheduleSync = async (delay = null) => { reg.scheduleSync = async (delay = null) => {
@ -164,7 +113,7 @@ reg.scheduleSync = async (delay = null) => {
} }
try { try {
const sync = await reg.synchronizer(syncTargetId); const sync = await reg.syncTarget(syncTargetId).synchronizer();
const contextKey = 'sync.' + syncTargetId + '.context'; const contextKey = 'sync.' + syncTargetId + '.context';
let context = Setting.value(contextKey); let context = Setting.value(contextKey);
@ -195,11 +144,7 @@ reg.scheduleSync = async (delay = null) => {
} }
reg.syncStarted = async () => { reg.syncStarted = async () => {
const syncTarget = Setting.value('sync.target'); return reg.syncTarget().syncStarted();
if (!reg.synchronizers_[syncTarget]) return false;
if (!reg.syncHasAuth(syncTarget)) return false;
const sync = await reg.synchronizer(syncTarget);
return sync.state() != 'idle';
} }
reg.setupRecurrentSync = () => { reg.setupRecurrentSync = () => {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long