1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-15 09:04:04 +02:00
joplin/ReactNativeClient/lib/models/Setting.js

657 lines
29 KiB
JavaScript
Raw Normal View History

2017-12-14 20:12:14 +02:00
const BaseModel = require('lib/BaseModel.js');
const { Database } = require('lib/database.js');
const { Logger } = require('lib/logger.js');
const SyncTargetRegistry = require('lib/SyncTargetRegistry.js');
const { time } = require('lib/time-utils.js');
const { sprintf } = require('sprintf-js');
2018-02-21 21:58:28 +02:00
const ObjectUtils = require('lib/ObjectUtils');
const { toTitleCase } = require('lib/string-utils.js');
const { rtrimSlashes } = require('lib/path-utils.js');
const { _, supportedLocalesToLanguages, defaultLocale } = require('lib/locale.js');
const { shim } = require('lib/shim');
2017-05-12 22:17:23 +02:00
class Setting extends BaseModel {
static tableName() {
return 'settings';
}
2017-07-03 21:50:45 +02:00
static modelType() {
return BaseModel.TYPE_SETTING;
2017-06-19 21:26:27 +02:00
}
static metadata() {
if (this.metadata_) return this.metadata_;
const platform = shim.platformName();
2019-04-18 15:59:17 +02:00
const emptyDirWarning = _('Attention: If you change this location, make sure you copy all your content to it before syncing, otherwise all files will be removed! See the FAQ for more details: %s', 'https://joplinapp.org/faq/');
// A "public" setting means that it will show up in the various config screens (or config command for the CLI tool), however
// if if private a setting might still be handled and modified by the app. For instance, the settings related to sorting notes are not
// public for the mobile and desktop apps because they are handled separately in menus.
this.metadata_ = {
'activeFolderId': { value: '', type: Setting.TYPE_STRING, public: false },
'firstStart': { value: true, type: Setting.TYPE_BOOL, public: false },
'locale': { value: defaultLocale(), type: Setting.TYPE_STRING, isEnum: true, public: true, label: () => _('Language'), options: () => {
2018-02-21 21:58:28 +02:00
return ObjectUtils.sortByValue(supportedLocalesToLanguages());
}},
'dateFormat': { value: Setting.DATE_FORMAT_1, type: Setting.TYPE_STRING, isEnum: true, public: true, label: () => _('Date format'), options: () => {
let options = {}
const now = (new Date('2017-01-30T12:00:00')).getTime();
options[Setting.DATE_FORMAT_1] = time.formatMsToLocal(now, Setting.DATE_FORMAT_1);
options[Setting.DATE_FORMAT_2] = time.formatMsToLocal(now, Setting.DATE_FORMAT_2);
options[Setting.DATE_FORMAT_3] = time.formatMsToLocal(now, Setting.DATE_FORMAT_3);
options[Setting.DATE_FORMAT_4] = time.formatMsToLocal(now, Setting.DATE_FORMAT_4);
options[Setting.DATE_FORMAT_5] = time.formatMsToLocal(now, Setting.DATE_FORMAT_5);
options[Setting.DATE_FORMAT_6] = time.formatMsToLocal(now, Setting.DATE_FORMAT_6);
return options;
}},
'timeFormat': { value: Setting.TIME_FORMAT_1, type: Setting.TYPE_STRING, isEnum: true, public: true, label: () => _('Time format'), options: () => {
let options = {}
const now = (new Date('2017-01-30T20:30:00')).getTime();
options[Setting.TIME_FORMAT_1] = time.formatMsToLocal(now, Setting.TIME_FORMAT_1);
options[Setting.TIME_FORMAT_2] = time.formatMsToLocal(now, Setting.TIME_FORMAT_2);
return options;
}},
'theme': { value: Setting.THEME_LIGHT, type: Setting.TYPE_INT, public: true, appTypes: ['mobile', 'desktop'], isEnum: true, label: () => _('Theme'), section: 'appearance', options: () => {
let output = {};
output[Setting.THEME_LIGHT] = _('Light');
output[Setting.THEME_DARK] = _('Dark');
return output;
}},
'uncompletedTodosOnTop': { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, appTypes: ['cli'], label: () => _('Uncompleted to-dos on top') },
'showCompletedTodos': { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, appTypes: ['cli'], label: () => _('Show completed to-dos') },
'notes.sortOrder.field': { value: 'user_updated_time', type: Setting.TYPE_STRING, section: 'note', isEnum: true, public: true, appTypes: ['cli'], label: () => _('Sort notes by'), options: () => {
const Note = require('lib/models/Note');
const noteSortFields = ['user_updated_time', 'user_created_time', 'title'];
const options = {};
for (let i = 0; i < noteSortFields.length; i++) {
options[noteSortFields[i]] = toTitleCase(Note.fieldToLabel(noteSortFields[i]));
}
return options;
}},
'notes.sortOrder.reverse': { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, label: () => _('Reverse sort order'), appTypes: ['cli'] },
'folders.sortOrder.field': { value: 'title', type: Setting.TYPE_STRING, isEnum: true, public: true, appTypes: ['cli'], label: () => _('Sort notebooks by'), options: () => {
const Folder = require('lib/models/Folder');
const folderSortFields = ['title', 'last_note_user_updated_time'];
const options = {};
for (let i = 0; i < folderSortFields.length; i++) {
options[folderSortFields[i]] = toTitleCase(Folder.fieldToLabel(folderSortFields[i]));
}
return options;
}},
'folders.sortOrder.reverse': { value: false, type: Setting.TYPE_BOOL, public: true, label: () => _('Reverse sort order'), appTypes: ['cli'] },
'trackLocation': { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, label: () => _('Save geo-location with notes') },
'newTodoFocus': { value: 'title', type: Setting.TYPE_STRING, section: 'note', isEnum: true, public: true, appTypes: ['desktop'], label: () => _('When creating a new to-do:'), options: () => {
return {
'title': _('Focus title'),
'body': _('Focus body'),
};
}},
'newNoteFocus': { value: 'body', type: Setting.TYPE_STRING, section: 'note', isEnum: true, public: true, appTypes: ['desktop'], label: () => _('When creating a new note:'), options: () => {
return {
'title': _('Focus title'),
'body': _('Focus body'),
};
}},
'markdown.softbreaks': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable soft breaks') },
'markdown.plugin.katex': {value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable math expressions')},
'markdown.plugin.mark': {value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ==mark== syntax')},
'markdown.plugin.footnote': {value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable footnotes')},
'markdown.plugin.toc': {value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable table of contents extension')},
'markdown.plugin.sub': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ~sub~ syntax')},
'markdown.plugin.sup': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ^sup^ syntax')},
'markdown.plugin.deflist': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable deflist syntax')},
'markdown.plugin.abbr': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable abbreviation syntax')},
'markdown.plugin.emoji': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable markdown emoji')},
'markdown.plugin.insert': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ++insert++ syntax')},
'markdown.plugin.multitable': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable multimarkdown table extension')},
// Tray icon (called AppIndicator) doesn't work in Ubuntu
// http://www.webupd8.org/2017/04/fix-appindicator-not-working-for.html
// Might be fixed in Electron 18.x but no non-beta release yet. So for now
// by default we disable it on Linux.
'showTrayIcon': { value: platform !== 'linux', type: Setting.TYPE_BOOL, section:'application', public: true, appTypes: ['desktop'], label: () => _('Show tray icon'), description: () => {
2018-10-24 19:47:04 +02:00
return platform === 'linux' ? _('Note: Does not work in all desktop environments.') : _('This will allow Joplin to run in the background. It is recommended to enable this setting so that your notes are constantly being synchronised, thus reducing the number of conflicts.');
}},
'startMinimized': { value: false, type: Setting.TYPE_BOOL, section:'application', public: true, appTypes: ['desktop'], label: () => _('Start application minimised in the tray icon') },
'collapsedFolderIds': { value: [], type: Setting.TYPE_ARRAY, public: false },
'db.ftsEnabled': { value: -1, type: Setting.TYPE_INT, public: false },
2017-12-12 23:58:57 +02:00
'encryption.enabled': { value: false, type: Setting.TYPE_BOOL, public: false },
'encryption.activeMasterKeyId': { value: '', type: Setting.TYPE_STRING, public: false },
'encryption.passwordCache': { value: {}, type: Setting.TYPE_OBJECT, public: false, secure: true },
'style.zoom': {value: 100, type: Setting.TYPE_INT, public: true, appTypes: ['desktop'], section: 'appearance', label: () => _('Global zoom percentage'), minimum: 50, maximum: 500, step: 10},
'style.editor.fontSize': {value: 13, type: Setting.TYPE_INT, public: true, appTypes: ['desktop'], section: 'appearance', label: () => _('Editor font size'), minimum: 4, maximum: 50, step: 1},
'style.editor.fontFamily': {value: "", type: Setting.TYPE_STRING, public: true, appTypes: ['desktop'], section: 'appearance', label: () => _('Editor font family'), description: () => _('This must be *monospace* font or it will not work properly. If the font is incorrect or empty, it will default to a generic monospace font.')},
'style.sidebar.width': {value: 150, minimum: 80, maximum: 400, type: Setting.TYPE_INT, public: false, appTypes: ['desktop'] },
'style.noteList.width': {value: 150, minimum: 80, maximum: 400, type: Setting.TYPE_INT, public: false, appTypes: ['desktop'] },
'autoUpdateEnabled': { value: true, type: Setting.TYPE_BOOL, section:'application', public: true, appTypes: ['desktop'], label: () => _('Automatically update the application') },
2019-04-18 15:59:17 +02:00
'autoUpdate.includePreReleases': { value: false, type: Setting.TYPE_BOOL, section:'application', public: true, appTypes: ['desktop'], label: () => _('Get pre-releases when checking for updates'), description: () => _('See the pre-release page for more details: %s', 'https://joplinapp.org/prereleases') },
'clipperServer.autoStart': { value: false, type: Setting.TYPE_BOOL, public: false },
'sync.interval': { value: 300, type: Setting.TYPE_INT, section:'sync', isEnum: true, public: true, label: () => _('Synchronisation interval'), options: () => {
return {
0: _('Disabled'),
300: _('%d minutes', 5),
600: _('%d minutes', 10),
1800: _('%d minutes', 30),
3600: _('%d hour', 1),
43200: _('%d hours', 12),
86400: _('%d hours', 24),
};
}},
'noteVisiblePanes': { value: ['editor', 'viewer'], type: Setting.TYPE_ARRAY, public: false, appTypes: ['desktop'] },
'sidebarVisibility': { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] },
'tagHeaderIsExpanded': { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] },
'folderHeaderIsExpanded': { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] },
'editor': { value: '', type: Setting.TYPE_STRING, subType: 'file_path_and_args', public: true, appTypes: ['cli', 'desktop'], label: () => _('Text editor command'), description: () => _('The editor command (may include arguments) that will be used to open a note. If none is provided it will try to auto-detect the default editor.') },
'showAdvancedOptions': { value: false, type: Setting.TYPE_BOOL, public: true, appTypes: ['mobile' ], label: () => _('Show advanced options') },
'sync.target': { value: SyncTargetRegistry.nameToId('dropbox'), type: Setting.TYPE_INT, isEnum: true, public: true, section:'sync', label: () => _('Synchronisation target'), description: (appType) => { return appType !== 'cli' ? null : _('The target to synchonise to. Each sync target may have additional parameters which are named as `sync.NUM.NAME` (all documented below).') }, options: () => {
return SyncTargetRegistry.idAndLabelPlainObject();
}},
'sync.resourceDownloadMode': { value: 'always', type: Setting.TYPE_STRING, section: 'sync', public: true, isEnum: true, appTypes: ['mobile', 'desktop'], label: () => _('Attachment download behaviour'), description: () => _('In "Manual" mode, attachments are downloaded only when you click on them. In "Auto", they are downloaded when you open the note. In "Always", all the attachments are downloaded whether you open the note or not.'), options: () => {
return {
'always': _('Always'),
'manual': _('Manual'),
'auto': _('Auto'),
};
}},
'sync.maxConcurrentConnections': {value: 5, type: Setting.TYPE_INT, public: true, section: 'sync', label: () => _('Max concurrent connections'), minimum: 1, maximum: 20, step: 1},
'sync.2.path': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => {
try {
return settings['sync.target'] == SyncTargetRegistry.nameToId('filesystem')
} catch (error) {
return false;
}
}, filter: (value) => {
return value ? rtrimSlashes(value) : '';
}, public: true, label: () => _('Directory to synchronise with (absolute path)'), description: () => emptyDirWarning },
'sync.5.path': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('nextcloud') }, public: true, label: () => _('Nextcloud WebDAV URL'), description: () => emptyDirWarning },
'sync.5.username': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('nextcloud') }, public: true, label: () => _('Nextcloud username') },
'sync.5.password': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('nextcloud') }, public: true, label: () => _('Nextcloud password'), secure: true },
'sync.6.path': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('webdav') }, public: true, label: () => _('WebDAV URL'), description: () => emptyDirWarning },
'sync.6.username': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('webdav') }, public: true, label: () => _('WebDAV username') },
'sync.6.password': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('webdav') }, public: true, label: () => _('WebDAV password'), secure: true },
'sync.3.auth': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.4.auth': { value: '', type: Setting.TYPE_STRING, public: false },
2018-03-26 19:33:55 +02:00
'sync.7.auth': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.1.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.2.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.3.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.4.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.5.context': { value: '', type: Setting.TYPE_STRING, public: false },
'sync.6.context': { value: '', type: Setting.TYPE_STRING, public: false },
2018-03-26 19:33:55 +02:00
'sync.7.context': { value: '', type: Setting.TYPE_STRING, public: false },
'net.customCertificates': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return [SyncTargetRegistry.nameToId('nextcloud'), SyncTargetRegistry.nameToId('webdav')].indexOf(settings['sync.target']) >= 0 }, public: true, appTypes: ['desktop', 'cli'], label: () => _('Custom TLS certificates'), description: () => _('Comma-separated list of paths to directories to load the certificates from, or path to individual cert files. For example: /my/cert_dir, /other/custom.pem. Note that if you make changes to the TLS settings, you must save your changes before clicking on "Check synchronisation configuration".') },
'net.ignoreTlsErrors': { value: false, type: Setting.TYPE_BOOL, section:'sync', show: (settings) => { return [SyncTargetRegistry.nameToId('nextcloud'), SyncTargetRegistry.nameToId('webdav')].indexOf(settings['sync.target']) >= 0 }, public: true, appTypes: ['desktop', 'cli'], label: () => _('Ignore TLS certificate errors') },
2018-09-28 20:24:57 +02:00
'api.token': { value: null, type: Setting.TYPE_STRING, public: false },
'resourceService.lastProcessedChangeId': { value: 0, type: Setting.TYPE_INT, public: false },
2018-12-10 20:54:46 +02:00
'searchEngine.lastProcessedChangeId': { value: 0, type: Setting.TYPE_INT, public: false },
'revisionService.lastProcessedChangeId': { value: 0, type: Setting.TYPE_INT, public: false },
2019-01-13 18:05:07 +02:00
'searchEngine.initialIndexingDone': { value: false, type: Setting.TYPE_BOOL, public: false },
'revisionService.enabled': { section: 'revisionService', value: true, type: Setting.TYPE_BOOL, public: true, label: () => _('Enable note history') },
'revisionService.ttlDays': { section: 'revisionService', value: 90, type: Setting.TYPE_INT, public: true, minimum: 1, maximum: 365 * 2, step: 1, unitLabel: (value = null) => { return value === null ? _('days') : _('%d days', value) }, label: () => _('Keep note history for') },
'revisionService.intervalBetweenRevisions': { section: 'revisionService', value: 1000 * 60 * 10, type: Setting.TYPE_INT, public: false },
'revisionService.oldNoteInterval': { section: 'revisionService', value: 1000 * 60 * 60 * 24 * 7, type: Setting.TYPE_INT, public: false },
'welcome.wasBuilt': { value: false, type: Setting.TYPE_BOOL, public: false },
'welcome.enabled': { value: true, type: Setting.TYPE_BOOL, public: false },
};
return this.metadata_;
}
2017-07-24 20:58:11 +02:00
static settingMetadata(key) {
const metadata = this.metadata();
if (!(key in metadata)) throw new Error('Unknown key: ' + key);
let output = Object.assign({}, metadata[key]);
2017-05-12 22:17:23 +02:00
output.key = key;
return output;
}
2017-10-30 02:29:10 +02:00
static keyExists(key) {
return key in this.metadata();
2017-10-30 02:29:10 +02:00
}
static keyDescription(key, appType = null) {
const md = this.settingMetadata(key);
if (!md.description) return null;
return md.description(appType);
}
2017-08-22 19:57:35 +02:00
static keys(publicOnly = false, appType = null) {
if (!this.keys_) {
const metadata = this.metadata();
2017-08-22 19:57:35 +02:00
this.keys_ = [];
for (let n in metadata) {
if (!metadata.hasOwnProperty(n)) continue;
2017-08-22 19:57:35 +02:00
this.keys_.push(n);
}
2017-05-16 23:46:21 +02:00
}
2017-08-22 19:57:35 +02:00
if (appType || publicOnly) {
let output = [];
for (let i = 0; i < this.keys_.length; i++) {
const md = this.settingMetadata(this.keys_[i]);
if (publicOnly && !md.public) continue;
if (appType && md.appTypes && md.appTypes.indexOf(appType) < 0) continue;
output.push(md.key);
}
return output;
} else {
return this.keys_;
2017-06-27 22:16:03 +02:00
}
}
2017-07-31 22:51:24 +02:00
static isPublic(key) {
2017-08-22 19:57:35 +02:00
return this.keys(true).indexOf(key) >= 0;
2017-07-31 22:51:24 +02:00
}
2017-05-12 22:17:23 +02:00
static load() {
this.cancelScheduleSave();
2017-05-12 22:17:23 +02:00
this.cache_ = [];
2017-06-19 21:26:27 +02:00
return this.modelSelectAll('SELECT * FROM settings').then((rows) => {
this.cache_ = [];
2017-07-24 22:36:49 +02:00
for (let i = 0; i < rows.length; i++) {
let c = rows[i];
2017-10-30 02:29:10 +02:00
if (!this.keyExists(c.key)) continue;
2017-07-25 23:55:26 +02:00
c.value = this.formatValue(c.key, c.value);
c.value = this.filterValue(c.key, c.value);
2017-07-25 23:55:26 +02:00
this.cache_.push(c);
2017-07-24 22:36:49 +02:00
}
2017-10-21 18:53:43 +02:00
this.dispatchUpdateAll();
});
}
static toPlainObject() {
2017-10-21 18:53:43 +02:00
const keys = this.keys();
let keyToValues = {};
for (let i = 0; i < keys.length; i++) {
keyToValues[keys[i]] = this.value(keys[i]);
}
return keyToValues;
}
static dispatchUpdateAll() {
2017-10-21 18:53:43 +02:00
this.dispatch({
2017-11-08 23:22:24 +02:00
type: 'SETTING_UPDATE_ALL',
settings: this.toPlainObject(),
2017-05-12 22:17:23 +02:00
});
}
2017-06-24 20:51:43 +02:00
static setConstant(key, value) {
2017-07-06 23:30:45 +02:00
if (!(key in this.constants_)) throw new Error('Unknown constant key: ' + key);
2017-06-24 20:51:43 +02:00
this.constants_[key] = value;
}
2017-05-12 22:17:23 +02:00
static setValue(key, value) {
2017-06-19 20:58:49 +02:00
if (!this.cache_) throw new Error('Settings have not been initialized!');
2017-07-31 22:51:24 +02:00
value = this.formatValue(key, value);
value = this.filterValue(key, value);
2017-05-12 22:17:23 +02:00
for (let i = 0; i < this.cache_.length; i++) {
2017-07-24 20:58:11 +02:00
let c = this.cache_[i];
if (c.key == key) {
const md = this.settingMetadata(key);
2017-07-25 23:55:26 +02:00
if (md.isEnum === true) {
2017-07-24 20:58:11 +02:00
if (!this.isAllowedEnumOption(key, value)) {
throw new Error(_('Invalid option value: "%s". Possible values are: %s.', value, this.enumOptionsDoc(key)));
}
}
if (c.value === value) return;
2017-07-25 23:55:26 +02:00
// Don't log this to prevent sensitive info (passwords, auth tokens...) to end up in logs
// this.logger().info('Setting: ' + key + ' = ' + c.value + ' => ' + value);
2017-07-25 23:55:26 +02:00
2019-02-16 03:12:43 +02:00
if (('minimum' in md) && value < md.minimum) value = md.minimum;
if (('maximum' in md) && value > md.maximum) value = md.maximum;
2017-11-14 20:02:58 +02:00
c.value = value;
this.dispatch({
2017-11-08 23:22:24 +02:00
type: 'SETTING_UPDATE_ONE',
key: key,
value: c.value,
});
this.scheduleSave();
2017-05-12 22:17:23 +02:00
return;
}
}
2017-07-25 23:55:26 +02:00
this.cache_.push({
key: key,
value: this.formatValue(key, value),
});
this.dispatch({
2017-11-08 23:22:24 +02:00
type: 'SETTING_UPDATE_ONE',
key: key,
value: this.formatValue(key, value),
});
this.scheduleSave();
}
static setObjectKey(settingKey, objectKey, value) {
let o = this.value(settingKey);
if (typeof o !== 'object') o = {};
o[objectKey] = value;
this.setValue(settingKey, o);
}
static deleteObjectKey(settingKey, objectKey) {
const o = this.value(settingKey);
if (typeof o !== 'object') return;
delete o[objectKey];
this.setValue(settingKey, o);
}
static valueToString(key, value) {
const md = this.settingMetadata(key);
value = this.formatValue(key, value);
if (md.type == Setting.TYPE_INT) return value.toFixed(0);
if (md.type == Setting.TYPE_BOOL) return value ? '1' : '0';
if (md.type == Setting.TYPE_ARRAY) return value ? JSON.stringify(value) : '[]';
2017-11-14 20:02:58 +02:00
if (md.type == Setting.TYPE_OBJECT) return value ? JSON.stringify(value) : '{}';
if (md.type == Setting.TYPE_STRING) return value ? value + '' : '';
throw new Error('Unhandled value type: ' + md.type);
2017-05-12 22:17:23 +02:00
}
static filterValue(key, value) {
const md = this.settingMetadata(key);
return md.filter ? md.filter(value) : value;
}
2017-07-25 23:55:26 +02:00
static formatValue(key, value) {
const md = this.settingMetadata(key);
2018-01-07 21:29:57 +02:00
if (md.type == Setting.TYPE_INT) return !value ? 0 : Math.floor(Number(value));
if (md.type == Setting.TYPE_BOOL) {
2017-07-26 23:07:27 +02:00
if (typeof value === 'string') {
value = value.toLowerCase();
if (value === 'true') return true;
if (value === 'false') return false;
value = Number(value);
}
return !!value;
}
if (md.type === Setting.TYPE_ARRAY) {
2017-11-14 20:02:58 +02:00
if (!value) return [];
if (Array.isArray(value)) return value;
if (typeof value === 'string') return JSON.parse(value);
return [];
}
2017-11-14 20:02:58 +02:00
if (md.type === Setting.TYPE_OBJECT) {
if (!value) return {};
if (typeof value === 'object') return value;
if (typeof value === 'string') return JSON.parse(value);
return {};
}
if (md.type === Setting.TYPE_STRING) {
if (!value) return '';
return value + '';
}
throw new Error('Unhandled value type: ' + md.type);
2017-07-25 20:57:06 +02:00
}
2017-05-12 22:17:23 +02:00
static value(key) {
// Need to copy arrays and objects since in setValue(), the old value and new one is compared
// with strict equality and the value is updated only if changed. However if the caller acquire
// and object and change a key, the objects will be detected as equal. By returning a copy
// we avoid this problem.
function copyIfNeeded(value) {
if (value === null || value === undefined) return value;
if (Array.isArray(value)) return value.slice();
if (typeof value === 'object') return Object.assign({}, value);
return value;
}
if (key in this.constants_) {
2017-11-20 00:08:58 +02:00
const v = this.constants_[key];
const output = typeof v === 'function' ? v() : v;
if (output == 'SET_ME') throw new Error('Setting constant has not been set: ' + key);
return output;
}
2017-06-24 20:51:43 +02:00
2017-06-19 20:58:49 +02:00
if (!this.cache_) throw new Error('Settings have not been initialized!');
2017-05-12 22:17:23 +02:00
for (let i = 0; i < this.cache_.length; i++) {
if (this.cache_[i].key == key) {
return copyIfNeeded(this.cache_[i].value);
2017-05-12 22:17:23 +02:00
}
}
2017-07-25 23:55:26 +02:00
const md = this.settingMetadata(key);
return copyIfNeeded(md.value);
2017-05-12 22:17:23 +02:00
}
2017-07-24 20:58:11 +02:00
static isEnum(key) {
const md = this.settingMetadata(key);
2017-07-25 23:55:26 +02:00
return md.isEnum === true;
2017-07-24 20:58:11 +02:00
}
static enumOptionValues(key) {
const options = this.enumOptions(key);
let output = [];
for (let n in options) {
if (!options.hasOwnProperty(n)) continue;
output.push(n);
}
return output;
}
static enumOptionLabel(key, value) {
const options = this.enumOptions(key);
for (let n in options) {
if (n == value) return options[n];
}
return '';
}
static enumOptions(key) {
const metadata = this.metadata();
if (!metadata[key]) throw new Error('Unknown key: ' + key);
if (!metadata[key].options) throw new Error('No options for: ' + key);
return metadata[key].options();
2017-07-24 20:58:11 +02:00
}
static enumOptionsDoc(key, templateString = null) {
if (templateString === null) templateString = '%s: %s';
2017-07-24 20:58:11 +02:00
const options = this.enumOptions(key);
let output = [];
for (let n in options) {
if (!options.hasOwnProperty(n)) continue;
output.push(sprintf(templateString, n, options[n]));
2017-07-24 20:58:11 +02:00
}
return output.join(', ');
}
static isAllowedEnumOption(key, value) {
const options = this.enumOptions(key);
return !!options[value];
}
// For example, if settings is:
// { sync.5.path: 'http://example', sync.5.username: 'testing' }
// and baseKey is 'sync.5', the function will return
// { path: 'http://example', username: 'testing' }
static subValues(baseKey, settings) {
2017-05-16 23:46:21 +02:00
let output = {};
for (let key in settings) {
if (!settings.hasOwnProperty(key)) continue;
if (key.indexOf(baseKey) === 0) {
const subKey = key.substr(baseKey.length + 1);
output[subKey] = settings[key];
2017-05-16 23:46:21 +02:00
}
}
return output;
}
static async saveAll() {
if (!this.saveTimeoutId_) return Promise.resolve();
2017-05-19 21:12:09 +02:00
2017-06-25 12:41:03 +02:00
this.logger().info('Saving settings...');
clearTimeout(this.saveTimeoutId_);
this.saveTimeoutId_ = null;
2017-05-19 21:12:09 +02:00
2017-06-11 23:11:14 +02:00
let queries = [];
queries.push('DELETE FROM settings');
for (let i = 0; i < this.cache_.length; i++) {
let s = Object.assign({}, this.cache_[i]);
s.value = this.valueToString(s.key, s.value);
queries.push(Database.insertQuery(this.tableName(), s));
2017-06-11 23:11:14 +02:00
}
await BaseModel.db().transactionExecBatch(queries);
this.logger().info('Settings have been saved.');
2017-05-19 21:12:09 +02:00
}
static scheduleSave() {
if (!Setting.autoSaveEnabled) return;
if (this.saveTimeoutId_) clearTimeout(this.saveTimeoutId_);
2017-05-19 21:12:09 +02:00
this.saveTimeoutId_ = setTimeout(() => {
2017-05-19 21:12:09 +02:00
this.saveAll();
2017-05-12 22:17:23 +02:00
}, 500);
}
static cancelScheduleSave() {
if (this.saveTimeoutId_) clearTimeout(this.saveTimeoutId_);
this.saveTimeoutId_ = null;
2017-06-19 21:26:27 +02:00
}
2017-07-23 20:26:50 +02:00
static publicSettings(appType) {
if (!appType) throw new Error('appType is required');
const metadata = this.metadata();
2017-07-23 20:26:50 +02:00
let output = {};
for (let key in metadata) {
if (!metadata.hasOwnProperty(key)) continue;
let s = Object.assign({}, metadata[key]);
2017-07-23 20:26:50 +02:00
if (!s.public) continue;
if (s.appTypes && s.appTypes.indexOf(appType) < 0) continue;
s.value = this.value(key);
output[key] = s;
}
return output;
}
static typeToString(typeId) {
if (typeId === Setting.TYPE_INT) return 'int';
if (typeId === Setting.TYPE_STRING) return 'string';
if (typeId === Setting.TYPE_BOOL) return 'bool';
if (typeId === Setting.TYPE_ARRAY) return 'array';
2017-11-14 20:02:58 +02:00
if (typeId === Setting.TYPE_OBJECT) return 'object';
}
static groupMetadatasBySections(metadatas) {
let sections = [];
const generalSection = { name: 'general', metadatas: [] };
const nameToSections = {};
nameToSections['general'] = generalSection;
sections.push(generalSection);
for (let i = 0; i < metadatas.length; i++) {
const md = metadatas[i];
if (!md.section) {
generalSection.metadatas.push(md);
} else {
if (!nameToSections[md.section]) {
nameToSections[md.section] = { name: md.section, metadatas: [] };
sections.push(nameToSections[md.section]);
}
nameToSections[md.section].metadatas.push(md);
}
}
return sections;
}
static sectionNameToLabel(name) {
if (name === 'general') return _('General');
if (name === 'sync') return _('Synchronisation');
if (name === 'appearance') return _('Appearance');
if (name === 'note') return _('Note');
if (name === 'plugins') return _('Plugins');
if (name === 'application') return _('Application');
if (name === 'revisionService') return _('Note History');
return name;
}
2019-02-23 17:53:14 +02:00
static appTypeToLabel(name) {
// Not translated for now because only used on Welcome notes (which are not translated)
if (name === 'cli') return 'CLI';
return name[0].toUpperCase() + name.substr(1).toLowerCase();
}
2017-05-12 22:17:23 +02:00
}
2017-07-25 23:55:26 +02:00
Setting.TYPE_INT = 1;
Setting.TYPE_STRING = 2;
Setting.TYPE_BOOL = 3;
Setting.TYPE_ARRAY = 4;
2017-11-14 20:02:58 +02:00
Setting.TYPE_OBJECT = 5;
2017-07-25 23:55:26 +02:00
2017-07-31 22:51:24 +02:00
Setting.THEME_LIGHT = 1;
Setting.THEME_DARK = 2;
Setting.DATE_FORMAT_1 = 'DD/MM/YYYY'
Setting.DATE_FORMAT_2 = 'DD/MM/YY';
Setting.DATE_FORMAT_3 = 'MM/DD/YYYY';
Setting.DATE_FORMAT_4 = 'MM/DD/YY';
Setting.DATE_FORMAT_5 = 'YYYY-MM-DD';
Setting.DATE_FORMAT_6 = 'DD.MM.YYYY';
Setting.TIME_FORMAT_1 = 'HH:mm';
Setting.TIME_FORMAT_2 = 'h:mm A';
2017-06-24 20:51:43 +02:00
// Contains constants that are set by the application and
// cannot be modified by the user:
Setting.constants_ = {
env: 'SET_ME',
isDemo: false,
appName: 'joplin',
appId: 'SET_ME', // Each app should set this identifier
appType: 'SET_ME', // 'cli' or 'mobile'
resourceDirName: '',
resourceDir: '',
profileDir: '',
tempDir: '',
openDevTools: false,
2017-06-24 20:51:43 +02:00
}
Setting.autoSaveEnabled = true;
module.exports = Setting;