up modules; prettier

This commit is contained in:
antelle 2020-06-01 16:53:51 +02:00
parent 09fd37820b
commit e0b65bbebf
No known key found for this signature in database
GPG Key ID: 63C9777AAB7C563C
137 changed files with 887 additions and 881 deletions

View File

@ -10,7 +10,7 @@ const pkg = require('./package.json');
debug.enable('electron-notarize'); debug.enable('electron-notarize');
module.exports = function(grunt) { module.exports = function (grunt) {
require('time-grunt')(grunt); require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt); require('load-grunt-tasks')(grunt);

View File

@ -1,27 +1,28 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8" />
<title>Not Found</title> <title>Not Found</title>
<style> <style>
body { body {
font-family: -apple-system, "BlinkMacSystemFont", "Raleway", "Helvetica Neue", "Helvetica", "Arial", sans-serif; font-family: -apple-system, 'BlinkMacSystemFont', 'Raleway', 'Helvetica Neue',
font-feature-settings: "liga" 0; 'Helvetica', 'Arial', sans-serif;
text-align: center; font-feature-settings: 'liga' 0;
background: #F5F5F5; text-align: center;
font-weight: 300; background: #f5f5f5;
} font-weight: 300;
h1 { }
font-size: 3em; h1 {
margin-top: 10vh; font-size: 3em;
} margin-top: 10vh;
p { }
line-height: 1.5em; p {
} line-height: 1.5em;
</style> }
</head> </style>
<body> </head>
<h1>404 Not Found</h1> <body>
<p>Sorry, the page you're looking for was not found.</p> <h1>404 Not Found</h1>
</body> <p>Sorry, the page you're looking for was not found.</p>
</body>
</html> </html>

View File

@ -46,7 +46,7 @@ ready(() => {
.then(initStorage) .then(initStorage)
.then(showApp) .then(showApp)
.then(postInit) .then(postInit)
.catch(e => { .catch((e) => {
appModel.appLogger.error('Error starting app', e); appModel.appLogger.error('Error starting app', e);
}); });
@ -57,7 +57,7 @@ ready(() => {
); );
} }
return FeatureTester.test() return FeatureTester.test()
.catch(e => { .catch((e) => {
Alerts.error({ Alerts.error({
header: Locale.appSettingsError, header: Locale.appSettingsError,
body: Locale.appNotSupportedError, body: Locale.appNotSupportedError,
@ -119,7 +119,7 @@ ready(() => {
.then(() => { .then(() => {
SettingsManager.setBySettings(appModel.settings); SettingsManager.setBySettings(appModel.settings);
}) })
.catch(e => { .catch((e) => {
if (!appModel.settings.cacheConfigSettings) { if (!appModel.settings.cacheConfigSettings) {
showSettingsLoadError(); showSettingsLoadError();
throw e; throw e;
@ -146,7 +146,7 @@ ready(() => {
const protocolIsInsecure = ['https:', 'file:', 'app:'].indexOf(location.protocol) < 0; const protocolIsInsecure = ['https:', 'file:', 'app:'].indexOf(location.protocol) < 0;
const hostIsInsecure = location.hostname !== 'localhost'; const hostIsInsecure = location.hostname !== 'localhost';
if (protocolIsInsecure && hostIsInsecure && !skipHttpsWarning) { if (protocolIsInsecure && hostIsInsecure && !skipHttpsWarning) {
return new Promise(resolve => { return new Promise((resolve) => {
Alerts.error({ Alerts.error({
header: Locale.appSecWarn, header: Locale.appSecWarn,
icon: 'user-secret', icon: 'user-secret',
@ -163,7 +163,7 @@ ready(() => {
}); });
} else { } else {
showView(); showView();
return new Promise(resolve => requestAnimationFrame(resolve)); return new Promise((resolve) => requestAnimationFrame(resolve));
} }
}); });
} }

View File

@ -3,7 +3,7 @@ import { Ranking } from 'util/data/ranking';
const urlPartsRegex = /^(\w+:\/\/)?(?:(?:www|wwws|secure)\.)?([^\/]+)\/?(.*)/; const urlPartsRegex = /^(\w+:\/\/)?(?:(?:www|wwws|secure)\.)?([^\/]+)\/?(.*)/;
const AutoTypeFilter = function(windowInfo, appModel) { const AutoTypeFilter = function (windowInfo, appModel) {
this.title = windowInfo.title; this.title = windowInfo.title;
this.url = windowInfo.url; this.url = windowInfo.url;
this.text = ''; this.text = '';
@ -11,34 +11,34 @@ const AutoTypeFilter = function(windowInfo, appModel) {
this.appModel = appModel; this.appModel = appModel;
}; };
AutoTypeFilter.prototype.getEntries = function() { AutoTypeFilter.prototype.getEntries = function () {
const filter = { const filter = {
text: this.text, text: this.text,
autoType: true autoType: true
}; };
this.prepareFilter(); this.prepareFilter();
let entries = this.appModel.getEntriesByFilter(filter).map(e => [e, this.getEntryRank(e)]); let entries = this.appModel.getEntriesByFilter(filter).map((e) => [e, this.getEntryRank(e)]);
if (!this.ignoreWindowInfo) { if (!this.ignoreWindowInfo) {
entries = entries.filter(e => e[1]); entries = entries.filter((e) => e[1]);
} }
entries = entries.sort((x, y) => entries = entries.sort((x, y) =>
x[1] === y[1] ? x[0].title.localeCompare(y[0].title) : y[1] - x[1] x[1] === y[1] ? x[0].title.localeCompare(y[0].title) : y[1] - x[1]
); );
entries = entries.map(p => p[0]); entries = entries.map((p) => p[0]);
return new SearchResultCollection(entries, { comparator: 'none' }); return new SearchResultCollection(entries, { comparator: 'none' });
}; };
AutoTypeFilter.prototype.hasWindowInfo = function() { AutoTypeFilter.prototype.hasWindowInfo = function () {
return this.title || this.url; return this.title || this.url;
}; };
AutoTypeFilter.prototype.prepareFilter = function() { AutoTypeFilter.prototype.prepareFilter = function () {
this.titleLower = this.title ? this.title.toLowerCase() : null; this.titleLower = this.title ? this.title.toLowerCase() : null;
this.urlLower = this.url ? this.url.toLowerCase() : null; this.urlLower = this.url ? this.url.toLowerCase() : null;
this.urlParts = this.url ? urlPartsRegex.exec(this.urlLower) : null; this.urlParts = this.url ? urlPartsRegex.exec(this.urlLower) : null;
}; };
AutoTypeFilter.prototype.getEntryRank = function(entry) { AutoTypeFilter.prototype.getEntryRank = function (entry) {
let rank = 0; let rank = 0;
if (this.titleLower && entry.title) { if (this.titleLower && entry.title) {
rank += Ranking.getStringRank(entry.title.toLowerCase(), this.titleLower); rank += Ranking.getStringRank(entry.title.toLowerCase(), this.titleLower);

View File

@ -11,7 +11,7 @@ const MaxSteps = 1000;
const MaxCopy = 2; const MaxCopy = 2;
const FakeCharAlphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz123456789O0oIl'; const FakeCharAlphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz123456789O0oIl';
const AutoTypeObfuscator = function(chars) { const AutoTypeObfuscator = function (chars) {
this.chars = chars; this.chars = chars;
this.inputChars = []; this.inputChars = [];
this.inputCursor = 0; this.inputCursor = 0;
@ -21,7 +21,7 @@ const AutoTypeObfuscator = function(chars) {
this.copyCount = 0; this.copyCount = 0;
}; };
AutoTypeObfuscator.prototype.obfuscate = function() { AutoTypeObfuscator.prototype.obfuscate = function () {
while (!this.finished()) { while (!this.finished()) {
this.step(); this.step();
if (this.stepCount++ > MaxSteps) { if (this.stepCount++ > MaxSteps) {
@ -35,16 +35,16 @@ AutoTypeObfuscator.prototype.obfuscate = function() {
return this.ops; return this.ops;
}; };
AutoTypeObfuscator.prototype.finished = function() { AutoTypeObfuscator.prototype.finished = function () {
return ( return (
this.chars.length === this.inputChars.length && this.chars.length === this.inputChars.length &&
this.chars.every(function(ch, ix) { this.chars.every(function (ch, ix) {
return this.inputChars[ix].ch === ch; return this.inputChars[ix].ch === ch;
}, this) }, this)
); );
}; };
AutoTypeObfuscator.prototype.step = function() { AutoTypeObfuscator.prototype.step = function () {
const isFake = this.stepCount < MaxFakeOps && Math.random() > this.stepCount / MaxFakeOps; const isFake = this.stepCount < MaxFakeOps && Math.random() > this.stepCount / MaxFakeOps;
if (isFake) { if (isFake) {
this.stepFake(); this.stepFake();
@ -52,11 +52,11 @@ AutoTypeObfuscator.prototype.step = function() {
this.stepReal(); this.stepReal();
} }
if (logger.getLevel() >= Logger.Level.Debug) { if (logger.getLevel() >= Logger.Level.Debug) {
logger.debug('value', this.inputChars.map(ic => ic.ch).join('')); logger.debug('value', this.inputChars.map((ic) => ic.ch).join(''));
} }
}; };
AutoTypeObfuscator.prototype.stepFake = function() { AutoTypeObfuscator.prototype.stepFake = function () {
const pos = Math.floor(Math.random() * (this.inputChars.length + 1)); const pos = Math.floor(Math.random() * (this.inputChars.length + 1));
const ch = FakeCharAlphabet[Math.floor(Math.random() * FakeCharAlphabet.length)]; const ch = FakeCharAlphabet[Math.floor(Math.random() * FakeCharAlphabet.length)];
logger.info('step.fake', pos, ch); logger.info('step.fake', pos, ch);
@ -85,7 +85,7 @@ AutoTypeObfuscator.prototype.stepFake = function() {
} }
}; };
AutoTypeObfuscator.prototype.stepReal = function() { AutoTypeObfuscator.prototype.stepReal = function () {
const possibleActions = []; const possibleActions = [];
const inputRealPositions = []; const inputRealPositions = [];
let i; let i;
@ -134,7 +134,7 @@ AutoTypeObfuscator.prototype.stepReal = function() {
} }
}; };
AutoTypeObfuscator.prototype.moveToPos = function(pos) { AutoTypeObfuscator.prototype.moveToPos = function (pos) {
logger.debug('moveToPos', pos); logger.debug('moveToPos', pos);
while (this.inputCursor > pos) { while (this.inputCursor > pos) {
this.moveLeft(); this.moveLeft();
@ -144,21 +144,21 @@ AutoTypeObfuscator.prototype.moveToPos = function(pos) {
} }
}; };
AutoTypeObfuscator.prototype.moveLeft = function() { AutoTypeObfuscator.prototype.moveLeft = function () {
logger.debug('moveLeft'); logger.debug('moveLeft');
this.ops.push({ type: 'key', value: 'left' }); this.ops.push({ type: 'key', value: 'left' });
this.inputCursor--; this.inputCursor--;
this.inputSel = 0; this.inputSel = 0;
}; };
AutoTypeObfuscator.prototype.moveRight = function() { AutoTypeObfuscator.prototype.moveRight = function () {
logger.debug('moveRight'); logger.debug('moveRight');
this.ops.push({ type: 'key', value: 'right' }); this.ops.push({ type: 'key', value: 'right' });
this.inputCursor++; this.inputCursor++;
this.inputSel = 0; this.inputSel = 0;
}; };
AutoTypeObfuscator.prototype.inputChar = function(ch) { AutoTypeObfuscator.prototype.inputChar = function (ch) {
logger.debug('inputChar', ch); logger.debug('inputChar', ch);
this.ops.push({ type: 'text', value: ch }); this.ops.push({ type: 'text', value: ch });
this.inputChars.splice(this.inputCursor, this.inputSel, { ch }); this.inputChars.splice(this.inputCursor, this.inputSel, { ch });
@ -166,7 +166,7 @@ AutoTypeObfuscator.prototype.inputChar = function(ch) {
this.inputSel = 0; this.inputSel = 0;
}; };
AutoTypeObfuscator.prototype.copyPaste = function(ch) { AutoTypeObfuscator.prototype.copyPaste = function (ch) {
logger.debug('copyPaste', ch); logger.debug('copyPaste', ch);
this.ops.push({ type: 'cmd', value: 'copyPaste', arg: ch }); this.ops.push({ type: 'cmd', value: 'copyPaste', arg: ch });
this.inputChars.splice(this.inputCursor, this.inputSel, { ch }); this.inputChars.splice(this.inputCursor, this.inputSel, { ch });
@ -174,7 +174,7 @@ AutoTypeObfuscator.prototype.copyPaste = function(ch) {
this.inputSel = 0; this.inputSel = 0;
}; };
AutoTypeObfuscator.prototype.selectText = function(backward, count) { AutoTypeObfuscator.prototype.selectText = function (backward, count) {
logger.debug('selectText', backward ? 'left' : 'right', count); logger.debug('selectText', backward ? 'left' : 'right', count);
const ops = []; const ops = [];
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
@ -192,7 +192,7 @@ AutoTypeObfuscator.prototype.selectText = function(backward, count) {
this.inputSel = count; this.inputSel = count;
}; };
AutoTypeObfuscator.prototype.deleteText = function(backward) { AutoTypeObfuscator.prototype.deleteText = function (backward) {
logger.debug('deleteText', backward ? 'left' : 'right'); logger.debug('deleteText', backward ? 'left' : 'right');
this.ops.push({ type: 'key', value: backward ? 'bs' : 'del' }); this.ops.push({ type: 'key', value: backward ? 'bs' : 'del' });
if (this.inputSel) { if (this.inputSel) {

View File

@ -1,6 +1,6 @@
import { AutoTypeRunner } from 'auto-type/auto-type-runner'; import { AutoTypeRunner } from 'auto-type/auto-type-runner';
const AutoTypeParser = function(sequence) { const AutoTypeParser = function (sequence) {
this.sequence = sequence; this.sequence = sequence;
this.ix = 0; this.ix = 0;
this.states = []; this.states = [];
@ -8,7 +8,7 @@ const AutoTypeParser = function(sequence) {
AutoTypeParser.opRegex = /^(.*?)(?:([\s:=])[\s:=]*(.*))?$/; AutoTypeParser.opRegex = /^(.*?)(?:([\s:=])[\s:=]*(.*))?$/;
AutoTypeParser.prototype.parse = function() { AutoTypeParser.prototype.parse = function () {
const len = this.sequence.length; const len = this.sequence.length;
this.pushState(); this.pushState();
while (this.ix < len) { while (this.ix < len) {
@ -45,14 +45,14 @@ AutoTypeParser.prototype.parse = function() {
return new AutoTypeRunner(this.state().ops); return new AutoTypeRunner(this.state().ops);
}; };
AutoTypeParser.prototype.pushState = function() { AutoTypeParser.prototype.pushState = function () {
this.states.unshift({ this.states.unshift({
modifiers: null, modifiers: null,
ops: [] ops: []
}); });
}; };
AutoTypeParser.prototype.popState = function() { AutoTypeParser.prototype.popState = function () {
if (this.states.length <= 1) { if (this.states.length <= 1) {
throw 'Unexpected ")" at index ' + this.ix; throw 'Unexpected ")" at index ' + this.ix;
} }
@ -60,11 +60,11 @@ AutoTypeParser.prototype.popState = function() {
this.addState(state); this.addState(state);
}; };
AutoTypeParser.prototype.state = function() { AutoTypeParser.prototype.state = function () {
return this.states[0]; return this.states[0];
}; };
AutoTypeParser.prototype.readOp = function() { AutoTypeParser.prototype.readOp = function () {
const toIx = this.sequence.indexOf('}', this.ix + 2); const toIx = this.sequence.indexOf('}', this.ix + 2);
if (toIx < 0) { if (toIx < 0) {
throw 'Mismatched "{" at index ' + this.ix; throw 'Mismatched "{" at index ' + this.ix;
@ -79,7 +79,7 @@ AutoTypeParser.prototype.readOp = function() {
this.addOp(op, sep, arg); this.addOp(op, sep, arg);
}; };
AutoTypeParser.prototype.readModifier = function(modifier) { AutoTypeParser.prototype.readModifier = function (modifier) {
const state = this.state(); const state = this.state();
if (!state.modifiers) { if (!state.modifiers) {
state.modifiers = {}; state.modifiers = {};
@ -91,14 +91,14 @@ AutoTypeParser.prototype.readModifier = function(modifier) {
state.modifiers[modifier] = true; state.modifiers[modifier] = true;
}; };
AutoTypeParser.prototype.resetModifiers = function() { AutoTypeParser.prototype.resetModifiers = function () {
const state = this.state(); const state = this.state();
const modifiers = state.modifiers; const modifiers = state.modifiers;
state.modifiers = null; state.modifiers = null;
return modifiers; return modifiers;
}; };
AutoTypeParser.prototype.addState = function(state) { AutoTypeParser.prototype.addState = function (state) {
this.state().ops.push({ this.state().ops.push({
type: 'group', type: 'group',
value: state.ops, value: state.ops,
@ -106,7 +106,7 @@ AutoTypeParser.prototype.addState = function(state) {
}); });
}; };
AutoTypeParser.prototype.addChar = function(ch) { AutoTypeParser.prototype.addChar = function (ch) {
this.state().ops.push({ this.state().ops.push({
type: 'text', type: 'text',
value: ch, value: ch,
@ -114,7 +114,7 @@ AutoTypeParser.prototype.addChar = function(ch) {
}); });
}; };
AutoTypeParser.prototype.addOp = function(op, sep, arg) { AutoTypeParser.prototype.addOp = function (op, sep, arg) {
this.state().ops.push({ this.state().ops.push({
type: 'op', type: 'op',
value: op, value: op,

View File

@ -9,7 +9,7 @@ const emitterLogger = new Logger(
localStorage.debugAutoType ? Logger.Level.All : Logger.Level.Warn localStorage.debugAutoType ? Logger.Level.All : Logger.Level.Warn
); );
const AutoTypeRunner = function(ops) { const AutoTypeRunner = function (ops) {
this.ops = ops; this.ops = ops;
this.pendingResolvesCount = 0; this.pendingResolvesCount = 0;
this.entry = null; this.entry = null;
@ -142,7 +142,7 @@ AutoTypeRunner.Substitutions = {
} }
}; };
AutoTypeRunner.prototype.resolve = function(entry, context, callback) { AutoTypeRunner.prototype.resolve = function (entry, context, callback) {
this.entry = entry; this.entry = entry;
this.context = context; this.context = context;
try { try {
@ -157,7 +157,7 @@ AutoTypeRunner.prototype.resolve = function(entry, context, callback) {
} }
}; };
AutoTypeRunner.prototype.resolveOps = function(ops) { AutoTypeRunner.prototype.resolveOps = function (ops) {
for (let i = 0, len = ops.length; i < len; i++) { for (let i = 0, len = ops.length; i < len; i++) {
const op = ops[i]; const op = ops[i];
if (op.type === 'group') { if (op.type === 'group') {
@ -168,7 +168,7 @@ AutoTypeRunner.prototype.resolveOps = function(ops) {
} }
}; };
AutoTypeRunner.prototype.resolveOp = function(op) { AutoTypeRunner.prototype.resolveOp = function (op) {
if (op.value.length === 1 && !op.sep) { if (op.value.length === 1 && !op.sep) {
// {x} // {x}
op.type = 'text'; op.type = 'text';
@ -224,7 +224,7 @@ AutoTypeRunner.prototype.resolveOp = function(op) {
} }
}; };
AutoTypeRunner.prototype.tryParseCommand = function(op) { AutoTypeRunner.prototype.tryParseCommand = function (op) {
switch (op.value.toLowerCase()) { switch (op.value.toLowerCase()) {
case 'clearfield': case 'clearfield':
// {CLEARFIELD} // {CLEARFIELD}
@ -263,7 +263,7 @@ AutoTypeRunner.prototype.tryParseCommand = function(op) {
} }
}; };
AutoTypeRunner.prototype.getEntryFieldKeys = function(field, op) { AutoTypeRunner.prototype.getEntryFieldKeys = function (field, op) {
if (!field || !this.entry) { if (!field || !this.entry) {
return ''; return '';
} }
@ -274,7 +274,7 @@ AutoTypeRunner.prototype.getEntryFieldKeys = function(field, op) {
if (value.isProtected) { if (value.isProtected) {
op.type = 'group'; op.type = 'group';
const ops = []; const ops = [];
value.forEachChar(ch => { value.forEachChar((ch) => {
if (ch === 10 || ch === 13) { if (ch === 10 || ch === 13) {
ops.push({ type: 'key', value: 'enter' }); ops.push({ type: 'key', value: 'enter' });
} else { } else {
@ -289,7 +289,7 @@ AutoTypeRunner.prototype.getEntryFieldKeys = function(field, op) {
} }
op.type = 'group'; op.type = 'group';
const partsOps = []; const partsOps = [];
parts.forEach(part => { parts.forEach((part) => {
if (partsOps.length) { if (partsOps.length) {
partsOps.push({ type: 'key', value: 'enter' }); partsOps.push({ type: 'key', value: 'enter' });
} }
@ -301,11 +301,11 @@ AutoTypeRunner.prototype.getEntryFieldKeys = function(field, op) {
} }
}; };
AutoTypeRunner.prototype.getEntryGroupName = function() { AutoTypeRunner.prototype.getEntryGroupName = function () {
return this.entry && this.entry.group.title; return this.entry && this.entry.group.title;
}; };
AutoTypeRunner.prototype.dt = function(part) { AutoTypeRunner.prototype.dt = function (part) {
switch (part) { switch (part) {
case 'simple': case 'simple':
return ( return (
@ -333,7 +333,7 @@ AutoTypeRunner.prototype.dt = function(part) {
} }
}; };
AutoTypeRunner.prototype.udt = function(part) { AutoTypeRunner.prototype.udt = function (part) {
switch (part) { switch (part) {
case 'simple': case 'simple':
return ( return (
@ -361,7 +361,7 @@ AutoTypeRunner.prototype.udt = function(part) {
} }
}; };
AutoTypeRunner.prototype.getOtp = function(op) { AutoTypeRunner.prototype.getOtp = function (op) {
if (!this.entry) { if (!this.entry) {
return ''; return '';
} }
@ -375,7 +375,7 @@ AutoTypeRunner.prototype.getOtp = function(op) {
return AutoTypeRunner.PendingResolve; return AutoTypeRunner.PendingResolve;
}; };
AutoTypeRunner.prototype.pendingResolved = function(op, value, error) { AutoTypeRunner.prototype.pendingResolved = function (op, value, error) {
const wasPending = op.value === AutoTypeRunner.PendingResolve; const wasPending = op.value === AutoTypeRunner.PendingResolve;
if (value) { if (value) {
op.value = value; op.value = value;
@ -390,11 +390,11 @@ AutoTypeRunner.prototype.pendingResolved = function(op, value, error) {
} }
}; };
AutoTypeRunner.prototype.obfuscate = function() { AutoTypeRunner.prototype.obfuscate = function () {
this.obfuscateOps(this.ops); this.obfuscateOps(this.ops);
}; };
AutoTypeRunner.prototype.obfuscateOps = function(ops) { AutoTypeRunner.prototype.obfuscateOps = function (ops) {
for (let i = 0, len = ops.length; i < len; i++) { for (let i = 0, len = ops.length; i < len; i++) {
const op = ops[i]; const op = ops[i];
if (op.mod) { if (op.mod) {
@ -403,7 +403,7 @@ AutoTypeRunner.prototype.obfuscateOps = function(ops) {
if (op.type === 'text') { if (op.type === 'text') {
this.obfuscateOp(op); this.obfuscateOp(op);
} else if (op.type === 'group') { } else if (op.type === 'group') {
const onlyText = op.value.every(grOp => grOp.type === 'text' && !grOp.mod); const onlyText = op.value.every((grOp) => grOp.type === 'text' && !grOp.mod);
if (onlyText) { if (onlyText) {
this.obfuscateOp(op); this.obfuscateOp(op);
} else { } else {
@ -413,7 +413,7 @@ AutoTypeRunner.prototype.obfuscateOps = function(ops) {
} }
}; };
AutoTypeRunner.prototype.obfuscateOp = function(op) { AutoTypeRunner.prototype.obfuscateOp = function (op) {
let letters = []; let letters = [];
if (op.type === 'text') { if (op.type === 'text') {
if (!op.value || op.value.length <= 1) { if (!op.value || op.value.length <= 1) {
@ -421,7 +421,7 @@ AutoTypeRunner.prototype.obfuscateOp = function(op) {
} }
letters = op.value.split(''); letters = op.value.split('');
} else { } else {
op.value.forEach(grOp => letters.push(...grOp.value.split(''))); op.value.forEach((grOp) => letters.push(...grOp.value.split('')));
} }
if (letters.length <= 1) { if (letters.length <= 1) {
return; return;
@ -431,7 +431,7 @@ AutoTypeRunner.prototype.obfuscateOp = function(op) {
op.type = 'group'; op.type = 'group';
}; };
AutoTypeRunner.prototype.run = function(callback, windowId) { AutoTypeRunner.prototype.run = function (callback, windowId) {
this.emitter = AutoTypeEmitterFactory.create(this.emitNext.bind(this), windowId); this.emitter = AutoTypeEmitterFactory.create(this.emitNext.bind(this), windowId);
this.emitterState = { this.emitterState = {
callback, callback,
@ -445,7 +445,7 @@ AutoTypeRunner.prototype.run = function(callback, windowId) {
this.emitNext(); this.emitNext();
}; };
AutoTypeRunner.prototype.emitNext = function(err) { AutoTypeRunner.prototype.emitNext = function (err) {
if (err) { if (err) {
this.emitterState.finished = true; this.emitterState.finished = true;
this.emitterState.callback(err); this.emitterState.callback(err);
@ -518,8 +518,8 @@ AutoTypeRunner.prototype.emitNext = function(err) {
} }
}; };
AutoTypeRunner.prototype.setEmitterMod = function(addedMod) { AutoTypeRunner.prototype.setEmitterMod = function (addedMod) {
Object.keys(addedMod).forEach(function(mod) { Object.keys(addedMod).forEach(function (mod) {
if (addedMod[mod] && !this.emitterState.activeMod[mod]) { if (addedMod[mod] && !this.emitterState.activeMod[mod]) {
emitterLogger.debug('mod', mod, true); emitterLogger.debug('mod', mod, true);
this.emitter.setMod(mod, true); this.emitter.setMod(mod, true);
@ -528,8 +528,8 @@ AutoTypeRunner.prototype.setEmitterMod = function(addedMod) {
}, this); }, this);
}; };
AutoTypeRunner.prototype.resetEmitterMod = function(targetState) { AutoTypeRunner.prototype.resetEmitterMod = function (targetState) {
Object.keys(this.emitterState.activeMod).forEach(function(mod) { Object.keys(this.emitterState.activeMod).forEach(function (mod) {
if (this.emitterState.activeMod[mod] && !targetState[mod]) { if (this.emitterState.activeMod[mod] && !targetState[mod]) {
emitterLogger.debug('mod', mod, false); emitterLogger.debug('mod', mod, false);
this.emitter.setMod(mod, false); this.emitter.setMod(mod, false);

View File

@ -59,13 +59,13 @@ const ModMap = {
'^^': '^' '^^': '^'
}; };
const AutoTypeEmitter = function(callback) { const AutoTypeEmitter = function (callback) {
this.callback = callback; this.callback = callback;
this.mod = {}; this.mod = {};
this.pendingScript = []; this.pendingScript = [];
}; };
AutoTypeEmitter.prototype.setMod = function(mod, enabled) { AutoTypeEmitter.prototype.setMod = function (mod, enabled) {
if (enabled) { if (enabled) {
this.mod[ModMap[mod]] = true; this.mod[ModMap[mod]] = true;
} else { } else {
@ -73,12 +73,12 @@ AutoTypeEmitter.prototype.setMod = function(mod, enabled) {
} }
}; };
AutoTypeEmitter.prototype.text = function(text) { AutoTypeEmitter.prototype.text = function (text) {
this.pendingScript.push('text ' + this.modString() + ' ' + text); this.pendingScript.push('text ' + this.modString() + ' ' + text);
this.callback(); this.callback();
}; };
AutoTypeEmitter.prototype.key = function(key) { AutoTypeEmitter.prototype.key = function (key) {
if (typeof key !== 'number') { if (typeof key !== 'number') {
if (!KeyMap[key]) { if (!KeyMap[key]) {
return this.callback('Bad key: ' + key); return this.callback('Bad key: ' + key);
@ -89,17 +89,17 @@ AutoTypeEmitter.prototype.key = function(key) {
this.callback(); this.callback();
}; };
AutoTypeEmitter.prototype.copyPaste = function(text) { AutoTypeEmitter.prototype.copyPaste = function (text) {
this.pendingScript.push('copypaste ' + text); this.pendingScript.push('copypaste ' + text);
this.callback(); this.callback();
}; };
AutoTypeEmitter.prototype.wait = function(time) { AutoTypeEmitter.prototype.wait = function (time) {
this.pendingScript.push('wait ' + time); this.pendingScript.push('wait ' + time);
this.callback(); this.callback();
}; };
AutoTypeEmitter.prototype.waitComplete = function() { AutoTypeEmitter.prototype.waitComplete = function () {
if (this.pendingScript.length) { if (this.pendingScript.length) {
const script = this.pendingScript.join('\n'); const script = this.pendingScript.join('\n');
this.pendingScript.length = 0; this.pendingScript.length = 0;
@ -109,16 +109,16 @@ AutoTypeEmitter.prototype.waitComplete = function() {
} }
}; };
AutoTypeEmitter.prototype.setDelay = function(delay) { AutoTypeEmitter.prototype.setDelay = function (delay) {
this.delay = delay || 0; this.delay = delay || 0;
this.callback('Not implemented'); this.callback('Not implemented');
}; };
AutoTypeEmitter.prototype.modString = function() { AutoTypeEmitter.prototype.modString = function () {
return Object.keys(this.mod).join(''); return Object.keys(this.mod).join('');
}; };
AutoTypeEmitter.prototype.runScript = function(script) { AutoTypeEmitter.prototype.runScript = function (script) {
Launcher.spawn({ Launcher.spawn({
cmd: AutoTypeNativeHelper.getHelperPath(), cmd: AutoTypeNativeHelper.getHelperPath(),
data: script, data: script,

View File

@ -59,7 +59,7 @@ const ModMap = {
'^^': 'ctrl' '^^': 'ctrl'
}; };
const AutoTypeEmitter = function(callback, windowId) { const AutoTypeEmitter = function (callback, windowId) {
this.callback = callback; this.callback = callback;
if (typeof windowId !== 'undefined' && windowId) { if (typeof windowId !== 'undefined' && windowId) {
this.windowParameter = '--window ' + windowId + ' '; this.windowParameter = '--window ' + windowId + ' ';
@ -70,7 +70,7 @@ const AutoTypeEmitter = function(callback, windowId) {
this.pendingScript = []; this.pendingScript = [];
}; };
AutoTypeEmitter.prototype.setMod = function(mod, enabled) { AutoTypeEmitter.prototype.setMod = function (mod, enabled) {
if (enabled) { if (enabled) {
this.mod[ModMap[mod]] = true; this.mod[ModMap[mod]] = true;
} else { } else {
@ -78,23 +78,23 @@ AutoTypeEmitter.prototype.setMod = function(mod, enabled) {
} }
}; };
AutoTypeEmitter.prototype.text = function(text) { AutoTypeEmitter.prototype.text = function (text) {
this.pendingScript.push('keyup ctrl alt shift t'); this.pendingScript.push('keyup ctrl alt shift t');
Object.keys(this.mod).forEach(mod => { Object.keys(this.mod).forEach((mod) => {
this.pendingScript.push('keydown ' + this.windowParameter + ModMap[mod]); this.pendingScript.push('keydown ' + this.windowParameter + ModMap[mod]);
}); });
text.split('').forEach(char => { text.split('').forEach((char) => {
this.pendingScript.push( this.pendingScript.push(
'key ' + this.windowParameter + 'U' + char.charCodeAt(0).toString(16) 'key ' + this.windowParameter + 'U' + char.charCodeAt(0).toString(16)
); );
}); });
Object.keys(this.mod).forEach(mod => { Object.keys(this.mod).forEach((mod) => {
this.pendingScript.push('keyup ' + this.windowParameter + ModMap[mod]); this.pendingScript.push('keyup ' + this.windowParameter + ModMap[mod]);
}); });
this.waitComplete(); this.waitComplete();
}; };
AutoTypeEmitter.prototype.key = function(key) { AutoTypeEmitter.prototype.key = function (key) {
const isSpecialKey = typeof key !== 'number'; const isSpecialKey = typeof key !== 'number';
if (isSpecialKey) { if (isSpecialKey) {
if (!KeyMap[key]) { if (!KeyMap[key]) {
@ -112,7 +112,7 @@ AutoTypeEmitter.prototype.key = function(key) {
} }
}; };
AutoTypeEmitter.prototype.copyPaste = function(text) { AutoTypeEmitter.prototype.copyPaste = function (text) {
this.pendingScript.push('sleep 0.5'); this.pendingScript.push('sleep 0.5');
Launcher.setClipboardText(text); Launcher.setClipboardText(text);
this.pendingScript.push('key --clearmodifiers ' + this.windowParameter + 'shift+Insert'); this.pendingScript.push('key --clearmodifiers ' + this.windowParameter + 'shift+Insert');
@ -120,12 +120,12 @@ AutoTypeEmitter.prototype.copyPaste = function(text) {
this.waitComplete(); this.waitComplete();
}; };
AutoTypeEmitter.prototype.wait = function(time) { AutoTypeEmitter.prototype.wait = function (time) {
this.pendingScript.push('sleep ' + time / 1000); this.pendingScript.push('sleep ' + time / 1000);
this.callback(); this.callback();
}; };
AutoTypeEmitter.prototype.waitComplete = function(callback) { AutoTypeEmitter.prototype.waitComplete = function (callback) {
if (this.pendingScript.length) { if (this.pendingScript.length) {
const script = this.pendingScript.join(' '); const script = this.pendingScript.join(' ');
this.pendingScript.length = 0; this.pendingScript.length = 0;
@ -135,15 +135,15 @@ AutoTypeEmitter.prototype.waitComplete = function(callback) {
} }
}; };
AutoTypeEmitter.prototype.modString = function() { AutoTypeEmitter.prototype.modString = function () {
let mod = ''; let mod = '';
Object.keys(this.mod).forEach(key => { Object.keys(this.mod).forEach((key) => {
mod += key + '+'; mod += key + '+';
}); });
return mod; return mod;
}; };
AutoTypeEmitter.prototype.runScript = function(script, callback) { AutoTypeEmitter.prototype.runScript = function (script, callback) {
Launcher.spawn({ Launcher.spawn({
cmd: 'xdotool', cmd: 'xdotool',
args: ['-'], args: ['-'],

View File

@ -59,13 +59,13 @@ const ModMap = {
'^^': '^' '^^': '^'
}; };
const AutoTypeEmitter = function(callback) { const AutoTypeEmitter = function (callback) {
this.callback = callback; this.callback = callback;
this.mod = {}; this.mod = {};
this.pendingScript = []; this.pendingScript = [];
}; };
AutoTypeEmitter.prototype.setMod = function(mod, enabled) { AutoTypeEmitter.prototype.setMod = function (mod, enabled) {
if (enabled) { if (enabled) {
this.mod[ModMap[mod]] = true; this.mod[ModMap[mod]] = true;
} else { } else {
@ -73,14 +73,14 @@ AutoTypeEmitter.prototype.setMod = function(mod, enabled) {
} }
}; };
AutoTypeEmitter.prototype.text = function(text) { AutoTypeEmitter.prototype.text = function (text) {
if (text) { if (text) {
this.pendingScript.push('text ' + this.modStr() + ' ' + text); this.pendingScript.push('text ' + this.modStr() + ' ' + text);
} }
this.callback(); this.callback();
}; };
AutoTypeEmitter.prototype.key = function(key) { AutoTypeEmitter.prototype.key = function (key) {
if (typeof key !== 'number') { if (typeof key !== 'number') {
if (!KeyMap[key]) { if (!KeyMap[key]) {
return this.callback('Bad key: ' + key); return this.callback('Bad key: ' + key);
@ -91,17 +91,17 @@ AutoTypeEmitter.prototype.key = function(key) {
this.callback(); this.callback();
}; };
AutoTypeEmitter.prototype.copyPaste = function(text) { AutoTypeEmitter.prototype.copyPaste = function (text) {
this.pendingScript.push('copypaste ' + text); this.pendingScript.push('copypaste ' + text);
this.callback(); this.callback();
}; };
AutoTypeEmitter.prototype.wait = function(time) { AutoTypeEmitter.prototype.wait = function (time) {
this.pendingScript.push('wait ' + time); this.pendingScript.push('wait ' + time);
this.callback(); this.callback();
}; };
AutoTypeEmitter.prototype.waitComplete = function() { AutoTypeEmitter.prototype.waitComplete = function () {
if (this.pendingScript.length) { if (this.pendingScript.length) {
const script = this.pendingScript.join('\n'); const script = this.pendingScript.join('\n');
this.pendingScript.length = 0; this.pendingScript.length = 0;
@ -111,16 +111,16 @@ AutoTypeEmitter.prototype.waitComplete = function() {
} }
}; };
AutoTypeEmitter.prototype.setDelay = function(delay) { AutoTypeEmitter.prototype.setDelay = function (delay) {
this.delay = delay || 0; this.delay = delay || 0;
this.callback('Not implemented'); this.callback('Not implemented');
}; };
AutoTypeEmitter.prototype.modStr = function() { AutoTypeEmitter.prototype.modStr = function () {
return Object.keys(this.mod).join(''); return Object.keys(this.mod).join('');
}; };
AutoTypeEmitter.prototype.runScript = function(script) { AutoTypeEmitter.prototype.runScript = function (script) {
Launcher.spawn({ Launcher.spawn({
cmd: AutoTypeNativeHelper.getHelperPath(), cmd: AutoTypeNativeHelper.getHelperPath(),
data: script, data: script,

View File

@ -23,9 +23,9 @@ const OtherAppsScript =
' end tell\n' + ' end tell\n' +
'end tell'; 'end tell';
const AutoTypeHelper = function() {}; const AutoTypeHelper = function () {};
AutoTypeHelper.prototype.getActiveWindowInfo = function(callback) { AutoTypeHelper.prototype.getActiveWindowInfo = function (callback) {
AutoTypeHelper.exec(ForeMostAppScript, (err, out) => { AutoTypeHelper.exec(ForeMostAppScript, (err, out) => {
if (err) { if (err) {
return callback(err); return callback(err);
@ -81,7 +81,7 @@ AutoTypeHelper.prototype.getActiveWindowInfo = function(callback) {
}); });
}; };
AutoTypeHelper.exec = function(script, callback) { AutoTypeHelper.exec = function (script, callback) {
Launcher.spawn({ Launcher.spawn({
cmd: 'osascript', cmd: 'osascript',
args: ['-e', script], args: ['-e', script],

View File

@ -1,8 +1,8 @@
import { Launcher } from 'comp/launcher'; import { Launcher } from 'comp/launcher';
const AutoTypeHelper = function() {}; const AutoTypeHelper = function () {};
AutoTypeHelper.prototype.getActiveWindowInfo = function(callback) { AutoTypeHelper.prototype.getActiveWindowInfo = function (callback) {
Launcher.spawn({ Launcher.spawn({
cmd: 'xdotool', cmd: 'xdotool',
args: ['getactivewindow', 'getwindowname', 'getactivewindow'], args: ['getactivewindow', 'getwindowname', 'getactivewindow'],

View File

@ -1,9 +1,9 @@
import { AutoTypeNativeHelper } from 'auto-type/helper/auto-type-native-helper'; import { AutoTypeNativeHelper } from 'auto-type/helper/auto-type-native-helper';
import { Launcher } from 'comp/launcher'; import { Launcher } from 'comp/launcher';
const AutoTypeHelper = function() {}; const AutoTypeHelper = function () {};
AutoTypeHelper.prototype.getActiveWindowInfo = function(callback) { AutoTypeHelper.prototype.getActiveWindowInfo = function (callback) {
Launcher.spawn({ Launcher.spawn({
cmd: AutoTypeNativeHelper.getHelperPath(), cmd: AutoTypeNativeHelper.getHelperPath(),
args: ['--window-info'], args: ['--window-info'],

View File

@ -26,11 +26,11 @@ const AutoType = {
if (!this.enabled) { if (!this.enabled) {
return; return;
} }
Events.on('auto-type', e => this.handleEvent(e)); Events.on('auto-type', (e) => this.handleEvent(e));
Events.on('main-window-blur', e => this.mainWindowBlur(e)); Events.on('main-window-blur', (e) => this.mainWindowBlur(e));
Events.on('main-window-focus', e => this.mainWindowFocus(e)); Events.on('main-window-focus', (e) => this.mainWindowFocus(e));
Events.on('main-window-will-close', e => this.mainWindowWillClose(e)); Events.on('main-window-will-close', (e) => this.mainWindowWillClose(e));
Events.on('closed-open-view', e => this.processPendingEvent(e)); Events.on('closed-open-view', (e) => this.processPendingEvent(e));
}, },
handleEvent(e) { handleEvent(e) {
@ -62,7 +62,7 @@ const AutoType = {
}, },
runAndHandleResult(result, windowId) { runAndHandleResult(result, windowId) {
this.run(result, windowId, err => { this.run(result, windowId, (err) => {
if (err) { if (err) {
Alerts.error({ Alerts.error({
header: Locale.autoTypeError, header: Locale.autoTypeError,
@ -86,7 +86,7 @@ const AutoType = {
const parser = new AutoTypeParser(sequence); const parser = new AutoTypeParser(sequence);
const runner = parser.parse(); const runner = parser.parse();
logger.debug('Parsed', this.printOps(runner.ops)); logger.debug('Parsed', this.printOps(runner.ops));
runner.resolve(result.entry, context, err => { runner.resolve(result.entry, context, (err) => {
if (err) { if (err) {
this.running = false; this.running = false;
logger.error('Resolve error', err); logger.error('Resolve error', err);
@ -103,7 +103,7 @@ const AutoType = {
} }
logger.debug('Obfuscated'); logger.debug('Obfuscated');
} }
runner.run(err => { runner.run((err) => {
this.running = false; this.running = false;
if (err) { if (err) {
logger.error('Run error', err); logger.error('Run error', err);
@ -237,7 +237,7 @@ const AutoType = {
this.focusMainWindow(); this.focusMainWindow();
evt.filter.ignoreWindowInfo = true; evt.filter.ignoreWindowInfo = true;
this.selectEntryView = new AutoTypeSelectView({ filter: evt.filter }); this.selectEntryView = new AutoTypeSelectView({ filter: evt.filter });
this.selectEntryView.on('result', result => { this.selectEntryView.on('result', (result) => {
logger.debug('Entry selected', result); logger.debug('Entry selected', result);
this.selectEntryView.off('result'); this.selectEntryView.off('result');
this.selectEntryView.remove(); this.selectEntryView.remove();

View File

@ -5,19 +5,19 @@ class FileCollection extends Collection {
static model = Model; static model = Model;
hasOpenFiles() { hasOpenFiles() {
return this.some(file => file.active); return this.some((file) => file.active);
} }
hasUnsavedFiles() { hasUnsavedFiles() {
return this.some(file => file.modified); return this.some((file) => file.modified);
} }
hasDirtyFiles() { hasDirtyFiles() {
return this.some(file => file.dirty); return this.some((file) => file.dirty);
} }
getByName(name) { getByName(name) {
return this.find(file => file.name.toLowerCase() === name.toLowerCase()); return this.find((file) => file.name.toLowerCase() === name.toLowerCase());
} }
} }

View File

@ -6,7 +6,7 @@ class FileInfoCollection extends Collection {
static model = FileInfoModel; static model = FileInfoModel;
load() { load() {
return SettingsStore.load('file-info').then(data => { return SettingsStore.load('file-info').then((data) => {
if (data) { if (data) {
for (const item of data) { for (const item of data) {
this.push(new FileInfoModel(item)); this.push(new FileInfoModel(item));
@ -20,7 +20,7 @@ class FileInfoCollection extends Collection {
} }
getMatch(storage, name, path) { getMatch(storage, name, path) {
return this.find(fi => { return this.find((fi) => {
return ( return (
(fi.storage || '') === (storage || '') && (fi.storage || '') === (storage || '') &&
(fi.name || '') === (name || '') && (fi.name || '') === (name || '') &&
@ -30,7 +30,7 @@ class FileInfoCollection extends Collection {
} }
getByName(name) { getByName(name) {
return this.find(file => file.name.toLowerCase() === name.toLowerCase()); return this.find((file) => file.name.toLowerCase() === name.toLowerCase());
} }
} }

View File

@ -17,7 +17,7 @@ const AppRightsChecker = {
if (!Launcher.getAppPath().startsWith(this.AppPath)) { if (!Launcher.getAppPath().startsWith(this.AppPath)) {
return; return;
} }
this.needRunInstaller(needRun => { this.needRunInstaller((needRun) => {
if (needRun) { if (needRun) {
this.showAlert(); this.showAlert();
this.runInstaller(); this.runInstaller();
@ -26,7 +26,7 @@ const AppRightsChecker = {
}, },
needRunInstaller(callback) { needRunInstaller(callback) {
Launcher.statFile(this.AppPath, stat => { Launcher.statFile(this.AppPath, (stat) => {
const folderIsRoot = stat && stat.uid === 0; const folderIsRoot = stat && stat.uid === 0;
callback(!folderIsRoot); callback(!folderIsRoot);
}); });
@ -46,7 +46,7 @@ const AppRightsChecker = {
{ result: 'skip', title: Locale.alertDoNotAsk, error: true }, { result: 'skip', title: Locale.alertDoNotAsk, error: true },
Alerts.buttons.ok Alerts.buttons.ok
], ],
success: result => { success: (result) => {
if (result === 'skip') { if (result === 'skip') {
this.dontAskAnymore(); this.dontAskAnymore();
} }
@ -59,7 +59,7 @@ const AppRightsChecker = {
Launcher.spawn({ Launcher.spawn({
cmd: this.AppPath + '/Contents/Installer/KeeWeb Installer.app/Contents/MacOS/applet', cmd: this.AppPath + '/Contents/Installer/KeeWeb Installer.app/Contents/MacOS/applet',
complete: () => { complete: () => {
this.needRunInstaller(needRun => { this.needRunInstaller((needRun) => {
if (this.alert && !needRun) { if (this.alert && !needRun) {
this.alert.closeWithResult('cancel'); this.alert.closeWithResult('cancel');
} }
@ -69,7 +69,7 @@ const AppRightsChecker = {
}, },
dontAskAnymore() { dontAskAnymore() {
this.needRunInstaller(needRun => { this.needRunInstaller((needRun) => {
if (needRun) { if (needRun) {
AppSettingsModel.skipFolderRightsWarning = true; AppSettingsModel.skipFolderRightsWarning = true;
} }

View File

@ -20,7 +20,7 @@ const ChalRespCalculator = {
if (!params) { if (!params) {
return null; return null;
} }
return challenge => { return (challenge) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
challenge = Buffer.from(challenge); challenge = Buffer.from(challenge);
const hexChallenge = challenge.toString('hex'); const hexChallenge = challenge.toString('hex');
@ -60,7 +60,7 @@ const ChalRespCalculator = {
if (err) { if (err) {
if (err.noKey) { if (err.noKey) {
logger.info('YubiKey ChalResp: no key'); logger.info('YubiKey ChalResp: no key');
this._showNoKeyAlert(params.serial, err => { this._showNoKeyAlert(params.serial, (err) => {
if (err) { if (err) {
return callback(err); return callback(err);
} }
@ -69,7 +69,7 @@ const ChalRespCalculator = {
return; return;
} else if (err.touchRequested) { } else if (err.touchRequested) {
logger.info('YubiKey ChalResp: touch requested'); logger.info('YubiKey ChalResp: touch requested');
touchAlert = this._showTouchAlert(params.serial, err => { touchAlert = this._showTouchAlert(params.serial, (err) => {
touchAlert = null; touchAlert = null;
userCanceled = true; userCanceled = true;
@ -114,7 +114,7 @@ const ChalRespCalculator = {
logger.error('YubiKey list error', err); logger.error('YubiKey list error', err);
return; return;
} }
const isAttached = list.some(yk => yk.serial === serial); const isAttached = list.some((yk) => yk.serial === serial);
logger.info(isAttached ? 'YubiKey found' : 'YubiKey not found'); logger.info(isAttached ? 'YubiKey found' : 'YubiKey not found');
if (isAttached) { if (isAttached) {
Events.off('usb-devices-changed', onUsbDevicesChanged); Events.off('usb-devices-changed', onUsbDevicesChanged);

View File

@ -3,19 +3,19 @@ import { UrlFormat } from 'util/formatting/url-format';
const ChooserAppKey = 'qp7ctun6qt5n9d6'; const ChooserAppKey = 'qp7ctun6qt5n9d6';
const DropboxChooser = function(callback) { const DropboxChooser = function (callback) {
this.cb = callback; this.cb = callback;
this.onMessage = this.onMessage.bind(this); this.onMessage = this.onMessage.bind(this);
}; };
DropboxChooser.prototype.callback = function(err, res) { DropboxChooser.prototype.callback = function (err, res) {
if (this.cb) { if (this.cb) {
this.cb(err, res); this.cb(err, res);
} }
this.cb = null; this.cb = null;
}; };
DropboxChooser.prototype.choose = function() { DropboxChooser.prototype.choose = function () {
const windowFeatures = 'width=640,height=552,left=357,top=100,resizable=yes,location=yes'; const windowFeatures = 'width=640,height=552,left=357,top=100,resizable=yes,location=yes';
const url = this.buildUrl(); const url = this.buildUrl();
this.popup = window.open(url, 'dropbox', windowFeatures); this.popup = window.open(url, 'dropbox', windowFeatures);
@ -26,7 +26,7 @@ DropboxChooser.prototype.choose = function() {
this.closeInt = setInterval(this.checkClose.bind(this), 200); this.closeInt = setInterval(this.checkClose.bind(this), 200);
}; };
DropboxChooser.prototype.buildUrl = function() { DropboxChooser.prototype.buildUrl = function () {
return UrlFormat.makeUrl('https://www.dropbox.com/chooser', { return UrlFormat.makeUrl('https://www.dropbox.com/chooser', {
origin: window.location.protocol + '//' + window.location.host, origin: window.location.protocol + '//' + window.location.host,
'app_key': AppSettingsModel.dropboxAppKey || ChooserAppKey, 'app_key': AppSettingsModel.dropboxAppKey || ChooserAppKey,
@ -40,7 +40,7 @@ DropboxChooser.prototype.buildUrl = function() {
}); });
}; };
DropboxChooser.prototype.onMessage = function(e) { DropboxChooser.prototype.onMessage = function (e) {
if (e.source !== this.popup || e.origin !== 'https://www.dropbox.com') { if (e.source !== this.popup || e.origin !== 'https://www.dropbox.com') {
return; return;
} }
@ -69,7 +69,7 @@ DropboxChooser.prototype.onMessage = function(e) {
} }
}; };
DropboxChooser.prototype.checkClose = function() { DropboxChooser.prototype.checkClose = function () {
if (this.popup.closed) { if (this.popup.closed) {
clearInterval(this.closeInt); clearInterval(this.closeInt);
window.removeEventListener('message', this.onMessage); window.removeEventListener('message', this.onMessage);
@ -79,7 +79,7 @@ DropboxChooser.prototype.checkClose = function() {
} }
}; };
DropboxChooser.prototype.success = function(params) { DropboxChooser.prototype.success = function (params) {
if (!params || !params[0] || !params[0].link || params[0].is_dir) { if (!params || !params[0] || !params[0].link || params[0].is_dir) {
return this.callback('bad result'); return this.callback('bad result');
} }
@ -87,7 +87,7 @@ DropboxChooser.prototype.success = function(params) {
this.readFile(this.result.link); this.readFile(this.result.link);
}; };
DropboxChooser.prototype.readFile = function(url) { DropboxChooser.prototype.readFile = function (url) {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => { xhr.addEventListener('load', () => {
this.callback(null, { name: this.result.name, data: xhr.response }); this.callback(null, { name: this.result.name, data: xhr.response });

View File

@ -67,16 +67,16 @@ const GeneratorPresets = {
get all() { get all() {
let presets = this.builtIn; let presets = this.builtIn;
presets.forEach(preset => { presets.forEach((preset) => {
preset.builtIn = true; preset.builtIn = true;
}); });
const setting = AppSettingsModel.generatorPresets; const setting = AppSettingsModel.generatorPresets;
if (setting) { if (setting) {
if (setting.user) { if (setting.user) {
presets = presets.concat(setting.user.map(item => ({ ...item }))); presets = presets.concat(setting.user.map((item) => ({ ...item })));
} }
let hasDefault = false; let hasDefault = false;
presets.forEach(preset => { presets.forEach((preset) => {
if (setting.disabled && setting.disabled[preset.name]) { if (setting.disabled && setting.disabled[preset.name]) {
preset.disabled = true; preset.disabled = true;
} }
@ -93,7 +93,7 @@ const GeneratorPresets = {
}, },
get enabled() { get enabled() {
const allPresets = this.all.filter(preset => !preset.disabled); const allPresets = this.all.filter((preset) => !preset.disabled);
if (!allPresets.length) { if (!allPresets.length) {
allPresets.push(this.defaultPreset); allPresets.push(this.defaultPreset);
} }
@ -110,7 +110,7 @@ const GeneratorPresets = {
add(preset) { add(preset) {
const setting = this.getOrCreateSetting(); const setting = this.getOrCreateSetting();
if (preset.name && !setting.user.filter(p => p.name === preset.name).length) { if (preset.name && !setting.user.filter((p) => p.name === preset.name).length) {
setting.user.push(preset); setting.user.push(preset);
this.save(setting); this.save(setting);
} }
@ -118,13 +118,13 @@ const GeneratorPresets = {
remove(name) { remove(name) {
const setting = this.getOrCreateSetting(); const setting = this.getOrCreateSetting();
setting.user = setting.user.filter(p => p.name !== name); setting.user = setting.user.filter((p) => p.name !== name);
this.save(setting); this.save(setting);
}, },
setPreset(name, props) { setPreset(name, props) {
const setting = this.getOrCreateSetting(); const setting = this.getOrCreateSetting();
const preset = setting.user.filter(p => p.name === name)[0]; const preset = setting.user.filter((p) => p.name === name)[0];
if (preset) { if (preset) {
Object.assign(preset, props); Object.assign(preset, props);
this.save(setting); this.save(setting);

View File

@ -56,7 +56,7 @@ const Shortcuts = {
} }
return shortcutValue return shortcutValue
.split(/\+/g) .split(/\+/g)
.map(part => { .map((part) => {
switch (part) { switch (part) {
case 'Ctrl': case 'Ctrl':
return this.ctrlShortcutSymbol(formatting); return this.ctrlShortcutSymbol(formatting);

View File

@ -30,7 +30,7 @@ const StartProfiler = {
printReport(name, operations, totalTime) { printReport(name, operations, totalTime) {
const message = const message =
`${name} started in ${totalTime}ms: ` + `${name} started in ${totalTime}ms: ` +
operations.map(op => `${op.name}=${Math.round(op.elapsed)}ms`).join(', '); operations.map((op) => `${op.name}=${Math.round(op.elapsed)}ms`).join(', ');
logger.info(message); logger.info(message);
}, },

View File

@ -43,7 +43,7 @@ const Updater = {
if (!Launcher && navigator.serviceWorker && !RuntimeInfo.beta && !RuntimeInfo.devMode) { if (!Launcher && navigator.serviceWorker && !RuntimeInfo.beta && !RuntimeInfo.devMode) {
navigator.serviceWorker navigator.serviceWorker
.register('service-worker.js') .register('service-worker.js')
.then(reg => { .then((reg) => {
logger.info('Service worker registered'); logger.info('Service worker registered');
reg.addEventListener('updatefound', () => { reg.addEventListener('updatefound', () => {
if (reg.active) { if (reg.active) {
@ -52,7 +52,7 @@ const Updater = {
} }
}); });
}) })
.catch(e => { .catch((e) => {
logger.error('Failed to register a service worker', e); logger.error('Failed to register a service worker', e);
}); });
} }
@ -99,7 +99,7 @@ const Updater = {
Transport.httpGet({ Transport.httpGet({
url: Links.Manifest, url: Links.Manifest,
utf8: true, utf8: true,
success: data => { success: (data) => {
const dt = new Date(); const dt = new Date();
const match = data.match(/#\s*(\d+\-\d+\-\d+):v([\d+\.\w]+)/); const match = data.match(/#\s*(\d+\-\d+\-\d+):v([\d+\.\w]+)/);
logger.info('Update check: ' + (match ? match[0] : 'unknown')); logger.info('Update check: ' + (match ? match[0] : 'unknown'));
@ -145,7 +145,7 @@ const Updater = {
UpdateModel.set({ updateStatus: 'found' }); UpdateModel.set({ updateStatus: 'found' });
} }
}, },
error: e => { error: (e) => {
logger.error('Update check error', e); logger.error('Update check error', e);
UpdateModel.set({ UpdateModel.set({
status: 'error', status: 'error',
@ -186,10 +186,10 @@ const Updater = {
url: Links.UpdateDesktop.replace('{ver}', ver), url: Links.UpdateDesktop.replace('{ver}', ver),
file: 'KeeWeb-' + ver + '.zip', file: 'KeeWeb-' + ver + '.zip',
cache: !startedByUser, cache: !startedByUser,
success: filePath => { success: (filePath) => {
UpdateModel.set({ updateStatus: 'extracting' }); UpdateModel.set({ updateStatus: 'extracting' });
logger.info('Extracting update file', this.UpdateCheckFiles, filePath); logger.info('Extracting update file', this.UpdateCheckFiles, filePath);
this.extractAppUpdate(filePath, err => { this.extractAppUpdate(filePath, (err) => {
if (err) { if (err) {
logger.error('Error extracting update', err); logger.error('Error extracting update', err);
UpdateModel.set({ UpdateModel.set({
@ -225,7 +225,7 @@ const Updater = {
const zip = new StreamZip({ file: updateFile, storeEntries: true }); const zip = new StreamZip({ file: updateFile, storeEntries: true });
zip.on('error', cb); zip.on('error', cb);
zip.on('ready', () => { zip.on('ready', () => {
const containsAll = expectedFiles.every(expFile => { const containsAll = expectedFiles.every((expFile) => {
const entry = zip.entry(expFile); const entry = zip.entry(expFile);
return entry && entry.isFile; return entry && entry.isFile;
}); });
@ -234,7 +234,7 @@ const Updater = {
} }
this.validateArchiveSignature(updateFile, zip) this.validateArchiveSignature(updateFile, zip)
.then(() => { .then(() => {
zip.extract(null, appPath, err => { zip.extract(null, appPath, (err) => {
zip.close(); zip.close();
if (err) { if (err) {
return cb(err); return cb(err);
@ -243,7 +243,7 @@ const Updater = {
cb(); cb();
}); });
}) })
.catch(e => { .catch((e) => {
return cb('Invalid archive: ' + e); return cb('Invalid archive: ' + e);
}); });
}); });
@ -264,7 +264,7 @@ const Updater = {
.catch(() => { .catch(() => {
throw new Error('Error verifying signature'); throw new Error('Error verifying signature');
}) })
.then(isValid => { .then((isValid) => {
if (!isValid) { if (!isValid) {
throw new Error('Invalid signature'); throw new Error('Invalid signature');
} }

View File

@ -46,7 +46,7 @@ const UsbListener = {
this.attachedYubiKeys = this.usb this.attachedYubiKeys = this.usb
.getDeviceList() .getDeviceList()
.filter(this.isYubiKey) .filter(this.isYubiKey)
.map(device => ({ device })); .map((device) => ({ device }));
if (this.attachedYubiKeys.length > 0) { if (this.attachedYubiKeys.length > 0) {
logger.info(`${this.attachedYubiKeys.length} YubiKey(s) found`, logger.ts(ts)); logger.info(`${this.attachedYubiKeys.length} YubiKey(s) found`, logger.ts(ts));
@ -89,7 +89,7 @@ const UsbListener = {
deviceDetached(device) { deviceDetached(device) {
if (UsbListener.isYubiKey(device)) { if (UsbListener.isYubiKey(device)) {
const index = UsbListener.attachedYubiKeys.findIndex( const index = UsbListener.attachedYubiKeys.findIndex(
yk => yk.device.deviceAddress === device.deviceAddress (yk) => yk.device.deviceAddress === device.deviceAddress
); );
if (index >= 0) { if (index >= 0) {
UsbListener.attachedYubiKeys.splice(index, 1); UsbListener.attachedYubiKeys.splice(index, 1);

View File

@ -25,7 +25,7 @@ const YubiKey = {
if (this.ykmanStatus === 'ok') { if (this.ykmanStatus === 'ok') {
return Promise.resolve(this.ykmanStatus); return Promise.resolve(this.ykmanStatus);
} }
return new Promise(resolve => { return new Promise((resolve) => {
this.ykmanStatus = 'checking'; this.ykmanStatus = 'checking';
Launcher.spawn({ Launcher.spawn({
cmd: 'ykman', cmd: 'ykman',
@ -121,13 +121,13 @@ const YubiKey = {
const yubiKeysIncludingEmpty = stdout const yubiKeysIncludingEmpty = stdout
.trim() .trim()
.split(/\n/g) .split(/\n/g)
.map(line => { .map((line) => {
const fullName = line; const fullName = line;
const serial = (line.match(/\d{5,}$/g) || [])[0]; const serial = (line.match(/\d{5,}$/g) || [])[0];
return { fullName, serial }; return { fullName, serial };
}); });
const yubiKeys = yubiKeysIncludingEmpty.filter(s => s.serial); const yubiKeys = yubiKeysIncludingEmpty.filter((s) => s.serial);
if ( if (
yubiKeysIncludingEmpty.length === 1 && yubiKeysIncludingEmpty.length === 1 &&
@ -176,7 +176,7 @@ const YubiKey = {
cmd: 'ykman', cmd: 'ykman',
args: ['config', 'usb', '-e', 'oath', '-f'], args: ['config', 'usb', '-e', 'oath', '-f'],
noStdOutLogging: true, noStdOutLogging: true,
complete: err => { complete: (err) => {
logger.info('Repair complete', err ? 'with error' : 'OK'); logger.info('Repair complete', err ? 'with error' : 'OK');
if (err) { if (err) {
Events.off('usb-devices-changed', onDevicesChangedDuringRepair); Events.off('usb-devices-changed', onDevicesChangedDuringRepair);

View File

@ -44,7 +44,7 @@ class KeyHandler {
offKey(key, handler, thisArg) { offKey(key, handler, thisArg) {
if (this.shortcuts[key]) { if (this.shortcuts[key]) {
this.shortcuts[key] = this.shortcuts[key].filter( this.shortcuts[key] = this.shortcuts[key].filter(
sh => sh.handler !== handler || sh.thisArg !== thisArg (sh) => sh.handler !== handler || sh.thisArg !== thisArg
); );
} }
} }

View File

@ -16,7 +16,7 @@ const PopupNotifier = {
window.open = noop; window.open = noop;
} else { } else {
const windowOpen = window.open; const windowOpen = window.open;
window.open = function(...args) { window.open = function (...args) {
const win = windowOpen.apply(window, args); const win = windowOpen.apply(window, args);
if (win) { if (win) {
PopupNotifier.deferCheckClosed(win); PopupNotifier.deferCheckClosed(win);

View File

@ -1,6 +1,6 @@
import kdbxweb from 'kdbxweb'; import kdbxweb from 'kdbxweb';
const SecureInput = function() { const SecureInput = function () {
this.el = null; this.el = null;
this.minChar = 0x1400 + Math.round(Math.random() * 100); this.minChar = 0x1400 + Math.round(Math.random() * 100);
this.maxLen = 1024; this.maxLen = 1024;
@ -9,13 +9,13 @@ const SecureInput = function() {
this.salt = new Uint32Array(0); this.salt = new Uint32Array(0);
}; };
SecureInput.prototype.setElement = function(el) { SecureInput.prototype.setElement = function (el) {
this.el = el; this.el = el;
this.el.val(this.pseudoValue); this.el.val(this.pseudoValue);
this.el.on('input', this._input.bind(this)); this.el.on('input', this._input.bind(this));
}; };
SecureInput.prototype.reset = function() { SecureInput.prototype.reset = function () {
this.el = null; this.el = null;
this.length = 0; this.length = 0;
this.pseudoValue = ''; this.pseudoValue = '';
@ -28,7 +28,7 @@ SecureInput.prototype.reset = function() {
this.salt = new Uint32Array(0); this.salt = new Uint32Array(0);
}; };
SecureInput.prototype._input = function() { SecureInput.prototype._input = function () {
const selStart = this.el[0].selectionStart; const selStart = this.el[0].selectionStart;
const value = this.el.val(); const value = this.el.val();
let newPs = ''; let newPs = '';
@ -63,11 +63,11 @@ SecureInput.prototype._input = function() {
this.el[0].selectionEnd = selStart; this.el[0].selectionEnd = selStart;
}; };
SecureInput.prototype._getChar = function(ix) { SecureInput.prototype._getChar = function (ix) {
return String.fromCharCode(this.minChar + ix); return String.fromCharCode(this.minChar + ix);
}; };
SecureInput.prototype._isSpecialChar = function(ch) { SecureInput.prototype._isSpecialChar = function (ch) {
return ch >= this.minChar && ch <= this.minChar + this.maxLen; return ch >= this.minChar && ch <= this.minChar + this.maxLen;
}; };

View File

@ -27,7 +27,7 @@ const Transport = {
logger.info('GET ' + config.url); logger.info('GET ' + config.url);
const opts = Launcher.req('url').parse(config.url); const opts = Launcher.req('url').parse(config.url);
opts.headers = { 'User-Agent': navigator.userAgent }; opts.headers = { 'User-Agent': navigator.userAgent };
Launcher.resolveProxy(config.url, proxy => { Launcher.resolveProxy(config.url, (proxy) => {
logger.info( logger.info(
'Request to ' + 'Request to ' +
config.url + config.url +
@ -41,7 +41,7 @@ const Transport = {
opts.path = config.url; opts.path = config.url;
} }
Launcher.req(proto) Launcher.req(proto)
.get(opts, res => { .get(opts, (res) => {
logger.info('Response from ' + config.url + ': ' + res.statusCode); logger.info('Response from ' + config.url + ': ' + res.statusCode);
if (res.statusCode === 200) { if (res.statusCode === 200) {
if (config.file) { if (config.file) {
@ -52,12 +52,12 @@ const Transport = {
config.success(tmpFile); config.success(tmpFile);
}); });
}); });
file.on('error', err => { file.on('error', (err) => {
config.error(err); config.error(err);
}); });
} else { } else {
let data = []; let data = [];
res.on('data', chunk => { res.on('data', (chunk) => {
data.push(chunk); data.push(chunk);
}); });
res.on('end', () => { res.on('end', () => {
@ -79,7 +79,7 @@ const Transport = {
config.error('HTTP status ' + res.statusCode); config.error('HTTP status ' + res.statusCode);
} }
}) })
.on('error', e => { .on('error', (e) => {
logger.error('Cannot GET ' + config.url, e); logger.error('Cannot GET ' + config.url, e);
if (tmpFile) { if (tmpFile) {
fs.unlink(tmpFile, noop); fs.unlink(tmpFile, noop);

View File

@ -31,13 +31,15 @@ function walkGroup(db, group, parents) {
) { ) {
return ''; return '';
} }
const self = group.entries.map(entry => walkEntry(db, entry, parents)).join('\n'); const self = group.entries.map((entry) => walkEntry(db, entry, parents)).join('\n');
const children = group.groups.map(childGroup => walkGroup(db, childGroup, parents)).join('\n'); const children = group.groups
.map((childGroup) => walkGroup(db, childGroup, parents))
.join('\n');
return self + children; return self + children;
} }
function walkEntry(db, entry, parents) { function walkEntry(db, entry, parents) {
const path = parents.map(group => group.name).join(' / '); const path = parents.map((group) => group.name).join(' / ');
const fields = []; const fields = [];
for (const field of FieldMapping) { for (const field of FieldMapping) {
const value = entryField(entry, field.name); const value = entryField(entry, field.name);
@ -78,7 +80,7 @@ function walkEntry(db, entry, parents) {
} }
return { name, data }; return { name, data };
}) })
.filter(att => att.name && att.data); .filter((att) => att.name && att.data);
return Templates.entry({ return Templates.entry({
path, path,
@ -99,7 +101,7 @@ function entryField(entry, fieldName) {
const KdbxToHtml = { const KdbxToHtml = {
convert(db, options) { convert(db, options) {
const content = db.groups.map(group => walkGroup(db, group, [])).join('\n'); const content = db.groups.map((group) => walkGroup(db, group, [])).join('\n');
return Templates.db({ return Templates.db({
name: options.name, name: options.name,
date: DateFormat.dtStr(Date.now()), date: DateFormat.dtStr(Date.now()),

View File

@ -51,7 +51,7 @@ class OtpQrReader {
click: '', click: '',
enter: '', enter: '',
buttons, buttons,
complete: res => { complete: (res) => {
this.alert = null; this.alert = null;
this.stopListenClipboard(); this.stopListenClipboard();
if (res === 'select') { if (res === 'select') {
@ -94,7 +94,7 @@ class OtpQrReader {
pasteEvent(e) { pasteEvent(e) {
const item = [...e.clipboardData.items].find( const item = [...e.clipboardData.items].find(
item => item.kind === 'file' && item.type.indexOf('image') !== -1 (item) => item.kind === 'file' && item.type.indexOf('image') !== -1
); );
if (!item) { if (!item) {
logger.debug('Paste without file'); logger.debug('Paste without file');

View File

@ -31,7 +31,7 @@ const Launcher = {
}, },
getDataPath(...args) { getDataPath(...args) {
const storagePath = window.cordova.file.externalDataDirectory; const storagePath = window.cordova.file.externalDataDirectory;
return [storagePath].concat(Array.from(args)).filter(s => !!s); return [storagePath].concat(Array.from(args)).filter((s) => !!s);
}, },
getUserDataPath(fileName) { getUserDataPath(fileName) {
return this.getDataPath('userdata', fileName).join('/'); return this.getDataPath('userdata', fileName).join('/');
@ -52,10 +52,10 @@ const Launcher = {
return [...parts].join('/'); return [...parts].join('/');
}, },
writeFile(path, data, callback) { writeFile(path, data, callback) {
const createFile = filePath => { const createFile = (filePath) => {
window.resolveLocalFileSystemURL( window.resolveLocalFileSystemURL(
filePath.dir, filePath.dir,
dir => { (dir) => {
dir.getFile(filePath.file, { create: true }, writeFile); dir.getFile(filePath.file, { create: true }, writeFile);
}, },
callback, callback,
@ -63,8 +63,8 @@ const Launcher = {
); );
}; };
const writeFile = fileEntry => { const writeFile = (fileEntry) => {
fileEntry.createWriter(fileWriter => { fileEntry.createWriter((fileWriter) => {
fileWriter.onerror = callback; fileWriter.onerror = callback;
fileWriter.onwriteend = () => callback(); fileWriter.onwriteend = () => callback();
fileWriter.write(data); fileWriter.write(data);
@ -85,9 +85,9 @@ const Launcher = {
readFile(path, encoding, callback) { readFile(path, encoding, callback) {
window.resolveLocalFileSystemURL( window.resolveLocalFileSystemURL(
path, path,
fileEntry => { (fileEntry) => {
fileEntry.file( fileEntry.file(
file => { (file) => {
const reader = new FileReader(); const reader = new FileReader();
reader.onerror = callback; reader.onerror = callback;
reader.onloadend = () => { reader.onloadend = () => {
@ -98,23 +98,23 @@ const Launcher = {
}; };
reader.readAsArrayBuffer(file); reader.readAsArrayBuffer(file);
}, },
err => callback(undefined, err) (err) => callback(undefined, err)
); );
}, },
err => callback(undefined, err) (err) => callback(undefined, err)
); );
}, },
fileExists(path, callback) { fileExists(path, callback) {
window.resolveLocalFileSystemURL( window.resolveLocalFileSystemURL(
path, path,
fileEntry => callback(true), (fileEntry) => callback(true),
() => callback(false) () => callback(false)
); );
}, },
deleteFile(path, callback) { deleteFile(path, callback) {
window.resolveLocalFileSystemURL( window.resolveLocalFileSystemURL(
path, path,
fileEntry => { (fileEntry) => {
fileEntry.remove(callback, callback, callback); fileEntry.remove(callback, callback, callback);
}, },
callback callback
@ -123,18 +123,18 @@ const Launcher = {
statFile(path, callback) { statFile(path, callback) {
window.resolveLocalFileSystemURL( window.resolveLocalFileSystemURL(
path, path,
fileEntry => { (fileEntry) => {
fileEntry.file( fileEntry.file(
file => { (file) => {
callback({ callback({
ctime: new Date(file.lastModified), ctime: new Date(file.lastModified),
mtime: new Date(file.lastModified) mtime: new Date(file.lastModified)
}); });
}, },
err => callback(undefined, err) (err) => callback(undefined, err)
); );
}, },
err => callback(undefined, err) (err) => callback(undefined, err)
); );
}, },
mkdir(dir, callback) { mkdir(dir, callback) {
@ -144,7 +144,7 @@ const Launcher = {
dirEntry.getDirectory( dirEntry.getDirectory(
name, name,
{ create: true }, { create: true },
dirEntry => { (dirEntry) => {
if (path.length) { if (path.length) {
// there is more to create // there is more to create
createDir(dirEntry, path, callback); createDir(dirEntry, path, callback);
@ -159,12 +159,12 @@ const Launcher = {
const localPath = dir const localPath = dir
.replace(basePath, '') .replace(basePath, '')
.split('/') .split('/')
.filter(s => !!s); .filter((s) => !!s);
if (localPath.length) { if (localPath.length) {
window.resolveLocalFileSystemURL( window.resolveLocalFileSystemURL(
basePath, basePath,
dirEntry => { (dirEntry) => {
createDir(dirEntry, localPath, callback); createDir(dirEntry, localPath, callback);
}, },
callback callback
@ -229,9 +229,9 @@ const Launcher = {
}, },
// spawn(config) {}, // spawn(config) {},
openFileChooser(callback) { openFileChooser(callback) {
const onFileSelected = function(selected) { const onFileSelected = function (selected) {
window.resolveLocalFileSystemURL(selected.uri, fileEntry => { window.resolveLocalFileSystemURL(selected.uri, (fileEntry) => {
fileEntry.file(file => { fileEntry.file((file) => {
file.path = file.localURL; file.path = file.localURL;
file.name = selected.name; file.name = selected.name;
callback(null, file); callback(null, file);
@ -249,7 +249,7 @@ const Launcher = {
}, },
register(fileId, password, callback) { register(fileId, password, callback) {
FingerprintAuth.isAvailable(result => { FingerprintAuth.isAvailable((result) => {
if (!result.isAvailable) { if (!result.isAvailable) {
return; return;
} }
@ -260,7 +260,7 @@ const Launcher = {
password: password.getText() password: password.getText()
}; };
FingerprintAuth.encrypt(encryptConfig, result => { FingerprintAuth.encrypt(encryptConfig, (result) => {
callback(result.token); callback(result.token);
}); });
}); });
@ -273,7 +273,7 @@ const Launcher = {
const decryptConfig = { ...this.config, username: fileId, token }; const decryptConfig = { ...this.config, username: fileId, token };
FingerprintAuth.decrypt(decryptConfig, result => { FingerprintAuth.decrypt(decryptConfig, (result) => {
callback(result.password); callback(result.password);
}); });
} }

View File

@ -36,9 +36,7 @@ const Launcher = {
}, },
devTools: true, devTools: true,
openDevTools() { openDevTools() {
this.electron() this.electron().remote.getCurrentWindow().webContents.openDevTools({ mode: 'bottom' });
.remote.getCurrentWindow()
.webContents.openDevTools({ mode: 'bottom' });
}, },
getSaveFileName(defaultPath, callback) { getSaveFileName(defaultPath, callback) {
if (defaultPath) { if (defaultPath) {
@ -51,7 +49,7 @@ const Launcher = {
defaultPath, defaultPath,
filters: [{ name: Locale.launcherFileFilter, extensions: ['kdbx'] }] filters: [{ name: Locale.launcherFileFilter, extensions: ['kdbx'] }]
}) })
.then(res => callback(res.filePath)); .then((res) => callback(res.filePath));
}, },
getUserDataPath(fileName) { getUserDataPath(fileName) {
if (!this.userDataPath) { if (!this.userDataPath) {
@ -99,8 +97,8 @@ const Launcher = {
const path = this.req('path'); const path = this.req('path');
const stack = []; const stack = [];
const collect = function(dir, stack, callback) { const collect = function (dir, stack, callback) {
fs.exists(dir, exists => { fs.exists(dir, (exists) => {
if (exists) { if (exists) {
return callback(); return callback();
} }
@ -115,12 +113,12 @@ const Launcher = {
}); });
}; };
const create = function(stack, callback) { const create = function (stack, callback) {
if (!stack.length) { if (!stack.length) {
return callback(); return callback();
} }
fs.mkdir(stack.shift(), err => (err ? callback(err) : create(stack, callback))); fs.mkdir(stack.shift(), (err) => (err ? callback(err) : create(stack, callback)));
}; };
collect(dir, stack, () => create(stack, callback)); collect(dir, stack, () => create(stack, callback));
@ -211,7 +209,7 @@ const Launcher = {
resolveProxy(url, callback) { resolveProxy(url, callback) {
const window = this.getMainWindow(); const window = this.getMainWindow();
const session = window.webContents.session; const session = window.webContents.session;
session.resolveProxy(url).then(proxy => { session.resolveProxy(url).then((proxy) => {
const match = /^proxy\s+([\w\.]+):(\d+)+\s*/i.exec(proxy); const match = /^proxy\s+([\w\.]+):(\d+)+\s*/i.exec(proxy);
proxy = match && match[1] ? { host: match[1], port: +match[2] } : null; proxy = match && match[1] ? { host: match[1], port: +match[2] } : null;
callback(proxy); callback(proxy);
@ -235,10 +233,10 @@ const Launcher = {
const ts = logger.ts(); const ts = logger.ts();
let complete = config.complete; let complete = config.complete;
const ps = this.req('child_process').spawn(config.cmd, config.args); const ps = this.req('child_process').spawn(config.cmd, config.args);
[ps.stdin, ps.stdout, ps.stderr].forEach(s => s.setEncoding('utf-8')); [ps.stdin, ps.stdout, ps.stderr].forEach((s) => s.setEncoding('utf-8'));
let stderr = ''; let stderr = '';
let stdout = ''; let stdout = '';
ps.stderr.on('data', d => { ps.stderr.on('data', (d) => {
stderr += d.toString('utf-8'); stderr += d.toString('utf-8');
if (config.throwOnStdErr) { if (config.throwOnStdErr) {
try { try {
@ -246,10 +244,10 @@ const Launcher = {
} catch {} } catch {}
} }
}); });
ps.stdout.on('data', d => { ps.stdout.on('data', (d) => {
stdout += d.toString('utf-8'); stdout += d.toString('utf-8');
}); });
ps.on('close', code => { ps.on('close', (code) => {
stdout = stdout.trim(); stdout = stdout.trim();
stderr = stderr.trim(); stderr = stderr.trim();
const msg = 'spawn ' + config.cmd + ': ' + code + ', ' + logger.ts(ts); const msg = 'spawn ' + config.cmd + ': ' + code + ', ' + logger.ts(ts);
@ -263,7 +261,7 @@ const Launcher = {
complete = null; complete = null;
} }
}); });
ps.on('error', err => { ps.on('error', (err) => {
logger.error('spawn error: ' + config.cmd + ', ' + logger.ts(ts), err); logger.error('spawn error: ' + config.cmd + ', ' + logger.ts(ts), err);
if (complete) { if (complete) {
complete(err); complete(err);
@ -309,10 +307,10 @@ Events.on('launcher-exit-request', () => {
}); });
Events.on('launcher-minimize', () => setTimeout(() => Events.emit('app-minimized'), 0)); Events.on('launcher-minimize', () => setTimeout(() => Events.emit('app-minimized'), 0));
Events.on('launcher-started-minimized', () => setTimeout(() => Launcher.minimizeApp(), 0)); Events.on('launcher-started-minimized', () => setTimeout(() => Launcher.minimizeApp(), 0));
Events.on('start-profile', data => StartProfiler.reportAppProfile(data)); Events.on('start-profile', (data) => StartProfiler.reportAppProfile(data));
Events.on('log', e => new Logger(e.category || 'remote-app')[e.method || 'info'](e.message)); Events.on('log', (e) => new Logger(e.category || 'remote-app')[e.method || 'info'](e.message));
window.launcherOpen = file => Launcher.openFile(file); window.launcherOpen = (file) => Launcher.openFile(file);
if (window.launcherOpenedFile) { if (window.launcherOpenedFile) {
logger.info('Open file request', window.launcherOpenedFile); logger.info('Open file request', window.launcherOpenedFile);
Launcher.openFile(window.launcherOpenedFile); Launcher.openFile(window.launcherOpenedFile);
@ -328,7 +326,7 @@ Events.on('app-ready', () =>
}, 0) }, 0)
); );
Launcher.remoteApp().on('remote-app-event', e => { Launcher.remoteApp().on('remote-app-event', (e) => {
if (window.debugRemoteAppEvents) { if (window.debugRemoteAppEvents) {
logger.debug('remote-app-event', e.name); logger.debug('remote-app-event', e.name);
} }

View File

@ -15,15 +15,15 @@ const SettingsStore = {
}); });
} }
return loadPromise return loadPromise
.then(data => (data ? JSON.parse(data) : null)) .then((data) => (data ? JSON.parse(data) : null))
.catch(err => { .catch((err) => {
logger.error(`Error loading ${key}`, err); logger.error(`Error loading ${key}`, err);
}); });
}, },
save(key, data) { save(key, data) {
if (Launcher) { if (Launcher) {
return Launcher.saveConfig(key, JSON.stringify(data)).catch(err => { return Launcher.saveConfig(key, JSON.stringify(data)).catch((err) => {
logger.error(`Error saving ${key}`, err); logger.error(`Error saving ${key}`, err);
}); });
} }

View File

@ -187,7 +187,7 @@ class Collection {
} }
get(id) { get(id) {
return this.find(model => model.id === id); return this.find((model) => model.id === id);
} }
remove(idOrModel) { remove(idOrModel) {

View File

@ -130,7 +130,7 @@ class View extends EventEmitter {
} }
for (const [event, handlers] of Object.entries(eventsMap)) { for (const [event, handlers] of Object.entries(eventsMap)) {
this.debugLogger?.debug('Bind', 'view', event, handlers); this.debugLogger?.debug('Bind', 'view', event, handlers);
const listener = e => this.eventListener(e, handlers); const listener = (e) => this.eventListener(e, handlers);
this.eventListeners[event] = listener; this.eventListeners[event] = listener;
this.el.addEventListener(event, listener); this.el.addEventListener(event, listener);
} }
@ -152,7 +152,7 @@ class View extends EventEmitter {
for (const cfg of this.elementEventListeners) { for (const cfg of this.elementEventListeners) {
const els = this.el.querySelectorAll(cfg.selector); const els = this.el.querySelectorAll(cfg.selector);
this.debugLogger?.debug('Bind', 'element', cfg.event, cfg.selector, els.length); this.debugLogger?.debug('Bind', 'element', cfg.event, cfg.selector, els.length);
cfg.listener = e => this.eventListener(e, [cfg]); cfg.listener = (e) => this.eventListener(e, [cfg]);
for (const el of els) { for (const el of els) {
el.addEventListener(cfg.event, cfg.listener); el.addEventListener(cfg.event, cfg.listener);
cfg.els.push(el); cfg.els.push(el);
@ -209,7 +209,7 @@ class View extends EventEmitter {
for (const view of Object.values(this.views)) { for (const view of Object.values(this.views)) {
if (view) { if (view) {
if (view instanceof Array) { if (view instanceof Array) {
view.forEach(v => v.remove()); view.forEach((v) => v.remove());
} else { } else {
view.remove(); view.remove();
} }

View File

@ -1,6 +1,6 @@
import Handlebars from 'hbs'; import Handlebars from 'hbs';
Handlebars.registerHelper('cmp', function(lvalue, rvalue, op, options) { Handlebars.registerHelper('cmp', function (lvalue, rvalue, op, options) {
let cond; let cond;
switch (op) { switch (op) {
case '<': case '<':

View File

@ -1,5 +1,5 @@
import Handlebars from 'hbs'; import Handlebars from 'hbs';
Handlebars.registerHelper('ifemptyoreq', function(lvalue, rvalue, options) { Handlebars.registerHelper('ifemptyoreq', function (lvalue, rvalue, options) {
return !lvalue || lvalue === rvalue ? options.fn(this) : options.inverse(this); return !lvalue || lvalue === rvalue ? options.fn(this) : options.inverse(this);
}); });

View File

@ -1,5 +1,5 @@
import Handlebars from 'hbs'; import Handlebars from 'hbs';
Handlebars.registerHelper('ifeq', function(lvalue, rvalue, options) { Handlebars.registerHelper('ifeq', function (lvalue, rvalue, options) {
return lvalue === rvalue ? options.fn(this) : options.inverse(this); return lvalue === rvalue ? options.fn(this) : options.inverse(this);
}); });

View File

@ -1,5 +1,5 @@
import Handlebars from 'hbs'; import Handlebars from 'hbs';
Handlebars.registerHelper('ifneq', function(lvalue, rvalue, options) { Handlebars.registerHelper('ifneq', function (lvalue, rvalue, options) {
return lvalue !== rvalue ? options.fn(this) : options.inverse(this); return lvalue !== rvalue ? options.fn(this) : options.inverse(this);
}); });

View File

@ -1,7 +1,7 @@
import Handlebars from 'hbs'; import Handlebars from 'hbs';
import { Locale } from 'util/locale'; import { Locale } from 'util/locale';
Handlebars.registerHelper('res', function(key, options) { Handlebars.registerHelper('res', function (key, options) {
let value = Locale[key]; let value = Locale[key];
if (value) { if (value) {
const ix = value.indexOf('{}'); const ix = value.indexOf('{}');
@ -12,7 +12,7 @@ Handlebars.registerHelper('res', function(key, options) {
return value; return value;
}); });
Handlebars.registerHelper('Res', key => { Handlebars.registerHelper('Res', (key) => {
let value = Locale[key]; let value = Locale[key];
if (value) { if (value) {
value = value[0].toUpperCase() + value.substr(1); value = value[0].toUpperCase() + value.substr(1);

View File

@ -91,7 +91,7 @@ class AppModel {
this.appLogger.error('Error loading app config', xhr.statusText, xhr.status); this.appLogger.error('Error loading app config', xhr.statusText, xhr.status);
reject('Error loading app config'); reject('Error loading app config');
}); });
}).then(config => { }).then((config) => {
return this.applyUserConfig(config); return this.applyUserConfig(config);
}); });
} }
@ -116,7 +116,7 @@ class AppModel {
} }
config.files config.files
.filter( .filter(
file => (file) =>
file && file &&
file.storage && file.storage &&
file.name && file.name &&
@ -124,7 +124,7 @@ class AppModel {
!this.fileInfos.getMatch(file.storage, file.name, file.path) !this.fileInfos.getMatch(file.storage, file.name, file.path)
) )
.map( .map(
file => (file) =>
new FileInfoModel({ new FileInfoModel({
id: IdGenerator.uuid(), id: IdGenerator.uuid(),
name: file.name, name: file.name,
@ -134,10 +134,10 @@ class AppModel {
}) })
) )
.reverse() .reverse()
.forEach(fi => this.fileInfos.unshift(fi)); .forEach((fi) => this.fileInfos.unshift(fi));
} }
if (config.plugins) { if (config.plugins) {
const pluginsPromises = config.plugins.map(plugin => const pluginsPromises = config.plugins.map((plugin) =>
PluginManager.installIfNew(plugin.url, plugin.manifest, true) PluginManager.installIfNew(plugin.url, plugin.manifest, true)
); );
return Promise.all(pluginsPromises).then(() => { return Promise.all(pluginsPromises).then(() => {
@ -180,10 +180,10 @@ class AppModel {
_addTags(file) { _addTags(file) {
const tagsHash = {}; const tagsHash = {};
this.tags.forEach(tag => { this.tags.forEach((tag) => {
tagsHash[tag.toLowerCase()] = true; tagsHash[tag.toLowerCase()] = true;
}); });
file.forEachEntry({}, entry => { file.forEachEntry({}, (entry) => {
for (const tag of entry.tags) { for (const tag of entry.tags) {
if (!tagsHash[tag.toLowerCase()]) { if (!tagsHash[tag.toLowerCase()]) {
tagsHash[tag.toLowerCase()] = true; tagsHash[tag.toLowerCase()] = true;
@ -198,7 +198,7 @@ class AppModel {
if (this.tags.length) { if (this.tags.length) {
this.menu.tagsSection.scrollable = true; this.menu.tagsSection.scrollable = true;
this.menu.tagsSection.setItems( this.menu.tagsSection.setItems(
this.tags.map(tag => { this.tags.map((tag) => {
return { return {
title: tag, title: tag,
icon: 'tag', icon: 'tag',
@ -226,7 +226,7 @@ class AppModel {
} }
renameTag(from, to) { renameTag(from, to) {
this.files.forEach(file => file.renameTag && file.renameTag(from, to)); this.files.forEach((file) => file.renameTag && file.renameTag(from, to));
this.updateTags(); this.updateTags();
} }
@ -256,7 +256,7 @@ class AppModel {
} }
emptyTrash() { emptyTrash() {
this.files.forEach(file => file.emptyTrash && file.emptyTrash()); this.files.forEach((file) => file.emptyTrash && file.emptyTrash());
this.refresh(); this.refresh();
} }
@ -306,14 +306,14 @@ class AppModel {
const preparedFilter = this.prepareFilter(filter); const preparedFilter = this.prepareFilter(filter);
const entries = new SearchResultCollection(); const entries = new SearchResultCollection();
const devicesToMatchOtpEntries = this.files.filter(file => file.external); const devicesToMatchOtpEntries = this.files.filter((file) => file.external);
const matchedOtpEntrySet = this.settings.yubiKeyMatchEntries ? new Set() : undefined; const matchedOtpEntrySet = this.settings.yubiKeyMatchEntries ? new Set() : undefined;
this.files this.files
.filter(file => !file.external) .filter((file) => !file.external)
.forEach(file => { .forEach((file) => {
file.forEachEntry(preparedFilter, entry => { file.forEachEntry(preparedFilter, (entry) => {
if (matchedOtpEntrySet) { if (matchedOtpEntrySet) {
for (const device of devicesToMatchOtpEntries) { for (const device of devicesToMatchOtpEntries) {
const matchingEntry = device.getMatchingEntry(entry); const matchingEntry = device.getMatchingEntry(entry);
@ -328,7 +328,7 @@ class AppModel {
if (devicesToMatchOtpEntries.length) { if (devicesToMatchOtpEntries.length) {
for (const device of devicesToMatchOtpEntries) { for (const device of devicesToMatchOtpEntries) {
device.forEachEntry(preparedFilter, entry => { device.forEachEntry(preparedFilter, (entry) => {
if (!matchedOtpEntrySet || !matchedOtpEntrySet.has(entry)) { if (!matchedOtpEntrySet || !matchedOtpEntrySet.has(entry)) {
entries.push(entry); entries.push(entry);
} }
@ -340,10 +340,10 @@ class AppModel {
} }
addTrashGroups(collection) { addTrashGroups(collection) {
this.files.forEach(file => { this.files.forEach((file) => {
const trashGroup = file.getTrashGroup && file.getTrashGroup(); const trashGroup = file.getTrashGroup && file.getTrashGroup();
if (trashGroup) { if (trashGroup) {
trashGroup.getOwnSubGroups().forEach(group => { trashGroup.getOwnSubGroups().forEach((group) => {
collection.unshift(GroupModel.fromGroup(group, file, trashGroup)); collection.unshift(GroupModel.fromGroup(group, file, trashGroup));
}); });
} }
@ -359,10 +359,10 @@ class AppModel {
const exact = filter.advanced && filter.advanced.exact; const exact = filter.advanced && filter.advanced.exact;
if (!exact && filter.text) { if (!exact && filter.text) {
const textParts = filter.text.split(/\s+/).filter(s => s); const textParts = filter.text.split(/\s+/).filter((s) => s);
if (textParts.length) { if (textParts.length) {
filter.textParts = textParts; filter.textParts = textParts;
filter.textLowerParts = filter.textLower.split(/\s+/).filter(s => s); filter.textLowerParts = filter.textLower.split(/\s+/).filter((s) => s);
} }
} }
@ -375,14 +375,14 @@ class AppModel {
const selGroupId = this.filter.group; const selGroupId = this.filter.group;
let file, group; let file, group;
if (selGroupId) { if (selGroupId) {
this.files.some(f => { this.files.some((f) => {
file = f; file = f;
group = f.getGroup(selGroupId); group = f.getGroup(selGroupId);
return group; return group;
}); });
} }
if (!group) { if (!group) {
file = this.files.find(f => f.active && !f.readOnly); file = this.files.find((f) => f.active && !f.readOnly);
group = file.groups[0]; group = file.groups[0];
} }
return { group, file }; return { group, file };
@ -390,10 +390,10 @@ class AppModel {
completeUserNames(part) { completeUserNames(part) {
const userNames = {}; const userNames = {};
this.files.forEach(file => { this.files.forEach((file) => {
file.forEachEntry( file.forEachEntry(
{ text: part, textLower: part.toLowerCase(), advanced: { user: true } }, { text: part, textLower: part.toLowerCase(), advanced: { user: true } },
entry => { (entry) => {
const userName = entry.user; const userName = entry.user;
if (userName) { if (userName) {
userNames[userName] = (userNames[userName] || 0) + 1; userNames[userName] = (userNames[userName] || 0) + 1;
@ -407,13 +407,13 @@ class AppModel {
if (matches.length > maxResults) { if (matches.length > maxResults) {
matches.length = maxResults; matches.length = maxResults;
} }
return matches.map(m => m[0]); return matches.map((m) => m[0]);
} }
getEntryTemplates() { getEntryTemplates() {
const entryTemplates = []; const entryTemplates = [];
this.files.forEach(file => { this.files.forEach((file) => {
file.forEachEntryTemplate?.(entry => { file.forEachEntryTemplate?.((entry) => {
entryTemplates.push({ file, entry }); entryTemplates.push({ file, entry });
}); });
}); });
@ -421,7 +421,7 @@ class AppModel {
} }
canCreateEntries() { canCreateEntries() {
return this.files.some(f => f.active && !f.readOnly); return this.files.some((f) => f.active && !f.readOnly);
} }
createNewEntry(args) { createNewEntry(args) {
@ -667,7 +667,7 @@ class AppModel {
fingerprint: (fileInfo && fileInfo.fingerprint) || null, fingerprint: (fileInfo && fileInfo.fingerprint) || null,
chalResp: params.chalResp chalResp: params.chalResp
}); });
const openComplete = err => { const openComplete = (err) => {
if (err) { if (err) {
return callback(err); return callback(err);
} }
@ -723,7 +723,7 @@ class AppModel {
storage: params.storage, storage: params.storage,
path: params.path path: params.path
}); });
file.importWithXml(params.fileXml, err => { file.importWithXml(params.fileXml, (err) => {
logger.info('Import xml complete ' + (err ? 'with error' : ''), err); logger.info('Import xml complete ' + (err ? 'with error' : ''), err);
if (err) { if (err) {
return callback(err); return callback(err);
@ -812,7 +812,7 @@ class AppModel {
this.saveFileFingerprint(file, params.password); this.saveFileFingerprint(file, params.password);
} }
if (this.settings.yubiKeyAutoOpen) { if (this.settings.yubiKeyAutoOpen) {
if (this.attachedYubiKeysCount > 0 && !this.files.some(f => f.external)) { if (this.attachedYubiKeysCount > 0 && !this.files.some((f) => f.external)) {
this.tryOpenOtpDeviceInBackground(); this.tryOpenOtpDeviceInBackground();
} }
} }
@ -882,7 +882,7 @@ class AppModel {
}); });
} }
file.setSyncProgress(); file.setSyncProgress();
const complete = err => { const complete = (err) => {
if (!file.active) { if (!file.active) {
return callback && callback('File is closed'); return callback && callback('File is closed');
} }
@ -922,7 +922,7 @@ class AppModel {
if (err) { if (err) {
return complete(err); return complete(err);
} }
Storage.cache.save(fileInfo.id, null, data, err => { Storage.cache.save(fileInfo.id, null, data, (err) => {
logger.info('Saved to cache', err || 'no error'); logger.info('Saved to cache', err || 'no error');
complete(err); complete(err);
if (!err) { if (!err) {
@ -946,7 +946,7 @@ class AppModel {
if (err) { if (err) {
return complete(err); return complete(err);
} }
file.mergeOrUpdate(data, options.remoteKey, err => { file.mergeOrUpdate(data, options.remoteKey, (err) => {
logger.info('Merge complete', err || 'no error'); logger.info('Merge complete', err || 'no error');
this.refresh(); this.refresh();
if (err) { if (err) {
@ -966,7 +966,7 @@ class AppModel {
saveToCacheAndStorage(); saveToCacheAndStorage();
} else if (file.dirty) { } else if (file.dirty) {
logger.info('Saving not modified dirty file to cache'); logger.info('Saving not modified dirty file to cache');
Storage.cache.save(fileInfo.id, null, data, err => { Storage.cache.save(fileInfo.id, null, data, (err) => {
if (err) { if (err) {
return complete(err); return complete(err);
} }
@ -981,7 +981,7 @@ class AppModel {
}); });
}); });
}; };
const saveToStorage = data => { const saveToStorage = (data) => {
logger.info('Save data to storage'); logger.info('Save data to storage');
const storageRev = fileInfo.storage === storage ? fileInfo.rev : undefined; const storageRev = fileInfo.storage === storage ? fileInfo.rev : undefined;
Storage[storage].save( Storage[storage].save(
@ -1029,7 +1029,7 @@ class AppModel {
saveToStorage(data); saveToStorage(data);
} else { } else {
logger.info('Saving to cache'); logger.info('Saving to cache');
Storage.cache.save(fileInfo.id, null, data, err => { Storage.cache.save(fileInfo.id, null, data, (err) => {
if (err) { if (err) {
return complete(err); return complete(err);
} }
@ -1056,7 +1056,7 @@ class AppModel {
logger.error('Error getting file data', e); logger.error('Error getting file data', e);
return complete(err); return complete(err);
} }
Storage.cache.save(fileInfo.id, null, data, e => { Storage.cache.save(fileInfo.id, null, data, (e) => {
if (e) { if (e) {
logger.error('Error saving to cache', e); logger.error('Error saving to cache', e);
} }
@ -1129,7 +1129,7 @@ class AppModel {
if (Storage[backup.storage].getPathForName) { if (Storage[backup.storage].getPathForName) {
path = Storage[backup.storage].getPathForName(path); path = Storage[backup.storage].getPathForName(path);
} }
Storage[backup.storage].save(path, opts, data, err => { Storage[backup.storage].save(path, opts, data, (err) => {
if (err) { if (err) {
logger.error('Backup error', err); logger.error('Backup error', err);
} else { } else {
@ -1147,14 +1147,14 @@ class AppModel {
if (Storage[backup.storage].getPathForName) { if (Storage[backup.storage].getPathForName) {
folderPath = Storage[backup.storage].getPathForName(folderPath).replace('.kdbx', ''); folderPath = Storage[backup.storage].getPathForName(folderPath).replace('.kdbx', '');
} }
Storage[backup.storage].stat(folderPath, opts, err => { Storage[backup.storage].stat(folderPath, opts, (err) => {
if (err) { if (err) {
if (err.notFound) { if (err.notFound) {
logger.info('Backup folder does not exist'); logger.info('Backup folder does not exist');
if (!Storage[backup.storage].mkdir) { if (!Storage[backup.storage].mkdir) {
return callback('Mkdir not supported by ' + backup.storage); return callback('Mkdir not supported by ' + backup.storage);
} }
Storage[backup.storage].mkdir(folderPath, err => { Storage[backup.storage].mkdir(folderPath, (err) => {
if (err) { if (err) {
logger.error('Error creating backup folder', err); logger.error('Error creating backup folder', err);
callback('Error creating backup folder'); callback('Error creating backup folder');
@ -1227,7 +1227,7 @@ class AppModel {
saveFileFingerprint(file, password) { saveFileFingerprint(file, password) {
if (Launcher && Launcher.fingerprints && !file.fingerprint) { if (Launcher && Launcher.fingerprints && !file.fingerprint) {
const fileInfo = this.fileInfos.get(file.id); const fileInfo = this.fileInfos.get(file.id);
Launcher.fingerprints.register(file.id, password, token => { Launcher.fingerprints.register(file.id, password, (token) => {
if (token) { if (token) {
fileInfo.fingerprint = token; fileInfo.fingerprint = token;
this.fileInfos.save(); this.fileInfos.save();
@ -1246,7 +1246,7 @@ class AppModel {
} }
const isNewYubiKey = UsbListener.attachedYubiKeys.length > attachedYubiKeysCount; const isNewYubiKey = UsbListener.attachedYubiKeys.length > attachedYubiKeysCount;
const hasOpenFiles = this.files.some(file => file.active && !file.external); const hasOpenFiles = this.files.some((file) => file.active && !file.external);
if (isNewYubiKey && hasOpenFiles && !this.openingOtpDevice) { if (isNewYubiKey && hasOpenFiles && !this.openingOtpDevice) {
this.tryOpenOtpDeviceInBackground(); this.tryOpenOtpDeviceInBackground();
@ -1255,7 +1255,7 @@ class AppModel {
tryOpenOtpDeviceInBackground() { tryOpenOtpDeviceInBackground() {
this.appLogger.debug('Auto-opening a YubiKey'); this.appLogger.debug('Auto-opening a YubiKey');
this.openOtpDevice(err => { this.openOtpDevice((err) => {
this.appLogger.debug('YubiKey auto-open complete', err); this.appLogger.debug('YubiKey auto-open complete', err);
}); });
} }
@ -1263,7 +1263,7 @@ class AppModel {
openOtpDevice(callback) { openOtpDevice(callback) {
this.openingOtpDevice = true; this.openingOtpDevice = true;
const device = new YubiKeyOtpModel(); const device = new YubiKeyOtpModel();
device.open(err => { device.open((err) => {
this.openingOtpDevice = false; this.openingOtpDevice = false;
if (!err) { if (!err) {
this.addFile(device); this.addFile(device);

View File

@ -9,7 +9,7 @@ class AppSettingsModel extends Model {
} }
load() { load() {
return SettingsStore.load('app-settings').then(data => { return SettingsStore.load('app-settings').then((data) => {
if (data) { if (data) {
this.upgrade(data); this.upgrade(data);
this.set(data, { silent: true }); this.set(data, { silent: true });

View File

@ -107,10 +107,10 @@ class EntryModel extends Model {
text += value.toLowerCase() + '\n'; text += value.toLowerCase() + '\n';
} }
} }
this.entry.tags.forEach(tag => { this.entry.tags.forEach((tag) => {
text += tag.toLowerCase() + '\n'; text += tag.toLowerCase() + '\n';
}); });
this.attachments.forEach(att => { this.attachments.forEach((att) => {
text += att.title.toLowerCase() + '\n'; text += att.title.toLowerCase() + '\n';
}); });
this.searchText = text; this.searchText = text;
@ -128,7 +128,7 @@ class EntryModel extends Model {
} }
_buildSearchTags() { _buildSearchTags() {
this.searchTags = this.entry.tags.map(tag => tag.toLowerCase()); this.searchTags = this.entry.tags.map((tag) => tag.toLowerCase());
} }
_buildSearchColor() { _buildSearchColor() {
@ -217,7 +217,7 @@ class EntryModel extends Model {
resolveFieldReferences() { resolveFieldReferences() {
this.hasFieldRefs = false; this.hasFieldRefs = false;
FieldRefFields.forEach(field => { FieldRefFields.forEach((field) => {
const fieldValue = this[field]; const fieldValue = this[field];
const refValue = this._resolveFieldReference(fieldValue); const refValue = this._resolveFieldReference(fieldValue);
if (refValue !== undefined) { if (refValue !== undefined) {
@ -230,7 +230,7 @@ class EntryModel extends Model {
getFieldValue(field) { getFieldValue(field) {
field = field.toLowerCase(); field = field.toLowerCase();
let resolvedField; let resolvedField;
Object.keys(this.entry.fields).some(entryField => { Object.keys(this.entry.fields).some((entryField) => {
if (entryField.toLowerCase() === field) { if (entryField.toLowerCase() === field) {
resolvedField = entryField; resolvedField = entryField;
return true; return true;
@ -310,7 +310,7 @@ class EntryModel extends Model {
} }
renameTag(from, to) { renameTag(from, to) {
const ix = this.entry.tags.findIndex(tag => tag.toLowerCase() === from.toLowerCase()); const ix = this.entry.tags.findIndex((tag) => tag.toLowerCase() === from.toLowerCase());
if (ix < 0) { if (ix < 0) {
return; return;
} }
@ -350,7 +350,7 @@ class EntryModel extends Model {
addAttachment(name, data) { addAttachment(name, data) {
this._entryModified(); this._entryModified();
return this.file.db.createBinary(data).then(binaryRef => { return this.file.db.createBinary(data).then((binaryRef) => {
this.entry.binaries[name] = binaryRef; this.entry.binaries[name] = binaryRef;
this._fillByEntry(); this._fillByEntry();
}); });
@ -363,7 +363,7 @@ class EntryModel extends Model {
} }
getHistory() { getHistory() {
const history = this.entry.history.map(function(rec) { const history = this.entry.history.map(function (rec) {
return EntryModel.fromEntry(rec, this.group, this.file); return EntryModel.fromEntry(rec, this.group, this.file);
}, this); }, this);
history.push(this); history.push(this);
@ -466,7 +466,7 @@ class EntryModel extends Model {
} else if (otpUrl.toLowerCase().lastIndexOf('otpauth:', 0) !== 0) { } else if (otpUrl.toLowerCase().lastIndexOf('otpauth:', 0) !== 0) {
// KeeOTP plugin format // KeeOTP plugin format
const args = {}; const args = {};
otpUrl.split('&').forEach(part => { otpUrl.split('&').forEach((part) => {
const parts = part.split('=', 2); const parts = part.split('=', 2);
args[parts[0]] = decodeURIComponent(parts[1]).replace(/=/g, ''); args[parts[0]] = decodeURIComponent(parts[1]).replace(/=/g, '');
}); });

View File

@ -13,7 +13,7 @@ class ExternalOtpEntryModel extends ExternalEntryModel {
return; return;
} }
const gen = { const gen = {
next: callback => { next: (callback) => {
if (gen.otp && gen.expires) { if (gen.otp && gen.expires) {
const timeLeft = gen.expires - Date.now(); const timeLeft = gen.expires - Date.now();
if (timeLeft > 0) { if (timeLeft > 0) {
@ -26,7 +26,7 @@ class ExternalOtpEntryModel extends ExternalEntryModel {
}); });
return; return;
} }
gen.promise = new Promise(resolve => { gen.promise = new Promise((resolve) => {
gen.otpState = this.device.getOtp(this, (err, otp, timeLeft) => { gen.otpState = this.device.getOtp(this, (err, otp, timeLeft) => {
gen.otpState = null; gen.otpState = null;
gen.promise = null; gen.promise = null;

View File

@ -34,7 +34,7 @@ class YubiKeyOtpModel extends ExternalOtpDeviceModel {
const openErrors = []; const openErrors = [];
const openNextYubiKey = () => { const openNextYubiKey = () => {
const yubiKey = yubiKeys.shift(); const yubiKey = yubiKeys.shift();
this._addYubiKey(yubiKey.serial, err => { this._addYubiKey(yubiKey.serial, (err) => {
if (YubiKey.aborted) { if (YubiKey.aborted) {
return callback('Aborted'); return callback('Aborted');
} }

View File

@ -29,7 +29,7 @@ class FileModel extends Model {
const ts = logger.ts(); const ts = logger.ts();
kdbxweb.Kdbx.load(fileData, credentials) kdbxweb.Kdbx.load(fileData, credentials)
.then(db => { .then((db) => {
this.db = db; this.db = db;
this.readModel(); this.readModel();
this.setOpenFile({ passwordLength: password ? password.textLength : 0 }); this.setOpenFile({ passwordLength: password ? password.textLength : 0 });
@ -50,7 +50,7 @@ class FileModel extends Model {
); );
callback(); callback();
}) })
.catch(err => { .catch((err) => {
if ( if (
err.code === kdbxweb.Consts.ErrorCodes.InvalidKey && err.code === kdbxweb.Consts.ErrorCodes.InvalidKey &&
password && password &&
@ -74,14 +74,14 @@ class FileModel extends Model {
if (header.kdfParameters) { if (header.kdfParameters) {
return header.kdfParameters return header.kdfParameters
.keys() .keys()
.map(key => { .map((key) => {
const val = header.kdfParameters.get(key); const val = header.kdfParameters.get(key);
if (val instanceof ArrayBuffer) { if (val instanceof ArrayBuffer) {
return undefined; return undefined;
} }
return key + '=' + val; return key + '=' + val;
}) })
.filter(p => p) .filter((p) => p)
.join('&'); .join('&');
} else if (header.keyEncryptionRounds) { } else if (header.keyEncryptionRounds) {
return header.keyEncryptionRounds + ' rounds'; return header.keyEncryptionRounds + ' rounds';
@ -105,14 +105,14 @@ class FileModel extends Model {
const password = kdbxweb.ProtectedValue.fromString(''); const password = kdbxweb.ProtectedValue.fromString('');
const credentials = new kdbxweb.Credentials(password); const credentials = new kdbxweb.Credentials(password);
kdbxweb.Kdbx.loadXml(fileXml, credentials) kdbxweb.Kdbx.loadXml(fileXml, credentials)
.then(db => { .then((db) => {
this.db = db; this.db = db;
this.readModel(); this.readModel();
this.set({ active: true, created: true }); this.set({ active: true, created: true });
logger.info('Imported file ' + this.name + ': ' + logger.ts(ts)); logger.info('Imported file ' + this.name + ': ' + logger.ts(ts));
callback(); callback();
}) })
.catch(err => { .catch((err) => {
logger.error('Error importing file', err.code, err.message, err); logger.error('Error importing file', err.code, err.message, err);
callback(err); callback(err);
}); });
@ -128,7 +128,7 @@ class FileModel extends Model {
const demoFile = kdbxweb.ByteUtils.arrayToBuffer( const demoFile = kdbxweb.ByteUtils.arrayToBuffer(
kdbxweb.ByteUtils.base64ToBytes(demoFileData) kdbxweb.ByteUtils.base64ToBytes(demoFileData)
); );
kdbxweb.Kdbx.load(demoFile, credentials).then(db => { kdbxweb.Kdbx.load(demoFile, credentials).then((db) => {
this.db = db; this.db = db;
this.name = 'Demo'; this.name = 'Demo';
this.readModel(); this.readModel();
@ -169,7 +169,7 @@ class FileModel extends Model {
}, },
{ silent: true } { silent: true }
); );
this.db.groups.forEach(function(group) { this.db.groups.forEach(function (group) {
let groupModel = this.getGroup(this.subId(group.uuid.id)); let groupModel = this.getGroup(this.subId(group.uuid.id));
if (groupModel) { if (groupModel) {
groupModel.setGroup(group, this); groupModel.setGroup(group, this);
@ -235,9 +235,9 @@ class FileModel extends Model {
const entryMap = {}; const entryMap = {};
const groupMap = {}; const groupMap = {};
this.forEachGroup( this.forEachGroup(
group => { (group) => {
groupMap[group.id] = group; groupMap[group.id] = group;
group.forEachOwnEntry(null, entry => { group.forEachOwnEntry(null, (entry) => {
entryMap[entry.id] = entry; entryMap[entry.id] = entry;
}); });
}, },
@ -249,7 +249,7 @@ class FileModel extends Model {
resolveFieldReferences() { resolveFieldReferences() {
const entryMap = this.entryMap; const entryMap = this.entryMap;
Object.keys(entryMap).forEach(e => { Object.keys(entryMap).forEach((e) => {
entryMap[e].resolveFieldReferences(); entryMap[e].resolveFieldReferences();
}); });
} }
@ -297,7 +297,7 @@ class FileModel extends Model {
} }
credentialsPromise.then(() => { credentialsPromise.then(() => {
kdbxweb.Kdbx.load(fileData, credentials) kdbxweb.Kdbx.load(fileData, credentials)
.then(remoteDb => { .then((remoteDb) => {
if (this.modified) { if (this.modified) {
try { try {
if (remoteKey && remoteDb.meta.keyChanged > this.db.meta.keyChanged) { if (remoteKey && remoteDb.meta.keyChanged > this.db.meta.keyChanged) {
@ -319,7 +319,7 @@ class FileModel extends Model {
this.reload(); this.reload();
callback(); callback();
}) })
.catch(err => { .catch((err) => {
logger.error('Error opening file to merge', err.code, err.message, err); logger.error('Error opening file to merge', err.code, err.message, err);
callback(err); callback(err);
}); });
@ -374,7 +374,7 @@ class FileModel extends Model {
top.forEachOwnEntry(filter, callback); top.forEachOwnEntry(filter, callback);
} }
if (!filter.group || filter.subGroups) { if (!filter.group || filter.subGroups) {
top.forEachGroup(group => { top.forEachGroup((group) => {
group.forEachOwnEntry(filter, callback); group.forEachOwnEntry(filter, callback);
}, filter); }, filter);
} }
@ -382,7 +382,7 @@ class FileModel extends Model {
} }
forEachGroup(callback, filter) { forEachGroup(callback, filter) {
this.groups.forEach(group => { this.groups.forEach((group) => {
if (callback(group) !== false) { if (callback(group) !== false) {
group.forEachGroup(callback, filter); group.forEachGroup(callback, filter);
} }
@ -426,17 +426,17 @@ class FileModel extends Model {
this.db.cleanup({ binaries: true }); this.db.cleanup({ binaries: true });
this.db this.db
.save() .save()
.then(data => { .then((data) => {
cb(data); cb(data);
}) })
.catch(err => { .catch((err) => {
logger.error('Error saving file', this.name, err); logger.error('Error saving file', this.name, err);
cb(undefined, err); cb(undefined, err);
}); });
} }
getXml(cb) { getXml(cb) {
this.db.saveXml(true).then(xml => { this.db.saveXml(true).then((xml) => {
cb(xml); cb(xml);
}); });
} }
@ -493,7 +493,7 @@ class FileModel extends Model {
return; return;
} }
this.setOpenFile({ passwordLength: this.passwordLength }); this.setOpenFile({ passwordLength: this.passwordLength });
this.forEachEntry({ includeDisabled: true }, entry => entry.setSaved()); this.forEachEntry({ includeDisabled: true }, (entry) => entry.setSaved());
} }
setPassword(password) { setPassword(password) {
@ -649,11 +649,11 @@ class FileModel extends Model {
trashGroup trashGroup
.getOwnSubGroups() .getOwnSubGroups()
.slice() .slice()
.forEach(function(group) { .forEach(function (group) {
this.db.move(group, null); this.db.move(group, null);
modified = true; modified = true;
}, this); }, this);
trashGroup.group.entries.slice().forEach(function(entry) { trashGroup.group.entries.slice().forEach(function (entry) {
this.db.move(entry, null); this.db.move(entry, null);
modified = true; modified = true;
}, this); }, this);
@ -666,7 +666,7 @@ class FileModel extends Model {
} }
getCustomIcons() { getCustomIcons() {
return mapObject(this.db.meta.customIcons, customIcon => return mapObject(this.db.meta.customIcons, (customIcon) =>
IconUrlFormat.toDataUrl(customIcon) IconUrlFormat.toDataUrl(customIcon)
); );
} }
@ -680,7 +680,7 @@ class FileModel extends Model {
} }
renameTag(from, to) { renameTag(from, to) {
this.forEachEntry({}, entry => entry.renameTag(from, to)); this.forEachEntry({}, (entry) => entry.renameTag(from, to));
} }
setFormatVersion(version) { setFormatVersion(version) {

View File

@ -39,7 +39,7 @@ class GroupModel extends MenuItemModel {
const items = this.items; const items = this.items;
const entries = this.entries; const entries = this.entries;
const itemsArray = group.groups.map(subGroup => { const itemsArray = group.groups.map((subGroup) => {
let g = file.getGroup(file.subId(subGroup.uuid.id)); let g = file.getGroup(file.subId(subGroup.uuid.id));
if (g) { if (g) {
g.setGroup(subGroup, file, this); g.setGroup(subGroup, file, this);
@ -50,7 +50,7 @@ class GroupModel extends MenuItemModel {
}, this); }, this);
items.push(...itemsArray); items.push(...itemsArray);
const entriesArray = group.entries.map(entry => { const entriesArray = group.entries.map((entry) => {
let e = file.getEntry(file.subId(entry.uuid.id)); let e = file.getEntry(file.subId(entry.uuid.id));
if (e) { if (e) {
e.setEntry(entry, this, file); e.setEntry(entry, this, file);
@ -101,7 +101,7 @@ class GroupModel extends MenuItemModel {
forEachGroup(callback, filter) { forEachGroup(callback, filter) {
let result = true; let result = true;
this.items.forEach(group => { this.items.forEach((group) => {
if (group.matches(filter)) { if (group.matches(filter)) {
result = result =
callback(group) !== false && group.forEachGroup(callback, filter) !== false; callback(group) !== false && group.forEachGroup(callback, filter) !== false;
@ -111,7 +111,7 @@ class GroupModel extends MenuItemModel {
} }
forEachOwnEntry(filter, callback) { forEachOwnEntry(filter, callback) {
this.entries.forEach(function(entry) { this.entries.forEach(function (entry) {
if (entry.matches(filter)) { if (entry.matches(filter)) {
callback(entry, this); callback(entry, this);
} }

View File

@ -49,7 +49,7 @@ class MenuModel extends Model {
drop: true drop: true
} }
]); ]);
Colors.AllColors.forEach(color => { Colors.AllColors.forEach((color) => {
const option = { const option = {
cls: 'fa ' + color + '-color', cls: 'fa ' + color + '-color',
value: color, value: color,
@ -96,7 +96,7 @@ class MenuModel extends Model {
this.aboutSection, this.aboutSection,
this.helpSection, this.helpSection,
this.filesSection this.filesSection
].filter(s => s) ].filter((s) => s)
); );
this.sections = this.menus.app; this.sections = this.menus.app;
@ -113,7 +113,7 @@ class MenuModel extends Model {
this._select(section, sel.item); this._select(section, sel.item);
} }
if (sections === this.menus.app) { if (sections === this.menus.app) {
this.colorsItem.options.forEach(opt => { this.colorsItem.options.forEach((opt) => {
opt.active = opt === sel.option; opt.active = opt === sel.option;
}); });
const selColor = const selColor =
@ -135,7 +135,7 @@ class MenuModel extends Model {
_selectPrevious() { _selectPrevious() {
let previousItem = null; let previousItem = null;
const processSection = section => { const processSection = (section) => {
if (section.visible === false) { if (section.visible === false) {
return true; return true;
} }
@ -144,7 +144,7 @@ class MenuModel extends Model {
} }
const items = section.items; const items = section.items;
if (items) { if (items) {
items.forEach(it => { items.forEach((it) => {
if (it.active && previousItem) { if (it.active && previousItem) {
this.select({ item: previousItem }); this.select({ item: previousItem });
return false; return false;
@ -155,13 +155,13 @@ class MenuModel extends Model {
}; };
const sections = this.sections; const sections = this.sections;
sections.forEach(section => processSection(section)); sections.forEach((section) => processSection(section));
} }
_selectNext() { _selectNext() {
let activeItem = null; let activeItem = null;
const processSection = section => { const processSection = (section) => {
if (section.visible === false) { if (section.visible === false) {
return true; return true;
} }
@ -172,7 +172,7 @@ class MenuModel extends Model {
} }
const items = section.items; const items = section.items;
if (items) { if (items) {
items.forEach(it => { items.forEach((it) => {
if (it.active) { if (it.active) {
activeItem = it; activeItem = it;
} }
@ -182,7 +182,7 @@ class MenuModel extends Model {
}; };
const sections = this.sections; const sections = this.sections;
sections.forEach(section => processSection(section)); sections.forEach((section) => processSection(section));
} }
_select(item, selectedItem) { _select(item, selectedItem) {

View File

@ -19,14 +19,14 @@ class MenuSectionModel extends Model {
removeAllItems() { removeAllItems() {
this.items.length = 0; this.items.length = 0;
if (this.defaultItems) { if (this.defaultItems) {
this.items.push(...this.defaultItems.map(item => new MenuItemModel(item))); this.items.push(...this.defaultItems.map((item) => new MenuItemModel(item)));
} }
this.emit('change-items'); this.emit('change-items');
} }
removeByFile(file) { removeByFile(file) {
const items = this.items; const items = this.items;
items.find(item => { items.find((item) => {
if (item.file === file || item.file === file) { if (item.file === file || item.file === file) {
items.remove(item); items.remove(item);
return true; return true;

View File

@ -8,7 +8,7 @@ class RuntimeDataModel extends Model {
} }
load() { load() {
return SettingsStore.load('runtime-data').then(data => { return SettingsStore.load('runtime-data').then((data) => {
if (data) { if (data) {
this.set(data, { silent: true }); this.set(data, { silent: true });
} }

View File

@ -3,7 +3,7 @@ import { SettingsStore } from 'comp/settings/settings-store';
class UpdateModel extends Model { class UpdateModel extends Model {
load() { load() {
return SettingsStore.load('update-info').then(data => { return SettingsStore.load('update-info').then((data) => {
if (data) { if (data) {
try { try {
for (const [key, val] of Object.entries(data)) { for (const [key, val] of Object.entries(data)) {

View File

@ -19,7 +19,7 @@ const PluginGallery = {
this.loading = true; this.loading = true;
this.loadError = false; this.loadError = false;
const ts = this.logger.ts(); const ts = this.logger.ts();
return new Promise(resolve => { return new Promise((resolve) => {
this.logger.debug('Loading plugins...'); this.logger.debug('Loading plugins...');
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.open('GET', Links.Plugins + '/plugins.json'); xhr.open('GET', Links.Plugins + '/plugins.json');
@ -34,14 +34,14 @@ const PluginGallery = {
resolve(); resolve();
}); });
}) })
.then(data => { .then((data) => {
this.loading = false; this.loading = false;
if (!data) { if (!data) {
this.loadError = true; this.loadError = true;
Events.emit('plugin-gallery-load-complete'); Events.emit('plugin-gallery-load-complete');
return; return;
} }
return this.verifySignature(data).then(gallery => { return this.verifySignature(data).then((gallery) => {
this.loadError = !gallery; this.loadError = !gallery;
if (gallery) { if (gallery) {
this.logger.debug( this.logger.debug(
@ -55,7 +55,7 @@ const PluginGallery = {
return gallery; return gallery;
}); });
}) })
.catch(e => { .catch((e) => {
this.loadError = true; this.loadError = true;
this.logger.error('Error loading plugin gallery', e); this.logger.error('Error loading plugin gallery', e);
Events.emit('plugin-gallery-load-complete'); Events.emit('plugin-gallery-load-complete');
@ -68,22 +68,22 @@ const PluginGallery = {
kdbxweb.ByteUtils.stringToBytes(dataToVerify), kdbxweb.ByteUtils.stringToBytes(dataToVerify),
gallery.signature gallery.signature
) )
.then(isValid => { .then((isValid) => {
if (isValid) { if (isValid) {
return gallery; return gallery;
} }
this.logger.error('JSON signature invalid'); this.logger.error('JSON signature invalid');
}) })
.catch(e => { .catch((e) => {
this.logger.error('Error verifying plugins signature', e); this.logger.error('Error verifying plugins signature', e);
}); });
}, },
getCachedGallery() { getCachedGallery() {
const ts = this.logger.ts(); const ts = this.logger.ts();
return SettingsStore.load('plugin-gallery').then(data => { return SettingsStore.load('plugin-gallery').then((data) => {
if (data) { if (data) {
return this.verifySignature(data).then(gallery => { return this.verifySignature(data).then((gallery) => {
this.logger.debug(`Loaded cached plugin gallery`, this.logger.ts(ts)); this.logger.debug(`Loaded cached plugin gallery`, this.logger.ts(ts));
return gallery; return gallery;
}); });

View File

@ -21,7 +21,7 @@ class PluginManager extends Model {
init() { init() {
const ts = logger.ts(); const ts = logger.ts();
return SettingsStore.load('plugins').then(state => { return SettingsStore.load('plugins').then((state) => {
if (!state) { if (!state) {
return; return;
} }
@ -32,10 +32,10 @@ class PluginManager extends Model {
if (!state || !state.plugins || !state.plugins.length) { if (!state || !state.plugins || !state.plugins.length) {
return; return;
} }
return PluginGallery.getCachedGallery().then(gallery => { return PluginGallery.getCachedGallery().then((gallery) => {
const promises = state.plugins.map(plugin => this.loadPlugin(plugin, gallery)); const promises = state.plugins.map((plugin) => this.loadPlugin(plugin, gallery));
return Promise.all(promises).then(loadedPlugins => { return Promise.all(promises).then((loadedPlugins) => {
this.plugins.push(...loadedPlugins.filter(plugin => plugin)); this.plugins.push(...loadedPlugins.filter((plugin) => plugin));
logger.info(`Loaded ${this.plugins.length} plugins`, logger.ts(ts)); logger.info(`Loaded ${this.plugins.length} plugins`, logger.ts(ts));
}); });
}); });
@ -45,7 +45,7 @@ class PluginManager extends Model {
install(url, expectedManifest, skipSignatureValidation) { install(url, expectedManifest, skipSignatureValidation) {
this.emit('change'); this.emit('change');
return Plugin.loadFromUrl(url, expectedManifest) return Plugin.loadFromUrl(url, expectedManifest)
.then(plugin => { .then((plugin) => {
return this.uninstall(plugin.id).then(() => { return this.uninstall(plugin.id).then(() => {
if (skipSignatureValidation) { if (skipSignatureValidation) {
plugin.skipSignatureValidation = true; plugin.skipSignatureValidation = true;
@ -57,14 +57,14 @@ class PluginManager extends Model {
}); });
}); });
}) })
.catch(e => { .catch((e) => {
this.emit('change'); this.emit('change');
throw e; throw e;
}); });
} }
installIfNew(url, expectedManifest, skipSignatureValidation) { installIfNew(url, expectedManifest, skipSignatureValidation) {
const plugin = this.plugins.find(p => p.url === url); const plugin = this.plugins.find((p) => p.url === url);
if (plugin && plugin.status !== 'invalid') { if (plugin && plugin.status !== 'invalid') {
return Promise.resolve(); return Promise.resolve();
} }
@ -123,19 +123,19 @@ class PluginManager extends Model {
const url = oldPlugin.url; const url = oldPlugin.url;
this.emit('change'); this.emit('change');
return Plugin.loadFromUrl(url) return Plugin.loadFromUrl(url)
.then(newPlugin => { .then((newPlugin) => {
return oldPlugin return oldPlugin
.update(newPlugin) .update(newPlugin)
.then(() => { .then(() => {
this.emit('change'); this.emit('change');
this.saveState(); this.saveState();
}) })
.catch(e => { .catch((e) => {
this.emit('change'); this.emit('change');
throw e; throw e;
}); });
}) })
.catch(e => { .catch((e) => {
this.emit('change'); this.emit('change');
throw e; throw e;
}); });
@ -152,7 +152,7 @@ class PluginManager extends Model {
} }
runAutoUpdate() { runAutoUpdate() {
const queue = this.plugins.filter(p => p.autoUpdate).map(p => p.id); const queue = this.plugins.filter((p) => p.autoUpdate).map((p) => p.id);
if (!queue.length) { if (!queue.length) {
return Promise.resolve(); return Promise.resolve();
} }
@ -172,9 +172,7 @@ class PluginManager extends Model {
const updateNext = () => { const updateNext = () => {
const pluginId = queue.shift(); const pluginId = queue.shift();
if (pluginId) { if (pluginId) {
return this.update(pluginId) return this.update(pluginId).catch(noop).then(updateNext);
.catch(noop)
.then(updateNext);
} }
}; };
return updateNext(); return updateNext();
@ -189,7 +187,7 @@ class PluginManager extends Model {
let enabled = desc.enabled; let enabled = desc.enabled;
if (enabled) { if (enabled) {
const galleryPlugin = gallery const galleryPlugin = gallery
? gallery.plugins.find(pl => pl.manifest.name === desc.manifest.name) ? gallery.plugins.find((pl) => pl.manifest.name === desc.manifest.name)
: null; : null;
const expectedPublicKeys = galleryPlugin const expectedPublicKeys = galleryPlugin
? [galleryPlugin.manifest.publicKey] ? [galleryPlugin.manifest.publicKey]
@ -206,7 +204,7 @@ class PluginManager extends Model {
SettingsStore.save('plugins', { SettingsStore.save('plugins', {
autoUpdateAppVersion: this.autoUpdateAppVersion, autoUpdateAppVersion: this.autoUpdateAppVersion,
autoUpdateDate: this.autoUpdateDate, autoUpdateDate: this.autoUpdateDate,
plugins: this.plugins.map(plugin => ({ plugins: this.plugins.map((plugin) => ({
manifest: plugin.manifest, manifest: plugin.manifest,
url: plugin.url, url: plugin.url,
enabled: plugin.status === 'active', enabled: plugin.status === 'active',

View File

@ -64,7 +64,7 @@ class Plugin extends Model {
.then(() => { .then(() => {
this.installTime = this.logger.ts() - ts; this.installTime = this.logger.ts() - ts;
}) })
.catch(err => { .catch((err) => {
this.logger.error('Error installing plugin', err); this.logger.error('Error installing plugin', err);
this.set({ this.set({
status: PluginStatus.STATUS_ERROR, status: PluginStatus.STATUS_ERROR,
@ -166,7 +166,7 @@ class Plugin extends Model {
); );
this.resources = {}; this.resources = {};
const ts = this.logger.ts(); const ts = this.logger.ts();
const results = Object.keys(manifest.resources).map(res => const results = Object.keys(manifest.resources).map((res) =>
this.loadResource(res, local, manifest) this.loadResource(res, local, manifest)
); );
return Promise.all(results) return Promise.all(results)
@ -209,9 +209,9 @@ class Plugin extends Model {
const url = this.url + this.getResourcePath(type) + '?v=' + manifest.version; const url = this.url + this.getResourcePath(type) + '?v=' + manifest.version;
res = httpGet(url, true); res = httpGet(url, true);
} }
return res.then(data => { return res.then((data) => {
this.logger.debug('Resource data loaded', type, this.logger.ts(ts)); this.logger.debug('Resource data loaded', type, this.logger.ts(ts));
return this.verifyResource(data, type).then(data => { return this.verifyResource(data, type).then((data) => {
this.resources[type] = data; this.resources[type] = data;
}); });
}); });
@ -222,7 +222,7 @@ class Plugin extends Model {
const manifest = this.manifest; const manifest = this.manifest;
const signature = manifest.resources[type]; const signature = manifest.resources[type];
return SignatureVerifier.verify(data, signature, manifest.publicKey) return SignatureVerifier.verify(data, signature, manifest.publicKey)
.then(valid => { .then((valid) => {
if (valid) { if (valid) {
this.logger.debug('Resource signature validated', type, this.logger.ts(ts)); this.logger.debug('Resource signature validated', type, this.logger.ts(ts));
return data; return data;
@ -254,7 +254,7 @@ class Plugin extends Model {
.then(() => { .then(() => {
this.status = PluginStatus.STATUS_ACTIVE; this.status = PluginStatus.STATUS_ACTIVE;
}) })
.catch(e => { .catch((e) => {
this.logger.info('Install error', e); this.logger.info('Install error', e);
this.status = PluginStatus.STATUS_ERROR; this.status = PluginStatus.STATUS_ERROR;
return this.disable().then(() => { return this.disable().then(() => {
@ -268,7 +268,7 @@ class Plugin extends Model {
for (const key of Object.keys(this.resources)) { for (const key of Object.keys(this.resources)) {
resourceSavePromises.push(this.saveResource(key, this.resources[key])); resourceSavePromises.push(this.saveResource(key, this.resources[key]));
} }
return Promise.all(resourceSavePromises).catch(e => { return Promise.all(resourceSavePromises).catch((e) => {
this.logger.debug('Error saving plugin resources', e); this.logger.debug('Error saving plugin resources', e);
return this.uninstall().then(() => { return this.uninstall().then(() => {
throw 'Error saving plugin resources'; throw 'Error saving plugin resources';
@ -279,7 +279,7 @@ class Plugin extends Model {
saveResource(key, value) { saveResource(key, value) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const storageKey = this.getStorageResourcePath(key); const storageKey = this.getStorageResourcePath(key);
io.save(storageKey, value, e => { io.save(storageKey, value, (e) => {
if (e) { if (e) {
reject(e); reject(e);
} else { } else {
@ -298,7 +298,7 @@ class Plugin extends Model {
} }
deleteResource(key) { deleteResource(key) {
return new Promise(resolve => { return new Promise((resolve) => {
const storageKey = this.getStorageResourcePath(key); const storageKey = this.getStorageResourcePath(key);
io.remove(storageKey, () => resolve()); io.remove(storageKey, () => resolve());
}); });
@ -567,7 +567,7 @@ class Plugin extends Model {
}); });
this.logger.info('Update complete', this.logger.ts(ts)); this.logger.info('Update complete', this.logger.ts(ts));
}) })
.catch(err => { .catch((err) => {
this.logger.error('Error updating plugin', err); this.logger.error('Error updating plugin', err);
if (prevStatus === PluginStatus.STATUS_ACTIVE) { if (prevStatus === PluginStatus.STATUS_ACTIVE) {
this.logger.info('Activating previous version'); this.logger.info('Activating previous version');
@ -606,7 +606,7 @@ class Plugin extends Model {
const settings = this.module.exports.getSettings(); const settings = this.module.exports.getSettings();
const settingsPrefix = this.getSettingPrefix(); const settingsPrefix = this.getSettingPrefix();
if (settings instanceof Array) { if (settings instanceof Array) {
return settings.map(setting => { return settings.map((setting) => {
setting = { ...setting }; setting = { ...setting };
const value = AppSettingsModel[settingsPrefix + setting.name]; const value = AppSettingsModel[settingsPrefix + setting.name];
if (value !== undefined) { if (value !== undefined) {
@ -642,11 +642,11 @@ class Plugin extends Model {
commonLogger.info('Installing plugin from url', url); commonLogger.info('Installing plugin from url', url);
const manifestUrl = url + 'manifest.json'; const manifestUrl = url + 'manifest.json';
return httpGet(manifestUrl) return httpGet(manifestUrl)
.catch(e => { .catch((e) => {
commonLogger.error('Error loading plugin manifest', e); commonLogger.error('Error loading plugin manifest', e);
throw 'Error loading plugin manifest'; throw 'Error loading plugin manifest';
}) })
.then(manifest => { .then((manifest) => {
try { try {
manifest = JSON.parse(manifest); manifest = JSON.parse(manifest);
} catch (e) { } catch (e) {

View File

@ -41,14 +41,14 @@ const ThemeVars = {
const locals = []; const locals = [];
while (replaced) { while (replaced) {
replaced = false; replaced = false;
result = result.replace(/([\w\-]+)\([^()]+\)/, fnText => { result = result.replace(/([\w\-]+)\([^()]+\)/, (fnText) => {
replaced = true; replaced = true;
const [, name, argsStr] = fnText.match(/([\w\-]+)\((.*)\)/); const [, name, argsStr] = fnText.match(/([\w\-]+)\((.*)\)/);
const args = argsStr const args = argsStr
.trim() .trim()
.split(/\s*,\s*/) .split(/\s*,\s*/)
.filter(arg => arg) .filter((arg) => arg)
.map(arg => this.resolveArg(arg, cssStyle, locals)); .map((arg) => this.resolveArg(arg, cssStyle, locals));
locals.push(this.fn[name](...args)); locals.push(this.fn[name](...args));
return 'L' + (locals.length - 1); return 'L' + (locals.length - 1);
}); });

View File

@ -1,7 +1,7 @@
import { DateFormat } from 'util/formatting/date-format'; import { DateFormat } from 'util/formatting/date-format';
import { Locale } from 'util/locale'; import { Locale } from 'util/locale';
const EntryPresenter = function(descField, noColor, activeEntryId) { const EntryPresenter = function (descField, noColor, activeEntryId) {
this.entry = null; this.entry = null;
this.descField = descField; this.descField = descField;
this.noColor = noColor || ''; this.noColor = noColor || '';
@ -85,7 +85,7 @@ EntryPresenter.prototype = {
return this.updated; return this.updated;
case 'attachments': case 'attachments':
return ( return (
this.entry.attachments.map(a => a.title).join(', ') || this.entry.attachments.map((a) => a.title).join(', ') ||
'(' + Locale.listNoAttachments + ')' '(' + Locale.listNoAttachments + ')'
); );
default: default:

View File

@ -236,12 +236,12 @@ class StorageDropbox extends StorageBase {
_encodeJsonHttpHeader(json) { _encodeJsonHttpHeader(json) {
return json.replace( return json.replace(
/[\u007f-\uffff]/g, /[\u007f-\uffff]/g,
c => '\\u' + ('000' + c.charCodeAt(0).toString(16)).slice(-4) (c) => '\\u' + ('000' + c.charCodeAt(0).toString(16)).slice(-4)
); );
} }
_apiCall(args) { _apiCall(args) {
this._oauthAuthorize(err => { this._oauthAuthorize((err) => {
if (err) { if (err) {
return args.error(err); return args.error(err);
} }
@ -307,7 +307,7 @@ class StorageDropbox extends StorageBase {
this._apiCall({ this._apiCall({
method: 'files/get_metadata', method: 'files/get_metadata',
data: { path }, data: { path },
success: stat => { success: (stat) => {
if (stat['.tag'] === 'file') { if (stat['.tag'] === 'file') {
stat = { rev: stat.rev }; stat = { rev: stat.rev };
} else if (stat['.tag'] === 'folder') { } else if (stat['.tag'] === 'folder') {
@ -341,7 +341,7 @@ class StorageDropbox extends StorageBase {
apiArg: arg, apiArg: arg,
data, data,
responseType: 'json', responseType: 'json',
success: stat => { success: (stat) => {
this.logger.debug('Saved', path, stat.rev, this.logger.ts(ts)); this.logger.debug('Saved', path, stat.rev, this.logger.ts(ts));
callback(null, { rev: stat.rev }); callback(null, { rev: stat.rev });
}, },
@ -358,9 +358,9 @@ class StorageDropbox extends StorageBase {
path: this._toFullPath(dir || ''), path: this._toFullPath(dir || ''),
recursive: false recursive: false
}, },
success: data => { success: (data) => {
this.logger.debug('Listed', this.logger.ts(ts)); this.logger.debug('Listed', this.logger.ts(ts));
const fileList = data.entries.map(f => ({ const fileList = data.entries.map((f) => ({
name: f.name, name: f.name,
path: this._toRelPath(f.path_display), path: this._toRelPath(f.path_display),
rev: f.rev, rev: f.rev,

View File

@ -19,7 +19,7 @@ class StorageFileCache extends StorageBase {
const path = Launcher.getUserDataPath('OfflineFiles'); const path = Launcher.getUserDataPath('OfflineFiles');
const setPath = err => { const setPath = (err) => {
this.path = err ? null : path; this.path = err ? null : path;
if (err) { if (err) {
this.logger.error('Error opening local offline storage', err); this.logger.error('Error opening local offline storage', err);
@ -27,7 +27,7 @@ class StorageFileCache extends StorageBase {
return callback && callback(err); return callback && callback(err);
}; };
Launcher.fileExists(path, exists => { Launcher.fileExists(path, (exists) => {
if (exists) { if (exists) {
setPath(); setPath();
} else { } else {
@ -38,12 +38,12 @@ class StorageFileCache extends StorageBase {
save(id, opts, data, callback) { save(id, opts, data, callback) {
this.logger.debug('Save', id); this.logger.debug('Save', id);
this.initFs(err => { this.initFs((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
const ts = this.logger.ts(); const ts = this.logger.ts();
Launcher.writeFile(this.getPath(id), data, err => { Launcher.writeFile(this.getPath(id), data, (err) => {
if (err) { if (err) {
this.logger.error('Error saving to cache', id, err); this.logger.error('Error saving to cache', id, err);
return callback && callback(err); return callback && callback(err);
@ -58,7 +58,7 @@ class StorageFileCache extends StorageBase {
load(id, opts, callback) { load(id, opts, callback) {
this.logger.debug('Load', id); this.logger.debug('Load', id);
this.initFs(err => { this.initFs((err) => {
if (err) { if (err) {
return callback && callback(null, err); return callback && callback(null, err);
} }
@ -78,7 +78,7 @@ class StorageFileCache extends StorageBase {
remove(id, opts, callback) { remove(id, opts, callback) {
this.logger.debug('Remove', id); this.logger.debug('Remove', id);
this.initFs(err => { this.initFs((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -86,9 +86,9 @@ class StorageFileCache extends StorageBase {
const ts = this.logger.ts(); const ts = this.logger.ts();
const path = this.getPath(id); const path = this.getPath(id);
Launcher.fileExists(path, exists => { Launcher.fileExists(path, (exists) => {
if (exists) { if (exists) {
Launcher.deleteFile(path, err => { Launcher.deleteFile(path, (err) => {
if (err) { if (err) {
this.logger.error('Error removing from cache', id, err); this.logger.error('Error removing from cache', id, err);
} else { } else {

View File

@ -14,7 +14,7 @@ class StorageFile extends StorageBase {
this.logger.debug('Load', path); this.logger.debug('Load', path);
const ts = this.logger.ts(); const ts = this.logger.ts();
const onError = e => { const onError = (e) => {
this.logger.error('Error reading local file', path, e); this.logger.error('Error reading local file', path, e);
if (callback) { if (callback) {
callback(e, null); callback(e, null);
@ -62,7 +62,7 @@ class StorageFile extends StorageBase {
this.logger.debug('Save', path, rev); this.logger.debug('Save', path, rev);
const ts = this.logger.ts(); const ts = this.logger.ts();
const onError = e => { const onError = (e) => {
if (Object.prototype.hasOwnProperty.call(e, 'code') && e.code === 'EISDIR') { if (Object.prototype.hasOwnProperty.call(e, 'code') && e.code === 'EISDIR') {
e.isDir = true; e.isDir = true;
} }
@ -73,7 +73,7 @@ class StorageFile extends StorageBase {
}; };
const write = () => { const write = () => {
Launcher.writeFile(path, data, err => { Launcher.writeFile(path, data, (err) => {
if (err) { if (err) {
return onError(err); return onError(err);
} }
@ -111,7 +111,7 @@ class StorageFile extends StorageBase {
this.logger.debug('Make dir', path); this.logger.debug('Make dir', path);
const ts = this.logger.ts(); const ts = this.logger.ts();
Launcher.mkdir(path, err => { Launcher.mkdir(path, (err) => {
if (err) { if (err) {
this.logger.error('Error making local dir', path, err); this.logger.error('Error making local dir', path, err);
if (callback) { if (callback) {
@ -158,7 +158,7 @@ class StorageFile extends StorageBase {
const names = Launcher.parsePath(path); const names = Launcher.parsePath(path);
const watcher = fileWatchers[names.dir]; const watcher = fileWatchers[names.dir];
if (watcher) { if (watcher) {
const ix = watcher.callbacks.findIndex(cb => cb.file === names.file); const ix = watcher.callbacks.findIndex((cb) => cb.file === names.file);
if (ix >= 0) { if (ix >= 0) {
watcher.callbacks.splice(ix, 1); watcher.callbacks.splice(ix, 1);
} }
@ -173,7 +173,7 @@ class StorageFile extends StorageBase {
fsWatcherChange(dirname, evt, fileName) { fsWatcherChange(dirname, evt, fileName) {
const watcher = fileWatchers[dirname]; const watcher = fileWatchers[dirname];
if (watcher) { if (watcher) {
watcher.callbacks.forEach(cb => { watcher.callbacks.forEach((cb) => {
if (cb.file === fileName && typeof cb.callback === 'function') { if (cb.file === fileName && typeof cb.callback === 'function') {
this.logger.debug('File changed', dirname, evt, fileName); this.logger.debug('File changed', dirname, evt, fileName);
cb.callback(); cb.callback();

View File

@ -35,11 +35,11 @@ class StorageGDrive extends StorageBase {
this._xhr({ this._xhr({
url, url,
responseType: 'arraybuffer', responseType: 'arraybuffer',
success: response => { success: (response) => {
this.logger.debug('Loaded', path, stat.rev, this.logger.ts(ts)); this.logger.debug('Loaded', path, stat.rev, this.logger.ts(ts));
return callback && callback(null, response, { rev: stat.rev }); return callback && callback(null, response, { rev: stat.rev });
}, },
error: err => { error: (err) => {
this.logger.error('Load error', path, err, this.logger.ts(ts)); this.logger.error('Load error', path, err, this.logger.ts(ts));
return callback && callback(err); return callback && callback(err);
} }
@ -51,7 +51,7 @@ class StorageGDrive extends StorageBase {
if (path.lastIndexOf(NewFileIdPrefix, 0) === 0) { if (path.lastIndexOf(NewFileIdPrefix, 0) === 0) {
return callback && callback({ notFound: true }); return callback && callback({ notFound: true });
} }
this._oauthAuthorize(err => { this._oauthAuthorize((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -61,12 +61,12 @@ class StorageGDrive extends StorageBase {
this._xhr({ this._xhr({
url, url,
responseType: 'json', responseType: 'json',
success: response => { success: (response) => {
const rev = response.headRevisionId; const rev = response.headRevisionId;
this.logger.debug('Stated', path, rev, this.logger.ts(ts)); this.logger.debug('Stated', path, rev, this.logger.ts(ts));
return callback && callback(null, { rev }); return callback && callback(null, { rev });
}, },
error: err => { error: (err) => {
this.logger.error('Stat error', this.logger.ts(ts), err); this.logger.error('Stat error', this.logger.ts(ts), err);
return callback && callback(err); return callback && callback(err);
} }
@ -75,7 +75,7 @@ class StorageGDrive extends StorageBase {
} }
save(path, opts, data, callback, rev) { save(path, opts, data, callback, rev) {
this._oauthAuthorize(err => { this._oauthAuthorize((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -134,7 +134,7 @@ class StorageGDrive extends StorageBase {
data, data,
dataType, dataType,
dataIsMultipart, dataIsMultipart,
success: response => { success: (response) => {
this.logger.debug('Saved', path, this.logger.ts(ts)); this.logger.debug('Saved', path, this.logger.ts(ts));
const newRev = response.headRevisionId; const newRev = response.headRevisionId;
if (!newRev) { if (!newRev) {
@ -145,7 +145,7 @@ class StorageGDrive extends StorageBase {
callback(null, { rev: newRev, path: isNew ? response.id : null }) callback(null, { rev: newRev, path: isNew ? response.id : null })
); );
}, },
error: err => { error: (err) => {
this.logger.error('Save error', path, err, this.logger.ts(ts)); this.logger.error('Save error', path, err, this.logger.ts(ts));
return callback && callback(err); return callback && callback(err);
} }
@ -155,7 +155,7 @@ class StorageGDrive extends StorageBase {
} }
list(dir, callback) { list(dir, callback) {
this._oauthAuthorize(err => { this._oauthAuthorize((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -179,13 +179,13 @@ class StorageGDrive extends StorageBase {
this._xhr({ this._xhr({
url, url,
responseType: 'json', responseType: 'json',
success: response => { success: (response) => {
if (!response) { if (!response) {
this.logger.error('List error', this.logger.ts(ts)); this.logger.error('List error', this.logger.ts(ts));
return callback && callback('list error'); return callback && callback('list error');
} }
this.logger.debug('Listed', this.logger.ts(ts)); this.logger.debug('Listed', this.logger.ts(ts));
const fileList = response.files.map(f => ({ const fileList = response.files.map((f) => ({
name: f.name, name: f.name,
path: f.id, path: f.id,
rev: f.headRevisionId, rev: f.headRevisionId,
@ -201,7 +201,7 @@ class StorageGDrive extends StorageBase {
} }
return callback && callback(null, fileList); return callback && callback(null, fileList);
}, },
error: err => { error: (err) => {
this.logger.error('List error', this.logger.ts(ts), err); this.logger.error('List error', this.logger.ts(ts), err);
return callback && callback(err); return callback && callback(err);
} }
@ -222,7 +222,7 @@ class StorageGDrive extends StorageBase {
this.logger.debug('Removed', path, this.logger.ts(ts)); this.logger.debug('Removed', path, this.logger.ts(ts));
return callback && callback(); return callback && callback();
}, },
error: err => { error: (err) => {
this.logger.error('Remove error', path, err, this.logger.ts(ts)); this.logger.error('Remove error', path, err, this.logger.ts(ts));
return callback && callback(err); return callback && callback(err);
} }

View File

@ -17,7 +17,7 @@ class StorageOneDrive extends StorageBase {
} }
load(path, opts, callback) { load(path, opts, callback) {
this._oauthAuthorize(err => { this._oauthAuthorize((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -27,7 +27,7 @@ class StorageOneDrive extends StorageBase {
this._xhr({ this._xhr({
url, url,
responseType: 'json', responseType: 'json',
success: response => { success: (response) => {
const downloadUrl = response['@microsoft.graph.downloadUrl']; const downloadUrl = response['@microsoft.graph.downloadUrl'];
let rev = response.eTag; let rev = response.eTag;
if (!downloadUrl || !response.eTag) { if (!downloadUrl || !response.eTag) {
@ -49,13 +49,13 @@ class StorageOneDrive extends StorageBase {
this.logger.debug('Loaded', path, rev, this.logger.ts(ts)); this.logger.debug('Loaded', path, rev, this.logger.ts(ts));
return callback && callback(null, response, { rev }); return callback && callback(null, response, { rev });
}, },
error: err => { error: (err) => {
this.logger.error('Load error', path, err, this.logger.ts(ts)); this.logger.error('Load error', path, err, this.logger.ts(ts));
return callback && callback(err); return callback && callback(err);
} }
}); });
}, },
error: err => { error: (err) => {
this.logger.error('Load error', path, err, this.logger.ts(ts)); this.logger.error('Load error', path, err, this.logger.ts(ts));
return callback && callback(err); return callback && callback(err);
} }
@ -64,7 +64,7 @@ class StorageOneDrive extends StorageBase {
} }
stat(path, opts, callback) { stat(path, opts, callback) {
this._oauthAuthorize(err => { this._oauthAuthorize((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -74,7 +74,7 @@ class StorageOneDrive extends StorageBase {
this._xhr({ this._xhr({
url, url,
responseType: 'json', responseType: 'json',
success: response => { success: (response) => {
const rev = response.eTag; const rev = response.eTag;
if (!rev) { if (!rev) {
this.logger.error('Stat error', path, 'no eTag', this.logger.ts(ts)); this.logger.error('Stat error', path, 'no eTag', this.logger.ts(ts));
@ -96,7 +96,7 @@ class StorageOneDrive extends StorageBase {
} }
save(path, opts, data, callback, rev) { save(path, opts, data, callback, rev) {
this._oauthAuthorize(err => { this._oauthAuthorize((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -123,7 +123,7 @@ class StorageOneDrive extends StorageBase {
this.logger.debug('Saved', path, rev, this.logger.ts(ts)); this.logger.debug('Saved', path, rev, this.logger.ts(ts));
return callback && callback(null, { rev }); return callback && callback(null, { rev });
}, },
error: err => { error: (err) => {
this.logger.error('Save error', path, err, this.logger.ts(ts)); this.logger.error('Save error', path, err, this.logger.ts(ts));
return callback && callback(err); return callback && callback(err);
} }
@ -132,7 +132,7 @@ class StorageOneDrive extends StorageBase {
} }
list(dir, callback) { list(dir, callback) {
this._oauthAuthorize(err => { this._oauthAuthorize((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -142,15 +142,15 @@ class StorageOneDrive extends StorageBase {
this._xhr({ this._xhr({
url, url,
responseType: 'json', responseType: 'json',
success: response => { success: (response) => {
if (!response || !response.value) { if (!response || !response.value) {
this.logger.error('List error', this.logger.ts(ts), response); this.logger.error('List error', this.logger.ts(ts), response);
return callback && callback('list error'); return callback && callback('list error');
} }
this.logger.debug('Listed', this.logger.ts(ts)); this.logger.debug('Listed', this.logger.ts(ts));
const fileList = response.value const fileList = response.value
.filter(f => f.name) .filter((f) => f.name)
.map(f => ({ .map((f) => ({
name: f.name, name: f.name,
path: f.parentReference.path + '/' + f.name, path: f.parentReference.path + '/' + f.name,
rev: f.eTag, rev: f.eTag,
@ -158,7 +158,7 @@ class StorageOneDrive extends StorageBase {
})); }));
return callback && callback(null, fileList); return callback && callback(null, fileList);
}, },
error: err => { error: (err) => {
this.logger.error('List error', this.logger.ts(ts), err); this.logger.error('List error', this.logger.ts(ts), err);
return callback && callback(err); return callback && callback(err);
} }
@ -179,7 +179,7 @@ class StorageOneDrive extends StorageBase {
this.logger.debug('Removed', path, this.logger.ts(ts)); this.logger.debug('Removed', path, this.logger.ts(ts));
return callback && callback(); return callback && callback();
}, },
error: err => { error: (err) => {
this.logger.error('Remove error', path, err, this.logger.ts(ts)); this.logger.error('Remove error', path, err, this.logger.ts(ts));
return callback && callback(err); return callback && callback(err);
} }
@ -187,7 +187,7 @@ class StorageOneDrive extends StorageBase {
} }
mkdir(path, callback) { mkdir(path, callback) {
this._oauthAuthorize(err => { this._oauthAuthorize((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -206,7 +206,7 @@ class StorageOneDrive extends StorageBase {
this.logger.debug('Made dir', path, this.logger.ts(ts)); this.logger.debug('Made dir', path, this.logger.ts(ts));
return callback && callback(); return callback && callback();
}, },
error: err => { error: (err) => {
this.logger.error('Make dir error', path, err, this.logger.ts(ts)); this.logger.error('Make dir error', path, err, this.logger.ts(ts));
return callback && callback(err); return callback && callback(err);
} }

View File

@ -92,13 +92,13 @@ class StorageWebDav extends StorageBase {
} }
save(path, opts, data, callback, rev) { save(path, opts, data, callback, rev) {
const cb = function(err, xhr, stat) { const cb = function (err, xhr, stat) {
if (callback) { if (callback) {
callback(err, stat); callback(err, stat);
callback = null; callback = null;
} }
}; };
const tmpPath = path.replace(/[^\/]+$/, m => '.' + m) + '.' + Date.now(); const tmpPath = path.replace(/[^\/]+$/, (m) => '.' + m) + '.' + Date.now();
const saveOpts = { const saveOpts = {
path, path,
user: opts ? opts.user : null, user: opts ? opts.user : null,
@ -134,7 +134,7 @@ class StorageWebDav extends StorageBase {
data, data,
nostat: true nostat: true
}, },
err => { (err) => {
if (err) { if (err) {
return cb(err); return cb(err);
} }
@ -193,7 +193,7 @@ class StorageWebDav extends StorageBase {
'Overwrite': 'T' 'Overwrite': 'T'
} }
}, },
err => { (err) => {
if (err) { if (err) {
return cb(err); return cb(err);
} }
@ -222,7 +222,7 @@ class StorageWebDav extends StorageBase {
data, data,
nostat: true nostat: true
}, },
err => { (err) => {
if (err) { if (err) {
return cb(err); return cb(err);
} }

View File

@ -1,6 +1,6 @@
const idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; const idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
const IoBrowserCache = function(config) { const IoBrowserCache = function (config) {
this.db = null; this.db = null;
this.cacheName = config.cacheName; this.cacheName = config.cacheName;
this.logger = config.logger; this.logger = config.logger;
@ -13,19 +13,19 @@ Object.assign(IoBrowserCache.prototype, {
} }
try { try {
const req = idb.open(this.cacheName); const req = idb.open(this.cacheName);
req.onerror = e => { req.onerror = (e) => {
this.logger.error('Error opening indexed db', e); this.logger.error('Error opening indexed db', e);
if (callback) { if (callback) {
callback(e); callback(e);
} }
}; };
req.onsuccess = e => { req.onsuccess = (e) => {
this.db = e.target.result; this.db = e.target.result;
if (callback) { if (callback) {
callback(); callback();
} }
}; };
req.onupgradeneeded = e => { req.onupgradeneeded = (e) => {
const db = e.target.result; const db = e.target.result;
db.createObjectStore('files'); db.createObjectStore('files');
}; };
@ -39,7 +39,7 @@ Object.assign(IoBrowserCache.prototype, {
save(id, data, callback) { save(id, data, callback) {
this.logger.debug('Save', id); this.logger.debug('Save', id);
this.initDb(err => { this.initDb((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }
@ -72,16 +72,13 @@ Object.assign(IoBrowserCache.prototype, {
load(id, callback) { load(id, callback) {
this.logger.debug('Load', id); this.logger.debug('Load', id);
this.initDb(err => { this.initDb((err) => {
if (err) { if (err) {
return callback && callback(err, null); return callback && callback(err, null);
} }
try { try {
const ts = this.logger.ts(); const ts = this.logger.ts();
const req = this.db const req = this.db.transaction(['files'], 'readonly').objectStore('files').get(id);
.transaction(['files'], 'readonly')
.objectStore('files')
.get(id);
req.onsuccess = () => { req.onsuccess = () => {
this.logger.debug('Loaded', id, this.logger.ts(ts)); this.logger.debug('Loaded', id, this.logger.ts(ts));
if (callback) { if (callback) {
@ -105,7 +102,7 @@ Object.assign(IoBrowserCache.prototype, {
remove(id, callback) { remove(id, callback) {
this.logger.debug('Remove', id); this.logger.debug('Remove', id);
this.initDb(err => { this.initDb((err) => {
if (err) { if (err) {
return callback && callback(err); return callback && callback(err);
} }

View File

@ -1,6 +1,6 @@
import { Launcher } from 'comp/launcher'; import { Launcher } from 'comp/launcher';
const IoFileCache = function(config) { const IoFileCache = function (config) {
this.basePath = null; this.basePath = null;
this.cacheName = config.cacheName; this.cacheName = config.cacheName;
this.logger = config.logger; this.logger = config.logger;
@ -12,7 +12,7 @@ Object.assign(IoFileCache.prototype, {
return callback(); return callback();
} }
const basePath = Launcher.getUserDataPath(this.cacheName); const basePath = Launcher.getUserDataPath(this.cacheName);
Launcher.mkdir(basePath, err => { Launcher.mkdir(basePath, (err) => {
if (err) { if (err) {
this.logger.error('Error creating plugin folder'); this.logger.error('Error creating plugin folder');
} else { } else {
@ -27,14 +27,14 @@ Object.assign(IoFileCache.prototype, {
}, },
save(id, data, callback) { save(id, data, callback) {
this.initFs(err => { this.initFs((err) => {
if (err) { if (err) {
return callback && callback(err, null); return callback && callback(err, null);
} }
this.logger.debug('Save', id); this.logger.debug('Save', id);
const ts = this.logger.ts(); const ts = this.logger.ts();
const path = this.resolvePath(id); const path = this.resolvePath(id);
Launcher.writeFile(path, data, err => { Launcher.writeFile(path, data, (err) => {
if (err) { if (err) {
this.logger.error('Error saving file', id, err); this.logger.error('Error saving file', id, err);
if (callback) { if (callback) {
@ -51,7 +51,7 @@ Object.assign(IoFileCache.prototype, {
}, },
load(id, callback) { load(id, callback) {
this.initFs(err => { this.initFs((err) => {
if (err) { if (err) {
return callback && callback(err, null); return callback && callback(err, null);
} }
@ -75,14 +75,14 @@ Object.assign(IoFileCache.prototype, {
}, },
remove(id, callback) { remove(id, callback) {
this.initFs(err => { this.initFs((err) => {
if (err) { if (err) {
return callback && callback(err, null); return callback && callback(err, null);
} }
this.logger.debug('Remove', id); this.logger.debug('Remove', id);
const ts = this.logger.ts(); const ts = this.logger.ts();
const path = this.resolvePath(id); const path = this.resolvePath(id);
Launcher.deleteFile(path, err => { Launcher.deleteFile(path, (err) => {
if (err) { if (err) {
this.logger.error('Error removing file', id, err); this.logger.error('Error removing file', id, err);
if (callback) { if (callback) {

View File

@ -11,7 +11,7 @@ function createOAuthSession() {
const codeVerifierBytes = kdbxweb.ByteUtils.arrayToBuffer( const codeVerifierBytes = kdbxweb.ByteUtils.arrayToBuffer(
kdbxweb.ByteUtils.stringToBytes(codeVerifier) kdbxweb.ByteUtils.stringToBytes(codeVerifier)
); );
kdbxweb.CryptoEngine.sha256(codeVerifierBytes).then(hash => { kdbxweb.CryptoEngine.sha256(codeVerifierBytes).then((hash) => {
const codeChallenge = kdbxweb.ByteUtils.bytesToBase64(hash) const codeChallenge = kdbxweb.ByteUtils.bytesToBase64(hash)
.replace(/\+/g, '-') .replace(/\+/g, '-')
.replace(/\//g, '_') .replace(/\//g, '_')

View File

@ -69,14 +69,14 @@ class StorageBase {
'Authorization': 'Bearer ' + this._oauthToken.accessToken 'Authorization': 'Bearer ' + this._oauthToken.accessToken
}; };
} }
this._httpRequest(config, response => { this._httpRequest(config, (response) => {
this.logger.info('HTTP response', response.status); this.logger.info('HTTP response', response.status);
const statuses = config.statuses || [200]; const statuses = config.statuses || [200];
if (statuses.indexOf(response.status) >= 0) { if (statuses.indexOf(response.status) >= 0) {
return config.success && config.success(response.response, response); return config.success && config.success(response.response, response);
} }
if (response.status === 401 && this._oauthToken) { if (response.status === 401 && this._oauthToken) {
this._oauthGetNewToken(err => { this._oauthGetNewToken((err) => {
if (err) { if (err) {
return config.error && config.error('unauthorized', response); return config.error && config.error('unauthorized', response);
} else { } else {
@ -112,7 +112,7 @@ class StorageBase {
onLoad({ onLoad({
status: xhr.status, status: xhr.status,
response: xhr.response, response: xhr.response,
getResponseHeader: name => xhr.getResponseHeader(name) getResponseHeader: (name) => xhr.getResponseHeader(name)
}); });
}); });
xhr.addEventListener('error', () => { xhr.addEventListener('error', () => {
@ -152,7 +152,7 @@ class StorageBase {
let data; let data;
if (config.data) { if (config.data) {
if (config.dataIsMultipart) { if (config.dataIsMultipart) {
data = Buffer.concat(config.data.map(chunk => Buffer.from(chunk))); data = Buffer.concat(config.data.map((chunk) => Buffer.from(chunk)));
} else { } else {
data = Buffer.from(config.data); data = Buffer.from(config.data);
} }
@ -167,7 +167,7 @@ class StorageBase {
closed = true; closed = true;
}); });
req.on('response', res => { req.on('response', (res) => {
const chunks = []; const chunks = [];
const onClose = () => { const onClose = () => {
this.logger.debug( this.logger.debug(
@ -194,10 +194,10 @@ class StorageBase {
onLoad({ onLoad({
status: res.statusCode, status: res.statusCode,
response, response,
getResponseHeader: name => res.headers[name.toLowerCase()] getResponseHeader: (name) => res.headers[name.toLowerCase()]
}); });
}; };
res.on('data', chunk => { res.on('data', (chunk) => {
chunks.push(chunk); chunks.push(chunk);
if (closed && !res.readable) { if (closed && !res.readable) {
// sometimes 'close' event arrives faster in Electron // sometimes 'close' event arrives faster in Electron
@ -207,7 +207,7 @@ class StorageBase {
// in Electron it's not res.on('end'), like in node.js, which is a bit weird // in Electron it's not res.on('end'), like in node.js, which is a bit weird
req.on('close', onClose); req.on('close', onClose);
}); });
req.on('error', e => { req.on('error', (e) => {
this.logger.error('HTTP error', opts.method, config.url, e); this.logger.error('HTTP error', opts.method, config.url, e);
return config.error && config.error('network error', {}); return config.error && config.error('network error', {});
}); });
@ -250,7 +250,7 @@ class StorageBase {
location: 'yes' location: 'yes'
}; };
settings = Object.keys(settings) settings = Object.keys(settings)
.map(key => key + '=' + settings[key]) .map((key) => key + '=' + settings[key])
.join(','); .join(',');
return window.open(url, title, settings, extras); return window.open(url, title, settings, extras);
@ -310,8 +310,8 @@ class StorageBase {
Launcher.openLink(url); Launcher.openLink(url);
callback('browser-auth-started'); callback('browser-auth-started');
}); });
listener.on('error', err => callback(err)); listener.on('error', (err) => callback(err));
listener.on('result', result => this._oauthCodeReceived(result, session)); listener.on('result', (result) => this._oauthCodeReceived(result, session));
return; return;
} }
@ -329,7 +329,7 @@ class StorageBase {
callback('OAuth: popup closed'); callback('OAuth: popup closed');
}; };
const windowMessage = e => { const windowMessage = (e) => {
if (e.origin !== location.origin) { if (e.origin !== location.origin) {
return; return;
} }
@ -462,7 +462,7 @@ class StorageBase {
...pkceParams ...pkceParams
}), }),
dataType: 'application/x-www-form-urlencoded', dataType: 'application/x-www-form-urlencoded',
success: response => { success: (response) => {
this.logger.debug('OAuth code exchanged', response); this.logger.debug('OAuth code exchanged', response);
const token = this._oauthProcessReturn(response); const token = this._oauthProcessReturn(response);
if (token && token.error) { if (token && token.error) {
@ -470,7 +470,7 @@ class StorageBase {
} }
callback?.(); callback?.();
}, },
error: err => { error: (err) => {
this.logger.error('Error exchanging OAuth code', err); this.logger.error('Error exchanging OAuth code', err);
callback?.('OAuth code exchange error: ' + err); callback?.('OAuth code exchange error: ' + err);
} }
@ -493,7 +493,7 @@ class StorageBase {
'refresh_token': refreshToken 'refresh_token': refreshToken
}), }),
dataType: 'application/x-www-form-urlencoded', dataType: 'application/x-www-form-urlencoded',
success: response => { success: (response) => {
this.logger.debug('Refresh token exchanged'); this.logger.debug('Refresh token exchanged');
this._oauthProcessReturn({ this._oauthProcessReturn({
'refresh_token': refreshToken, 'refresh_token': refreshToken,

View File

@ -15,7 +15,7 @@ const StorageOAuthListener = {
} }
const listener = {}; const listener = {};
Object.keys(EventEmitter.prototype).forEach(key => { Object.keys(EventEmitter.prototype).forEach((key) => {
listener[key] = EventEmitter.prototype[key]; listener[key] = EventEmitter.prototype[key];
}); });
@ -38,7 +38,7 @@ const StorageOAuthListener = {
logger.info(`Starting OAuth listener on port ${port}...`); logger.info(`Starting OAuth listener on port ${port}...`);
server.listen(port); server.listen(port);
server.on('error', err => { server.on('error', (err) => {
logger.error('Failed to start OAuth listener', err); logger.error('Failed to start OAuth listener', err);
listener.emit('error', 'Failed to start OAuth listener: ' + err); listener.emit('error', 'Failed to start OAuth listener: ' + err);
server.close(); server.close();

View File

@ -2,7 +2,7 @@ import { Colors } from 'const/colors';
const KnownColors = {}; const KnownColors = {};
const Color = function(arg) { const Color = function (arg) {
const rgbaMatch = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(,\s*([\d.]+))?\)$/.exec(arg); const rgbaMatch = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(,\s*([\d.]+))?\)$/.exec(arg);
if (rgbaMatch) { if (rgbaMatch) {
this.r = +rgbaMatch[1]; this.r = +rgbaMatch[1];
@ -35,7 +35,7 @@ const Color = function(arg) {
} }
}; };
Color.prototype.setHsl = function() { Color.prototype.setHsl = function () {
const r = this.r / 255; const r = this.r / 255;
const g = this.g / 255; const g = this.g / 255;
const b = this.b / 255; const b = this.b / 255;
@ -70,25 +70,25 @@ Color.prototype.setHsl = function() {
this.l = l; this.l = l;
}; };
Color.prototype.toHex = function() { Color.prototype.toHex = function () {
return '#' + hex(this.r) + hex(this.g) + hex(this.b); return '#' + hex(this.r) + hex(this.g) + hex(this.b);
}; };
Color.prototype.toRgba = function() { Color.prototype.toRgba = function () {
return `rgba(${Math.round(this.r)},${Math.round(this.g)},${Math.round(this.b)},${this.a})`; return `rgba(${Math.round(this.r)},${Math.round(this.g)},${Math.round(this.b)},${this.a})`;
}; };
Color.prototype.toHsla = function() { Color.prototype.toHsla = function () {
return `hsla(${Math.round(this.h * 100)},${Math.round(this.s * 100)}%,${Math.round( return `hsla(${Math.round(this.h * 100)},${Math.round(this.s * 100)}%,${Math.round(
this.l * 100 this.l * 100
)}%,${this.a})`; )}%,${this.a})`;
}; };
Color.prototype.distanceTo = function(color) { Color.prototype.distanceTo = function (color) {
return Math.abs(this.h - color.h); return Math.abs(this.h - color.h);
}; };
Color.prototype.mix = function(another, weight) { Color.prototype.mix = function (another, weight) {
const res = new Color(this); const res = new Color(this);
const anotherWeight = 1 - weight; const anotherWeight = 1 - weight;
res.r = this.r * weight + another.r * anotherWeight; res.r = this.r * weight + another.r * anotherWeight;
@ -98,7 +98,7 @@ Color.prototype.mix = function(another, weight) {
return res; return res;
}; };
Color.getNearest = function(colorStr) { Color.getNearest = function (colorStr) {
const color = new Color(colorStr); const color = new Color(colorStr);
if (!color.s) { if (!color.s) {
return null; return null;
@ -115,7 +115,7 @@ Color.getNearest = function(colorStr) {
return selected; return selected;
}; };
Color.getKnownBgColor = function(knownColor) { Color.getKnownBgColor = function (knownColor) {
return Colors.BgColors[knownColor] ? '#' + Colors.BgColors[knownColor] : undefined; return Colors.BgColors[knownColor] ? '#' + Colors.BgColors[knownColor] : undefined;
}; };

View File

@ -8,29 +8,29 @@ const ciCompare =
const Comparators = { const Comparators = {
stringComparator(field, asc) { stringComparator(field, asc) {
if (asc) { if (asc) {
return function(x, y) { return function (x, y) {
return ciCompare(x[field] || LastChar, y[field] || LastChar); return ciCompare(x[field] || LastChar, y[field] || LastChar);
}; };
} else { } else {
return function(x, y) { return function (x, y) {
return ciCompare(y[field], x[field]); return ciCompare(y[field], x[field]);
}; };
} }
}, },
rankComparator() { rankComparator() {
return function(x, y) { return function (x, y) {
return y.getRank(this.filter) - x.getRank(this.filter); return y.getRank(this.filter) - x.getRank(this.filter);
}; };
}, },
dateComparator(field, asc) { dateComparator(field, asc) {
if (asc) { if (asc) {
return function(x, y) { return function (x, y) {
return x[field] - y[field]; return x[field] - y[field];
}; };
} else { } else {
return function(x, y) { return function (x, y) {
return y[field] - x[field]; return y[field] - x[field];
}; };
} }

View File

@ -2,7 +2,7 @@ import { Logger } from 'util/logger';
const logger = new Logger('otp'); const logger = new Logger('otp');
const Otp = function(url, params) { const Otp = function (url, params) {
if (['hotp', 'totp'].indexOf(params.type) < 0) { if (['hotp', 'totp'].indexOf(params.type) < 0) {
throw 'Bad type: ' + params.type; throw 'Bad type: ' + params.type;
} }
@ -39,7 +39,7 @@ const Otp = function(url, params) {
} }
}; };
Otp.prototype.next = function(callback) { Otp.prototype.next = function (callback) {
let valueForHashing; let valueForHashing;
let timeLeft; let timeLeft;
if (this.type === 'totp') { if (this.type === 'totp') {
@ -71,33 +71,33 @@ Otp.prototype.next = function(callback) {
}); });
}; };
Otp.prototype.hmac = function(data, callback) { Otp.prototype.hmac = function (data, callback) {
const subtle = window.crypto.subtle || window.crypto.webkitSubtle; const subtle = window.crypto.subtle || window.crypto.webkitSubtle;
const algo = { name: 'HMAC', hash: { name: this.algorithm.replace('SHA', 'SHA-') } }; const algo = { name: 'HMAC', hash: { name: this.algorithm.replace('SHA', 'SHA-') } };
subtle subtle
.importKey('raw', this.key, algo, false, ['sign']) .importKey('raw', this.key, algo, false, ['sign'])
.then(key => { .then((key) => {
subtle subtle
.sign(algo, key, data) .sign(algo, key, data)
.then(sig => { .then((sig) => {
callback(sig); callback(sig);
}) })
.catch(err => { .catch((err) => {
callback(null, err); callback(null, err);
}); });
}) })
.catch(err => { .catch((err) => {
callback(null, err); callback(null, err);
}); });
}; };
Otp.hmacToDigits = function(hmac, length) { Otp.hmacToDigits = function (hmac, length) {
let code = hmac.toString(); let code = hmac.toString();
code = Otp.leftPad(code.substr(code.length - length), length); code = Otp.leftPad(code.substr(code.length - length), length);
return code; return code;
}; };
Otp.hmacToSteamCode = function(hmac) { Otp.hmacToSteamCode = function (hmac) {
const steamChars = '23456789BCDFGHJKMNPQRTVWXY'; const steamChars = '23456789BCDFGHJKMNPQRTVWXY';
let code = ''; let code = '';
for (let i = 0; i < 5; ++i) { for (let i = 0; i < 5; ++i) {
@ -107,7 +107,7 @@ Otp.hmacToSteamCode = function(hmac) {
return code; return code;
}; };
Otp.fromBase32 = function(str) { Otp.fromBase32 = function (str) {
str = str.replace(/\s/g, ''); str = str.replace(/\s/g, '');
const alphabet = 'abcdefghijklmnopqrstuvwxyz234567'; const alphabet = 'abcdefghijklmnopqrstuvwxyz234567';
let bin = ''; let bin = '';
@ -127,14 +127,14 @@ Otp.fromBase32 = function(str) {
return hex.buffer; return hex.buffer;
}; };
Otp.leftPad = function(str, len) { Otp.leftPad = function (str, len) {
while (str.length < len) { while (str.length < len) {
str = '0' + str; str = '0' + str;
} }
return str; return str;
}; };
Otp.parseUrl = function(url) { Otp.parseUrl = function (url) {
const match = /^otpauth:\/\/(\w+)\/([^\?]+)\?(.*)/i.exec(url); const match = /^otpauth:\/\/(\w+)\/([^\?]+)\?(.*)/i.exec(url);
if (!match) { if (!match) {
throw 'Not OTP url'; throw 'Not OTP url';
@ -149,18 +149,18 @@ Otp.parseUrl = function(url) {
} }
} }
params.type = match[1].toLowerCase(); params.type = match[1].toLowerCase();
match[3].split('&').forEach(part => { match[3].split('&').forEach((part) => {
const parts = part.split('=', 2); const parts = part.split('=', 2);
params[parts[0].toLowerCase()] = decodeURIComponent(parts[1]); params[parts[0].toLowerCase()] = decodeURIComponent(parts[1]);
}); });
return new Otp(url, params); return new Otp(url, params);
}; };
Otp.isSecret = function(str) { Otp.isSecret = function (str) {
return !!Otp.fromBase32(str); return !!Otp.fromBase32(str);
}; };
Otp.makeUrl = function(secret, period, digits) { Otp.makeUrl = function (secret, period, digits) {
return ( return (
'otpauth://totp/default?secret=' + 'otpauth://totp/default?secret=' +
secret + secret +

View File

@ -11,7 +11,7 @@ const SignatureVerifier = {
verify(data, signature, pk) { verify(data, signature, pk) {
if (!pk) { if (!pk) {
const pks = this.getPublicKeys(); const pks = this.getPublicKeys();
return this.verify(data, signature, pks[0]).then(isValid => { return this.verify(data, signature, pks[0]).then((isValid) => {
if (isValid || !pks[1]) { if (isValid || !pks[1]) {
return isValid; return isValid;
} }
@ -29,7 +29,7 @@ const SignatureVerifier = {
pk = kdbxweb.ByteUtils.base64ToBytes(pk); pk = kdbxweb.ByteUtils.base64ToBytes(pk);
subtle subtle
.importKey(keyFormat, pk, algo, false, ['verify']) .importKey(keyFormat, pk, algo, false, ['verify'])
.then(cryptoKey => { .then((cryptoKey) => {
try { try {
subtle subtle
.verify( .verify(
@ -38,10 +38,10 @@ const SignatureVerifier = {
kdbxweb.ByteUtils.arrayToBuffer(signature), kdbxweb.ByteUtils.arrayToBuffer(signature),
kdbxweb.ByteUtils.arrayToBuffer(data) kdbxweb.ByteUtils.arrayToBuffer(data)
) )
.then(isValid => { .then((isValid) => {
resolve(isValid); resolve(isValid);
}) })
.catch(e => { .catch((e) => {
this.logger.error('Verify error', e); this.logger.error('Verify error', e);
reject(e); reject(e);
}); });
@ -50,7 +50,7 @@ const SignatureVerifier = {
reject(e); reject(e);
} }
}) })
.catch(e => { .catch((e) => {
this.logger.error('ImportKey error', e); this.logger.error('ImportKey error', e);
reject(e); reject(e);
}); });
@ -63,7 +63,7 @@ const SignatureVerifier = {
getPublicKeys() { getPublicKeys() {
if (!this.publicKeys) { if (!this.publicKeys) {
this.publicKeys = [publicKeyData, publicKeyDataNew].map(pk => this.publicKeys = [publicKeyData, publicKeyDataNew].map((pk) =>
pk.match(/-+BEGIN PUBLIC KEY-+([\s\S]+?)-+END PUBLIC KEY-+/)[1].replace(/\s+/g, '') pk.match(/-+BEGIN PUBLIC KEY-+([\s\S]+?)-+END PUBLIC KEY-+/)[1].replace(/\s+/g, '')
); );
} }

View File

@ -159,7 +159,7 @@ class EntrySearch {
let matches = false; let matches = false;
if (adv.other || adv.protect) { if (adv.other || adv.protect) {
const fieldNames = Object.keys(fields); const fieldNames = Object.keys(fields);
matches = fieldNames.some(field => { matches = fieldNames.some((field) => {
if (BuiltInFields.indexOf(field) >= 0) { if (BuiltInFields.indexOf(field) >= 0) {
return false; return false;
} }

View File

@ -21,7 +21,7 @@ const PasswordPresenter = {
return ''; return '';
} }
let result = ''; let result = '';
value.forEachChar(ch => { value.forEachChar((ch) => {
result += ch === 10 ? '\n' : '•'; result += ch === 10 ? '\n' : '•';
}); });
return result; return result;
@ -33,7 +33,7 @@ const PasswordPresenter = {
const gen = new RandomNameGenerator(); const gen = new RandomNameGenerator();
let ix = 0; let ix = 0;
value.forEachChar(char => { value.forEachChar((char) => {
const charHtml = charCodeToHtml(char); const charHtml = charCodeToHtml(char);
items.push({ html: charHtml, order: ix }); items.push({ html: charHtml, order: ix });

View File

@ -24,11 +24,11 @@ const StringFormat = {
}, },
camelCase(str) { camelCase(str) {
return str.replace(this.camelCaseRegex, match => match[1].toUpperCase()); return str.replace(this.camelCaseRegex, (match) => match[1].toUpperCase());
}, },
pascalCase(str) { pascalCase(str) {
return this.capFirst(str.replace(this.camelCaseRegex, match => match[1].toUpperCase())); return this.capFirst(str.replace(this.camelCaseRegex, (match) => match[1].toUpperCase()));
} }
}; };

View File

@ -31,8 +31,8 @@ const PasswordGenerator = {
return this.generatePronounceable(opts); return this.generatePronounceable(opts);
} }
const ranges = Object.keys(CharRanges) const ranges = Object.keys(CharRanges)
.filter(r => opts[r]) .filter((r) => opts[r])
.map(r => CharRanges[r]); .map((r) => CharRanges[r]);
if (opts.include && opts.include.length) { if (opts.include && opts.include.length) {
ranges.push(opts.include); ranges.push(opts.include);
} }
@ -84,7 +84,7 @@ const PasswordGenerator = {
let length = 0; let length = 0;
if (password) { if (password) {
const charRanges = CharRanges; const charRanges = CharRanges;
password.forEachChar(ch => { password.forEachChar((ch) => {
length++; length++;
ch = String.fromCharCode(ch); ch = String.fromCharCode(ch);
for (const [range, chars] of Object.entries(charRanges)) { for (const [range, chars] of Object.entries(charRanges)) {

View File

@ -13,9 +13,9 @@ const KdbxwebInit = {
argon2(password, salt, memory, iterations, length, parallelism, type, version) { argon2(password, salt, memory, iterations, length, parallelism, type, version) {
const args = { password, salt, memory, iterations, length, parallelism, type, version }; const args = { password, salt, memory, iterations, length, parallelism, type, version };
return this.loadRuntime(memory).then(runtime => { return this.loadRuntime(memory).then((runtime) => {
const ts = logger.ts(); const ts = logger.ts();
return runtime.hash(args).then(hash => { return runtime.hash(args).then((hash) => {
logger.debug('Hash computed', logger.ts(ts)); logger.debug('Hash computed', logger.ts(ts));
return hash; return hash;
}); });
@ -108,7 +108,7 @@ const KdbxwebInit = {
const blob = new Blob([script], { type: 'application/javascript' }); const blob = new Blob([script], { type: 'application/javascript' });
const objectUrl = URL.createObjectURL(blob); const objectUrl = URL.createObjectURL(blob);
const worker = new Worker(objectUrl); const worker = new Worker(objectUrl);
const onMessage = e => { const onMessage = (e) => {
switch (e.data.op) { switch (e.data.op) {
case 'log': case 'log':
logger.debug(...e.data.args); logger.debug(...e.data.args);
@ -125,7 +125,7 @@ const KdbxwebInit = {
hash(args) { hash(args) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
worker.postMessage(args); worker.postMessage(args);
const onHashMessage = e => { const onHashMessage = (e) => {
worker.removeEventListener( worker.removeEventListener(
'message', 'message',
onHashMessage onHashMessage
@ -164,7 +164,7 @@ const KdbxwebInit = {
}); });
global.Module = { global.Module = {
wasmJSMethod: 'native-wasm', wasmJSMethod: 'native-wasm',
wasmBinary: Uint8Array.from(atob(wasmBinaryBase64), c => c.charCodeAt(0)), wasmBinary: Uint8Array.from(atob(wasmBinaryBase64), (c) => c.charCodeAt(0)),
print(...args) { print(...args) {
logger.debug(...args); logger.debug(...args);
}, },
@ -175,7 +175,7 @@ const KdbxwebInit = {
logger.debug('WebAssembly runtime loaded (main thread)', logger.ts(ts)); logger.debug('WebAssembly runtime loaded (main thread)', logger.ts(ts));
clearTimeout(loadTimeout); clearTimeout(loadTimeout);
resolve({ resolve({
hash: args => { hash: (args) => {
const hash = this.calcHash(global.Module, args); const hash = this.calcHash(global.Module, args);
global.Module.unloadRuntime(); global.Module.unloadRuntime();
global.Module = undefined; global.Module = undefined;
@ -193,16 +193,16 @@ const KdbxwebInit = {
} catch (err) { } catch (err) {
reject(err); reject(err);
} }
}).catch(err => { }).catch((err) => {
logger.warn('WebAssembly error', err); logger.warn('WebAssembly error', err);
throw new Error('WebAssembly error'); throw new Error('WebAssembly error');
}); });
}, },
// eslint-disable-next-line object-shorthand // eslint-disable-next-line object-shorthand
workerPostRun: function() { workerPostRun: function () {
self.postMessage({ op: 'postRun' }); self.postMessage({ op: 'postRun' });
self.onmessage = e => { self.onmessage = (e) => {
try { try {
/* eslint-disable-next-line no-undef */ /* eslint-disable-next-line no-undef */
const hash = Module.calcHash(Module, e.data); const hash = Module.calcHash(Module, e.data);
@ -214,7 +214,7 @@ const KdbxwebInit = {
}, },
// eslint-disable-next-line object-shorthand // eslint-disable-next-line object-shorthand
calcHash: function(Module, args) { calcHash: function (Module, args) {
let { password, salt } = args; let { password, salt } = args;
const { memory, iterations, length, parallelism, type, version } = args; const { memory, iterations, length, parallelism, type, version } = args;
const passwordLen = password.byteLength; const passwordLen = password.byteLength;

View File

@ -5,7 +5,7 @@ const ExpectedFieldRefByteLength = ExpectedFieldRefChars.length;
kdbxweb.ProtectedValue.prototype.isProtected = true; kdbxweb.ProtectedValue.prototype.isProtected = true;
kdbxweb.ProtectedValue.prototype.forEachChar = function(fn) { kdbxweb.ProtectedValue.prototype.forEachChar = function (fn) {
const value = this._value; const value = this._value;
const salt = this._salt; const salt = this._salt;
let b, b1, b2, b3; let b, b1, b2, b3;
@ -79,16 +79,16 @@ Object.defineProperty(kdbxweb.ProtectedValue.prototype, 'textLength', {
} }
}); });
kdbxweb.ProtectedValue.prototype.includesLower = function(findLower) { kdbxweb.ProtectedValue.prototype.includesLower = function (findLower) {
return this.indexOfLower(findLower) !== -1; return this.indexOfLower(findLower) !== -1;
}; };
kdbxweb.ProtectedValue.prototype.indexOfLower = function(findLower) { kdbxweb.ProtectedValue.prototype.indexOfLower = function (findLower) {
let index = -1; let index = -1;
const foundSeqs = []; const foundSeqs = [];
const len = findLower.length; const len = findLower.length;
let chIndex = -1; let chIndex = -1;
this.forEachChar(ch => { this.forEachChar((ch) => {
chIndex++; chIndex++;
ch = String.fromCharCode(ch).toLowerCase(); ch = String.fromCharCode(ch).toLowerCase();
if (index !== -1) { if (index !== -1) {
@ -117,12 +117,12 @@ kdbxweb.ProtectedValue.prototype.indexOfLower = function(findLower) {
return index; return index;
}; };
kdbxweb.ProtectedValue.prototype.indexOfSelfInLower = function(targetLower) { kdbxweb.ProtectedValue.prototype.indexOfSelfInLower = function (targetLower) {
let firstCharIndex = -1; let firstCharIndex = -1;
let found = false; let found = false;
do { do {
let chIndex = -1; let chIndex = -1;
this.forEachChar(ch => { this.forEachChar((ch) => {
chIndex++; chIndex++;
ch = String.fromCharCode(ch).toLowerCase(); ch = String.fromCharCode(ch).toLowerCase();
if (chIndex === 0) { if (chIndex === 0) {
@ -141,7 +141,7 @@ kdbxweb.ProtectedValue.prototype.indexOfSelfInLower = function(targetLower) {
window.PV = kdbxweb.ProtectedValue; window.PV = kdbxweb.ProtectedValue;
kdbxweb.ProtectedValue.prototype.equals = function(other) { kdbxweb.ProtectedValue.prototype.equals = function (other) {
if (!other) { if (!other) {
return false; return false;
} }
@ -163,12 +163,12 @@ kdbxweb.ProtectedValue.prototype.equals = function(other) {
return true; return true;
}; };
kdbxweb.ProtectedValue.prototype.isFieldReference = function() { kdbxweb.ProtectedValue.prototype.isFieldReference = function () {
if (this.byteLength !== ExpectedFieldRefByteLength) { if (this.byteLength !== ExpectedFieldRefByteLength) {
return false; return false;
} }
let ix = 0; let ix = 0;
this.forEachChar(ch => { this.forEachChar((ch) => {
const expected = ExpectedFieldRefChars[ix++]; const expected = ExpectedFieldRefChars[ix++];
if (expected !== '0' && ch !== expected) { if (expected !== '0' && ch !== expected) {
return false; return false;

View File

@ -11,12 +11,12 @@ const MaxLogsToSave = 100;
const lastLogs = []; const lastLogs = [];
const Logger = function(name, id, level = Level.All) { const Logger = function (name, id, level = Level.All) {
this.prefix = name ? name + (id ? ':' + id : '') : 'default'; this.prefix = name ? name + (id ? ':' + id : '') : 'default';
this.level = level; this.level = level;
}; };
Logger.prototype.ts = function(ts) { Logger.prototype.ts = function (ts) {
if (ts) { if (ts) {
return Math.round(performance.now() - ts) + 'ms'; return Math.round(performance.now() - ts) + 'ms';
} else { } else {
@ -24,11 +24,11 @@ Logger.prototype.ts = function(ts) {
} }
}; };
Logger.prototype.getPrefix = function() { Logger.prototype.getPrefix = function () {
return new Date().toISOString() + ' [' + this.prefix + '] '; return new Date().toISOString() + ' [' + this.prefix + '] ';
}; };
Logger.prototype.debug = function(...args) { Logger.prototype.debug = function (...args) {
args[0] = this.getPrefix() + args[0]; args[0] = this.getPrefix() + args[0];
if (this.level >= Level.Debug) { if (this.level >= Level.Debug) {
Logger.saveLast('debug', args); Logger.saveLast('debug', args);
@ -36,7 +36,7 @@ Logger.prototype.debug = function(...args) {
} }
}; };
Logger.prototype.info = function(...args) { Logger.prototype.info = function (...args) {
args[0] = this.getPrefix() + args[0]; args[0] = this.getPrefix() + args[0];
if (this.level >= Level.Info) { if (this.level >= Level.Info) {
Logger.saveLast('info', args); Logger.saveLast('info', args);
@ -44,7 +44,7 @@ Logger.prototype.info = function(...args) {
} }
}; };
Logger.prototype.warn = function(...args) { Logger.prototype.warn = function (...args) {
args[0] = this.getPrefix() + args[0]; args[0] = this.getPrefix() + args[0];
if (this.level >= Level.Warn) { if (this.level >= Level.Warn) {
Logger.saveLast('warn', args); Logger.saveLast('warn', args);
@ -52,7 +52,7 @@ Logger.prototype.warn = function(...args) {
} }
}; };
Logger.prototype.error = function(...args) { Logger.prototype.error = function (...args) {
args[0] = this.getPrefix() + args[0]; args[0] = this.getPrefix() + args[0];
if (this.level >= Level.Error) { if (this.level >= Level.Error) {
Logger.saveLast('error', args); Logger.saveLast('error', args);
@ -60,22 +60,22 @@ Logger.prototype.error = function(...args) {
} }
}; };
Logger.prototype.setLevel = function(level) { Logger.prototype.setLevel = function (level) {
this.level = level; this.level = level;
}; };
Logger.prototype.getLevel = function() { Logger.prototype.getLevel = function () {
return this.level; return this.level;
}; };
Logger.saveLast = function(level, args) { Logger.saveLast = function (level, args) {
lastLogs.push({ level, args: Array.prototype.slice.call(args) }); lastLogs.push({ level, args: Array.prototype.slice.call(args) });
if (lastLogs.length > MaxLogsToSave) { if (lastLogs.length > MaxLogsToSave) {
lastLogs.shift(); lastLogs.shift();
} }
}; };
Logger.getLast = function() { Logger.getLast = function () {
return lastLogs; return lastLogs;
}; };

View File

@ -2,7 +2,7 @@ import { Events } from 'framework/events';
import { Features } from 'util/features'; import { Features } from 'util/features';
import { pick } from 'util/fn'; import { pick } from 'util/fn';
const Tip = function(el, config) { const Tip = function (el, config) {
this.el = el; this.el = el;
this.title = (config && config.title) || el.attr('title'); this.title = (config && config.title) || el.attr('title');
this.placement = (config && config.placement) || el.attr('tip-placement'); this.placement = (config && config.placement) || el.attr('tip-placement');
@ -19,7 +19,7 @@ const Tip = function(el, config) {
Tip.enabled = !Features.isMobile; Tip.enabled = !Features.isMobile;
Tip.prototype.init = function() { Tip.prototype.init = function () {
if (!Tip.enabled) { if (!Tip.enabled) {
return; return;
} }
@ -29,7 +29,7 @@ Tip.prototype.init = function() {
this.el.click(this.mouseleave); this.el.click(this.mouseleave);
}; };
Tip.prototype.show = function() { Tip.prototype.show = function () {
if ((!Tip.enabled && !this.force) || !this.title) { if ((!Tip.enabled && !this.force) || !this.title) {
return; return;
} }
@ -41,10 +41,7 @@ Tip.prototype.show = function() {
this.hideTimeout = null; this.hideTimeout = null;
} }
} }
const tipEl = (this.tipEl = $('<div></div>') const tipEl = (this.tipEl = $('<div></div>').addClass('tip').appendTo('body').text(this.title));
.addClass('tip')
.appendTo('body')
.text(this.title));
const rect = this.el[0].getBoundingClientRect(); const rect = this.el[0].getBoundingClientRect();
const tipRect = this.tipEl[0].getBoundingClientRect(); const tipRect = this.tipEl[0].getBoundingClientRect();
const placement = this.placement || this.getAutoPlacement(rect, tipRect); const placement = this.placement || this.getAutoPlacement(rect, tipRect);
@ -80,7 +77,7 @@ Tip.prototype.show = function() {
tipEl.css({ top, left }); tipEl.css({ top, left });
}; };
Tip.prototype.hide = function() { Tip.prototype.hide = function () {
if (this.tipEl) { if (this.tipEl) {
this.tipEl.remove(); this.tipEl.remove();
this.tipEl = null; this.tipEl = null;
@ -88,7 +85,7 @@ Tip.prototype.hide = function() {
} }
}; };
Tip.prototype.destroy = function() { Tip.prototype.destroy = function () {
this.hide(); this.hide();
this.el.off('mouseenter', this.mouseenter); this.el.off('mouseenter', this.mouseenter);
@ -105,7 +102,7 @@ Tip.prototype.destroy = function() {
} }
}; };
Tip.prototype.mouseenter = function() { Tip.prototype.mouseenter = function () {
if (this.showTimeout) { if (this.showTimeout) {
return; return;
} }
@ -115,7 +112,7 @@ Tip.prototype.mouseenter = function() {
}, 200); }, 200);
}; };
Tip.prototype.mouseleave = function() { Tip.prototype.mouseleave = function () {
if (this.tipEl) { if (this.tipEl) {
this.tipEl.addClass('tip--hide'); this.tipEl.addClass('tip--hide');
this.hideTimeout = setTimeout(() => { this.hideTimeout = setTimeout(() => {
@ -129,7 +126,7 @@ Tip.prototype.mouseleave = function() {
} }
}; };
Tip.prototype.getAutoPlacement = function(rect, tipRect) { Tip.prototype.getAutoPlacement = function (rect, tipRect) {
const padding = 20; const padding = 20;
const bodyRect = document.body.getBoundingClientRect(); const bodyRect = document.body.getBoundingClientRect();
const canShowToBottom = bodyRect.bottom - rect.bottom > padding + tipRect.height; const canShowToBottom = bodyRect.bottom - rect.bottom > padding + tipRect.height;
@ -155,7 +152,7 @@ Tip.prototype.getAutoPlacement = function(rect, tipRect) {
} }
}; };
Tip.createTips = function(container) { Tip.createTips = function (container) {
if (!Tip.enabled) { if (!Tip.enabled) {
return; return;
} }
@ -164,7 +161,7 @@ Tip.createTips = function(container) {
}); });
}; };
Tip.createTip = function(el, options) { Tip.createTip = function (el, options) {
if (!Tip.enabled && (!options || !options.force)) { if (!Tip.enabled && (!options || !options.force)) {
return; return;
} }
@ -176,7 +173,7 @@ Tip.createTip = function(el, options) {
return tip; return tip;
}; };
Tip.hideTips = function(container) { Tip.hideTips = function (container) {
if (!Tip.enabled || !container) { if (!Tip.enabled || !container) {
return; return;
} }
@ -185,13 +182,13 @@ Tip.hideTips = function(container) {
}); });
}; };
Tip.hideTip = function(el) { Tip.hideTip = function (el) {
if (el._tip) { if (el._tip) {
el._tip.hide(); el._tip.hide();
} }
}; };
Tip.updateTip = function(el, props) { Tip.updateTip = function (el, props) {
if (el._tip) { if (el._tip) {
el._tip.hide(); el._tip.hide();
Object.assign( Object.assign(
@ -201,7 +198,7 @@ Tip.updateTip = function(el, props) {
} }
}; };
Tip.destroyTips = function(container) { Tip.destroyTips = function (container) {
$('[data-title]', container).each((ix, el) => { $('[data-title]', container).each((ix, el) => {
if (el._tip) { if (el._tip) {
el._tip.destroy(); el._tip.destroy();

View File

@ -314,7 +314,9 @@ class AppView extends View {
} }
showFileSettings(e) { showFileSettings(e) {
const menuItem = this.model.menu.filesSection.items.find(item => item.file.id === e.fileId); const menuItem = this.model.menu.filesSection.items.find(
(item) => item.file.id === e.fileId
);
if (this.views.settings) { if (this.views.settings) {
if (this.views.settings.file === menuItem.file) { if (this.views.settings.file === menuItem.file) {
this.showEntries(); this.showEntries();
@ -380,7 +382,7 @@ class AppView extends View {
if (Launcher) { if (Launcher) {
if (!this.exitAlertShown) { if (!this.exitAlertShown) {
if (this.model.settings.autoSave) { if (this.model.settings.autoSave) {
this.saveAndLock(result => { this.saveAndLock((result) => {
if (result) { if (result) {
exit(); exit();
} }
@ -396,9 +398,9 @@ class AppView extends View {
{ result: 'exit', title: Locale.discardChanges, error: true }, { result: 'exit', title: Locale.discardChanges, error: true },
{ result: '', title: Locale.appDontExitBtn } { result: '', title: Locale.appDontExitBtn }
], ],
success: result => { success: (result) => {
if (result === 'save') { if (result === 'save') {
this.saveAndLock(result => { this.saveAndLock((result) => {
if (result) { if (result) {
exit(); exit();
} }
@ -532,7 +534,7 @@ class AppView extends View {
let pendingCallbacks = 0; let pendingCallbacks = 0;
const errorFiles = []; const errorFiles = [];
const that = this; const that = this;
this.model.files.forEach(function(file) { this.model.files.forEach(function (file) {
if (!file.dirty) { if (!file.dirty) {
return; return;
} }
@ -573,7 +575,7 @@ class AppView extends View {
closeAllFilesAndShowFirst() { closeAllFilesAndShowFirst() {
let fileToShow = this.model.files.find( let fileToShow = this.model.files.find(
file => !file.demo && !file.created && !file.external (file) => !file.demo && !file.created && !file.external
); );
this.model.closeAllFiles(); this.model.closeAllFiles();
if (!fileToShow) { if (!fileToShow) {
@ -599,7 +601,7 @@ class AppView extends View {
} }
saveAll() { saveAll() {
this.model.files.forEach(function(file) { this.model.files.forEach(function (file) {
this.model.syncFile(file); this.model.syncFile(file);
}, this); }, this);
} }
@ -729,8 +731,8 @@ class AppView extends View {
position: { left: e.pageX, top: e.pageY }, position: { left: e.pageX, top: e.pageY },
options: e.options options: e.options
}); });
menu.on('cancel', e => this.hideContextMenu()); menu.on('cancel', (e) => this.hideContextMenu());
menu.on('select', e => this.contextMenuSelect(e)); menu.on('select', (e) => this.contextMenuSelect(e));
this.views.contextMenu = menu; this.views.contextMenu = menu;
} }
} }
@ -801,7 +803,7 @@ class AppView extends View {
const reader = new FileReader(); const reader = new FileReader();
const logger = new Logger('import-csv'); const logger = new Logger('import-csv');
logger.info('Reading CSV...'); logger.info('Reading CSV...');
reader.onload = e => { reader.onload = (e) => {
logger.info('Parsing CSV...'); logger.info('Parsing CSV...');
const ts = logger.ts(); const ts = logger.ts();
const parser = new CsvParser(); const parser = new CsvParser();

View File

@ -75,7 +75,7 @@ class AutoTypeSelectView extends View {
const presenter = new EntryPresenter(null, noColor, this.result && this.result.id); const presenter = new EntryPresenter(null, noColor, this.result && this.result.id);
let itemsHtml = ''; let itemsHtml = '';
const itemTemplate = this.itemTemplate; const itemTemplate = this.itemTemplate;
this.entries.forEach(entry => { this.entries.forEach((entry) => {
presenter.present(entry); presenter.present(entry);
itemsHtml += itemTemplate(presenter, DefaultTemplateOptions); itemsHtml += itemTemplate(presenter, DefaultTemplateOptions);
}); });

View File

@ -23,18 +23,14 @@ class DetailsAttachmentView extends View {
case 'text': { case 'text': {
const reader = new FileReader(); const reader = new FileReader();
reader.addEventListener('loadend', () => { reader.addEventListener('loadend', () => {
$('<pre/>') $('<pre/>').text(reader.result).appendTo(dataEl);
.text(reader.result)
.appendTo(dataEl);
complete(); complete();
}); });
reader.readAsText(blob); reader.readAsText(blob);
return; return;
} }
case 'image': case 'image':
$('<img/>') $('<img/>').attr('src', URL.createObjectURL(blob)).appendTo(dataEl);
.attr('src', URL.createObjectURL(blob))
.appendTo(dataEl);
complete(); complete();
return; return;
} }

View File

@ -36,7 +36,7 @@ class DetailsAutoTypeView extends View {
seqInput(e) { seqInput(e) {
const el = e.target; const el = e.target;
const seq = el.value.trim(); const seq = el.value.trim();
AutoType.validate(this.model, seq, err => { AutoType.validate(this.model, seq, (err) => {
$(el).toggleClass('input--error', !!err); $(el).toggleClass('input--error', !!err);
if (!err) { if (!err) {
this.model.setAutoTypeSeq(seq); this.model.setAutoTypeSeq(seq);

View File

@ -57,10 +57,10 @@ function createDetailsFields(detailsView) {
); );
} else { } else {
const writeableFiles = AppModel.instance.files.filter( const writeableFiles = AppModel.instance.files.filter(
file => file.active && !file.readOnly (file) => file.active && !file.readOnly
); );
if (model.isJustCreated && writeableFiles.length > 1) { if (model.isJustCreated && writeableFiles.length > 1) {
const fileNames = writeableFiles.map(file => { const fileNames = writeableFiles.map((file) => {
return { id: file.id, value: file.name, selected: file === model.file }; return { id: file.id, value: file.name, selected: file === model.file };
}); });
fieldViews.push( fieldViews.push(

View File

@ -93,14 +93,14 @@ class DetailsHistoryView extends View {
this.buildTimeline(); this.buildTimeline();
this.timelineEl = this.$el.find('.details__history-timeline'); this.timelineEl = this.$el.find('.details__history-timeline');
this.bodyEl = this.$el.find('.details__history-body'); this.bodyEl = this.$el.find('.details__history-body');
this.timeline.forEach(function(item, ix) { this.timeline.forEach(function (item, ix) {
$('<i/>') $('<i/>')
.addClass('fa fa-circle details__history-timeline-item') .addClass('fa fa-circle details__history-timeline-item')
.css('left', item.pos * 100 + '%') .css('left', item.pos * 100 + '%')
.attr('data-id', ix) .attr('data-id', ix)
.appendTo(this.timelineEl); .appendTo(this.timelineEl);
}, this); }, this);
this.labels.forEach(function(label) { this.labels.forEach(function (label) {
$('<div/>') $('<div/>')
.addClass('details__history-timeline-label') .addClass('details__history-timeline-label')
.css('left', label.pos * 100 + '%') .css('left', label.pos * 100 + '%')
@ -115,7 +115,7 @@ class DetailsHistoryView extends View {
} }
removeFieldViews() { removeFieldViews() {
this.fieldViews.forEach(fieldView => fieldView.remove()); this.fieldViews.forEach((fieldView) => fieldView.remove());
this.fieldViews = []; this.fieldViews = [];
} }
@ -209,11 +209,11 @@ class DetailsHistoryView extends View {
new FieldViewReadOnly({ new FieldViewReadOnly({
name: 'Attachments', name: 'Attachments',
title: Locale.detAttachments, title: Locale.detAttachments,
value: this.record.attachments.map(att => att.title).join(', ') value: this.record.attachments.map((att) => att.title).join(', ')
}) })
); );
} }
this.fieldViews.forEach(fieldView => { this.fieldViews.forEach((fieldView) => {
fieldView.parent = this.bodyEl[0]; fieldView.parent = this.bodyEl[0];
fieldView.render(); fieldView.render();
fieldView.on('copy', this.fieldCopied.bind(this)); fieldView.on('copy', this.fieldCopied.bind(this));
@ -232,9 +232,7 @@ class DetailsHistoryView extends View {
} }
timelineItemClick(e) { timelineItemClick(e) {
const id = $(e.target) const id = $(e.target).closest('.details__history-timeline-item').data('id');
.closest('.details__history-timeline-item')
.data('id');
this.showRecord(id); this.showRecord(id);
} }
@ -253,7 +251,7 @@ class DetailsHistoryView extends View {
buildTimeline() { buildTimeline() {
const firstRec = this.history[0]; const firstRec = this.history[0];
const lastRec = this.history[this.history.length - 1]; const lastRec = this.history[this.history.length - 1];
this.timeline = this.history.map(rec => ({ this.timeline = this.history.map((rec) => ({
pos: (rec.updated - firstRec.updated) / (lastRec.updated - firstRec.updated), pos: (rec.updated - firstRec.updated) / (lastRec.updated - firstRec.updated),
rec rec
})); }));
@ -263,7 +261,7 @@ class DetailsHistoryView extends View {
firstRec.updated.getTime(), firstRec.updated.getTime(),
lastRec.updated.getTime(), lastRec.updated.getTime(),
format.round format.round
).map(label => ({ ).map((label) => ({
pos: (label - firstRec.updated) / (lastRec.updated - firstRec.updated), pos: (label - firstRec.updated) / (lastRec.updated - firstRec.updated),
val: label, val: label,
text: format.format(new Date(label)) text: format.format(new Date(label))

View File

@ -96,7 +96,7 @@ class DetailsView extends View {
} }
removeFieldViews() { removeFieldViews() {
this.fieldViews.forEach(fieldView => fieldView.remove()); this.fieldViews.forEach((fieldView) => fieldView.remove());
this.fieldViews = []; this.fieldViews = [];
this.hideFieldCopyTip(); this.hideFieldCopyTip();
} }
@ -136,7 +136,7 @@ class DetailsView extends View {
} }
getFieldView(name) { getFieldView(name) {
return this.fieldViews.find(fv => fv.model.name === name); return this.fieldViews.find((fv) => fv.model.name === name);
} }
addFieldViews() { addFieldViews() {
@ -152,7 +152,7 @@ class DetailsView extends View {
fieldView.render(); fieldView.render();
fieldView.on('change', this.fieldChanged.bind(this)); fieldView.on('change', this.fieldChanged.bind(this));
fieldView.on('copy', this.fieldCopied.bind(this)); fieldView.on('copy', this.fieldCopied.bind(this));
fieldView.on('autotype', e => this.autoType(e.source.model.sequence)); fieldView.on('autotype', (e) => this.autoType(e.source.model.sequence));
if (hideEmptyFields) { if (hideEmptyFields) {
const value = fieldView.model.value(); const value = fieldView.model.value();
if (!value || value.length === 0 || value.byteLength === 0) { if (!value || value.length === 0 || value.byteLength === 0) {
@ -223,7 +223,7 @@ class DetailsView extends View {
const hideEmptyFields = AppSettingsModel.hideEmptyFields; const hideEmptyFields = AppSettingsModel.hideEmptyFields;
const moreOptions = []; const moreOptions = [];
if (hideEmptyFields) { if (hideEmptyFields) {
this.fieldViews.forEach(fieldView => { this.fieldViews.forEach((fieldView) => {
if (fieldView.isHidden()) { if (fieldView.isHidden()) {
moreOptions.push({ moreOptions.push({
value: 'add:' + fieldView.model.name, value: 'add:' + fieldView.model.name,
@ -306,7 +306,7 @@ class DetailsView extends View {
default: default:
if (e.item.lastIndexOf('add:', 0) === 0) { if (e.item.lastIndexOf('add:', 0) === 0) {
const fieldName = e.item.substr(4); const fieldName = e.item.substr(4);
const fieldView = this.fieldViews.find(f => f.model.name === fieldName); const fieldView = this.fieldViews.find((f) => f.model.name === fieldName);
fieldView.show(); fieldView.show();
fieldView.edit(); fieldView.edit();
} }
@ -336,9 +336,7 @@ class DetailsView extends View {
} }
selectColor(e) { selectColor(e) {
let color = $(e.target) let color = $(e.target).closest('.details__colors-popup-item').data('color');
.closest('.details__colors-popup-item')
.data('color');
if (!color) { if (!color) {
return; return;
} }
@ -579,7 +577,7 @@ class DetailsView extends View {
} }
} }
this.entryUpdated(true); this.entryUpdated(true);
this.fieldViews.forEach(function(fieldView, ix) { this.fieldViews.forEach(function (fieldView, ix) {
if ( if (
fieldView instanceof FieldViewCustom && fieldView instanceof FieldViewCustom &&
!fieldView.model.newField && !fieldView.model.newField &&
@ -927,7 +925,7 @@ class DetailsView extends View {
otpEnterManually() { otpEnterManually() {
if (this.model.fields.otp) { if (this.model.fields.otp) {
const otpField = this.fieldViews.find(f => f.model.name === '$otp'); const otpField = this.fieldViews.find((f) => f.model.name === '$otp');
if (otpField) { if (otpField) {
otpField.edit(); otpField.edit();
} }
@ -967,7 +965,7 @@ class DetailsView extends View {
const hasOtp = sequence?.includes('{TOTP}') || (entry.external && !sequence); const hasOtp = sequence?.includes('{TOTP}') || (entry.external && !sequence);
if (hasOtp) { if (hasOtp) {
const otpField = this.getFieldView('$otp'); const otpField = this.getFieldView('$otp');
otpField.refreshOtp(err => { otpField.refreshOtp((err) => {
if (!err) { if (!err) {
Events.emit('auto-type', { Events.emit('auto-type', {
entry, entry,

View File

@ -153,7 +153,7 @@ class FieldViewOtp extends FieldViewText {
} }
copyValue() { copyValue() {
this.refreshOtp(err => { this.refreshOtp((err) => {
if (!err) { if (!err) {
super.copyValue(); super.copyValue();
} }

View File

@ -8,7 +8,7 @@ class FieldViewSelect extends FieldView {
return ( return (
'<select>' + '<select>' +
value value
.map(opt => { .map((opt) => {
return ( return (
'<option ' + '<option ' +
'value="' + 'value="' +
@ -28,7 +28,7 @@ class FieldViewSelect extends FieldView {
render() { render() {
super.render(); super.render();
this.valueEl.addClass('details__field-value--select'); this.valueEl.addClass('details__field-value--select');
this.valueEl.find('select:first').change(e => { this.valueEl.find('select:first').change((e) => {
this.triggerChange({ val: e.target.value, field: this.model.name }); this.triggerChange({ val: e.target.value, field: this.model.name });
}); });
} }

View File

@ -19,14 +19,14 @@ class FieldViewTags extends FieldViewText {
valueToTags(val) { valueToTags(val) {
const allTags = {}; const allTags = {};
this.model.tags.forEach(tag => { this.model.tags.forEach((tag) => {
allTags[tag.toLowerCase()] = tag; allTags[tag.toLowerCase()] = tag;
}); });
const valueTags = {}; const valueTags = {};
val.split(/\s*[;,:]\s*/) val.split(/\s*[;,:]\s*/)
.filter(tag => tag) .filter((tag) => tag)
.map(tag => allTags[tag.toLowerCase()] || tag) .map((tag) => allTags[tag.toLowerCase()] || tag)
.forEach(tag => { .forEach((tag) => {
valueTags[tag] = tag; valueTags[tag] = tag;
}); });
return Object.keys(valueTags); return Object.keys(valueTags);
@ -69,7 +69,7 @@ class FieldViewTags extends FieldViewText {
const tags = this.valueToTags(this.input.val()); const tags = this.valueToTags(this.input.val());
const last = tags[tags.length - 1]; const last = tags[tags.length - 1];
const isLastPart = last && this.model.tags.indexOf(last) < 0; const isLastPart = last && this.model.tags.indexOf(last) < 0;
return this.model.tags.filter(tag => { return this.model.tags.filter((tag) => {
return ( return (
tags.indexOf(tag) < 0 && tags.indexOf(tag) < 0 &&
(!isLastPart || tag.toLowerCase().indexOf(last.toLowerCase()) >= 0) (!isLastPart || tag.toLowerCase().indexOf(last.toLowerCase()) >= 0)

View File

@ -57,7 +57,7 @@ class FieldViewText extends FieldView {
click: this.fieldValueInputClick.bind(this), click: this.fieldValueInputClick.bind(this),
mousedown: this.fieldValueInputMouseDown.bind(this) mousedown: this.fieldValueInputMouseDown.bind(this)
}); });
const fieldValueBlurBound = e => this.fieldValueBlur(e); const fieldValueBlurBound = (e) => this.fieldValueBlur(e);
Events.on('click', fieldValueBlurBound); Events.on('click', fieldValueBlurBound);
this.stopBlurListener = () => Events.off('click', fieldValueBlurBound); this.stopBlurListener = () => Events.off('click', fieldValueBlurBound);
this.listenTo(Events, 'main-window-will-close', this.externalEndEdit); this.listenTo(Events, 'main-window-will-close', this.externalEndEdit);
@ -82,7 +82,7 @@ class FieldViewText extends FieldView {
createMobileControls() { createMobileControls() {
this.mobileControls = {}; this.mobileControls = {};
['cancel', 'apply'].forEach(action => { ['cancel', 'apply'].forEach((action) => {
this.mobileControls[action] = $('<div/>') this.mobileControls[action] = $('<div/>')
.addClass('details__field-value-btn details__field-value-btn-' + action) .addClass('details__field-value-btn details__field-value-btn-' + action)
.appendTo(this.labelEl) .appendTo(this.labelEl)

View File

@ -77,9 +77,7 @@ class FooterView extends View {
} }
showFile(e) { showFile(e) {
const fileId = $(e.target) const fileId = $(e.target).closest('.footer__db-item').data('file-id');
.closest('.footer__db-item')
.data('file-id');
if (fileId) { if (fileId) {
Events.emit('show-file', { fileId }); Events.emit('show-file', { fileId });
} }

View File

@ -32,8 +32,8 @@ class GeneratorPresetsView extends View {
render() { render() {
this.presets = GeneratorPresets.all; this.presets = GeneratorPresets.all;
if (!this.selected || !this.presets.some(p => p.name === this.selected)) { if (!this.selected || !this.presets.some((p) => p.name === this.selected)) {
this.selected = (this.presets.filter(p => p.default)[0] || this.presets[0]).name; this.selected = (this.presets.filter((p) => p.default)[0] || this.presets[0]).name;
} }
super.render({ super.render({
presets: this.presets, presets: this.presets,
@ -61,7 +61,7 @@ class GeneratorPresetsView extends View {
high: '¡¢£¤¥¦§©ª«¬®¯°±¹²´µ¶»¼÷¿ÀÖîü...' high: '¡¢£¤¥¦§©ª«¬®¯°±¹²´µ¶»¼÷¿ÀÖîü...'
}; };
return ['Upper', 'Lower', 'Digits', 'Special', 'Brackets', 'High', 'Ambiguous'].map( return ['Upper', 'Lower', 'Digits', 'Special', 'Brackets', 'High', 'Ambiguous'].map(
name => { (name) => {
const nameLower = name.toLowerCase(); const nameLower = name.toLowerCase();
return { return {
name: nameLower, name: nameLower,
@ -74,7 +74,7 @@ class GeneratorPresetsView extends View {
} }
getPreset(name) { getPreset(name) {
return this.presets.filter(p => p.name === name)[0]; return this.presets.filter((p) => p.name === name)[0];
} }
returnToApp() { returnToApp() {
@ -92,7 +92,7 @@ class GeneratorPresetsView extends View {
for (let i = 1; ; i++) { for (let i = 1; ; i++) {
const newName = 'Custom' + i; const newName = 'Custom' + i;
const newTitle = Locale.genPsNew + ' ' + i; const newTitle = Locale.genPsNew + ' ' + i;
if (!this.presets.filter(p => p.name === newName || p.title === newTitle).length) { if (!this.presets.filter((p) => p.name === newName || p.title === newTitle).length) {
name = newName; name = newName;
title = newTitle; title = newTitle;
break; break;
@ -128,9 +128,11 @@ class GeneratorPresetsView extends View {
changeTitle(e) { changeTitle(e) {
const title = $.trim(e.target.value); const title = $.trim(e.target.value);
if (title && title !== this.getPreset(this.selected).title) { if (title && title !== this.getPreset(this.selected).title) {
let duplicate = this.presets.some(p => p.title.toLowerCase() === title.toLowerCase()); let duplicate = this.presets.some((p) => p.title.toLowerCase() === title.toLowerCase());
if (!duplicate) { if (!duplicate) {
duplicate = this.reservedTitles.some(p => p.toLowerCase() === title.toLowerCase()); duplicate = this.reservedTitles.some(
(p) => p.toLowerCase() === title.toLowerCase()
);
} }
if (duplicate) { if (duplicate) {
$(e.target).addClass('input--error'); $(e.target).addClass('input--error');

View File

@ -62,7 +62,7 @@ class GeneratorView extends View {
super(model); super(model);
this.createPresets(); this.createPresets();
const preset = this.preset; const preset = this.preset;
this.gen = { ...this.presets.find(pr => pr.name === preset) }; this.gen = { ...this.presets.find((pr) => pr.name === preset) };
this.hide = AppSettingsModel.generatorHidePassword; this.hide = AppSettingsModel.generatorHidePassword;
$('body').one('click', this.remove.bind(this)); $('body').one('click', this.remove.bind(this));
this.listenTo(Events, 'lock-workspace', this.remove.bind(this)); this.listenTo(Events, 'lock-workspace', this.remove.bind(this));
@ -100,10 +100,10 @@ class GeneratorView extends View {
this.presets.splice(0, 0, derivedPreset); this.presets.splice(0, 0, derivedPreset);
this.preset = 'Derived'; this.preset = 'Derived';
} else { } else {
const defaultPreset = this.presets.filter(p => p.default)[0] || this.presets[0]; const defaultPreset = this.presets.filter((p) => p.default)[0] || this.presets[0];
this.preset = defaultPreset.name; this.preset = defaultPreset.name;
} }
this.presets.forEach(pr => { this.presets.forEach((pr) => {
pr.pseudoLength = this.lengthToPseudoValue(pr.length); pr.pseudoLength = this.lengthToPseudoValue(pr.length);
}); });
} }
@ -191,7 +191,7 @@ class GeneratorView extends View {
return; return;
} }
this.preset = name; this.preset = name;
const preset = this.presets.find(t => t.name === name); const preset = this.presets.find((t) => t.name === name);
this.gen = { ...preset }; this.gen = { ...preset };
this.render(); this.render();
} }

View File

@ -70,7 +70,7 @@ class GrpView extends View {
changeAutoTypeSeq(e) { changeAutoTypeSeq(e) {
const el = e.target; const el = e.target;
const seq = $.trim(el.value); const seq = $.trim(el.value);
AutoType.validate(null, seq, err => { AutoType.validate(null, seq, (err) => {
$(e.target).toggleClass('input--error', !!err); $(e.target).toggleClass('input--error', !!err);
if (!err) { if (!err) {
this.model.setAutoTypeSeq(seq); this.model.setAutoTypeSeq(seq);

View File

@ -69,7 +69,7 @@ class IconSelectView extends View {
.append(img); .append(img);
this.downloadingFavicon = false; this.downloadingFavicon = false;
}; };
img.onerror = e => { img.onerror = (e) => {
logger.error('Favicon download error: ' + url, e); logger.error('Favicon download error: ' + url, e);
this.$el.find('.icon-select__icon-download>i').removeClass('fa-spinner fa-spin'); this.$el.find('.icon-select__icon-download>i').removeClass('fa-spinner fa-spin');
this.$el this.$el
@ -86,7 +86,7 @@ class IconSelectView extends View {
} }
let url = this.model.url.replace( let url = this.model.url.replace(
/([^\/:]\/.*)?$/, /([^\/:]\/.*)?$/,
match => (match && match[0]) + '/favicon.ico' (match) => (match && match[0]) + '/favicon.ico'
); );
if (url.indexOf('://') < 0) { if (url.indexOf('://') < 0) {
url = 'http://' + url; url = 'http://' + url;
@ -108,7 +108,7 @@ class IconSelectView extends View {
const file = e.target.files[0]; const file = e.target.files[0];
if (file) { if (file) {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = e => { reader.onload = (e) => {
const img = document.createElement('img'); const img = document.createElement('img');
img.onload = () => { img.onload = () => {
this.setSpecialImage(img, 'select'); this.setSpecialImage(img, 'select');

View File

@ -69,7 +69,7 @@ class ImportCsvView extends View {
const col = +e.target.dataset.col; const col = +e.target.dataset.col;
const field = e.target.value; const field = e.target.value;
const isBuiltIn = this.knownFields.some(f => f.field === field); const isBuiltIn = this.knownFields.some((f) => f.field === field);
const mapping = field ? (isBuiltIn ? 'builtin' : 'custom') : 'ignore'; const mapping = field ? (isBuiltIn ? 'builtin' : 'custom') : 'ignore';
this.fieldMapping[col] = { this.fieldMapping[col] = {
@ -96,7 +96,7 @@ class ImportCsvView extends View {
guessFieldMapping() { guessFieldMapping() {
const usedFields = {}; const usedFields = {};
for (const fieldName of this.model.headers.map(f => f.trim())) { for (const fieldName of this.model.headers.map((f) => f.trim())) {
if (!fieldName || /^(group|grouping)$/i.test(fieldName)) { if (!fieldName || /^(group|grouping)$/i.test(fieldName)) {
this.fieldMapping.push({ type: 'ignore' }); this.fieldMapping.push({ type: 'ignore' });
continue; continue;
@ -121,7 +121,7 @@ class ImportCsvView extends View {
fillGroups() { fillGroups() {
this.groups = []; this.groups = [];
for (const file of this.appModel.files) { for (const file of this.appModel.files) {
file.forEachGroup(group => { file.forEachGroup((group) => {
const title = group.title; const title = group.title;
const spaces = []; const spaces = [];
for (let parent = group; parent.parentGroup; parent = parent.parentGroup) { for (let parent = group; parent.parentGroup; parent = parent.parentGroup) {

View File

@ -68,10 +68,7 @@ class KeyChangeView extends View {
this.keyFile = null; this.keyFile = null;
this.$el.find('.key-change__keyfile-name').empty(); this.$el.find('.key-change__keyfile-name').empty();
} }
this.$el this.$el.find('.key-change__file').val(null).click();
.find('.key-change__file')
.val(null)
.click();
this.inputEl.focus(); this.inputEl.focus();
} }
@ -79,7 +76,7 @@ class KeyChangeView extends View {
const file = e.target.files[0]; const file = e.target.files[0];
if (file) { if (file) {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = e => { reader.onload = (e) => {
this.keyFileName = file.name; this.keyFileName = file.name;
this.keyFileData = e.target.result; this.keyFileData = e.target.result;
this.$el.find('.key-change__keyfile-name').text(': ' + this.keyFileName); this.$el.find('.key-change__keyfile-name').text(': ' + this.keyFileName);

View File

@ -99,7 +99,7 @@ class ListSearchView extends View {
{ value: '-rank', icon: 'sort-amount-desc', loc: () => Locale.searchRank } { value: '-rank', icon: 'sort-amount-desc', loc: () => Locale.searchRank }
]; ];
this.sortIcons = {}; this.sortIcons = {};
this.sortOptions.forEach(opt => { this.sortOptions.forEach((opt) => {
this.sortIcons[opt.value] = opt.icon; this.sortIcons[opt.value] = opt.icon;
}); });
this.advancedSearch = { this.advancedSearch = {
@ -135,7 +135,7 @@ class ListSearchView extends View {
} }
setLocale() { setLocale() {
this.sortOptions.forEach(opt => { this.sortOptions.forEach((opt) => {
opt.text = opt.loc(); opt.text = opt.loc();
}); });
this.createOptions = [ this.createOptions = [
@ -161,7 +161,7 @@ class ListSearchView extends View {
removeKeypressHandler() {} removeKeypressHandler() {}
viewShown() { viewShown() {
const keypressHandler = e => this.documentKeyPress(e); const keypressHandler = (e) => this.documentKeyPress(e);
Events.on('keypress', keypressHandler); Events.on('keypress', keypressHandler);
this.removeKeypressHandler = () => Events.off('keypress', keypressHandler); this.removeKeypressHandler = () => Events.off('keypress', keypressHandler);
} }
@ -337,7 +337,7 @@ class ListSearchView extends View {
view.isSort = true; view.isSort = true;
this.listenTo(view, 'cancel', this.hideSearchOptions); this.listenTo(view, 'cancel', this.hideSearchOptions);
this.listenTo(view, 'select', this.sortDropdownSelect); this.listenTo(view, 'select', this.sortDropdownSelect);
this.sortOptions.forEach(function(opt) { this.sortOptions.forEach(function (opt) {
opt.active = this.model.sort === opt.value; opt.active = this.model.sort === opt.value;
}, this); }, this);
view.render({ view.render({
@ -377,7 +377,7 @@ class ListSearchView extends View {
const hasMultipleFiles = this.model.files.length > 1; const hasMultipleFiles = this.model.files.length > 1;
this.entryTemplates = {}; this.entryTemplates = {};
const options = []; const options = [];
entryTemplates.forEach(tmpl => { entryTemplates.forEach((tmpl) => {
const id = 'tmpl:' + tmpl.entry.id; const id = 'tmpl:' + tmpl.entry.id;
options.push({ options.push({
value: id, value: id,

View File

@ -93,14 +93,14 @@ class ListView extends View {
this.model.activeEntryId this.model.activeEntryId
); );
const columns = {}; const columns = {};
this.tableColumns.forEach(col => { this.tableColumns.forEach((col) => {
if (col.enabled) { if (col.enabled) {
columns[col.val] = true; columns[col.val] = true;
} }
}); });
presenter.columns = columns; presenter.columns = columns;
let itemsHtml = ''; let itemsHtml = '';
this.items.forEach(item => { this.items.forEach((item) => {
presenter.present(item); presenter.present(item);
itemsHtml += itemTemplate(presenter, DefaultTemplateOptions); itemsHtml += itemTemplate(presenter, DefaultTemplateOptions);
}, this); }, this);
@ -250,7 +250,7 @@ class ListView extends View {
this.throttleSetViewSizeSetting(size); this.throttleSetViewSizeSetting(size);
} }
throttleSetViewSizeSetting = throttle(size => { throttleSetViewSizeSetting = throttle((size) => {
AppSettingsModel.listViewWidth = size; AppSettingsModel.listViewWidth = size;
}, 1000); }, 1000);
@ -267,9 +267,7 @@ class ListView extends View {
itemDragStart(e) { itemDragStart(e) {
e.stopPropagation(); e.stopPropagation();
const id = $(e.target) const id = $(e.target).closest('.list__item').attr('id');
.closest('.list__item')
.attr('id');
e.dataTransfer.setData('text/entry', id); e.dataTransfer.setData('text/entry', id);
e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.effectAllowed = 'move';
DragDropInfo.dragObject = this.items.get(id); DragDropInfo.dragObject = this.items.get(id);
@ -285,7 +283,7 @@ class ListView extends View {
this.listenTo(view, 'cancel', this.hideOptionsDropdown); this.listenTo(view, 'cancel', this.hideOptionsDropdown);
this.listenTo(view, 'select', this.optionsDropdownSelect); this.listenTo(view, 'select', this.optionsDropdownSelect);
const targetElRect = this.$el.find('.list__table-options')[0].getBoundingClientRect(); const targetElRect = this.$el.find('.list__table-options')[0].getBoundingClientRect();
const options = this.tableColumns.map(col => ({ const options = this.tableColumns.map((col) => ({
value: col.val, value: col.val,
icon: col.enabled ? 'check-square-o' : 'square-o', icon: col.enabled ? 'check-square-o' : 'square-o',
text: StringFormat.capFirst(Locale[col.name]) text: StringFormat.capFirst(Locale[col.name])
@ -308,7 +306,7 @@ class ListView extends View {
} }
optionsDropdownSelect(e) { optionsDropdownSelect(e) {
const col = this.tableColumns.find(c => c.val === e.item); const col = this.tableColumns.find((c) => c.val === e.item);
col.enabled = !col.enabled; col.enabled = !col.enabled;
e.el.find('i:first').toggleClass('fa-check-square-o fa-square-o'); e.el.find('i:first').toggleClass('fa-check-square-o fa-square-o');
this.render(); this.render();
@ -318,7 +316,7 @@ class ListView extends View {
readTableColumnsEnabled() { readTableColumnsEnabled() {
const tableViewColumns = AppSettingsModel.tableViewColumns; const tableViewColumns = AppSettingsModel.tableViewColumns;
if (tableViewColumns && tableViewColumns.length) { if (tableViewColumns && tableViewColumns.length) {
this.tableColumns.forEach(col => { this.tableColumns.forEach((col) => {
col.enabled = tableViewColumns.indexOf(col.name) >= 0; col.enabled = tableViewColumns.indexOf(col.name) >= 0;
}); });
} }
@ -326,8 +324,8 @@ class ListView extends View {
saveTableColumnsEnabled() { saveTableColumnsEnabled() {
const tableViewColumns = this.tableColumns const tableViewColumns = this.tableColumns
.filter(column => column.enabled) .filter((column) => column.enabled)
.map(column => column.name); .map((column) => column.name);
AppSettingsModel.tableViewColumns = tableViewColumns; AppSettingsModel.tableViewColumns = tableViewColumns;
} }
} }

Some files were not shown because too many files have changed in this diff Show More