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

450 lines
12 KiB
JavaScript
Raw Normal View History

2017-07-10 22:03:46 +02:00
import { JoplinDatabase } from 'lib/joplin-database.js';
import { Database } from 'lib/database.js';
import { DatabaseDriverNode } from 'lib/database-driver-node.js';
import { BaseModel } from 'lib/base-model.js';
import { Folder } from 'lib/models/folder.js';
import { BaseItem } from 'lib/models/base-item.js';
import { Note } from 'lib/models/note.js';
import { Setting } from 'lib/models/setting.js';
import { Logger } from 'lib/logger.js';
import { sprintf } from 'sprintf-js';
import { reg } from 'lib/registry.js';
import { fileExtension } from 'lib/path-utils.js';
2017-07-25 20:57:06 +02:00
import { _, setLocale, defaultLocale, closestSupportedLocale } from 'lib/locale.js';
2017-07-10 22:03:46 +02:00
import os from 'os';
import fs from 'fs-extra';
2017-08-03 19:48:14 +02:00
import yargParser from 'yargs-parser';
2017-08-04 18:02:43 +02:00
import { handleAutocompletion, installAutocompletionFile } from './autocompletion.js';
2017-08-04 19:51:01 +02:00
import { cliUtils } from './cli-utils.js';
2017-07-10 22:03:46 +02:00
class Application {
constructor() {
this.showPromptString_ = true;
this.logger_ = new Logger();
this.dbLogger_ = new Logger();
2017-08-04 19:51:01 +02:00
this.autocompletion_ = { active: false };
this.commands_ = {};
this.commandMetadata_ = null;
2017-08-04 18:50:12 +02:00
this.activeCommand_ = null;
2017-08-04 19:11:10 +02:00
this.allCommandsLoaded_ = false;
2017-08-21 20:32:43 +02:00
this.showStackTraces_ = false;
2017-07-10 22:03:46 +02:00
}
currentFolder() {
return this.currentFolder_;
}
2017-07-16 00:47:11 +02:00
async refreshCurrentFolder() {
let newFolder = null;
if (this.currentFolder_) newFolder = await Folder.load(this.currentFolder_.id);
if (!newFolder) newFolder = await Folder.defaultFolder();
this.switchCurrentFolder(newFolder);
}
2017-07-10 22:03:46 +02:00
switchCurrentFolder(folder) {
this.currentFolder_ = folder;
Setting.setValue('activeFolderId', folder ? folder.id : '');
}
2017-07-17 21:19:01 +02:00
async guessTypeAndLoadItem(pattern, options = null) {
let type = BaseModel.TYPE_NOTE;
if (pattern.indexOf('/') === 0) {
type = BaseModel.TYPE_FOLDER;
pattern = pattern.substr(1);
}
return this.loadItem(type, pattern, options);
}
2017-07-15 17:35:40 +02:00
async loadItem(type, pattern, options = null) {
let output = await this.loadItems(type, pattern, options);
2017-07-10 22:03:46 +02:00
return output.length ? output[0] : null;
}
2017-07-11 20:17:23 +02:00
async loadItems(type, pattern, options = null) {
pattern = pattern ? pattern.toString() : '';
2017-07-15 17:35:40 +02:00
if (type == BaseModel.TYPE_FOLDER && (pattern == Folder.conflictFolderTitle() || pattern == Folder.conflictFolderId())) return [Folder.conflictFolder()];
2017-07-11 20:17:23 +02:00
if (!options) options = {};
2017-07-13 23:26:45 +02:00
2017-07-11 20:17:23 +02:00
const parent = options.parent ? options.parent : app().currentFolder();
const ItemClass = BaseItem.itemClass(type);
if (type == BaseModel.TYPE_NOTE && pattern.indexOf('*') >= 0) { // Handle it as pattern
if (!parent) throw new Error(_('No notebook selected.'));
return await Note.previews(parent.id, { titlePattern: pattern });
} else { // Single item
let item = null;
if (type == BaseModel.TYPE_NOTE) {
if (!parent) throw new Error(_('No notebook has been specified.'));
item = await ItemClass.loadFolderNoteByField(parent.id, 'title', pattern);
} else {
item = await ItemClass.loadByTitle(pattern);
}
if (item) return [item];
item = await ItemClass.load(pattern); // Load by id
if (item) return [item];
if (pattern.length >= 4) {
item = await ItemClass.loadByPartialId(pattern);
if (item) return [item];
}
}
return [];
2017-07-10 22:03:46 +02:00
}
// Handles the initial flags passed to main script and
// returns the remaining args.
async handleStartFlags_(argv) {
let matched = {};
argv = argv.slice(0);
argv.splice(0, 2); // First arguments are the node executable, and the node JS file
while (argv.length) {
let arg = argv[0];
let nextArg = argv.length >= 2 ? argv[1] : null;
if (arg == '--profile') {
2017-07-28 20:13:07 +02:00
if (!nextArg) throw new Error(_('Usage: %s', '--profile <dir-path>'));
2017-07-10 22:03:46 +02:00
matched.profileDir = nextArg;
argv.splice(0, 2);
continue;
}
if (arg == '--env') {
2017-07-28 20:13:07 +02:00
if (!nextArg) throw new Error(_('Usage: %s', '--env <dev|prod>'));
2017-07-10 22:03:46 +02:00
matched.env = nextArg;
argv.splice(0, 2);
continue;
}
2017-07-10 22:59:58 +02:00
if (arg == '--update-geolocation-disabled') {
Note.updateGeolocationEnabled_ = false;
argv.splice(0, 1);
continue;
}
2017-07-10 22:03:46 +02:00
if (arg == '--stack-trace-enabled') {
2017-08-21 20:32:43 +02:00
this.showStackTraces_ = true;
2017-07-10 22:03:46 +02:00
argv.splice(0, 1);
continue;
}
if (arg == '--log-level') {
2017-07-28 20:13:07 +02:00
if (!nextArg) throw new Error(_('Usage: %s', '--log-level <none|error|warn|info|debug>'));
2017-07-10 22:03:46 +02:00
matched.logLevel = Logger.levelStringToId(nextArg);
argv.splice(0, 2);
continue;
}
2017-08-04 19:51:01 +02:00
if (arg == '--autocompletion') {
this.autocompletion_.active = true;
argv.splice(0, 1);
continue;
}
2017-08-04 18:02:43 +02:00
if (arg == '--ac-install') {
this.autocompletion_.install = true;
argv.splice(0, 1);
continue;
}
2017-08-04 19:51:01 +02:00
if (arg == '--ac-current') {
if (!nextArg) throw new Error(_('Usage: %s', '--ac-current <num>'));
this.autocompletion_.current = nextArg;
argv.splice(0, 2);
continue;
}
if (arg == '--ac-line') {
if (!nextArg) throw new Error(_('Usage: %s', '--ac-line <line>'));
let line = nextArg.replace(/\|__QUOTE__\|/g, '"');
line = line.replace(/\|__SPACE__\|/g, ' ');
line = line.replace(/\|__OPEN_RB__\|/g, '(');
line = line.replace(/\|__OPEN_CB__\|/g, ')');
2017-08-04 19:51:01 +02:00
line = line.split('|__SEP__|');
this.autocompletion_.line = line;
argv.splice(0, 2);
continue;
}
2017-07-10 22:03:46 +02:00
if (arg.length && arg[0] == '-') {
throw new Error(_('Unknown flag: %s', arg));
} else {
break;
}
}
if (!matched.logLevel) matched.logLevel = Logger.LEVEL_INFO;
2017-07-11 01:17:03 +02:00
if (!matched.env) matched.env = 'prod';
2017-07-10 22:03:46 +02:00
return {
matched: matched,
argv: argv,
};
}
escapeShellArg(arg) {
if (arg.indexOf('"') >= 0 && arg.indexOf("'") >= 0) throw new Error(_('Command line argument "%s" contains both quotes and double-quotes - aborting.', arg)); // Hopeless case
let quote = '"';
if (arg.indexOf('"') >= 0) quote = "'";
if (arg.indexOf(' ') >= 0 || arg.indexOf("\t") >= 0) return quote + arg + quote;
return arg;
}
shellArgsToString(args) {
let output = [];
for (let i = 0; i < args.length; i++) {
output.push(this.escapeShellArg(args[i]));
}
return output.join(' ');
}
2017-07-18 20:49:47 +02:00
onLocaleChanged() {
2017-08-03 19:48:14 +02:00
return;
2017-07-18 20:49:47 +02:00
let currentCommands = this.vorpal().commands;
for (let i = 0; i < currentCommands.length; i++) {
let cmd = currentCommands[i];
if (cmd._name == 'help') {
cmd.description(_('Provides help for a given command.'));
} else if (cmd._name == 'exit') {
cmd.description(_('Exits the application.'));
} else if (cmd.__commandObject) {
cmd.description(cmd.__commandObject.description());
}
}
}
2017-08-03 19:48:14 +02:00
2017-08-04 19:51:01 +02:00
baseModelListener(action) {
switch (action.type) {
2017-07-18 20:49:47 +02:00
2017-08-04 19:51:01 +02:00
case 'NOTES_UPDATE_ONE':
case 'NOTES_DELETE':
case 'FOLDERS_UPDATE_ONE':
case 'FOLDER_DELETE':
2017-08-04 18:50:12 +02:00
//reg.scheduleSync();
2017-08-04 19:51:01 +02:00
break;
}
}
2017-08-04 19:11:10 +02:00
commands() {
if (this.allCommandsLoaded_) return this.commands_;
2017-07-10 22:03:46 +02:00
fs.readdirSync(__dirname).forEach((path) => {
if (path.indexOf('command-') !== 0) return;
const ext = fileExtension(path)
if (ext != 'js') return;
let CommandClass = require('./' + path);
let cmd = new CommandClass();
2017-07-19 00:14:20 +02:00
if (!cmd.enabled()) return;
2017-08-04 19:11:10 +02:00
cmd.log = (...object) => {
return console.log(...object);
}
2017-08-04 19:51:01 +02:00
this.commands_[cmd.name()] = cmd;
2017-07-10 22:03:46 +02:00
});
2017-08-04 19:11:10 +02:00
this.allCommandsLoaded_ = true;
return this.commands_;
}
async commandNames() {
const metadata = await this.commandMetadata();
let output = [];
for (let n in metadata) {
if (!metadata.hasOwnProperty(n)) continue;
output.push(n);
}
return output;
2017-07-10 22:03:46 +02:00
}
2017-08-04 19:51:01 +02:00
async commandMetadata() {
if (this.commandMetadata_) return this.commandMetadata_;
2017-07-24 22:36:49 +02:00
const osTmpdir = require('os-tmpdir');
2017-08-04 19:51:01 +02:00
const storage = require('node-persist');
await storage.init({ dir: osTmpdir() + '/commandMetadata', ttl: 1000 * 60 * 60 * 24 });
2017-07-24 22:36:49 +02:00
2017-08-04 19:51:01 +02:00
let output = await storage.getItem('metadata');
if (Setting.value('env') != 'dev' && output) {
this.commandMetadata_ = output;
return Object.assign({}, this.commandMetadata_);
}
2017-08-04 19:11:10 +02:00
const commands = this.commands();
2017-07-24 22:36:49 +02:00
2017-08-04 19:51:01 +02:00
output = {};
2017-08-04 19:11:10 +02:00
for (let n in commands) {
if (!commands.hasOwnProperty(n)) continue;
const cmd = commands[n];
2017-08-04 19:51:01 +02:00
output[n] = cmd.metadata();
2017-07-24 22:36:49 +02:00
}
2017-08-04 19:51:01 +02:00
await storage.setItem('metadata', output);
this.commandMetadata_ = output;
return Object.assign({}, this.commandMetadata_);
2017-07-24 22:36:49 +02:00
}
2017-08-03 19:48:14 +02:00
findCommandByName(name) {
2017-08-04 19:11:10 +02:00
if (this.commands_[name]) return this.commands_[name];
2017-08-03 19:48:14 +02:00
let CommandClass = null;
try {
CommandClass = require(__dirname + '/command-' + name + '.js');
2017-08-03 19:48:14 +02:00
} catch (error) {
let e = new Error('No such command: ' + name);
e.type = 'notFound';
throw e;
}
let cmd = new CommandClass();
cmd.log = (...object) => {
return console.log(...object);
}
2017-08-04 19:11:10 +02:00
this.commands_[name] = cmd;
return this.commands_[name];
2017-08-03 19:48:14 +02:00
}
async execCommand(argv) {
if (!argv.length) return this.execCommand(['help']);
2017-08-03 19:48:14 +02:00
const commandName = argv[0];
2017-08-04 18:50:12 +02:00
this.activeCommand_ = this.findCommandByName(commandName);
const cmdArgs = cliUtils.makeCommandArgs(this.activeCommand_, argv);
await this.activeCommand_.action(cmdArgs);
}
2017-08-20 16:29:18 +02:00
currentCommand() {
return this.activeCommand_;
2017-08-03 19:48:14 +02:00
}
async start() {
2017-07-10 22:03:46 +02:00
let argv = process.argv;
let startFlags = await this.handleStartFlags_(argv);
argv = startFlags.argv;
let initArgs = startFlags.matched;
if (argv.length) this.showPromptString_ = false;
2017-08-20 16:29:18 +02:00
if (process.argv[1].indexOf('joplindev') >= 0) {
if (!initArgs.profileDir) initArgs.profileDir = '/mnt/d/Temp/TestNotes2';
initArgs.logLevel = Logger.LEVEL_DEBUG;
initArgs.env = 'dev';
}
2017-08-04 18:02:43 +02:00
Setting.setConstant('appName', initArgs.env == 'dev' ? 'joplindev' : 'joplin');
2017-07-10 22:03:46 +02:00
const profileDir = initArgs.profileDir ? initArgs.profileDir : os.homedir() + '/.config/' + Setting.value('appName');
const resourceDir = profileDir + '/resources';
const tempDir = profileDir + '/tmp';
Setting.setConstant('env', initArgs.env);
Setting.setConstant('profileDir', profileDir);
Setting.setConstant('resourceDir', resourceDir);
Setting.setConstant('tempDir', tempDir);
await fs.mkdirp(profileDir, 0o755);
await fs.mkdirp(resourceDir, 0o755);
await fs.mkdirp(tempDir, 0o755);
this.logger_.addTarget('file', { path: profileDir + '/log.txt' });
this.logger_.setLevel(initArgs.logLevel);
reg.setLogger(this.logger_);
2017-07-24 22:36:49 +02:00
reg.dispatch = (o) => {};
2017-07-10 22:03:46 +02:00
this.dbLogger_.addTarget('file', { path: profileDir + '/log-database.txt' });
2017-07-23 16:11:44 +02:00
this.dbLogger_.setLevel(initArgs.logLevel);
2017-07-10 22:03:46 +02:00
const packageJson = require('./package.json');
this.logger_.info(sprintf('Starting %s %s (%s)...', packageJson.name, packageJson.version, Setting.value('env')));
this.logger_.info('Profile directory: ' + profileDir);
this.database_ = new JoplinDatabase(new DatabaseDriverNode());
this.database_.setLogger(this.dbLogger_);
await this.database_.open({ name: profileDir + '/database.sqlite' });
reg.setDb(this.database_);
2017-07-10 22:03:46 +02:00
BaseModel.db_ = this.database_;
2017-07-24 22:36:49 +02:00
BaseModel.dispatch = (action) => { this.baseModelListener(action) }
2017-07-10 22:03:46 +02:00
await Setting.load();
2017-07-25 20:57:06 +02:00
if (Setting.value('firstStart')) {
let locale = process.env.LANG;
if (!locale) locale = defaultLocale();
locale = locale.split('.');
locale = locale[0];
reg.logger().info('First start: detected locale as ' + locale);
Setting.setValue('locale', closestSupportedLocale(locale));
Setting.setValue('firstStart', 0)
}
2017-07-18 20:04:47 +02:00
setLocale(Setting.value('locale'));
2017-07-10 22:03:46 +02:00
let currentFolderId = Setting.value('activeFolderId');
this.currentFolder_ = null;
if (currentFolderId) this.currentFolder_ = await Folder.load(currentFolderId);
if (!this.currentFolder_) this.currentFolder_ = await Folder.defaultFolder();
Setting.setValue('activeFolderId', this.currentFolder_ ? this.currentFolder_.id : '');
2017-08-04 19:51:01 +02:00
if (this.autocompletion_.active) {
2017-08-04 18:02:43 +02:00
if (this.autocompletion_.install) {
try {
2017-08-22 19:57:35 +02:00
await installAutocompletionFile(Setting.value('appName'), Setting.value('profileDir'));
2017-08-04 18:02:43 +02:00
} catch (error) {
if (error.code == 'shellNotSupported') {
console.info(error.message);
return;
}
throw error;
}
} else {
let items = await handleAutocompletion(this.autocompletion_);
if (!items.length) return;
for (let i = 0; i < items.length; i++) {
items[i] = items[i].replace(/ /g, '\\ ');
2017-08-20 16:29:18 +02:00
items[i] = items[i].replace(/'/g, "\\'");
items[i] = items[i].replace(/:/g, "\\:");
items[i] = items[i].replace(/\(/g, '\\(');
items[i] = items[i].replace(/\)/g, '\\)');
2017-08-04 18:02:43 +02:00
}
console.info(items.join("\n"));
2017-08-04 19:51:01 +02:00
}
2017-08-04 18:02:43 +02:00
2017-08-04 19:51:01 +02:00
return;
}
2017-08-03 19:48:14 +02:00
2017-08-04 18:50:12 +02:00
try {
await this.execCommand(argv);
} catch (error) {
2017-08-21 20:32:43 +02:00
if (this.showStackTraces_) {
console.info(error);
} else {
console.info(error.message);
}
2017-08-04 18:50:12 +02:00
}
2017-07-10 22:03:46 +02:00
}
}
let application_ = null;
function app() {
if (application_) return application_;
application_ = new Application();
return application_;
}
export { app };