You've already forked joplin
mirror of
https://github.com/laurent22/joplin.git
synced 2025-11-06 09:19:22 +02:00
Chore: Apply eslint rules
This commit is contained in:
@@ -33,7 +33,7 @@ class AlarmService {
|
||||
// Delete alarms that correspond to non-existent notes
|
||||
const alarmIds = await Alarm.alarmIdsWithoutNotes();
|
||||
for (let i = 0; i < alarmIds.length; i++) {
|
||||
this.logger().info('Clearing notification for non-existing note. Alarm ' + alarmIds[i]);
|
||||
this.logger().info(`Clearing notification for non-existing note. Alarm ${alarmIds[i]}`);
|
||||
await this.driver().clearNotification(alarmIds[i]);
|
||||
}
|
||||
await Alarm.batchDelete(alarmIds);
|
||||
@@ -74,7 +74,7 @@ class AlarmService {
|
||||
// if the app has just started the notifications need to be set again. so we do this below.
|
||||
if (!driver.hasPersistentNotifications() && !driver.notificationIsSet(alarm.id)) {
|
||||
const notification = await Alarm.makeNotification(alarm, note);
|
||||
this.logger().info('Scheduling (non-persistent) notification for note ' + note.id, notification);
|
||||
this.logger().info(`Scheduling (non-persistent) notification for note ${note.id}`, notification);
|
||||
driver.scheduleNotification(notification);
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ class AlarmService {
|
||||
}
|
||||
|
||||
if (clearAlarm) {
|
||||
this.logger().info('Clearing notification for note ' + noteId);
|
||||
this.logger().info(`Clearing notification for note ${noteId}`);
|
||||
await driver.clearNotification(alarm.id);
|
||||
await Alarm.delete(alarm.id);
|
||||
}
|
||||
@@ -98,7 +98,7 @@ class AlarmService {
|
||||
alarm = await Alarm.byNoteId(note.id);
|
||||
|
||||
const notification = await Alarm.makeNotification(alarm, note);
|
||||
this.logger().info('Scheduling notification for note ' + note.id, notification);
|
||||
this.logger().info(`Scheduling notification for note ${note.id}`, notification);
|
||||
await driver.scheduleNotification(notification);
|
||||
} catch (error) {
|
||||
this.logger().error('Could not update notification', error);
|
||||
|
||||
@@ -28,12 +28,12 @@ class AlarmServiceDriver {
|
||||
}
|
||||
|
||||
async clearNotification(id) {
|
||||
return this.PushNotificationHandler_().cancelLocalNotifications({ id: id + '' });
|
||||
return this.PushNotificationHandler_().cancelLocalNotifications({ id: `${id}` });
|
||||
}
|
||||
|
||||
async scheduleNotification(notification) {
|
||||
const config = {
|
||||
id: notification.id + '',
|
||||
id: `${notification.id}`,
|
||||
message: notification.title,
|
||||
date: notification.date,
|
||||
};
|
||||
|
||||
@@ -55,7 +55,7 @@ class AlarmServiceDriver {
|
||||
}
|
||||
|
||||
async clearNotification(id) {
|
||||
PushNotificationIOS.cancelLocalNotifications({ id: id + '' });
|
||||
PushNotificationIOS.cancelLocalNotifications({ id: `${id}` });
|
||||
}
|
||||
|
||||
async scheduleNotification(notification) {
|
||||
@@ -66,10 +66,10 @@ class AlarmServiceDriver {
|
||||
|
||||
// ID must be a string and userInfo must be supplied otherwise cancel won't work
|
||||
const iosNotification = {
|
||||
id: notification.id + '',
|
||||
id: `${notification.id}`,
|
||||
alertTitle: notification.title,
|
||||
fireDate: notification.date,
|
||||
userInfo: { id: notification.id + '' },
|
||||
userInfo: { id: `${notification.id}` },
|
||||
};
|
||||
|
||||
if ('body' in notification) iosNotification.alertBody = notification.body;
|
||||
|
||||
@@ -28,7 +28,7 @@ class AlarmServiceDriverNode {
|
||||
if (interval < 0) return;
|
||||
|
||||
if (isNaN(interval)) {
|
||||
throw new Error('Trying to create a notification from an invalid object: ' + JSON.stringify(notification));
|
||||
throw new Error(`Trying to create a notification from an invalid object: ${JSON.stringify(notification)}`);
|
||||
}
|
||||
|
||||
const timeoutId = setTimeout(() => {
|
||||
|
||||
@@ -83,7 +83,7 @@ class DecryptionWorker {
|
||||
}
|
||||
|
||||
async clearDisabledItem(typeId, itemId) {
|
||||
await this.kvStore().deleteValue('decrypt:' + typeId + ':' + itemId);
|
||||
await this.kvStore().deleteValue(`decrypt:${typeId}:${itemId}`);
|
||||
}
|
||||
|
||||
dispatchReport(report) {
|
||||
@@ -98,7 +98,7 @@ class DecryptionWorker {
|
||||
if (!('errorHandler' in options)) options.errorHandler = 'log';
|
||||
|
||||
if (this.state_ !== 'idle') {
|
||||
this.logger().debug('DecryptionWorker: cannot start because state is "' + this.state_ + '"');
|
||||
this.logger().debug(`DecryptionWorker: cannot start because state is "${this.state_}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ class DecryptionWorker {
|
||||
itemCount: items.length,
|
||||
});
|
||||
|
||||
const counterKey = 'decrypt:' + item.type_ + ':' + item.id;
|
||||
const counterKey = `decrypt:${item.type_}:${item.id}`;
|
||||
|
||||
const clearDecryptionCounter = async () => {
|
||||
await this.kvStore().deleteValue(counterKey);
|
||||
@@ -161,7 +161,7 @@ class DecryptionWorker {
|
||||
try {
|
||||
const decryptCounter = await this.kvStore().incValue(counterKey);
|
||||
if (decryptCounter > this.maxDecryptionAttempts_) {
|
||||
this.logger().warn('DecryptionWorker: ' + item.id + ' decryption has failed more than 2 times - skipping it');
|
||||
this.logger().warn(`DecryptionWorker: ${item.id} decryption has failed more than 2 times - skipping it`);
|
||||
excludedIds.push(item.id);
|
||||
continue;
|
||||
}
|
||||
@@ -205,7 +205,7 @@ class DecryptionWorker {
|
||||
}
|
||||
|
||||
if (options.errorHandler === 'log') {
|
||||
this.logger().warn('DecryptionWorker: error for: ' + item.id + ' (' + ItemClass.tableName() + ')', error, item);
|
||||
this.logger().warn(`DecryptionWorker: error for: ${item.id} (${ItemClass.tableName()})`, error, item);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
@@ -234,7 +234,7 @@ class DecryptionWorker {
|
||||
this.dispatchReport({ state: 'idle' });
|
||||
|
||||
if (downloadedButEncryptedBlobCount) {
|
||||
this.logger().info('DecryptionWorker: Some resources have been downloaded but are not decrypted yet. Scheduling another decryption. Resource count: ' + downloadedButEncryptedBlobCount);
|
||||
this.logger().info(`DecryptionWorker: Some resources have been downloaded but are not decrypted yet. Scheduling another decryption. Resource count: ${downloadedButEncryptedBlobCount}`);
|
||||
this.scheduleStart();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ class EncryptionService {
|
||||
const passwords = Setting.value('encryption.passwordCache');
|
||||
const activeMasterKeyId = Setting.value('encryption.activeMasterKeyId');
|
||||
|
||||
this.logger().info('Trying to load ' + masterKeys.length + ' master keys...');
|
||||
this.logger().info(`Trying to load ${masterKeys.length} master keys...`);
|
||||
|
||||
for (let i = 0; i < masterKeys.length; i++) {
|
||||
const mk = masterKeys[i];
|
||||
@@ -106,11 +106,11 @@ class EncryptionService {
|
||||
try {
|
||||
await this.loadMasterKey(mk, password, activeMasterKeyId === mk.id);
|
||||
} catch (error) {
|
||||
this.logger().warn('Cannot load master key ' + mk.id + '. Invalid password?', error);
|
||||
this.logger().warn(`Cannot load master key ${mk.id}. Invalid password?`, error);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger().info('Loaded master keys: ' + this.loadedMasterKeysCount());
|
||||
this.logger().info(`Loaded master keys: ${this.loadedMasterKeysCount()}`);
|
||||
}
|
||||
|
||||
loadedMasterKeysCount() {
|
||||
@@ -166,7 +166,7 @@ class EncryptionService {
|
||||
|
||||
loadedMasterKey(id) {
|
||||
if (!this.loadedMasterKeys_[id]) {
|
||||
const error = new Error('Master key is not loaded: ' + id);
|
||||
const error = new Error(`Master key is not loaded: ${id}`);
|
||||
error.code = 'masterKeyNotLoaded';
|
||||
error.masterKeyId = id;
|
||||
throw error;
|
||||
@@ -299,7 +299,7 @@ class EncryptionService {
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Unknown encryption method: ' + method);
|
||||
throw new Error(`Unknown encryption method: ${method}`);
|
||||
}
|
||||
|
||||
async decrypt(method, key, cipherText) {
|
||||
@@ -317,7 +317,7 @@ class EncryptionService {
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Unknown decryption method: ' + method);
|
||||
throw new Error(`Unknown decryption method: ${method}`);
|
||||
}
|
||||
|
||||
async encryptAbstract_(source, destination, options = null) {
|
||||
@@ -358,10 +358,10 @@ class EncryptionService {
|
||||
if (!options) options = {};
|
||||
|
||||
const identifier = await source.read(5);
|
||||
if (!this.isValidHeaderIdentifier(identifier)) throw new JoplinError('Invalid encryption identifier. Data is not actually encrypted? ID was: ' + identifier, 'invalidIdentifier');
|
||||
if (!this.isValidHeaderIdentifier(identifier)) throw new JoplinError(`Invalid encryption identifier. Data is not actually encrypted? ID was: ${identifier}`, 'invalidIdentifier');
|
||||
const mdSizeHex = await source.read(6);
|
||||
const mdSize = parseInt(mdSizeHex, 16);
|
||||
if (isNaN(mdSize) || !mdSize) throw new Error('Invalid header metadata size: ' + mdSizeHex);
|
||||
if (isNaN(mdSize) || !mdSize) throw new Error(`Invalid header metadata size: ${mdSizeHex}`);
|
||||
const md = await source.read(parseInt(mdSizeHex, 16));
|
||||
const header = this.decodeHeader_(identifier + mdSizeHex + md);
|
||||
const masterKeyPlainText = this.loadedMasterKey(header.masterKeyId);
|
||||
@@ -371,7 +371,7 @@ class EncryptionService {
|
||||
while (true) {
|
||||
const lengthHex = await source.read(6);
|
||||
if (!lengthHex) break;
|
||||
if (lengthHex.length !== 6) throw new Error('Invalid block size: ' + lengthHex);
|
||||
if (lengthHex.length !== 6) throw new Error(`Invalid block size: ${lengthHex}`);
|
||||
const length = parseInt(lengthHex, 16);
|
||||
if (!length) continue; // Weird but could be not completely invalid (block of size 0) so continue decrypting
|
||||
|
||||
@@ -502,32 +502,32 @@ class EncryptionService {
|
||||
}
|
||||
|
||||
decodeHeaderVersion_(hexaByte) {
|
||||
if (hexaByte.length !== 2) throw new Error('Invalid header version length: ' + hexaByte);
|
||||
if (hexaByte.length !== 2) throw new Error(`Invalid header version length: ${hexaByte}`);
|
||||
return parseInt(hexaByte, 16);
|
||||
}
|
||||
|
||||
headerTemplate(version) {
|
||||
const r = this.headerTemplates_[version];
|
||||
if (!r) throw new Error('Unknown header version: ' + version);
|
||||
if (!r) throw new Error(`Unknown header version: ${version}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
encodeHeader_(header) {
|
||||
// Sanity check
|
||||
if (header.masterKeyId.length !== 32) throw new Error('Invalid master key ID size: ' + header.masterKeyId);
|
||||
if (header.masterKeyId.length !== 32) throw new Error(`Invalid master key ID size: ${header.masterKeyId}`);
|
||||
|
||||
let encryptionMetadata = '';
|
||||
encryptionMetadata += padLeft(header.encryptionMethod.toString(16), 2, '0');
|
||||
encryptionMetadata += header.masterKeyId;
|
||||
encryptionMetadata = padLeft(encryptionMetadata.length.toString(16), 6, '0') + encryptionMetadata;
|
||||
return 'JED01' + encryptionMetadata;
|
||||
return `JED01${encryptionMetadata}`;
|
||||
}
|
||||
|
||||
decodeHeader_(headerHexaBytes) {
|
||||
const reader = this.stringReader_(headerHexaBytes, true);
|
||||
const identifier = reader.read(3);
|
||||
const version = parseInt(reader.read(2), 16);
|
||||
if (identifier !== 'JED') throw new Error('Invalid header (missing identifier): ' + headerHexaBytes.substr(0, 64));
|
||||
if (identifier !== 'JED') throw new Error(`Invalid header (missing identifier): ${headerHexaBytes.substr(0, 64)}`);
|
||||
const template = this.headerTemplate(version);
|
||||
|
||||
parseInt(reader.read(6), 16); // Read the size and move the reader pointer forward
|
||||
@@ -546,7 +546,7 @@ class EncryptionService {
|
||||
} else if (type === 'hex') {
|
||||
// Already in hexa
|
||||
} else {
|
||||
throw new Error('Invalid type: ' + type);
|
||||
throw new Error(`Invalid type: ${type}`);
|
||||
}
|
||||
|
||||
output[name] = v;
|
||||
|
||||
@@ -51,7 +51,7 @@ class ExternalEditWatcher {
|
||||
if (!this.watcher_) {
|
||||
this.watcher_ = this.chokidar_.watch(fileToWatch);
|
||||
this.watcher_.on('all', async (event, path) => {
|
||||
this.logger().debug('ExternalEditWatcher: Event: ' + event + ': ' + path);
|
||||
this.logger().debug(`ExternalEditWatcher: Event: ${event}: ${path}`);
|
||||
|
||||
if (event === 'unlink') {
|
||||
// File are unwatched in the stopWatching functions below. When we receive an unlink event
|
||||
@@ -67,7 +67,7 @@ class ExternalEditWatcher {
|
||||
const note = await Note.load(id);
|
||||
|
||||
if (!note) {
|
||||
this.logger().warn('Watched note has been deleted: ' + id);
|
||||
this.logger().warn(`Watched note has been deleted: ${id}`);
|
||||
this.stopWatching(id);
|
||||
return;
|
||||
}
|
||||
@@ -101,12 +101,12 @@ class ExternalEditWatcher {
|
||||
}
|
||||
|
||||
noteIdToFilePath_(noteId) {
|
||||
return this.tempDir() + '/edit-' + noteId + '.md';
|
||||
return `${this.tempDir()}/edit-${noteId}.md`;
|
||||
}
|
||||
|
||||
noteFilePathToId_(path) {
|
||||
let id = path.split('/');
|
||||
if (!id.length) throw new Error('Invalid path: ' + path);
|
||||
if (!id.length) throw new Error(`Invalid path: ${path}`);
|
||||
id = id[id.length - 1];
|
||||
id = id.split('.');
|
||||
id.pop();
|
||||
@@ -125,7 +125,7 @@ class ExternalEditWatcher {
|
||||
|
||||
for (let i = 0; i < watchedPaths[dirName].length; i++) {
|
||||
const f = watchedPaths[dirName][i];
|
||||
output.push(this.tempDir() + '/' + f);
|
||||
output.push(`${this.tempDir()}/${f}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ class ExternalEditWatcher {
|
||||
|
||||
const s = splitCommandString(editorCommand, { handleEscape: false });
|
||||
const path = s.splice(0, 1);
|
||||
if (!path.length) throw new Error('Invalid editor command: ' + editorCommand);
|
||||
if (!path.length) throw new Error(`Invalid editor command: ${editorCommand}`);
|
||||
|
||||
return {
|
||||
path: path[0],
|
||||
@@ -187,7 +187,7 @@ class ExternalEditWatcher {
|
||||
const wrapError = error => {
|
||||
if (!error) return error;
|
||||
let msg = error.message ? [error.message] : [];
|
||||
msg.push('Command was: "' + path + '" ' + args.join(' '));
|
||||
msg.push(`Command was: "${path}" ${args.join(' ')}`);
|
||||
error.message = msg.join('\n\n');
|
||||
return error;
|
||||
};
|
||||
@@ -197,7 +197,7 @@ class ExternalEditWatcher {
|
||||
|
||||
const iid = setInterval(() => {
|
||||
if (subProcess && subProcess.pid) {
|
||||
this.logger().debug('Started editor with PID ' + subProcess.pid);
|
||||
this.logger().debug(`Started editor with PID ${subProcess.pid}`);
|
||||
clearInterval(iid);
|
||||
resolve();
|
||||
}
|
||||
@@ -224,7 +224,7 @@ class ExternalEditWatcher {
|
||||
|
||||
const cmd = this.textEditorCommand();
|
||||
if (!cmd) {
|
||||
bridge().openExternal('file://' + filePath);
|
||||
bridge().openExternal(`file://${filePath}`);
|
||||
} else {
|
||||
cmd.args.push(filePath);
|
||||
await this.spawnCommand(cmd.path, cmd.args, { detached: true });
|
||||
@@ -235,7 +235,7 @@ class ExternalEditWatcher {
|
||||
id: note.id,
|
||||
});
|
||||
|
||||
this.logger().info('ExternalEditWatcher: Started watching ' + filePath);
|
||||
this.logger().info(`ExternalEditWatcher: Started watching ${filePath}`);
|
||||
}
|
||||
|
||||
async stopWatching(noteId) {
|
||||
@@ -248,7 +248,7 @@ class ExternalEditWatcher {
|
||||
type: 'NOTE_FILE_WATCHER_REMOVE',
|
||||
id: noteId,
|
||||
});
|
||||
this.logger().info('ExternalEditWatcher: Stopped watching ' + filePath);
|
||||
this.logger().info(`ExternalEditWatcher: Stopped watching ${filePath}`);
|
||||
}
|
||||
|
||||
async stopWatchingAll() {
|
||||
@@ -273,7 +273,7 @@ class ExternalEditWatcher {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger().debug('ExternalEditWatcher: Update note file: ' + note.id);
|
||||
this.logger().debug(`ExternalEditWatcher: Update note file: ${note.id}`);
|
||||
|
||||
// When the note file is updated programmatically, we skip the next change event to
|
||||
// avoid update loops. We only want to listen to file changes made by the user.
|
||||
|
||||
@@ -79,12 +79,12 @@ class InteropService {
|
||||
];
|
||||
|
||||
importModules = importModules.map(a => {
|
||||
const className = a.importerClass || 'InteropService_Importer_' + toTitleCase(a.format);
|
||||
const className = a.importerClass || `InteropService_Importer_${toTitleCase(a.format)}`;
|
||||
const output = Object.assign(
|
||||
{},
|
||||
{
|
||||
type: 'importer',
|
||||
path: 'lib/services/' + className,
|
||||
path: `lib/services/${className}`,
|
||||
},
|
||||
a
|
||||
);
|
||||
@@ -93,12 +93,12 @@ class InteropService {
|
||||
});
|
||||
|
||||
exportModules = exportModules.map(a => {
|
||||
const className = 'InteropService_Exporter_' + toTitleCase(a.format);
|
||||
const className = `InteropService_Exporter_${toTitleCase(a.format)}`;
|
||||
return Object.assign(
|
||||
{},
|
||||
{
|
||||
type: 'exporter',
|
||||
path: 'lib/services/' + className,
|
||||
path: `lib/services/${className}`,
|
||||
},
|
||||
a
|
||||
);
|
||||
@@ -108,9 +108,9 @@ class InteropService {
|
||||
|
||||
this.modules_ = this.modules_.map(a => {
|
||||
a.fullLabel = function(moduleSource = null) {
|
||||
const label = [this.format.toUpperCase() + ' - ' + this.description];
|
||||
const label = [`${this.format.toUpperCase()} - ${this.description}`];
|
||||
if (moduleSource && this.sources.length > 1) {
|
||||
label.push('(' + (moduleSource === 'file' ? _('File') : _('Directory')) + ')');
|
||||
label.push(`(${moduleSource === 'file' ? _('File') : _('Directory')})`);
|
||||
}
|
||||
return label.join(' ');
|
||||
};
|
||||
|
||||
@@ -24,7 +24,7 @@ class InteropService_Exporter_Base {
|
||||
|
||||
async temporaryDirectory_(createIt) {
|
||||
const md5 = require('md5');
|
||||
const tempDir = require('os').tmpdir() + '/' + md5(Math.random() + Date.now());
|
||||
const tempDir = `${require('os').tmpdir()}/${md5(Math.random() + Date.now())}`;
|
||||
if (createIt) await require('fs-extra').mkdirp(tempDir);
|
||||
return tempDir;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ const { _ } = require('lib/locale');
|
||||
|
||||
class InteropService_Exporter_Jex extends InteropService_Exporter_Base {
|
||||
async init(destPath) {
|
||||
if (await shim.fsDriver().isDirectory(destPath)) throw new Error('Path is a directory: ' + destPath);
|
||||
if (await shim.fsDriver().isDirectory(destPath)) throw new Error(`Path is a directory: ${destPath}`);
|
||||
|
||||
this.tempDir_ = await this.temporaryDirectory_(false);
|
||||
this.destPath_ = destPath;
|
||||
|
||||
@@ -5,7 +5,7 @@ const { shim } = require('lib/shim');
|
||||
class InteropService_Exporter_Json extends InteropService_Exporter_Base {
|
||||
async init(destDir) {
|
||||
this.destDir_ = destDir;
|
||||
this.resourceDir_ = destDir ? destDir + '/resources' : null;
|
||||
this.resourceDir_ = destDir ? `${destDir}/resources` : null;
|
||||
|
||||
await shim.fsDriver().mkdir(this.destDir_);
|
||||
await shim.fsDriver().mkdir(this.resourceDir_);
|
||||
@@ -13,13 +13,13 @@ class InteropService_Exporter_Json extends InteropService_Exporter_Base {
|
||||
|
||||
async processItem(ItemClass, item) {
|
||||
const fileName = ItemClass.systemPath(item, 'json');
|
||||
const filePath = this.destDir_ + '/' + fileName;
|
||||
const filePath = `${this.destDir_}/${fileName}`;
|
||||
const serialized = JSON.stringify(item);
|
||||
await shim.fsDriver().writeFile(filePath, serialized, 'utf-8');
|
||||
}
|
||||
|
||||
async processResource(resource, filePath) {
|
||||
const destResourcePath = this.resourceDir_ + '/' + basename(filePath);
|
||||
const destResourcePath = `${this.resourceDir_}/${basename(filePath)}`;
|
||||
await shim.fsDriver().copy(filePath, destResourcePath);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ const { shim } = require('lib/shim');
|
||||
class InteropService_Exporter_Md extends InteropService_Exporter_Base {
|
||||
async init(destDir) {
|
||||
this.destDir_ = destDir;
|
||||
this.resourceDir_ = destDir ? destDir + '/_resources' : null;
|
||||
this.resourceDir_ = destDir ? `${destDir}/_resources` : null;
|
||||
this.createdDirs_ = [];
|
||||
|
||||
await shim.fsDriver().mkdir(this.destDir_);
|
||||
@@ -20,9 +20,9 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base {
|
||||
while (true) {
|
||||
if (item.type_ === BaseModel.TYPE_FOLDER) {
|
||||
if (pathPart) {
|
||||
output = pathPart + '/' + output;
|
||||
output = `${pathPart}/${output}`;
|
||||
} else {
|
||||
output = friendlySafeFilename(item.title, null, true) + '/' + output;
|
||||
output = `${friendlySafeFilename(item.title, null, true)}/${output}`;
|
||||
output = await shim.fsDriver().findUniqueFilename(output);
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,8 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base {
|
||||
|
||||
for (let i = 0; i < linkedResourceIds.length; i++) {
|
||||
const id = linkedResourceIds[i];
|
||||
const resourcePath = relativePath + '/_resources/' + basename(resourcePaths[id]);
|
||||
newBody = newBody.replace(new RegExp(':/' + id, 'g'), resourcePath);
|
||||
const resourcePath = `${relativePath}/_resources/${basename(resourcePaths[id])}`;
|
||||
newBody = newBody.replace(new RegExp(`:/${id}`, 'g'), resourcePath);
|
||||
}
|
||||
|
||||
return newBody;
|
||||
@@ -50,7 +50,7 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base {
|
||||
async processItem(ItemClass, item) {
|
||||
if ([BaseModel.TYPE_NOTE, BaseModel.TYPE_FOLDER].indexOf(item.type_) < 0) return;
|
||||
|
||||
const dirPath = this.destDir_ + '/' + (await this.makeDirPath_(item));
|
||||
const dirPath = `${this.destDir_}/${await this.makeDirPath_(item)}`;
|
||||
|
||||
if (this.createdDirs_.indexOf(dirPath) < 0) {
|
||||
await shim.fsDriver().mkdir(dirPath);
|
||||
@@ -58,7 +58,7 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base {
|
||||
}
|
||||
|
||||
if (item.type_ === BaseModel.TYPE_NOTE) {
|
||||
let noteFilePath = dirPath + '/' + friendlySafeFilename(item.title, null, true) + '.md';
|
||||
let noteFilePath = `${dirPath}/${friendlySafeFilename(item.title, null, true)}.md`;
|
||||
noteFilePath = await shim.fsDriver().findUniqueFilename(noteFilePath);
|
||||
const noteBody = await this.replaceResourceIdsByRelativePaths_(item);
|
||||
const modNote = Object.assign({}, item, { body: noteBody });
|
||||
@@ -68,7 +68,7 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base {
|
||||
}
|
||||
|
||||
async processResource(resource, filePath) {
|
||||
const destResourcePath = this.resourceDir_ + '/' + basename(filePath);
|
||||
const destResourcePath = `${this.resourceDir_}/${basename(filePath)}`;
|
||||
await shim.fsDriver().copy(filePath, destResourcePath);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ const { shim } = require('lib/shim');
|
||||
class InteropService_Exporter_Raw extends InteropService_Exporter_Base {
|
||||
async init(destDir) {
|
||||
this.destDir_ = destDir;
|
||||
this.resourceDir_ = destDir ? destDir + '/resources' : null;
|
||||
this.resourceDir_ = destDir ? `${destDir}/resources` : null;
|
||||
|
||||
await shim.fsDriver().mkdir(this.destDir_);
|
||||
await shim.fsDriver().mkdir(this.resourceDir_);
|
||||
@@ -13,12 +13,12 @@ class InteropService_Exporter_Raw extends InteropService_Exporter_Base {
|
||||
|
||||
async processItem(ItemClass, item) {
|
||||
const serialized = await ItemClass.serialize(item);
|
||||
const filePath = this.destDir_ + '/' + ItemClass.systemPath(item);
|
||||
const filePath = `${this.destDir_}/${ItemClass.systemPath(item)}`;
|
||||
await shim.fsDriver().writeFile(filePath, serialized, 'utf-8');
|
||||
}
|
||||
|
||||
async processResource(resource, filePath) {
|
||||
const destResourcePath = this.resourceDir_ + '/' + basename(filePath);
|
||||
const destResourcePath = `${this.resourceDir_}/${basename(filePath)}`;
|
||||
await shim.fsDriver().copy(filePath, destResourcePath);
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ class InteropService_Importer_Base {
|
||||
|
||||
async temporaryDirectory_(createIt) {
|
||||
const md5 = require('md5');
|
||||
const tempDir = require('os').tmpdir() + '/' + md5(Math.random() + Date.now());
|
||||
const tempDir = `${require('os').tmpdir()}/${md5(Math.random() + Date.now())}`;
|
||||
if (createIt) await require('fs-extra').mkdirp(tempDir);
|
||||
return tempDir;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ class InteropService_Importer_Jex extends InteropService_Importer_Base {
|
||||
cwd: tempDir,
|
||||
});
|
||||
} catch (error) {
|
||||
let msg = ['Cannot untar file ' + this.sourcePath_, error.message];
|
||||
let msg = [`Cannot untar file ${this.sourcePath_}`, error.message];
|
||||
if (error.data) msg.push(JSON.stringify(error.data));
|
||||
let e = new Error(msg.join(': '));
|
||||
throw e;
|
||||
|
||||
@@ -37,7 +37,7 @@ class InteropService_Importer_Md extends InteropService_Importer_Base {
|
||||
}
|
||||
|
||||
async importDirectory(dirPath, parentFolderId) {
|
||||
console.info('Import: ' + dirPath);
|
||||
console.info(`Import: ${dirPath}`);
|
||||
|
||||
const supportedFileExtension = this.metadata().fileExtensions;
|
||||
const stats = await shim.fsDriver().readDirStats(dirPath);
|
||||
@@ -47,16 +47,16 @@ class InteropService_Importer_Md extends InteropService_Importer_Base {
|
||||
if (stat.isDirectory()) {
|
||||
const folderTitle = await Folder.findUniqueItemTitle(basename(stat.path));
|
||||
const folder = await Folder.save({ title: folderTitle, parent_id: parentFolderId });
|
||||
this.importDirectory(dirPath + '/' + basename(stat.path), folder.id);
|
||||
this.importDirectory(`${dirPath}/${basename(stat.path)}`, folder.id);
|
||||
} else if (supportedFileExtension.indexOf(fileExtension(stat.path).toLowerCase()) >= 0) {
|
||||
this.importFile(dirPath + '/' + stat.path, parentFolderId);
|
||||
this.importFile(`${dirPath}/${stat.path}`, parentFolderId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async importFile(filePath, parentFolderId) {
|
||||
const stat = await shim.fsDriver().stat(filePath);
|
||||
if (!stat) throw new Error('Cannot read ' + filePath);
|
||||
if (!stat) throw new Error(`Cannot read ${filePath}`);
|
||||
const title = filename(filePath);
|
||||
const body = await shim.fsDriver().readFile(filePath);
|
||||
const note = {
|
||||
|
||||
@@ -77,7 +77,7 @@ class InteropService_Importer_Raw extends InteropService_Importer_Base {
|
||||
if (stat.isDirectory()) continue;
|
||||
if (fileExtension(stat.path).toLowerCase() !== 'md') continue;
|
||||
|
||||
const content = await shim.fsDriver().readFile(this.sourcePath_ + '/' + stat.path);
|
||||
const content = await shim.fsDriver().readFile(`${this.sourcePath_}/${stat.path}`);
|
||||
let item = await BaseItem.unserialize(content);
|
||||
const itemType = item.type_;
|
||||
const ItemClass = BaseItem.itemClass(item);
|
||||
@@ -146,11 +146,11 @@ class InteropService_Importer_Raw extends InteropService_Importer_Base {
|
||||
await NoteTag.save(noteTag, { isNew: true });
|
||||
}
|
||||
|
||||
if (await shim.fsDriver().isDirectory(this.sourcePath_ + '/resources')) {
|
||||
const resourceStats = await shim.fsDriver().readDirStats(this.sourcePath_ + '/resources');
|
||||
if (await shim.fsDriver().isDirectory(`${this.sourcePath_}/resources`)) {
|
||||
const resourceStats = await shim.fsDriver().readDirStats(`${this.sourcePath_}/resources`);
|
||||
|
||||
for (let i = 0; i < resourceStats.length; i++) {
|
||||
const resourceFilePath = this.sourcePath_ + '/resources/' + resourceStats[i].path;
|
||||
const resourceFilePath = `${this.sourcePath_}/resources/${resourceStats[i].path}`;
|
||||
const oldId = Resource.pathToId(resourceFilePath);
|
||||
const newId = itemIdMap[oldId];
|
||||
if (!newId) {
|
||||
|
||||
@@ -25,7 +25,7 @@ class KvStore extends BaseService {
|
||||
typeFromValue_(value) {
|
||||
if (typeof value === 'string') return KvStore.TYPE_TEXT;
|
||||
if (typeof value === 'number') return KvStore.TYPE_INT;
|
||||
throw new Error('Unsupported value type: ' + typeof value);
|
||||
throw new Error(`Unsupported value type: ${typeof value}`);
|
||||
}
|
||||
|
||||
formatValues_(kvs) {
|
||||
@@ -39,8 +39,8 @@ class KvStore extends BaseService {
|
||||
|
||||
formatValue_(value, type) {
|
||||
if (type === KvStore.TYPE_INT) return Number(value);
|
||||
if (type === KvStore.TYPE_TEXT) return value + '';
|
||||
throw new Error('Unknown type: ' + type);
|
||||
if (type === KvStore.TYPE_TEXT) return `${value}`;
|
||||
throw new Error(`Unknown type: ${type}`);
|
||||
}
|
||||
|
||||
async value(key) {
|
||||
@@ -84,7 +84,7 @@ class KvStore extends BaseService {
|
||||
}
|
||||
|
||||
async searchByPrefix(prefix) {
|
||||
let results = await this.db().selectAll('SELECT `key`, `value`, `type` FROM key_values WHERE `key` LIKE ?', [prefix + '%']);
|
||||
let results = await this.db().selectAll('SELECT `key`, `value`, `type` FROM key_values WHERE `key` LIKE ?', [`${prefix}%`]);
|
||||
return this.formatValues_(results);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,13 +21,13 @@ class MigrationService extends BaseService {
|
||||
const migrations = await Migration.migrationsToDo();
|
||||
|
||||
for (const migration of migrations) {
|
||||
this.logger().info('Running migration: ' + migration.number);
|
||||
this.logger().info(`Running migration: ${migration.number}`);
|
||||
|
||||
try {
|
||||
await this.runScript(migration.number);
|
||||
await Migration.delete(migration.id);
|
||||
} catch (error) {
|
||||
this.logger().error('Cannot run migration: ' + migration.number, error);
|
||||
this.logger().error(`Cannot run migration: ${migration.number}`, error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ class PluginManager {
|
||||
for (let i = 0; i < classes.length; i++) {
|
||||
const PluginClass = classes[i];
|
||||
|
||||
if (this.plugins_[PluginClass.manifest.name]) throw new Error('Already registered: ' + PluginClass.manifest.name);
|
||||
if (this.plugins_[PluginClass.manifest.name]) throw new Error(`Already registered: ${PluginClass.manifest.name}`);
|
||||
|
||||
this.plugins_[PluginClass.manifest.name] = {
|
||||
Class: PluginClass,
|
||||
|
||||
@@ -46,7 +46,7 @@ class ResourceFetcher extends BaseService {
|
||||
}
|
||||
|
||||
setFileApi(v) {
|
||||
if (v !== null && typeof v !== 'function') throw new Error('fileApi must be a function that returns the API. Type is ' + typeof v);
|
||||
if (v !== null && typeof v !== 'function') throw new Error(`fileApi must be a function that returns the API. Type is ${typeof v}`);
|
||||
this.fileApi_ = v;
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ class ResourceFetcher extends BaseService {
|
||||
};
|
||||
|
||||
if (!resource) {
|
||||
this.logger().info('ResourceFetcher: Attempting to download a resource that does not exist (has been deleted?): ' + resourceId);
|
||||
this.logger().info(`ResourceFetcher: Attempting to download a resource that does not exist (has been deleted?): ${resourceId}`);
|
||||
await completeDownload(false);
|
||||
return;
|
||||
}
|
||||
@@ -157,13 +157,13 @@ class ResourceFetcher extends BaseService {
|
||||
this.fetchingItems_[resourceId] = resource;
|
||||
|
||||
const localResourceContentPath = Resource.fullPath(resource, !!resource.encryption_blob_encrypted);
|
||||
const remoteResourceContentPath = this.resourceDirName_ + '/' + resource.id;
|
||||
const remoteResourceContentPath = `${this.resourceDirName_}/${resource.id}`;
|
||||
|
||||
await Resource.setLocalState(resource, { fetch_status: Resource.FETCH_STATUS_STARTED });
|
||||
|
||||
const fileApi = await this.fileApi();
|
||||
|
||||
this.logger().debug('ResourceFetcher: Downloading resource: ' + resource.id);
|
||||
this.logger().debug(`ResourceFetcher: Downloading resource: ${resource.id}`);
|
||||
|
||||
this.eventEmitter_.emit('downloadStarted', { id: resource.id });
|
||||
|
||||
@@ -171,11 +171,11 @@ class ResourceFetcher extends BaseService {
|
||||
.get(remoteResourceContentPath, { path: localResourceContentPath, target: 'file' })
|
||||
.then(async () => {
|
||||
await Resource.setLocalState(resource, { fetch_status: Resource.FETCH_STATUS_DONE });
|
||||
this.logger().debug('ResourceFetcher: Resource downloaded: ' + resource.id);
|
||||
this.logger().debug(`ResourceFetcher: Resource downloaded: ${resource.id}`);
|
||||
await completeDownload(true, localResourceContentPath);
|
||||
})
|
||||
.catch(async error => {
|
||||
this.logger().error('ResourceFetcher: Could not download resource: ' + resource.id, error);
|
||||
this.logger().error(`ResourceFetcher: Could not download resource: ${resource.id}`, error);
|
||||
await Resource.setLocalState(resource, { fetch_status: Resource.FETCH_STATUS_ERROR, fetch_error: error.message });
|
||||
await completeDownload();
|
||||
});
|
||||
@@ -210,7 +210,7 @@ class ResourceFetcher extends BaseService {
|
||||
if (this.addingResources_) return;
|
||||
this.addingResources_ = true;
|
||||
|
||||
this.logger().info('ResourceFetcher: Auto-add resources: Mode: ' + Setting.value('sync.resourceDownloadMode'));
|
||||
this.logger().info(`ResourceFetcher: Auto-add resources: Mode: ${Setting.value('sync.resourceDownloadMode')}`);
|
||||
|
||||
let count = 0;
|
||||
const resources = await Resource.needToBeFetched(Setting.value('sync.resourceDownloadMode'), limit);
|
||||
@@ -219,7 +219,7 @@ class ResourceFetcher extends BaseService {
|
||||
if (added) count++;
|
||||
}
|
||||
|
||||
this.logger().info('ResourceFetcher: Auto-added resources: ' + count);
|
||||
this.logger().info(`ResourceFetcher: Auto-added resources: ${count}`);
|
||||
this.addingResources_ = false;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ class ResourceService extends BaseService {
|
||||
if (!changes.length) break;
|
||||
|
||||
const noteIds = changes.map(a => a.item_id);
|
||||
const notes = await Note.modelSelectAll('SELECT id, title, body, encryption_applied FROM notes WHERE id IN ("' + noteIds.join('","') + '")');
|
||||
const notes = await Note.modelSelectAll(`SELECT id, title, body, encryption_applied FROM notes WHERE id IN ("${noteIds.join('","')}")`);
|
||||
|
||||
const noteById = noteId => {
|
||||
for (let i = 0; i < notes.length; i++) {
|
||||
@@ -66,12 +66,12 @@ class ResourceService extends BaseService {
|
||||
if (note) {
|
||||
await this.setAssociatedResources_(note);
|
||||
} else {
|
||||
this.logger().warn('ResourceService::indexNoteResources: A change was recorded for a note that has been deleted: ' + change.item_id);
|
||||
this.logger().warn(`ResourceService::indexNoteResources: A change was recorded for a note that has been deleted: ${change.item_id}`);
|
||||
}
|
||||
} else if (change.type === ItemChange.TYPE_DELETE) {
|
||||
await NoteResource.remove(change.item_id);
|
||||
} else {
|
||||
throw new Error('Invalid change type: ' + change.type);
|
||||
throw new Error(`Invalid change type: ${change.type}`);
|
||||
}
|
||||
|
||||
Setting.setValue('resourceService.lastProcessedChangeId', change.id);
|
||||
|
||||
@@ -127,7 +127,7 @@ class RevisionService extends BaseService {
|
||||
if (!changes.length) break;
|
||||
|
||||
const noteIds = changes.map(a => a.item_id);
|
||||
const notes = await Note.modelSelectAll('SELECT * FROM notes WHERE is_conflict = 0 AND encryption_applied = 0 AND id IN ("' + noteIds.join('","') + '")');
|
||||
const notes = await Note.modelSelectAll(`SELECT * FROM notes WHERE is_conflict = 0 AND encryption_applied = 0 AND id IN ("${noteIds.join('","')}")`);
|
||||
|
||||
for (let i = 0; i < changes.length; i++) {
|
||||
const change = changes[i];
|
||||
@@ -180,7 +180,7 @@ class RevisionService extends BaseService {
|
||||
|
||||
this.isCollecting_ = false;
|
||||
|
||||
this.logger().info('RevisionService::collectRevisions: Created revisions for ' + doneNoteIds.length + ' notes');
|
||||
this.logger().info(`RevisionService::collectRevisions: Created revisions for ${doneNoteIds.length} notes`);
|
||||
}
|
||||
|
||||
async deleteOldRevisions(ttl) {
|
||||
@@ -188,7 +188,7 @@ class RevisionService extends BaseService {
|
||||
}
|
||||
|
||||
async revisionNote(revisions, index) {
|
||||
if (index < 0 || index >= revisions.length) throw new Error('Invalid revision index: ' + index);
|
||||
if (index < 0 || index >= revisions.length) throw new Error(`Invalid revision index: ${index}`);
|
||||
|
||||
const rev = revisions[index];
|
||||
const merged = await Revision.mergeDiffs(rev, revisions);
|
||||
@@ -250,7 +250,7 @@ class RevisionService extends BaseService {
|
||||
await this.deleteOldRevisions(Setting.value('revisionService.ttlDays') * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
this.logger().info('RevisionService::maintenance: Done in ' + (Date.now() - startTime) + 'ms');
|
||||
this.logger().info(`RevisionService::maintenance: Done in ${Date.now() - startTime}ms`);
|
||||
}
|
||||
|
||||
runInBackground(collectRevisionInterval = null) {
|
||||
@@ -259,7 +259,7 @@ class RevisionService extends BaseService {
|
||||
|
||||
if (collectRevisionInterval === null) collectRevisionInterval = 1000 * 60 * 10;
|
||||
|
||||
this.logger().info('RevisionService::runInBackground: Starting background service with revision collection interval ' + collectRevisionInterval);
|
||||
this.logger().info(`RevisionService::runInBackground: Starting background service with revision collection interval ${collectRevisionInterval}`);
|
||||
|
||||
setTimeout(() => {
|
||||
this.maintenance();
|
||||
|
||||
@@ -61,7 +61,7 @@ class SearchEngine {
|
||||
|
||||
while (noteIds.length) {
|
||||
const currentIds = noteIds.splice(0, 100);
|
||||
const notes = await Note.modelSelectAll('SELECT id, title, body FROM notes WHERE id IN ("' + currentIds.join('","') + '") AND is_conflict = 0 AND encryption_applied = 0');
|
||||
const notes = await Note.modelSelectAll(`SELECT id, title, body FROM notes WHERE id IN ("${currentIds.join('","')}") AND is_conflict = 0 AND encryption_applied = 0`);
|
||||
const queries = [];
|
||||
|
||||
for (let i = 0; i < notes.length; i++) {
|
||||
@@ -137,7 +137,7 @@ class SearchEngine {
|
||||
if (!changes.length) break;
|
||||
|
||||
const noteIds = changes.map(a => a.item_id);
|
||||
const notes = await Note.modelSelectAll('SELECT id, title, body FROM notes WHERE id IN ("' + noteIds.join('","') + '") AND is_conflict = 0 AND encryption_applied = 0');
|
||||
const notes = await Note.modelSelectAll(`SELECT id, title, body FROM notes WHERE id IN ("${noteIds.join('","')}") AND is_conflict = 0 AND encryption_applied = 0`);
|
||||
const queries = [];
|
||||
|
||||
for (let i = 0; i < changes.length; i++) {
|
||||
@@ -155,7 +155,7 @@ class SearchEngine {
|
||||
queries.push({ sql: 'DELETE FROM notes_normalized WHERE id = ?', params: [change.item_id] });
|
||||
report.deleted++;
|
||||
} else {
|
||||
throw new Error('Invalid change type: ' + change.type);
|
||||
throw new Error(`Invalid change type: ${change.type}`);
|
||||
}
|
||||
|
||||
lastChangeId = change.id;
|
||||
@@ -252,7 +252,7 @@ class SearchEngine {
|
||||
|
||||
let regexString = pregQuote(term);
|
||||
if (regexString[regexString.length - 1] === '*') {
|
||||
regexString = regexString.substr(0, regexString.length - 2) + '[^' + pregQuote(' \t\n\r,.,+-*?!={}<>|:"\'()[]') + ']' + '*?';
|
||||
regexString = `${regexString.substr(0, regexString.length - 2)}[^${pregQuote(' \t\n\r,.,+-*?!={}<>|:"\'()[]')}]` + '*?';
|
||||
// regexString = regexString.substr(0, regexString.length - 2) + '.*?';
|
||||
}
|
||||
|
||||
@@ -372,9 +372,9 @@ class SearchEngine {
|
||||
|
||||
for (const key of parsedQuery.keys) {
|
||||
const term = parsedQuery.terms[key][0].value;
|
||||
if (key === '_') searchOptions.anywherePattern = '*' + term + '*';
|
||||
if (key === 'title') searchOptions.titlePattern = '*' + term + '*';
|
||||
if (key === 'body') searchOptions.bodyPattern = '*' + term + '*';
|
||||
if (key === '_') searchOptions.anywherePattern = `*${term}*`;
|
||||
if (key === 'title') searchOptions.titlePattern = `*${term}*`;
|
||||
if (key === 'body') searchOptions.bodyPattern = `*${term}*`;
|
||||
}
|
||||
|
||||
return Note.previews(null, searchOptions);
|
||||
@@ -397,7 +397,7 @@ class SearchEngine {
|
||||
this.orderResults_(rows, parsedQuery);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
this.logger().warn('Cannot execute MATCH query: ' + query + ': ' + error.message);
|
||||
this.logger().warn(`Cannot execute MATCH query: ${query}: ${error.message}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ class SearchEngineUtils {
|
||||
{
|
||||
order: [],
|
||||
fields: fields,
|
||||
conditions: ['id IN ("' + noteIds.join('","') + '")'],
|
||||
conditions: [`id IN ("${noteIds.join('","')}")`],
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
@@ -13,7 +13,7 @@ class ReportService {
|
||||
cell = this.csvValueToString(cell);
|
||||
let output = cell.replace(/"/, '""');
|
||||
if (this.csvCellRequiresQuotes(cell, ',')) {
|
||||
return '"' + output + '"';
|
||||
return `"${output}"`;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
@@ -55,7 +55,7 @@ class ReportService {
|
||||
for (let i = 0; i < itemTypes.length; i++) {
|
||||
const itemType = itemTypes[i];
|
||||
const ItemClass = BaseItem.getClassByItemType(itemType);
|
||||
const items = await ItemClass.modelSelectAll('SELECT items.id, items.updated_time, sync_items.sync_time FROM ' + ItemClass.tableName() + ' items JOIN sync_items ON sync_items.item_id = items.id');
|
||||
const items = await ItemClass.modelSelectAll(`SELECT items.id, items.updated_time, sync_items.sync_time FROM ${ItemClass.tableName()} items JOIN sync_items ON sync_items.item_id = items.id`);
|
||||
|
||||
for (let j = 0; j < items.length; j++) {
|
||||
const item = items[j];
|
||||
|
||||
@@ -72,7 +72,7 @@ class Api {
|
||||
|
||||
const pathParts = path.split('/');
|
||||
const callSuffix = pathParts.splice(0, 1)[0];
|
||||
let callName = 'action_' + callSuffix;
|
||||
let callName = `action_${callSuffix}`;
|
||||
return {
|
||||
callName: callName,
|
||||
params: pathParts,
|
||||
@@ -384,17 +384,17 @@ class Api {
|
||||
|
||||
const imageUrls = ArrayUtils.unique(markupLanguageUtils.extractImageUrls(note.markup_language, note.body));
|
||||
|
||||
this.logger().info('Request (' + requestId + '): Downloading images: ' + imageUrls.length);
|
||||
this.logger().info(`Request (${requestId}): Downloading images: ${imageUrls.length}`);
|
||||
|
||||
let result = await this.downloadImages_(imageUrls, allowFileProtocolImages);
|
||||
|
||||
this.logger().info('Request (' + requestId + '): Creating resources from paths: ' + Object.getOwnPropertyNames(result).length);
|
||||
this.logger().info(`Request (${requestId}): Creating resources from paths: ${Object.getOwnPropertyNames(result).length}`);
|
||||
|
||||
result = await this.createResourcesFromPaths_(result);
|
||||
await this.removeTempFiles_(result);
|
||||
note.body = this.replaceImageUrlsByResources_(note.markup_language, note.body, result, imageSizes);
|
||||
|
||||
this.logger().info('Request (' + requestId + '): Saving note...');
|
||||
this.logger().info(`Request (${requestId}): Saving note...`);
|
||||
|
||||
const saveOptions = this.defaultSaveOptions_(note, 'POST');
|
||||
saveOptions.autoTimestamp = false; // No auto-timestamp because user may have provided them
|
||||
@@ -413,7 +413,7 @@ class Api {
|
||||
note = await this.attachImageFromDataUrl_(note, requestNote.image_data_url, requestNote.crop_rect);
|
||||
}
|
||||
|
||||
this.logger().info('Request (' + requestId + '): Created note ' + note.id);
|
||||
this.logger().info(`Request (${requestId}): Created note ${note.id}`);
|
||||
|
||||
return note;
|
||||
}
|
||||
@@ -464,7 +464,7 @@ class Api {
|
||||
maxLineLen: 200,
|
||||
});
|
||||
|
||||
const styleTag = style.length ? '<style>' + styleString + '</style>' + '\n' : '';
|
||||
const styleTag = style.length ? `<style>${styleString}</style>` + '\n' : '';
|
||||
output.body = styleTag + minify(requestNote.body_html, minifyOptions);
|
||||
output.body = htmlUtils.prependBaseUrl(output.body, baseUrl);
|
||||
output.markup_language = Note.MARKUP_LANGUAGE_HTML;
|
||||
@@ -473,7 +473,7 @@ class Api {
|
||||
// Parsing will not work if the HTML is not wrapped in a top level tag, which is not guaranteed
|
||||
// when getting the content from elsewhere. So here wrap it - it won't change anything to the final
|
||||
// rendering but it makes sure everything will be parsed.
|
||||
output.body = await this.htmlToMdParser().parse('<div>' + requestNote.body_html + '</div>', {
|
||||
output.body = await this.htmlToMdParser().parse(`<div>${requestNote.body_html}</div>`, {
|
||||
baseUrl: baseUrl,
|
||||
anchorNames: requestNote.anchor_names ? requestNote.anchor_names : [],
|
||||
});
|
||||
@@ -506,8 +506,8 @@ class Api {
|
||||
const tempDir = Setting.value('tempDir');
|
||||
const mime = mimeUtils.fromDataUrl(imageDataUrl);
|
||||
let ext = mimeUtils.toFileExtension(mime) || '';
|
||||
if (ext) ext = '.' + ext;
|
||||
const tempFilePath = tempDir + '/' + md5(Math.random() + '_' + Date.now()) + ext;
|
||||
if (ext) ext = `.${ext}`;
|
||||
const tempFilePath = `${tempDir}/${md5(`${Math.random()}_${Date.now()}`)}${ext}`;
|
||||
const imageConvOptions = {};
|
||||
if (cropRect) imageConvOptions.cropRect = cropRect;
|
||||
await shim.imageFromDataUrl(imageDataUrl, tempFilePath, imageConvOptions);
|
||||
@@ -521,7 +521,7 @@ class Api {
|
||||
const newExt = mimeUtils.toFileExtension(mimeType);
|
||||
if (!newExt) return imagePath;
|
||||
|
||||
const newImagePath = imagePath + '.' + newExt;
|
||||
const newImagePath = `${imagePath}.${newExt}`;
|
||||
await shim.fsDriver().move(imagePath, newImagePath);
|
||||
return newImagePath;
|
||||
}
|
||||
@@ -536,16 +536,16 @@ class Api {
|
||||
output.push(stylesheet.value);
|
||||
} else if (stylesheet.type === 'url') {
|
||||
try {
|
||||
const tempPath = Setting.value('tempDir') + '/' + md5(Math.random() + '_' + Date.now()) + '.css';
|
||||
const tempPath = `${Setting.value('tempDir')}/${md5(`${Math.random()}_${Date.now()}`)}.css`;
|
||||
await shim.fetchBlob(stylesheet.value, { path: tempPath, maxRetry: 1 });
|
||||
const text = await shim.fsDriver().readFile(tempPath);
|
||||
output.push(text);
|
||||
await shim.fsDriver().remove(tempPath);
|
||||
} catch (error) {
|
||||
this.logger().warn('Cannot download stylesheet at ' + stylesheet.value, error);
|
||||
this.logger().warn(`Cannot download stylesheet at ${stylesheet.value}`, error);
|
||||
}
|
||||
} else {
|
||||
throw new Error('Invalid stylesheet type: ' + stylesheet.type);
|
||||
throw new Error(`Invalid stylesheet type: ${stylesheet.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -557,12 +557,12 @@ class Api {
|
||||
|
||||
const isDataUrl = url && url.toLowerCase().indexOf('data:') === 0;
|
||||
|
||||
const name = isDataUrl ? md5(Math.random() + '_' + Date.now()) : filename(url);
|
||||
const name = isDataUrl ? md5(`${Math.random()}_${Date.now()}`) : filename(url);
|
||||
let fileExt = isDataUrl ? mimeUtils.toFileExtension(mimeUtils.fromDataUrl(url)) : safeFileExtension(fileExtension(url).toLowerCase());
|
||||
if (!mimeUtils.fromFileExtension(fileExt)) fileExt = ''; // If the file extension is unknown - clear it.
|
||||
if (fileExt) fileExt = '.' + fileExt;
|
||||
let imagePath = tempDir + '/' + safeFilename(name) + fileExt;
|
||||
if (await shim.fsDriver().exists(imagePath)) imagePath = tempDir + '/' + safeFilename(name) + '_' + md5(Math.random() + '_' + Date.now()).substr(0, 10) + fileExt;
|
||||
if (fileExt) fileExt = `.${fileExt}`;
|
||||
let imagePath = `${tempDir}/${safeFilename(name)}${fileExt}`;
|
||||
if (await shim.fsDriver().exists(imagePath)) imagePath = `${tempDir}/${safeFilename(name)}_${md5(`${Math.random()}_${Date.now()}`).substr(0, 10)}${fileExt}`;
|
||||
|
||||
try {
|
||||
if (isDataUrl) {
|
||||
@@ -581,7 +581,7 @@ class Api {
|
||||
}
|
||||
return imagePath;
|
||||
} catch (error) {
|
||||
this.logger().warn('Cannot download image at ' + url, error);
|
||||
this.logger().warn(`Cannot download image at ${url}`, error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -619,7 +619,7 @@ class Api {
|
||||
const resource = await shim.createResourceFromPath(urlInfo.path);
|
||||
urlInfo.resource = resource;
|
||||
} catch (error) {
|
||||
this.logger().warn('Cannot create resource for ' + url, error);
|
||||
this.logger().warn(`Cannot create resource for ${url}`, error);
|
||||
}
|
||||
}
|
||||
return urls;
|
||||
@@ -632,7 +632,7 @@ class Api {
|
||||
try {
|
||||
await shim.fsDriver().remove(urlInfo.path);
|
||||
} catch (error) {
|
||||
this.logger().warn('Cannot remove ' + urlInfo.path, error);
|
||||
this.logger().warn(`Cannot remove ${urlInfo.path}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -668,7 +668,7 @@ class Api {
|
||||
imageSizesIndexes[urlInfo.originalUrl]++;
|
||||
|
||||
if (imageSize && (imageSize.naturalWidth !== imageSize.width || imageSize.naturalHeight !== imageSize.height)) {
|
||||
return '<img width="' + imageSize.width + '" height="' + imageSize.height + '" src="' + resourceUrl + '"/>';
|
||||
return `<img width="${imageSize.width}" height="${imageSize.height}" src="${resourceUrl}"/>`;
|
||||
} else {
|
||||
return before + resourceUrl + after;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user