1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-09-02 20:46:21 +02:00

Compare commits

..

2 Commits

Author SHA1 Message Date
Laurent Cozic
f98c693adf CLI v1.0.112 2018-07-25 17:51:13 +02:00
Laurent Cozic
6da80f3291 Trying to get proxy to work 2018-07-25 17:47:35 +02:00
644 changed files with 34504 additions and 106708 deletions

View File

@@ -1,48 +0,0 @@
*.min.js
.git/
.github/
_mydocs/
_releases/
Assets/
CliClient/build
CliClient/locales
CliClient/node_modules
CliClient/tests-build
CliClient/tests/enex_to_md
CliClient/tests/html_to_md
CliClient/tests/logs
CliClient/tests/support
CliClient/tests/sync
CliClient/tests/tmp
Clipper/joplin-webclipper/content_scripts/JSDOMParser.js
Clipper/joplin-webclipper/content_scripts/Readability-readerable.js
Clipper/joplin-webclipper/content_scripts/Readability.js
Clipper/joplin-webclipper/dist
Clipper/joplin-webclipper/icons
Clipper/joplin-webclipper/popup/build
Clipper/joplin-webclipper/popup/node_modules
docs/
ElectronClient/app/dist
ElectronClient/app/lib
ElectronClient/app/lib/vendor/sjcl-rn.js
ElectronClient/app/lib/vendor/sjcl.js
ElectronClient/app/locales
ElectronClient/app/node_modules
highlight.pack.js
node_modules/
ReactNativeClient/android
ReactNativeClient/ios
ReactNativeClient/lib/vendor/
ReactNativeClient/lib/welcomeAssets.js
ReactNativeClient/locales
ReactNativeClient/node_modules
readme/
Tools/node_modules
Tools/PortableAppsLauncher
Server/.git/
Server/.github/
Server/docs/
Server/dist/
Server/bin/
Server/node_modules/
ElectronClient/app/packageInfo.js

View File

@@ -1,85 +0,0 @@
module.exports = {
'env': {
'browser': true,
'es6': true,
'node': true,
},
"parser": "@typescript-eslint/parser",
'extends': ['eslint:recommended'],
'globals': {
'Atomics': 'readonly',
'SharedArrayBuffer': 'readonly',
// Jasmine variables
'expect': 'readonly',
'describe': 'readonly',
'it': 'readonly',
'beforeEach': 'readonly',
'jasmine': 'readonly',
// React Native variables
'__DEV__': 'readonly',
// Clipper variables
'browserSupportsPromises_': true,
'chrome': 'readonly',
'browser': 'readonly',
},
'parserOptions': {
'ecmaVersion': 2018,
"ecmaFeatures": {
"jsx": true,
},
"sourceType": "module",
},
'rules': {
// -------------------------------
// Code correctness
// -------------------------------
"react/jsx-uses-react": "error",
"react/jsx-uses-vars": "error",
"no-unused-vars": "error",
"no-constant-condition": 0,
"no-prototype-builtins": 0,
// This error is always a false positive so far since it detects
// possible race conditions in contexts where we know it cannot happen.
"require-atomic-updates": 0,
// "no-lonely-if": "error",
// -------------------------------
// Formatting
// -------------------------------
"space-in-parens": ["error", "never"],
"semi": ["error", "always"],
"eol-last": ["error", "always"],
"quotes": ["error", "single"],
"indent": ["error", "tab"],
"comma-dangle": ["error", "always-multiline"],
"no-trailing-spaces": "error",
"linebreak-style": ["error", "unix"],
"prefer-template": ["error"],
"template-curly-spacing": ["error", "never"],
"key-spacing": ["error", {
"beforeColon": false,
"afterColon": true,
"mode": "strict"
}],
"block-spacing": ["error"],
"brace-style": ["error", "1tbs", { "allowSingleLine": true }],
"no-spaced-func": ["error"],
"func-call-spacing": ["error"],
"space-before-function-paren": ["error", {
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}],
"multiline-comment-style": ["error", "separate-lines"],
"space-before-blocks": "error",
"spaced-comment": ["error", "always"],
"keyword-spacing": ["error", { "before": true, "after": true }]
},
"plugins": [
"react",
"@typescript-eslint",
],
};

5
.github/FUNDING.yml vendored
View File

@@ -1,5 +0,0 @@
# These are supported funding model platforms
patreon: joplin
github: laurent22
custom: https://joplinapp.org/donate/

View File

@@ -1,9 +0,0 @@
👉 Please follow one of these issue templates:
- https://github.com/laurent22/joplin/issues/new/choose
⚠️
The GitHub issue tracker is for **bugs** and **security issues** ONLY. For feature requests and support, please use the forum:
https://discourse.joplinapp.org/
⚠️
Note: to keep the backlog clean and actionable, issues may be immediately closed if they do not follow one of the above issue templates.

View File

@@ -1,48 +0,0 @@
---
name: "🐛 Bug Report"
about: Report a reproducible bug or regression in Joplin.
title: ''
labels: 'bug'
---
<!--
Please provide a clear and concise description of what the bug is. (In the section Steps To Reproduce.)
Include screenshots if needed.
Please test using the latest Joplin release to make sure your issue has not already been fixed.
-->
<!--
IMPORTANT: If you are reporting a clipper bug, please include an example URL that shows the issue.
Without the URL the issue is likely to be closed.
-->
## Environment
Joplin version:
Platform:
OS specifcs:
<!--
Platform can be one of: macOS, Linux, Windows, Android, iOS, terminal (or a combination)
OS specifcs: e.g. OS version, Linux distribution, Android/iOS version, ...
-->
## Steps To Reproduce
1.
2.
<!--
Issues without reproduction steps are likely to stall.
-->
Describe what you expected to happen:
## Logfile
<!--
Please attach a debug log. Issues without a debug log are likely to stall.
For information on how to collect a log file: https://joplinapp.org/debugging/
-->

View File

@@ -1,29 +0,0 @@
---
name: "🤔 Questions and Help"
about: The issue tracker is not for questions. Please ask questions on https://discourse.joplinapp.org/.
title: ''
labels: 'invalid'
---
⚠🚨⛔ The issue tracker is not for questions. ⛔🚨⚠
As it happens, support requests that are created as issues are likely to be closed. We want to make sure you are able to find the help you seek.
## Questions and Help
Please read the [documentation](https://joplinapp.org/) and [FAQ](https://joplinapp.org/faq/) first.
### https://discourse.joplinapp.org/
If you have still questions related to Joplin, please open a topic in the [forum](https://discourse.joplinapp.org/).
You can use your GitHub credentials to login to the forum.
## Links
- Documentation: https://joplinapp.org
- FAQ: https://joplinapp.org/faq/
- Forum: https://discourse.joplinapp.org
- How to enable end-to-end encryption: https://joplinapp.org/e2ee/
- API documentation: https://joplinapp.org/api/
- How to enable debug mode: https://joplinapp.org/debugging/

View File

@@ -1,15 +0,0 @@
<!--
Please prefix the title with the platform you are targetting:
- "Desktop" for the Windows/macOS/Linux app (Electron app)
- "Mobile" for the mobile app (or "Android" / "iOS" if the pull request only applies to one of the mobile platforms)
- "CLI" for the CLI app
If it's not related to any platform (such as a translation, change to the documentation, etc.), simply don't add a platform.
For example: "Desktop: Added new setting to change font", or "Mobile: Fixed config screen error"
PLEASE READ THE GUIDE FIRST: https://github.com/laurent22/joplin/blob/master/CONTRIBUTING.md
-->

25
.github/lock.yml vendored
View File

@@ -1,25 +0,0 @@
# Configuration for Lock Threads - https://github.com/dessant/lock-threads
# Number of days of inactivity before a closed issue or pull request is locked
daysUntilLock: 1
# Skip issues and pull requests created before a given timestamp. Timestamp must
# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable
skipCreatedBefore: false
# Issues and pull requests with these labels will be ignored. Set to `[]` to disable
exemptLabels: []
# Label to add before locking, such as `outdated`. Set to `false` to disable
lockLabel: false
# Comment to post before locking. Set to `false` to disable
lockComment: false
# Assign `resolved` as the reason for locking. Set to `false` to disable
setLockReason: false
# Limit to only `issues` or `pulls`
only: issues
# Optionally, specify configuration settings just for `issues` or `pulls`
# issues:
# exemptLabels:
# - help-wanted
# lockLabel: outdated
# pulls:
# daysUntilLock: 30
# Repository to extend settings from
# _extends: repo

25
.github/stale.yml vendored
View File

@@ -1,25 +0,0 @@
# Configuration for probot-stale - https://github.com/probot/stale
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 90
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- "good first issue"
- "essential"
- "essential-reviewed"
- "help wanted"
- "nice to have"
- "upstream"
- "backlog"
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
Hey there, it looks like there has been no activity on this issue recently. Has the issue been fixed, or does it still require the community's attention? This issue may be closed if no further activity occurs.
You may also label this issue as "backlog" and I will leave it open.
Thank you for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: >
Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please feel free to create a new issue with up-to-date information.
only: issues

5
.gitignore vendored Normal file → Executable file
View File

@@ -39,8 +39,5 @@ node_modules
Tools/github_oauth_token.txt
_releases
ReactNativeClient/lib/csstojs/
ReactNativeClient/lib/rnInjectedJs/
ElectronClient/app/gui/note-viewer/fonts/
ElectronClient/app/gui/note-viewer/lib.js
Tools/commit_hook.txt
.vscode/*
Tools/commit_hook.txt

View File

@@ -1,5 +1,5 @@
# Only build tags (Doesn't work - doesn't build anything)
if: tag IS present OR type = pull_request
if: tag IS present
rvm: 2.3.3
@@ -54,43 +54,8 @@ before_install:
script:
- |
# Install tools
npm install
cd Tools
npm install
cd ..
# Run test units
cd CliClient
npm install
./run_test.sh
testResult=$?
if [ $testResult -ne 0 ]; then
exit $testResult
fi
cd ..
# Run linter for pull requests only - this is so that
# bypassing eslint is allowed for urgent fixes.
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
npm run linter-ci ./
testResult=$?
if [ $testResult -ne 0 ]; then
exit $testResult
fi
fi
# Find out if we should run the build or not. Electron-builder gets stuck when
# builing PRs so we disable it in this case. The Linux build should provide
# enough info if the app builds or not.
# https://github.com/electron-userland/electron-builder/issues/4263
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
if [ "$TRAVIS_OS_NAME" == "osx" ]; then
exit 0
fi
fi
# Prepare the Electron app and build it
cd ElectronClient/app
cd ../ElectronClient/app
rsync -aP --delete ../../ReactNativeClient/lib/ lib/
npm install && USE_HARD_LINKS=false yarn dist
npm install && yarn dist

BIN
Assets/Adresse.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 986 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 336 KiB

After

Width:  |  Height:  |  Size: 335 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 244 KiB

After

Width:  |  Height:  |  Size: 254 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 249 KiB

View File

@@ -1,9 +1,7 @@
[![Travis Build Status](https://travis-ci.org/laurent22/joplin.svg?branch=master)](https://travis-ci.org/laurent22/joplin) [![Appveyor Build Status](https://ci.appveyor.com/api/projects/status/github/laurent22/joplin?branch=master&passingText=master%20-%20OK&svg=true)](https://ci.appveyor.com/project/laurent22/joplin)
# General information
- All the applications share the same library, which, for historical reasons, is in ReactNativeClient/lib. This library is copied to the relevant directories when building each app.
- In general, most of the backend (anything to do with the database, synchronisation, data import or export, etc.) is shared across all the apps, so when making a change please consider how it will affect all the apps.
- The translations are built by running CliClient/build-translation.sh. You normally don't need to run this if you haven't updated the translation since the compiled files are on the repository.
## macOS dependencies
@@ -11,6 +9,8 @@
echo 'export PATH="/usr/local/opt/gettext/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile
If you get a node-gyp related error you might need to manually install it: `npm install -g node-gyp`
## Linux and Windows (WSL) dependencies
- Install yarn - https://yarnpkg.com/lang/en/docs/install/
@@ -19,10 +19,11 @@
# Building the tools
Before building any of the applications, you need to build the tools and pre-commit hooks:
Before building any of the applications, you need to build the tools:
```
npm install && cd Tools && npm install
cd Tools
npm install
```
# Building the Electron application
@@ -36,10 +37,6 @@ yarn dist
If there's an error `while loading shared libraries: libgconf-2.so.4: cannot open shared object file: No such file or directory`, run `sudo apt-get install libgconf-2-4`
If you get a node-gyp related error you might need to manually install it: `npm install -g node-gyp`.
If you get the error `libtool: unrecognized option '-static'`, follow the instructions [in this post](https://stackoverflow.com/a/38552393/561309) to use the correct libtool version.
That will create the executable file in the `dist` directory.
From `/ElectronClient` you can also run `run.sh` to run the app for testing.
@@ -59,13 +56,9 @@ If node-gyp does not works (MSBUILD: error MSB3428: Could not load the Visual C+
If `yarn dist` fails, it may need administrative rights.
If you get an `error MSB8020: The build tools for v140 cannot be found.` try to run with a different toolset version, eg `npm install --toolset=v141` (See [here](https://github.com/mapbox/node-sqlite3/issues/1124) for more info).
The [building\_win32\_tips on this page](./readme/building_win32_tips.md) might be helpful.
# Building the Mobile application
First you need to setup React Native to build projects with native code. For this, follow the instructions on the [Get Started](https://facebook.github.io/react-native/docs/getting-started.html) tutorial, in the "React Native CLI Quickstart" tab.
First you need to setup React Native to build projects with native code. For this, follow the instructions on the [Get Started](https://facebook.github.io/react-native/docs/getting-started.html) tutorial, in the "Building Projects with Native Code" tab.
Then, from `/ReactNativeClient`, run `npm install`, then `react-native run-ios` or `react-native run-android`.
@@ -78,4 +71,4 @@ npm install
rsync --delete -aP ../ReactNativeClient/locales/ build/locales/
```
Run `run.sh` to start the application for testing.
Run `run.sh` to start the application for testing.

View File

@@ -1,73 +1,19 @@
# User support
The [Joplin Forum](https://discourse.joplinapp.org/) is the community driven place for user support, general discussion about Joplin, problems with installation, new features and software development questions. It is possible to login with your GitHub account. Don't use the issue tracker for support questions.
For general discussion about Joplin, user support, software development questions, and to discuss new features, please go to the [Joplin Forum](https://discourse.joplin.cozic.net/). It is possible to login with your GitHub account.
# Reporting a bug
File bugs in the [Github Issue Tracker](https://github.com/laurent22/joplin/issues?utf8=%E2%9C%93&q=is%3Aissue). Please follow these guidelines:
Please check first that it [has not already been reported](https://github.com/laurent22/joplin/issues?utf8=%E2%9C%93&q=is%3Aissue). Also consider [enabling debug mode](https://github.com/laurent22/joplin/blob/master/readme/debugging.md) before reporting the issue so that you can provide as much details as possible to help fix it.
- Search existing issues first, make sure yours hasn't already been reported.
- Consider [enabling debug mode](https://joplinapp.org/debugging/) so that you can provide as much details as possible when reporting the issue.
- Stay on topic, but describe the issue in detail so that others can reproduce it.
- **Provide a screenshot** if possible. A screenshot showing the problem is often more useful than a paragraph describing it.
- For web clipper bugs, **please provide the URL causing the issue**. Sometimes the clipper works in one page but not in another so it is important to know what URL has a problem.
If possible, **please provide a screenshot**. A screenshot showing the problem is often more useful than a paragraph describing it as it can make it immediately clear what the issue is.
# Feature requests
Please check that your request has not already been posted in the [Github Issue Tracker](https://github.com/laurent22/joplin/issues?utf8=%E2%9C%93&q=is%3Aissue). If it has, **up-voting the issue** increases the chances it'll be noticed and implemented in the future. "+1" comments are not tracked.
Again, please check that it has not already been requested. If it has, simply **up-vote the issue** - the ones with the most up-votes are likely to be implemented. "+1" comments are not tracked.
As a general rule, suggestions to *improve Joplin* should be posted first in the [Joplin Forum](https://discourse.joplinapp.org/) for discussion.
# Adding new features
Avoid listing multiple requests in one report in the [Github Issue Tracker](https://github.com/laurent22/joplin/issues?utf8=%E2%9C%93&q=is%3Aissue). One issue per request makes it easier to track and discuss it.
Finally, when submitting a pull request, don't forget to [test your code](#unit-tests).
# Contribute to the project
## Contributing to Joplin's translation
Joplin is available in multiple languages thanks to the help of its users. You can help translate Joplin to your language or keep it up to date. Please read the documentation about [Localisation](https://joplinapp.org/#localisation).
## Contributing to Joplin's code
If you want to start contributing to the project's code, please follow these guidelines before creating a pull request:
- Bug fixes are always welcome. Start by reviewing the list of [essential issues](https://github.com/laurent22/joplin/issues?q=is%3Aissue+is%3Aopen+label%3Aessential)
- Before adding a new feature, ask about it in the [Github Issue Tracker](https://github.com/laurent22/joplin/issues?utf8=%E2%9C%93&q=is%3Aissue) or the [Joplin Forum](https://discourse.joplinapp.org/), or check if existing discussions exist to make sure the new functionality is desired.
- **Changes that will consist in more than 50 lines of code should be discussed the [Joplin Forum](https://discourse.joplinapp.org/)**, so that you don't spend too much time implementing something that might not be accepted.
If you want to add a new feature, consider asking about it before implementing it or checking existing discussions to make sure it is within the scope of the project. Of course you are free to create the pull request directly but it is not guaranteed it is going to be accepted.
Building the apps is relatively easy - please [see the build instructions](https://github.com/laurent22/joplin/blob/master/BUILD.md) for more details.
## Coding style
Coding style is enforced by a pre-commit hook that runs eslint. This hook is installed whenever running `npm install` on any of the application directory. If for some reason the pre-commit hook didn't get installed, you can manually install it by running `npm install` at the root of the repository.
## Unit tests
When submitting a pull request for a new feature or bug fix, please add unit tests for your code. Unit testing GUI changes is not always possible so it is not required, but any change in a file under /lib for example should be unit tested.
The tests are under CliClient/tests. To get them running, you first need to build the CLI app:
cd CliClient
npm i
To run the test units, you must have an instance of the cli app running. In a first window navigate into `CliClient` and run:
```sh
./run.sh
```
> If you get an error like `Error: Cannot find module '../locales/index.js'`, this means you must (a) rebuild translations or (b) take > them from one of the other apps. To do option b, you can run the following command to copy them from the `ReactNativeClient` directory:>
>
> ```sh
> cd .. # Return to the root of the project
> rsync -aP ./ReactNativeClient/locales/ ./CliClient/build/locales/
> ```
Then run the tests in a second window. To run all the test units:
./run_test.sh
To run just one particular file:
./run_test.sh markdownUtils # Don't add the .js extension

View File

@@ -1,13 +0,0 @@
module.exports = {
"overrides": [
{
"files": ["tests/**/*.js"],
'rules': {
// Ignore all unused function arguments, because in some
// case they are kept to indicate the function signature.
"no-unused-vars": ["error", { "argsIgnorePattern": ".*" }],
"@typescript-eslint/no-unused-vars": 0,
}
},
],
};

View File

@@ -13,7 +13,6 @@ tests/fuzzing.*
tests/fuzzing -*
tests/logs/*
tests/cli-integration/
tests/tmp/
*.mo
*.*~
tests/sync

View File

@@ -1,11 +1,14 @@
const { _ } = require('lib/locale.js');
const { Logger } = require('lib/logger.js');
const Resource = require('lib/models/Resource.js');
const { netUtils } = require('lib/net-utils.js');
const http = require('http');
const urlParser = require('url');
const http = require("http");
const urlParser = require("url");
const enableServerDestroy = require('server-destroy');
class ResourceServer {
constructor() {
this.server_ = null;
this.logger_ = new Logger();
@@ -28,7 +31,7 @@ class ResourceServer {
baseUrl() {
if (!this.port_) return '';
return `http://127.0.0.1:${this.port_}`;
return 'http://127.0.0.1:' + this.port_;
}
setLinkHandler(handler) {
@@ -37,7 +40,7 @@ class ResourceServer {
async start() {
this.port_ = await netUtils.findAvailablePort([9167, 9267, 8167, 8267]);
if (!this.port_) {
if (!this.port_) {
this.logger().error('Could not find available port to start resource server. Please report the error at https://github.com/laurent22/joplin');
return;
}
@@ -45,15 +48,16 @@ class ResourceServer {
this.server_ = http.createServer();
this.server_.on('request', async (request, response) => {
const writeResponse = message => {
const writeResponse = (message) => {
response.write(message);
response.end();
};
}
const url = urlParser.parse(request.url, true);
let resourceId = url.pathname.split('/');
if (resourceId.length < 2) {
writeResponse(`Error: could not get resource ID from path name: ${url.pathname}`);
writeResponse('Error: could not get resource ID from path name: ' + url.pathname);
return;
}
resourceId = resourceId[1];
@@ -62,10 +66,9 @@ class ResourceServer {
try {
const done = await this.linkHandler_(resourceId, response);
if (!done) throw new Error(`Unhandled resource: ${resourceId}`);
if (!done) throw new Error('Unhandled resource: ' + resourceId);
} catch (error) {
response.setHeader('Content-Type', 'text/plain');
// eslint-disable-next-line require-atomic-updates
response.statusCode = 400;
response.write(error.message);
}
@@ -73,7 +76,7 @@ class ResourceServer {
response.end();
});
this.server_.on('error', error => {
this.server_.on('error', (error) => {
this.logger().error('Resource server:', error);
});
@@ -88,6 +91,7 @@ class ResourceServer {
if (this.server_) this.server_.destroy();
this.server_ = null;
}
}
module.exports = ResourceServer;
module.exports = ResourceServer;

View File

@@ -5,12 +5,13 @@ const Tag = require('lib/models/Tag.js');
const BaseModel = require('lib/BaseModel.js');
const Note = require('lib/models/Note.js');
const Resource = require('lib/models/Resource.js');
const { cliUtils } = require('./cli-utils.js');
const { reducer, defaultState } = require('lib/reducer.js');
const { splitCommandString } = require('lib/string-utils.js');
const { reg } = require('lib/registry.js');
const { _ } = require('lib/locale.js');
const Entities = require('html-entities').AllHtmlEntities;
const htmlentities = new Entities().encode;
const htmlentities = (new Entities()).encode;
const chalk = require('chalk');
const tk = require('terminal-kit');
@@ -19,10 +20,12 @@ const Renderer = require('tkwidgets/framework/Renderer.js');
const DecryptionWorker = require('lib/services/DecryptionWorker');
const BaseWidget = require('tkwidgets/BaseWidget.js');
const ListWidget = require('tkwidgets/ListWidget.js');
const TextWidget = require('tkwidgets/TextWidget.js');
const HLayoutWidget = require('tkwidgets/HLayoutWidget.js');
const VLayoutWidget = require('tkwidgets/VLayoutWidget.js');
const ReduxRootWidget = require('tkwidgets/ReduxRootWidget.js');
const RootWidget = require('tkwidgets/RootWidget.js');
const WindowWidget = require('tkwidgets/WindowWidget.js');
const NoteWidget = require('./gui/NoteWidget.js');
@@ -34,6 +37,7 @@ const StatusBarWidget = require('./gui/StatusBarWidget.js');
const ConsoleWidget = require('./gui/ConsoleWidget.js');
class AppGui {
constructor(app, store, keymap) {
try {
this.app_ = app;
@@ -46,12 +50,12 @@ class AppGui {
// Some keys are directly handled by the tkwidget framework
// so they need to be remapped in a different way.
this.tkWidgetKeys_ = {
focus_next: 'TAB',
focus_previous: 'SHIFT_TAB',
move_up: 'UP',
move_down: 'DOWN',
page_down: 'PAGE_DOWN',
page_up: 'PAGE_UP',
'focus_next': 'TAB',
'focus_previous': 'SHIFT_TAB',
'move_up': 'UP',
'move_down': 'DOWN',
'page_down': 'PAGE_DOWN',
'page_up': 'PAGE_UP',
};
this.renderer_ = null;
@@ -60,7 +64,7 @@ class AppGui {
this.renderer_ = new Renderer(this.term(), this.rootWidget_);
this.app_.on('modelAction', async event => {
this.app_.on('modelAction', async (event) => {
await this.handleModelAction(event.action);
});
@@ -79,7 +83,7 @@ class AppGui {
reg.setupRecurrentSync();
DecryptionWorker.instance().scheduleStart();
} catch (error) {
if (this.term_) { this.fullScreen(false); }
this.fullScreen(false);
console.error(error);
process.exit(1);
}
@@ -130,7 +134,7 @@ class AppGui {
};
folderList.name = 'folderList';
folderList.vStretch = true;
folderList.on('currentItemChange', async event => {
folderList.on('currentItemChange', async (event) => {
const item = folderList.currentItem;
if (item === '-') {
@@ -165,7 +169,7 @@ class AppGui {
});
}
});
this.rootWidget_.connect(folderList, state => {
this.rootWidget_.connect(folderList, (state) => {
return {
selectedFolderId: state.selectedFolderId,
selectedTagId: state.selectedTagId,
@@ -192,7 +196,7 @@ class AppGui {
id: note ? note.id : null,
});
});
this.rootWidget_.connect(noteList, state => {
this.rootWidget_.connect(noteList, (state) => {
return {
selectedNoteId: state.selectedNoteIds.length ? state.selectedNoteIds[0] : null,
items: state.notes,
@@ -206,7 +210,7 @@ class AppGui {
borderBottomWidth: 1,
borderLeftWidth: 1,
};
this.rootWidget_.connect(noteText, state => {
this.rootWidget_.connect(noteText, (state) => {
return {
noteId: state.selectedNoteIds.length ? state.selectedNoteIds[0] : null,
notes: state.notes,
@@ -221,7 +225,7 @@ class AppGui {
borderLeftWidth: 1,
borderRightWidth: 1,
};
this.rootWidget_.connect(noteMetadata, state => {
this.rootWidget_.connect(noteMetadata, (state) => {
return { noteId: state.selectedNoteIds.length ? state.selectedNoteIds[0] : null };
});
noteMetadata.hide();
@@ -288,7 +292,7 @@ class AppGui {
if (!cmd) return;
const isConfigPassword = cmd.indexOf('config ') >= 0 && cmd.indexOf('password') >= 0;
if (isConfigPassword) return;
this.stdout(chalk.cyan.bold(`> ${cmd}`));
this.stdout(chalk.cyan.bold('> ' + cmd));
}
setupKeymap(keymap) {
@@ -297,7 +301,7 @@ class AppGui {
for (let i = 0; i < keymap.length; i++) {
const item = Object.assign({}, keymap[i]);
if (!item.command) throw new Error(`Missing command for keymap item: ${JSON.stringify(item)}`);
if (!item.command) throw new Error('Missing command for keymap item: ' + JSON.stringify(item));
if (!('type' in item)) item.type = 'exec';
@@ -404,7 +408,7 @@ class AppGui {
activeListItem() {
const widget = this.widget('mainWindow').focusedWidget;
if (!widget) return null;
if (widget.name == 'noteList' || widget.name == 'folderList') {
return widget.currentItem;
}
@@ -426,21 +430,25 @@ class AppGui {
}
async processFunctionCommand(cmd) {
if (cmd === 'activate') {
const w = this.widget('mainWindow').focusedWidget;
if (w.name === 'folderList') {
this.widget('noteList').focus();
} else if (w.name === 'noteList' || w.name === 'noteText') {
this.processPromptCommand('edit $n');
}
} else if (cmd === 'delete') {
if (this.widget('folderList').hasFocus) {
const item = this.widget('folderList').selectedJoplinItem;
if (!item) return;
if (item.type_ === BaseModel.TYPE_FOLDER) {
await this.processPromptCommand(`rmbook ${item.id}`);
await this.processPromptCommand('rmbook ' + item.id);
} else if (item.type_ === BaseModel.TYPE_TAG) {
this.stdout(_('To delete a tag, untag the associated notes.'));
} else if (item.type_ === BaseModel.TYPE_SEARCH) {
@@ -454,7 +462,9 @@ class AppGui {
} else {
this.stdout(_('Please select the note or notebook to be deleted first.'));
}
} else if (cmd === 'toggle_console') {
if (!this.consoleIsShown()) {
this.showConsole();
this.minimizeConsole();
@@ -465,15 +475,22 @@ class AppGui {
this.maximizeConsole();
}
}
} else if (cmd === 'toggle_metadata') {
this.toggleNoteMetadata();
} else if (cmd === 'enter_command_line_mode') {
const cmd = await this.widget('statusBar').prompt();
if (!cmd) return;
this.addCommandToConsole(cmd);
await this.processPromptCommand(cmd);
await this.processPromptCommand(cmd);
} else {
throw new Error(`Unknown command: ${cmd}`);
throw new Error('Unknown command: ' + cmd);
}
}
@@ -484,7 +501,7 @@ class AppGui {
// this.logger().debug('Got command: ' + cmd);
try {
try {
let note = this.widget('noteList').currentItem;
let folder = this.widget('folderList').currentItem;
let args = splitCommandString(cmd);
@@ -494,7 +511,7 @@ class AppGui {
args[i] = note ? note.id : '';
} else if (args[i] == '$b') {
args[i] = folder ? folder.id : '';
} else if (args[i] == '$c') {
} else if (args[i] == '$c') {
const item = this.activeListItem();
args[i] = item ? item.id : '';
}
@@ -506,7 +523,7 @@ class AppGui {
}
this.widget('console').scrollBottom();
// Invalidate so that the screen is redrawn in case inputting a command has moved
// the GUI up (in particular due to autocompletion), it's moved back to the right position.
this.widget('root').invalidate();
@@ -586,17 +603,17 @@ class AppGui {
async setupResourceServer() {
const linkStyle = chalk.blue.underline;
const noteTextWidget = this.widget('noteText');
const resourceIdRegex = /^:\/[a-f0-9]+$/i;
const resourceIdRegex = /^:\/[a-f0-9]+$/i
const noteLinks = {};
const hasProtocol = function(s, protocols) {
if (!s) return false;
s = s.trim().toLowerCase();
for (let i = 0; i < protocols.length; i++) {
if (s.indexOf(`${protocols[i]}://`) === 0) return true;
if (s.indexOf(protocols[i] + '://') === 0) return true;
}
return false;
};
}
// By default, before the server is started, only the regular
// URLs appear in blue.
@@ -620,31 +637,29 @@ class AppGui {
const link = noteLinks[path];
if (link.type === 'url') {
response.writeHead(302, { Location: link.url });
response.writeHead(302, { 'Location': link.url });
return true;
}
if (link.type === 'item') {
const itemId = link.id;
let item = await BaseItem.loadItemById(itemId);
if (!item) throw new Error(`No item with ID ${itemId}`); // Should be nearly impossible
if (!item) throw new Error('No item with ID ' + itemId); // Should be nearly impossible
if (item.type_ === BaseModel.TYPE_RESOURCE) {
if (item.mime) response.setHeader('Content-Type', item.mime);
response.write(await Resource.content(item));
} else if (item.type_ === BaseModel.TYPE_NOTE) {
const html = [
`
const html = [`
<!DOCTYPE html>
<html class="client-nojs" lang="en" dir="ltr">
<head><meta charset="UTF-8"/></head><body>
`,
];
html.push(`<pre>${htmlentities(item.title)}\n\n${htmlentities(item.body)}</pre>`);
`];
html.push('<pre>' + htmlentities(item.title) + '\n\n' + htmlentities(item.body) + '</pre>');
html.push('</body></html>');
response.write(html.join(''));
} else {
throw new Error(`Unsupported item type: ${item.type_}`);
throw new Error('Unsupported item type: ' + item.type_);
}
return true;
@@ -664,7 +679,7 @@ class AppGui {
noteLinks[index] = {
type: 'item',
id: url.substr(2),
};
};
} else if (hasProtocol(url, ['http', 'https', 'file', 'ftp'])) {
noteLinks[index] = {
type: 'url',
@@ -676,7 +691,7 @@ class AppGui {
return url;
}
return linkStyle(`${this.resourceServer_.baseUrl()}/${index}`);
return linkStyle(this.resourceServer_.baseUrl() + '/' + index);
},
};
}
@@ -695,7 +710,8 @@ class AppGui {
term.grabInput();
term.on('key', async (name) => {
term.on('key', async (name, matches, data) => {
// -------------------------------------------------------------------------
// Handle special shortcuts
// -------------------------------------------------------------------------
@@ -713,13 +729,13 @@ class AppGui {
return;
}
if (name === 'CTRL_C') {
if (name === 'CTRL_C' ) {
const cmd = this.app().currentCommand();
if (!cmd || !cmd.cancellable() || this.commandCancelCalled_) {
this.stdout(_('Press Ctrl+D or type "exit" to exit the application'));
} else {
this.commandCancelCalled_ = true;
await cmd.cancel();
await cmd.cancel()
this.commandCancelCalled_ = false;
}
return;
@@ -728,8 +744,8 @@ class AppGui {
// -------------------------------------------------------------------------
// Build up current shortcut
// -------------------------------------------------------------------------
const now = new Date().getTime();
const now = (new Date()).getTime();
if (now - this.lastShortcutKeyTime_ > 800 || this.isSpecialKey(name)) {
this.currentShortcutKeys_ = [name];
@@ -777,7 +793,7 @@ class AppGui {
} else if (keymapItem.type === 'tkwidgets') {
this.widget('root').handleKey(this.tkWidgetKeys_[keymapItem.command]);
} else {
throw new Error(`Unknown command type: ${JSON.stringify(keymapItem)}`);
throw new Error('Unknown command type: ' + JSON.stringify(keymapItem));
}
}
@@ -797,6 +813,7 @@ class AppGui {
process.exit(1);
});
}
}
AppGui.INPUT_MODE_NORMAL = 1;

View File

@@ -1,5 +1,10 @@
const { BaseApplication } = require('lib/BaseApplication');
const { createStore, applyMiddleware } = require('redux');
const { reducer, defaultState } = require('lib/reducer.js');
const { JoplinDatabase } = require('lib/joplin-database.js');
const { Database } = require('lib/database.js');
const { FoldersScreenUtils } = require('lib/folders-screen-utils.js');
const { DatabaseDriverNode } = require('lib/database-driver-node.js');
const ResourceService = require('lib/services/ResourceService');
const BaseModel = require('lib/BaseModel.js');
const Folder = require('lib/models/Folder.js');
@@ -7,15 +12,20 @@ const BaseItem = require('lib/models/BaseItem.js');
const Note = require('lib/models/Note.js');
const Tag = require('lib/models/Tag.js');
const Setting = require('lib/models/Setting.js');
const { Logger } = require('lib/logger.js');
const { sprintf } = require('sprintf-js');
const { reg } = require('lib/registry.js');
const { fileExtension } = require('lib/path-utils.js');
const { _ } = require('lib/locale.js');
const { shim } = require('lib/shim.js');
const { _, setLocale, defaultLocale, closestSupportedLocale } = require('lib/locale.js');
const os = require('os');
const fs = require('fs-extra');
const { cliUtils } = require('./cli-utils.js');
const EventEmitter = require('events');
const Cache = require('lib/Cache');
const RevisionService = require('lib/services/RevisionService');
class Application extends BaseApplication {
constructor() {
super();
@@ -64,7 +74,7 @@ class Application extends BaseApplication {
// const response = await cliUtils.promptMcq(msg, answers);
// if (!response) return null;
// return output[response - 1];
return output[response - 1];
} else {
return output.length ? output[0] : null;
}
@@ -86,12 +96,10 @@ class Application extends BaseApplication {
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 (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
} else { // Single item
let item = null;
if (type == BaseModel.TYPE_NOTE) {
if (!parent) throw new Error(_('No notebook has been specified.'));
@@ -117,15 +125,15 @@ class Application extends BaseApplication {
}
setupCommand(cmd) {
cmd.setStdout(text => {
cmd.setStdout((text) => {
return this.stdout(text);
});
cmd.setDispatcher(action => {
cmd.setDispatcher((action) => {
if (this.store()) {
return this.store().dispatch(action);
} else {
return () => {};
return (action) => {};
}
});
@@ -136,10 +144,10 @@ class Application extends BaseApplication {
if (!options.answers) options.answers = options.booleanAnswerDefault === 'y' ? [_('Y'), _('n')] : [_('N'), _('y')];
if (options.type == 'boolean') {
message += ` (${options.answers.join('/')})`;
message += ' (' + options.answers.join('/') + ')';
}
let answer = await this.gui().prompt('', `${message} `, options);
let answer = await this.gui().prompt('', message + ' ', options);
if (options.type === 'boolean') {
if (answer === null) return false; // Pressed ESCAPE
@@ -176,12 +184,12 @@ class Application extends BaseApplication {
commands(uiType = null) {
if (!this.allCommandsLoaded_) {
fs.readdirSync(__dirname).forEach(path => {
fs.readdirSync(__dirname).forEach((path) => {
if (path.indexOf('command-') !== 0) return;
const ext = fileExtension(path);
const ext = fileExtension(path)
if (ext != 'js') return;
let CommandClass = require(`./${path}`);
let CommandClass = require('./' + path);
let cmd = new CommandClass();
if (!cmd.enabled()) return;
cmd = this.setupCommand(cmd);
@@ -248,7 +256,7 @@ class Application extends BaseApplication {
let CommandClass = null;
try {
CommandClass = require(`${__dirname}/command-${name}.js`);
CommandClass = require(__dirname + '/command-' + name + '.js');
} catch (error) {
if (error.message && error.message.indexOf('Cannot find module') >= 0) {
let e = new Error(_('No such command: %s', name));
@@ -267,27 +275,19 @@ class Application extends BaseApplication {
dummyGui() {
return {
isDummy: () => {
return true;
},
prompt: (initialText = '', promptString = '', options = null) => {
return cliUtils.prompt(initialText, promptString, options);
},
isDummy: () => { return true; },
prompt: (initialText = '', promptString = '', options = null) => { return cliUtils.prompt(initialText, promptString, options); },
showConsole: () => {},
maximizeConsole: () => {},
stdout: text => {
console.info(text);
},
fullScreen: () => {},
stdout: (text) => { console.info(text); },
fullScreen: (b=true) => {},
exit: () => {},
showModalOverlay: () => {},
showModalOverlay: (text) => {},
hideModalOverlay: () => {},
stdoutMaxWidth: () => {
return 100;
},
stdoutMaxWidth: () => { return 100; },
forceRender: () => {},
termSaveState: () => {},
termRestoreState: () => {},
termRestoreState: (state) => {},
};
}
@@ -299,7 +299,7 @@ class Application extends BaseApplication {
let outException = null;
try {
if (this.gui().isDummy() && !this.activeCommand_.supportsUi('cli')) throw new Error(_('The command "%s" is only available in GUI mode', this.activeCommand_.name()));
if (this.gui().isDummy() && !this.activeCommand_.supportsUi('cli')) throw new Error(_('The command "%s" is only available in GUI mode', this.activeCommand_.name()));
const cmdArgs = cliUtils.makeCommandArgs(this.activeCommand_, argv);
await this.activeCommand_.action(cmdArgs);
} catch (error) {
@@ -315,24 +315,24 @@ class Application extends BaseApplication {
async loadKeymaps() {
const defaultKeyMap = [
{ keys: [':'], type: 'function', command: 'enter_command_line_mode' },
{ keys: ['TAB'], type: 'function', command: 'focus_next' },
{ keys: ['SHIFT_TAB'], type: 'function', command: 'focus_previous' },
{ keys: ['UP'], type: 'function', command: 'move_up' },
{ keys: ['DOWN'], type: 'function', command: 'move_down' },
{ keys: ['PAGE_UP'], type: 'function', command: 'page_up' },
{ keys: ['PAGE_DOWN'], type: 'function', command: 'page_down' },
{ keys: ['ENTER'], type: 'function', command: 'activate' },
{ keys: ['DELETE', 'BACKSPACE'], type: 'function', command: 'delete' },
{ keys: [' '], command: 'todo toggle $n' },
{ keys: ['tc'], type: 'function', command: 'toggle_console' },
{ keys: ['tm'], type: 'function', command: 'toggle_metadata' },
{ keys: ['/'], type: 'prompt', command: 'search ""', cursorPosition: -2 },
{ keys: ['mn'], type: 'prompt', command: 'mknote ""', cursorPosition: -2 },
{ keys: ['mt'], type: 'prompt', command: 'mktodo ""', cursorPosition: -2 },
{ keys: ['mb'], type: 'prompt', command: 'mkbook ""', cursorPosition: -2 },
{ keys: ['yn'], type: 'prompt', command: 'cp $n ""', cursorPosition: -2 },
{ keys: ['dn'], type: 'prompt', command: 'mv $n ""', cursorPosition: -2 },
{ "keys": [":"], "type": "function", "command": "enter_command_line_mode" },
{ "keys": ["TAB"], "type": "function", "command": "focus_next" },
{ "keys": ["SHIFT_TAB"], "type": "function", "command": "focus_previous" },
{ "keys": ["UP"], "type": "function", "command": "move_up" },
{ "keys": ["DOWN"], "type": "function", "command": "move_down" },
{ "keys": ["PAGE_UP"], "type": "function", "command": "page_up" },
{ "keys": ["PAGE_DOWN"], "type": "function", "command": "page_down" },
{ "keys": ["ENTER"], "type": "function", "command": "activate" },
{ "keys": ["DELETE", "BACKSPACE"], "type": "function", "command": "delete" },
{ "keys": [" "], "command": "todo toggle $n" },
{ "keys": ["tc"], "type": "function", "command": "toggle_console" },
{ "keys": ["tm"], "type": "function", "command": "toggle_metadata" },
{ "keys": ["/"], "type": "prompt", "command": "search \"\"", "cursorPosition": -2 },
{ "keys": ["mn"], "type": "prompt", "command": "mknote \"\"", "cursorPosition": -2 },
{ "keys": ["mt"], "type": "prompt", "command": "mktodo \"\"", "cursorPosition": -2 },
{ "keys": ["mb"], "type": "prompt", "command": "mkbook \"\"", "cursorPosition": -2 },
{ "keys": ["yn"], "type": "prompt", "command": "cp $n \"\"", "cursorPosition": -2 },
{ "keys": ["dn"], "type": "prompt", "command": "mv $n \"\"", "cursorPosition": -2 }
];
// Filter the keymap item by command so that items in keymap.json can override
@@ -340,10 +340,10 @@ class Application extends BaseApplication {
const itemsByCommand = {};
for (let i = 0; i < defaultKeyMap.length; i++) {
itemsByCommand[defaultKeyMap[i].command] = defaultKeyMap[i];
itemsByCommand[defaultKeyMap[i].command] = defaultKeyMap[i]
}
const filePath = `${Setting.value('profileDir')}/keymap.json`;
const filePath = Setting.value('profileDir') + '/keymap.json';
if (await fs.pathExists(filePath)) {
try {
let configString = await fs.readFile(filePath, 'utf-8');
@@ -355,7 +355,7 @@ class Application extends BaseApplication {
}
} catch (error) {
let msg = error.message ? error.message : '';
msg = `Could not load keymap ${filePath}\n${msg}`;
msg = 'Could not load keymap ' + filePath + '\n' + msg;
error.message = msg;
throw error;
}
@@ -373,7 +373,7 @@ class Application extends BaseApplication {
async start(argv) {
argv = await super.start(argv);
cliUtils.setStdout(object => {
cliUtils.setStdout((object) => {
return this.stdout(object);
});
@@ -384,8 +384,6 @@ class Application extends BaseApplication {
this.currentFolder_ = await Folder.load(Setting.value('activeFolderId'));
await this.applySettingsSideEffects();
try {
await this.execCommand(argv);
} catch (error) {
@@ -396,14 +394,7 @@ class Application extends BaseApplication {
}
process.exit(1);
}
await Setting.saveAll();
// Need to call exit() explicitely, otherwise Node wait for any timeout to complete
// https://stackoverflow.com/questions/18050095
process.exit(0);
} else {
// Otherwise open the GUI
} else { // Otherwise open the GUI
this.initRedux();
const keymap = await this.loadKeymaps();
@@ -424,8 +415,6 @@ class Application extends BaseApplication {
ResourceService.runInBackground();
RevisionService.instance().runInBackground();
this.dispatch({
type: 'TAG_UPDATE_ALL',
items: tags,
@@ -437,6 +426,7 @@ class Application extends BaseApplication {
});
}
}
}
let application_ = null;
@@ -447,4 +437,4 @@ function app() {
return application_;
}
module.exports = { app };
module.exports = { app };

View File

@@ -10,42 +10,42 @@ async function handleAutocompletionPromise(line) {
// Auto-complete the command name
const names = await app().commandNames();
let words = getArguments(line);
// If there is only one word and it is not already a command name then you
// should look for commmands it could be
//If there is only one word and it is not already a command name then you
//should look for commmands it could be
if (words.length == 1) {
if (names.indexOf(words[0]) === -1) {
let x = names.filter(n => n.indexOf(words[0]) === 0);
let x = names.filter((n) => n.indexOf(words[0]) === 0);
if (x.length === 1) {
return `${x[0]} `;
return x[0] + ' ';
}
return x.length > 0 ? x.map(a => `${a} `) : line;
return x.length > 0 ? x.map((a) => a + ' ') : line;
} else {
return line;
}
}
// There is more than one word and it is a command
//There is more than one word and it is a command
const metadata = (await app().commandMetadata())[words[0]];
// If for some reason this command does not have any associated metadata
// just don't autocomplete. However, this should not happen.
//If for some reason this command does not have any associated metadata
//just don't autocomplete. However, this should not happen.
if (metadata === undefined) {
return line;
}
// complete an option
//complete an option
let next = words.length > 1 ? words[words.length - 1] : '';
let l = [];
if (next[0] === '-') {
for (let i = 0; i < metadata.options.length; i++) {
for (let i = 0; i<metadata.options.length; i++) {
const options = metadata.options[i][0].split(' ');
// if there are multiple options then they will be separated by comma and
// space. The comma should be removed
//if there are multiple options then they will be separated by comma and
//space. The comma should be removed
if (options[0][options[0].length - 1] === ',') {
options[0] = options[0].slice(0, -1);
}
if (words.includes(options[0]) || words.includes(options[1])) {
continue;
}
// First two elements are the flag and the third is the description
// Only autocomplete long
//First two elements are the flag and the third is the description
//Only autocomplete long
if (options.length > 1 && options[1].indexOf(next) === 0) {
l.push(options[1]);
} else if (options[0].indexOf(next) === 0) {
@@ -55,43 +55,44 @@ async function handleAutocompletionPromise(line) {
if (l.length === 0) {
return line;
}
let ret = l.map(a => toCommandLine(a));
ret.prefix = `${toCommandLine(words.slice(0, -1))} `;
let ret = l.map(a=>toCommandLine(a));
ret.prefix = toCommandLine(words.slice(0, -1)) + ' ';
return ret;
}
// Complete an argument
// Determine the number of positional arguments by counting the number of
// words that don't start with a - less one for the command name
const positionalArgs = words.filter(a => a.indexOf('-') !== 0).length - 1;
//Complete an argument
//Determine the number of positional arguments by counting the number of
//words that don't start with a - less one for the command name
const positionalArgs = words.filter((a)=>a.indexOf('-') !== 0).length - 1;
let cmdUsage = yargParser(metadata.usage)['_'];
cmdUsage.splice(0, 1);
if (cmdUsage.length >= positionalArgs) {
let argName = cmdUsage[positionalArgs - 1];
argName = cliUtils.parseCommandArg(argName).name;
const currentFolder = app().currentFolder();
if (argName == 'note' || argName == 'note-pattern') {
const notes = currentFolder ? await Note.previews(currentFolder.id, { titlePattern: `${next}*` }) : [];
l.push(...notes.map(n => n.title));
const notes = currentFolder ? await Note.previews(currentFolder.id, { titlePattern: next + '*' }) : [];
l.push(...notes.map((n) => n.title));
}
if (argName == 'notebook') {
const folders = await Folder.search({ titlePattern: `${next}*` });
l.push(...folders.map(n => n.title));
const folders = await Folder.search({ titlePattern: next + '*' });
l.push(...folders.map((n) => n.title));
}
if (argName == 'item') {
const notes = currentFolder ? await Note.previews(currentFolder.id, { titlePattern: `${next}*` }) : [];
const folders = await Folder.search({ titlePattern: `${next}*` });
l.push(...notes.map(n => n.title), folders.map(n => n.title));
const notes = currentFolder ? await Note.previews(currentFolder.id, { titlePattern: next + '*' }) : [];
const folders = await Folder.search({ titlePattern: next + '*' });
l.push(...notes.map((n) => n.title), folders.map((n) => n.title));
}
if (argName == 'tag') {
let tags = await Tag.search({ titlePattern: `${next}*` });
l.push(...tags.map(n => n.title));
let tags = await Tag.search({ titlePattern: next + '*' });
l.push(...tags.map((n) => n.title));
}
if (argName == 'file') {
@@ -112,11 +113,12 @@ async function handleAutocompletionPromise(line) {
if (l.length === 1) {
return toCommandLine([...words.slice(0, -1), l[0]]);
} else if (l.length > 1) {
let ret = l.map(a => toCommandLine(a));
ret.prefix = `${toCommandLine(words.slice(0, -1))} `;
let ret = l.map(a=>toCommandLine(a));
ret.prefix = toCommandLine(words.slice(0, -1)) + ' ';
return ret;
}
return line;
}
function handleAutocompletion(str, callback) {
handleAutocompletionPromise(str).then(function(res) {
@@ -125,24 +127,22 @@ function handleAutocompletion(str, callback) {
}
function toCommandLine(args) {
if (Array.isArray(args)) {
return args
.map(function(a) {
if (a.indexOf('"') !== -1 || a.indexOf(' ') !== -1) {
return `'${a}'`;
} else if (a.indexOf('\'') !== -1) {
return `"${a}"`;
} else {
return a;
}
})
.join(' ');
return args.map(function(a) {
if(a.indexOf('"') !== -1 || a.indexOf(' ') !== -1) {
return "'" + a + "'";
} else if (a.indexOf("'") !== -1) {
return '"' + a + '"';
} else {
return a;
}
}).join(' ');
} else {
if (args.indexOf('"') !== -1 || args.indexOf(' ') !== -1) {
return `'${args}' `;
} else if (args.indexOf('\'') !== -1) {
return `"${args}" `;
if(args.indexOf('"') !== -1 || args.indexOf(' ') !== -1) {
return "'" + args + "' ";
} else if (args.indexOf("'") !== -1) {
return '"' + args + '" ';
} else {
return `${args} `;
return args + ' ';
}
}
}
@@ -151,26 +151,27 @@ function getArguments(line) {
let inDoubleQuotes = false;
let currentWord = '';
let parsed = [];
for (let i = 0; i < line.length; i++) {
if (line[i] === '"') {
if (inDoubleQuotes) {
for(let i = 0; i<line.length; i++) {
if(line[i] === '"') {
if(inDoubleQuotes) {
inDoubleQuotes = false;
// maybe push word to parsed?
// currentWord += '"';
//maybe push word to parsed?
//currentWord += '"';
} else {
inDoubleQuotes = true;
// currentWord += '"';
//currentWord += '"';
}
} else if (line[i] === '\'') {
if (inSingleQuotes) {
} else if(line[i] === "'") {
if(inSingleQuotes) {
inSingleQuotes = false;
// maybe push word to parsed?
// currentWord += "'";
//maybe push word to parsed?
//currentWord += "'";
} else {
inSingleQuotes = true;
// currentWord += "'";
//currentWord += "'";
}
} else if (/\s/.test(line[i]) && !(inDoubleQuotes || inSingleQuotes)) {
} else if (/\s/.test(line[i]) &&
!(inDoubleQuotes || inSingleQuotes)) {
if (currentWord !== '') {
parsed.push(currentWord);
currentWord = '';

View File

@@ -2,6 +2,7 @@ const { _ } = require('lib/locale.js');
const { reg } = require('lib/registry.js');
class BaseCommand {
constructor() {
this.stdout_ = null;
this.prompt_ = null;
@@ -19,7 +20,7 @@ class BaseCommand {
throw new Error('Description not defined');
}
async action() {
async action(args) {
throw new Error('Action not defined');
}
@@ -92,6 +93,7 @@ class BaseCommand {
logger() {
return reg.logger();
}
}
module.exports = { BaseCommand };
module.exports = { BaseCommand };

View File

@@ -1,7 +1,7 @@
const fs = require('fs-extra');
const { fileExtension, dirname } = require('lib/path-utils.js');
const { fileExtension, basename, dirname } = require('lib/path-utils.js');
const wrap_ = require('word-wrap');
const { languageCode } = require('lib/locale.js');
const { _, setLocale, languageCode } = require('lib/locale.js');
const rootDir = dirname(dirname(__dirname));
const MAX_WIDTH = 78;
@@ -22,14 +22,14 @@ function renderOptions(options) {
let option = options[i];
const flag = option[0];
const indent = INDENT + INDENT + ' '.repeat(optionColWidth + 2);
let r = wrap(option[1], indent);
r = r.substr(flag.length + (INDENT + INDENT).length);
r = INDENT + INDENT + flag + r;
output.push(r);
}
return output.join('\n');
return output.join("\n");
}
function renderCommand(cmd) {
@@ -44,17 +44,17 @@ function renderCommand(cmd) {
output.push('');
output.push(optionString);
}
return output.join('\n');
return output.join("\n");
}
function getCommands() {
let output = [];
fs.readdirSync(__dirname).forEach(path => {
fs.readdirSync(__dirname).forEach((path) => {
if (path.indexOf('command-') !== 0) return;
const ext = fileExtension(path);
const ext = fileExtension(path)
if (ext != 'js') return;
let CommandClass = require(`./${path}`);
let CommandClass = require('./' + path);
let cmd = new CommandClass();
if (!cmd.enabled()) return;
if (cmd.hidden()) return;
@@ -87,14 +87,14 @@ function getHeader() {
let description = [];
description.push('Joplin is a note taking and to-do application, which can handle a large number of notes organised into notebooks.');
description.push('The notes are searchable, can be copied, tagged and modified with your own text editor.');
description.push('\n\n');
description.push("\n\n");
description.push('The notes can be synchronised with various target including the file system (for example with a network directory) or with Microsoft OneDrive.');
description.push('\n\n');
description.push("\n\n");
description.push('Notes exported from Evenotes via .enex files can be imported into Joplin, including the formatted content, resources (images, attachments, etc.) and complete metadata (geolocation, updated time, created time, etc.).');
output.push(wrap(description.join(''), INDENT));
return output.join('\n');
return output.join("\n");
}
function getFooter() {
@@ -102,18 +102,18 @@ function getFooter() {
output.push('WEBSITE');
output.push('');
output.push(`${INDENT}https://joplinapp.org`);
output.push(INDENT + 'https://joplin.cozic.net');
output.push('');
output.push('LICENSE');
output.push('');
let filePath = `${rootDir}/LICENSE_${languageCode()}`;
if (!fs.existsSync(filePath)) filePath = `${rootDir}/LICENSE`;
let filePath = rootDir + '/LICENSE_' + languageCode();
if (!fs.existsSync(filePath)) filePath = rootDir + '/LICENSE';
const licenseText = fs.readFileSync(filePath, 'utf8');
output.push(wrap(licenseText, INDENT));
return output.join('\n');
return output.join("\n");
}
async function main() {
@@ -128,12 +128,12 @@ async function main() {
}
const headerText = getHeader();
const commandsText = commandBlocks.join('\n\n');
const commandsText = commandBlocks.join("\n\n");
const footerText = getFooter();
console.info(`${headerText}\n\n` + 'USAGE' + `\n\n${commandsText}\n\n${footerText}`);
console.info(headerText + "\n\n" + 'USAGE' + "\n\n" + commandsText + "\n\n" + footerText);
}
main().catch(error => {
main().catch((error) => {
console.error(error);
});
});

View File

@@ -1,4 +1,4 @@
'use strict';
"use strict"
const fs = require('fs-extra');
const { Logger } = require('lib/logger.js');
@@ -10,14 +10,14 @@ const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const Setting = require('lib/models/Setting.js');
const { sprintf } = require('sprintf-js');
const exec = require('child_process').exec;
const exec = require('child_process').exec
process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled promise rejection', p, 'reason:', reason);
});
const baseDir = `${dirname(__dirname)}/tests/cli-integration`;
const joplinAppPath = `${__dirname}/main.js`;
const baseDir = dirname(__dirname) + '/tests/cli-integration';
const joplinAppPath = __dirname + '/main.js';
const logger = new Logger();
logger.addTarget('console');
@@ -32,17 +32,17 @@ db.setLogger(dbLogger);
function createClient(id) {
return {
id: id,
profileDir: `${baseDir}/client${id}`,
'id': id,
'profileDir': baseDir + '/client' + id,
};
}
const client = createClient(1);
function execCommand(client, command) {
let exePath = `node ${joplinAppPath}`;
let cmd = `${exePath} --update-geolocation-disabled --env dev --profile ${client.profileDir} ${command}`;
logger.info(`${client.id}: ${command}`);
function execCommand(client, command, options = {}) {
let exePath = 'node ' + joplinAppPath;
let cmd = exePath + ' --update-geolocation-disabled --env dev --profile ' + client.profileDir + ' ' + command;
logger.info(client.id + ': ' + command);
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
@@ -72,7 +72,14 @@ function assertEquals(expected, real) {
}
async function clearDatabase() {
await db.transactionExecBatch(['DELETE FROM folders', 'DELETE FROM notes', 'DELETE FROM tags', 'DELETE FROM note_tags', 'DELETE FROM resources', 'DELETE FROM deleted_items']);
await db.transactionExecBatch([
'DELETE FROM folders',
'DELETE FROM notes',
'DELETE FROM tags',
'DELETE FROM note_tags',
'DELETE FROM resources',
'DELETE FROM deleted_items',
]);
}
const testUnits = {};
@@ -94,7 +101,7 @@ testUnits.testFolders = async () => {
folders = await Folder.all();
assertEquals(0, folders.length);
};
}
testUnits.testNotes = async () => {
await execCommand(client, 'mkbook nb1');
@@ -114,16 +121,16 @@ testUnits.testNotes = async () => {
notes = await Note.all();
assertEquals(2, notes.length);
await execCommand(client, 'rm -f \'blabla*\'');
await execCommand(client, "rm -f 'blabla*'");
notes = await Note.all();
assertEquals(2, notes.length);
await execCommand(client, 'rm -f \'n*\'');
await execCommand(client, "rm -f 'n*'");
notes = await Note.all();
assertEquals(0, notes.length);
};
}
testUnits.testCat = async () => {
await execCommand(client, 'mkbook nb1');
@@ -138,7 +145,7 @@ testUnits.testCat = async () => {
r = await execCommand(client, 'cat -v mynote');
assertTrue(r.indexOf(note.id) >= 0);
};
}
testUnits.testConfig = async () => {
await execCommand(client, 'config editor vim');
@@ -152,7 +159,7 @@ testUnits.testConfig = async () => {
let r = await execCommand(client, 'config');
assertTrue(r.indexOf('editor') >= 0);
assertTrue(r.indexOf('subl') >= 0);
};
}
testUnits.testCp = async () => {
await execCommand(client, 'mkbook nb2');
@@ -173,7 +180,7 @@ testUnits.testCp = async () => {
notes = await Note.previews(f2.id);
assertEquals(1, notes.length);
assertEquals(notesF1[0].title, notes[0].title);
};
}
testUnits.testLs = async () => {
await execCommand(client, 'mkbook nb1');
@@ -183,7 +190,7 @@ testUnits.testLs = async () => {
assertTrue(r.indexOf('note1') >= 0);
assertTrue(r.indexOf('note2') >= 0);
};
}
testUnits.testMv = async () => {
await execCommand(client, 'mkbook nb2');
@@ -203,21 +210,21 @@ testUnits.testMv = async () => {
await execCommand(client, 'mknote note2');
await execCommand(client, 'mknote note3');
await execCommand(client, 'mknote blabla');
await execCommand(client, 'mv \'note*\' nb2');
await execCommand(client, "mv 'note*' nb2");
notes1 = await Note.previews(f1.id);
notes2 = await Note.previews(f2.id);
assertEquals(1, notes1.length);
assertEquals(4, notes2.length);
};
}
async function main() {
async function main(argv) {
await fs.remove(baseDir);
logger.info(await execCommand(client, 'version'));
await db.open({ name: `${client.profileDir}/database.sqlite` });
await db.open({ name: client.profileDir + '/database.sqlite' });
BaseModel.db_ = db;
await Setting.load();
@@ -230,13 +237,13 @@ async function main() {
await clearDatabase();
let testName = n.substr(4).toLowerCase();
process.stdout.write(`${testName}: `);
process.stdout.write(testName + ': ');
await testUnits[n]();
console.info('');
}
}
main(process.argv).catch(error => {
main(process.argv).catch((error) => {
console.info('');
logger.error(error);
});
});

View File

@@ -5,7 +5,7 @@ const stringPadding = require('string-padding');
const cliUtils = {};
cliUtils.printArray = function(logFunction, rows) {
cliUtils.printArray = function(logFunction, rows, headers = null) {
if (!rows.length) return '';
const ALIGN_LEFT = 0;
@@ -16,7 +16,7 @@ cliUtils.printArray = function(logFunction, rows) {
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
for (let j = 0; j < row.length; j++) {
let item = row[j];
let width = item ? item.toString().length : 0;
@@ -26,6 +26,7 @@ cliUtils.printArray = function(logFunction, rows) {
}
}
let lines = [];
for (let row = 0; row < rows.length; row++) {
let line = [];
for (let col = 0; col < colWidths.length; col++) {
@@ -36,7 +37,7 @@ cliUtils.printArray = function(logFunction, rows) {
}
logFunction(line.join(' '));
}
};
}
cliUtils.parseFlags = function(flags) {
let output = {};
@@ -55,10 +56,10 @@ cliUtils.parseFlags = function(flags) {
}
}
return output;
};
}
cliUtils.parseCommandArg = function(arg) {
if (arg.length <= 2) throw new Error(`Invalid command arg: ${arg}`);
if (arg.length <= 2) throw new Error('Invalid command arg: ' + arg);
const c1 = arg[0];
const c2 = arg[arg.length - 1];
@@ -69,9 +70,9 @@ cliUtils.parseCommandArg = function(arg) {
} else if (c1 == '[' && c2 == ']') {
return { required: false, name: name };
} else {
throw new Error(`Invalid command arg: ${arg}`);
throw new Error('Invalid command arg: ' + arg);
}
};
}
cliUtils.makeCommandArgs = function(cmd, argv) {
let cmdUsage = cmd.usage();
@@ -82,8 +83,9 @@ cliUtils.makeCommandArgs = function(cmd, argv) {
let booleanFlags = [];
let aliases = {};
for (let i = 0; i < options.length; i++) {
if (options[i].length != 2) throw new Error(`Invalid options: ${options[i]}`);
if (options[i].length != 2) throw new Error('Invalid options: ' + options[i]);
let flags = options[i][0];
let text = options[i][1];
flags = cliUtils.parseFlags(flags);
@@ -123,27 +125,27 @@ cliUtils.makeCommandArgs = function(cmd, argv) {
output.options = argOptions;
return output;
};
}
cliUtils.promptMcq = function(message, answers) {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
output: process.stdout
});
message += '\n\n';
message += "\n\n";
for (let n in answers) {
if (!answers.hasOwnProperty(n)) continue;
message += `${_('%s: %s', n, answers[n])}\n`;
message += _('%s: %s', n, answers[n]) + "\n";
}
message += '\n';
message += "\n";
message += _('Your choice: ');
return new Promise((resolve, reject) => {
rl.question(message, answer => {
rl.question(message, (answer) => {
rl.close();
if (!(answer in answers)) {
@@ -154,7 +156,7 @@ cliUtils.promptMcq = function(message, answers) {
resolve(answer);
});
});
};
}
cliUtils.promptConfirm = function(message, answers = null) {
if (!answers) answers = [_('Y'), _('n')];
@@ -162,24 +164,23 @@ cliUtils.promptConfirm = function(message, answers = null) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
output: process.stdout
});
message += ` (${answers.join('/')})`;
message += ' (' + answers.join('/') + ')';
return new Promise((resolve) => {
rl.question(`${message} `, answer => {
return new Promise((resolve, reject) => {
rl.question(message + ' ', (answer) => {
const ok = !answer || answer.toLowerCase() == answers[0].toLowerCase();
rl.close();
resolve(ok);
});
});
};
}
// Note: initialText is there to have the same signature as statusBar.prompt() so that
// it can be a drop-in replacement, however initialText is not used (and cannot be
// with readline.question?).
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
cliUtils.prompt = function(initialText = '', promptString = ':', options = null) {
if (!options) options = {};
@@ -188,9 +189,10 @@ cliUtils.prompt = function(initialText = '', promptString = ':', options = null)
const mutableStdout = new Writable({
write: function(chunk, encoding, callback) {
if (!this.muted) process.stdout.write(chunk, encoding);
if (!this.muted)
process.stdout.write(chunk, encoding);
callback();
},
}
});
const rl = readline.createInterface({
@@ -199,18 +201,18 @@ cliUtils.prompt = function(initialText = '', promptString = ':', options = null)
terminal: true,
});
return new Promise((resolve) => {
return new Promise((resolve, reject) => {
mutableStdout.muted = false;
rl.question(promptString, answer => {
rl.question(promptString, (answer) => {
rl.close();
if (options.secure) this.stdout_('');
if (!!options.secure) this.stdout_('');
resolve(answer);
});
mutableStdout.muted = !!options.secure;
});
};
}
let redrawStarted_ = false;
let redrawLastLog_ = null;
@@ -218,7 +220,7 @@ let redrawLastUpdateTime_ = 0;
cliUtils.setStdout = function(v) {
this.stdout_ = v;
};
}
cliUtils.redraw = function(s) {
const now = time.unixMs();
@@ -231,8 +233,8 @@ cliUtils.redraw = function(s) {
redrawLastLog_ = s;
}
redrawStarted_ = true;
};
redrawStarted_ = true;
}
cliUtils.redrawDone = function() {
if (!redrawStarted_) return;
@@ -243,6 +245,6 @@ cliUtils.redrawDone = function() {
redrawLastLog_ = null;
redrawStarted_ = false;
};
}
module.exports = { cliUtils };
module.exports = { cliUtils };

View File

@@ -1,300 +0,0 @@
const { BaseCommand } = require('./base-command.js');
const BaseItem = require('lib/models/BaseItem');
const BaseModel = require('lib/BaseModel');
const { toTitleCase } = require('lib/string-utils.js');
const { reg } = require('lib/registry.js');
const markdownUtils = require('lib/markdownUtils');
const { Database } = require('lib/database.js');
class Command extends BaseCommand {
usage() {
return 'apidoc';
}
description() {
return 'Build the API doc';
}
createPropertiesTable(tableFields) {
const headers = [
{ name: 'name', label: 'Name' },
{
name: 'type',
label: 'Type',
filter: value => {
return Database.enumName('fieldType', value);
},
},
{ name: 'description', label: 'Description' },
];
return markdownUtils.createMarkdownTable(headers, tableFields);
}
async action() {
const models = [
{
type: BaseModel.TYPE_NOTE,
},
{
type: BaseModel.TYPE_FOLDER,
},
{
type: BaseModel.TYPE_RESOURCE,
},
{
type: BaseModel.TYPE_TAG,
},
];
const lines = [];
lines.push('# Joplin API');
lines.push('');
lines.push('When the Web Clipper service is enabled, Joplin exposes a [REST API](https://en.wikipedia.org/wiki/Representational_state_transfer) which allows third-party applications to access Joplin\'s data and to create, modify or delete notes, notebooks, resources or tags.');
lines.push('');
lines.push('In order to use it, you\'ll first need to find on which port the service is running. To do so, open the Web Clipper Options in Joplin and if the service is running it should tell you on which port. Normally it runs on port **41184**. If you want to find it programmatically, you may follow this kind of algorithm:');
lines.push('');
lines.push('```javascript');
lines.push('let port = null;');
lines.push('for (let portToTest = 41184; portToTest <= 41194; portToTest++) {');
lines.push(' const result = pingPort(portToTest); // Call GET /ping');
lines.push(' if (result == \'JoplinClipperServer\') {');
lines.push(' port = portToTest; // Found the port');
lines.push(' break;');
lines.push(' }');
lines.push('}');
lines.push('```');
lines.push('');
lines.push('# Authorisation');
lines.push('');
lines.push('To prevent unauthorised applications from accessing the API, the calls must be authentified. To do so, you must provide a token as a query parameter for each API call. You can get this token from the Joplin desktop application, on the Web Clipper Options screen.');
lines.push('');
lines.push('This would be an example of valid cURL call using a token:');
lines.push('');
lines.push('\tcurl http://localhost:41184/notes?token=ABCD123ABCD123ABCD123ABCD123ABCD123');
lines.push('');
lines.push('In the documentation below, the token will not be specified every time however you will need to include it.');
lines.push('');
lines.push('# Using the API');
lines.push('');
lines.push('All the calls, unless noted otherwise, receives and send **JSON data**. For example to create a new note:');
lines.push('');
lines.push('\tcurl --data \'{ "title": "My note", "body": "Some note in **Markdown**"}\' http://localhost:41184/notes');
lines.push('');
lines.push('In the documentation below, the calls may include special parameters such as :id or :note_id. You would replace this with the item ID or note ID.');
lines.push('');
lines.push('For example, for the endpoint `DELETE /tags/:id/notes/:note_id`, to remove the tag with ID "ABCD1234" from the note with ID "EFGH789", you would run for example:');
lines.push('');
lines.push('\tcurl -X DELETE http://localhost:41184/tags/ABCD1234/notes/EFGH789');
lines.push('');
lines.push('The four verbs supported by the API are the following ones:');
lines.push('');
lines.push('* **GET**: To retrieve items (notes, notebooks, etc.).');
lines.push('* **POST**: To create new items. In general most item properties are optional. If you omit any, a default value will be used.');
lines.push('* **PUT**: To update an item. Note in a REST API, traditionally PUT is used to completely replace an item, however in this API it will only replace the properties that are provided. For example if you PUT {"title": "my new title"}, only the "title" property will be changed. The other properties will be left untouched (they won\'t be cleared nor changed).');
lines.push('* **DELETE**: To delete items.');
lines.push('');
lines.push('# Filtering data');
lines.push('');
lines.push('You can change the fields that will be returned by the API using the `fields=` query parameter, which takes a list of comma separated fields. For example, to get the longitude and latitude of a note, use this:');
lines.push('');
lines.push('\tcurl http://localhost:41184/notes/ABCD123?fields=longitude,latitude');
lines.push('');
lines.push('To get the IDs only of all the tags:');
lines.push('');
lines.push('\tcurl http://localhost:41184/tags?fields=id');
lines.push('');
lines.push('# Error handling');
lines.push('');
lines.push('In case of an error, an HTTP status code >= 400 will be returned along with a JSON object that provides more info about the error. The JSON object is in the format `{ "error": "description of error" }`.');
lines.push('');
lines.push('# About the property types');
lines.push('');
lines.push('* Text is UTF-8.');
lines.push('* All date/time are Unix timestamps in milliseconds.');
lines.push('* Booleans are integer values 0 or 1.');
lines.push('');
lines.push('# Testing if the service is available');
lines.push('');
lines.push('Call **GET /ping** to check if the service is available. It should return "JoplinClipperServer" if it works.');
lines.push('');
lines.push('# Searching');
lines.push('');
lines.push('Call **GET /search?query=YOUR_QUERY** to search for notes. This end-point supports the `field` parameter which is recommended to use so that you only get the data that you need. The query syntax is as described in the main documentation: https://joplinapp.org/#searching');
lines.push('');
for (let i = 0; i < models.length; i++) {
const model = models[i];
const ModelClass = BaseItem.getClassByItemType(model.type);
const tableName = ModelClass.tableName();
let tableFields = reg.db().tableFields(tableName, { includeDescription: true });
const singular = tableName.substr(0, tableName.length - 1);
if (model.type === BaseModel.TYPE_NOTE) {
tableFields = tableFields.slice();
tableFields.push({
name: 'body_html',
type: Database.enumId('fieldType', 'text'),
description: 'Note body, in HTML format',
});
tableFields.push({
name: 'base_url',
type: Database.enumId('fieldType', 'text'),
description: 'If `body_html` is provided and contains relative URLs, provide the `base_url` parameter too so that all the URLs can be converted to absolute ones. The base URL is basically where the HTML was fetched from, minus the query (everything after the \'?\'). For example if the original page was `https://stackoverflow.com/search?q=%5Bjava%5D+test`, the base URL is `https://stackoverflow.com/search`.',
});
tableFields.push({
name: 'image_data_url',
type: Database.enumId('fieldType', 'text'),
description: 'An image to attach to the note, in [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) format.',
});
tableFields.push({
name: 'crop_rect',
type: Database.enumId('fieldType', 'text'),
description: 'If an image is provided, you can also specify an optional rectangle that will be used to crop the image. In format `{ x: x, y: y, width: width, height: height }`',
});
// tableFields.push({
// name: 'tags',
// type: Database.enumId('fieldType', 'text'),
// description: 'Comma-separated list of tags. eg. `tag1,tag2`.',
// });
}
lines.push(`# ${toTitleCase(tableName)}`);
lines.push('');
if (model.type === BaseModel.TYPE_FOLDER) {
lines.push('This is actually a notebook. Internally notebooks are called "folders".');
lines.push('');
}
lines.push('## Properties');
lines.push('');
lines.push(this.createPropertiesTable(tableFields));
lines.push('');
lines.push(`## GET /${tableName}`);
lines.push('');
lines.push(`Gets all ${tableName}`);
lines.push('');
if (model.type === BaseModel.TYPE_FOLDER) {
lines.push('The folders are returned as a tree. The sub-notebooks of a notebook, if any, are under the `children` key.');
lines.push('');
}
lines.push(`## GET /${tableName}/:id`);
lines.push('');
lines.push(`Gets ${singular} with ID :id`);
lines.push('');
if (model.type === BaseModel.TYPE_TAG) {
lines.push('## GET /tags/:id/notes');
lines.push('');
lines.push('Gets all the notes with this tag.');
lines.push('');
}
if (model.type === BaseModel.TYPE_NOTE) {
lines.push('## GET /notes/:id/tags');
lines.push('');
lines.push('Gets all the tags attached to this note.');
lines.push('');
lines.push('## GET /notes/:id/resources');
lines.push('');
lines.push('Gets all the resources attached to this note.');
lines.push('');
}
if (model.type === BaseModel.TYPE_FOLDER) {
lines.push('## GET /folders/:id/notes');
lines.push('');
lines.push('Gets all the notes inside this folder.');
lines.push('');
}
if (model.type === BaseModel.TYPE_RESOURCE) {
lines.push('## GET /resources/:id/file');
lines.push('');
lines.push('Gets the actual file associated with this resource.');
lines.push('');
}
lines.push(`## POST /${tableName}`);
lines.push('');
lines.push(`Creates a new ${singular}`);
lines.push('');
if (model.type === BaseModel.TYPE_RESOURCE) {
lines.push('Creating a new resource is special because you also need to upload the file. Unlike other API calls, this one must have the "multipart/form-data" Content-Type. The file data must be passed to the "data" form field, and the other properties to the "props" form field. An example of a valid call with cURL would be:');
lines.push('');
lines.push('\tcurl -F \'data=@/path/to/file.jpg\' -F \'props={"title":"my resource title"}\' http://localhost:41184/resources');
lines.push('');
lines.push('The "data" field is required, while the "props" one is not. If not specified, default values will be used.');
lines.push('');
}
if (model.type === BaseModel.TYPE_TAG) {
lines.push('## POST /tags/:id/notes');
lines.push('');
lines.push('Post a note to this endpoint to add the tag to the note. The note data must at least contain an ID property (all other properties will be ignored).');
lines.push('');
}
if (model.type === BaseModel.TYPE_NOTE) {
lines.push('You can either specify the note body as Markdown by setting the `body` parameter, or in HTML by setting the `body_html`.');
lines.push('');
lines.push('Examples:');
lines.push('');
lines.push('* Create a note from some Markdown text');
lines.push('');
lines.push(' curl --data \'{ "title": "My note", "body": "Some note in **Markdown**"}\' http://127.0.0.1:41184/notes');
lines.push('');
lines.push('* Create a note from some HTML');
lines.push('');
lines.push(' curl --data \'{ "title": "My note", "body_html": "Some note in <b>HTML</b>"}\' http://127.0.0.1:41184/notes');
lines.push('');
lines.push('* Create a note and attach an image to it:');
lines.push('');
lines.push(' curl --data \'{ "title": "Image test", "body": "Here is Joplin icon:", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAANZJREFUeNoAyAA3/wFwtO3K6gUB/vz2+Prw9fj/+/r+/wBZKAAExOgF4/MC9ff+MRH6Ui4E+/0Bqc/zutj6AgT+/Pz7+vv7++nu82c4DlMqCvLs8goA/gL8/fz09fb59vXa6vzZ6vjT5fbn6voD/fwC8vX4UiT9Zi//APHyAP8ACgUBAPv5APz7BPj2+DIaC2o3E+3o6ywaC5fT6gD6/QD9/QEVf9kD+/dcLQgJA/7v8vqfwOf18wA1IAIEVycAyt//v9XvAPv7APz8LhoIAPz9Ri4OAgwARgx4W/6fVeEAAAAASUVORK5CYII="}\' http://127.0.0.1:41184/notes');
lines.push('');
lines.push('### Creating a note with a specific ID');
lines.push('');
lines.push('When a new note is created, it is automatically assigned a new unique ID so **normally you do not need to set the ID**. However, if for some reason you want to set it, you can supply it as the `id` property. It needs to be a 32 characters long hexadecimal string. **Make sure it is unique**, for example by generating it using whatever GUID function is available in your programming language.');
lines.push('');
lines.push(' curl --data \'{ "id": "00a87474082744c1a8515da6aa5792d2", "title": "My note with custom ID"}\' http://127.0.0.1:41184/notes');
lines.push('');
}
lines.push(`## PUT /${tableName}/:id`);
lines.push('');
lines.push(`Sets the properties of the ${singular} with ID :id`);
lines.push('');
lines.push(`## DELETE /${tableName}/:id`);
lines.push('');
lines.push(`Deletes the ${singular} with ID :id`);
lines.push('');
if (model.type === BaseModel.TYPE_TAG) {
lines.push('## DELETE /tags/:id/notes/:note_id');
lines.push('');
lines.push('Remove the tag from the note.');
lines.push('');
}
}
this.stdout(lines.join('\n'));
}
}
module.exports = Command;

View File

@@ -3,8 +3,10 @@ const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const { shim } = require('lib/shim.js');
const fs = require('fs-extra');
class Command extends BaseCommand {
usage() {
return 'attach <note> <file>';
}
@@ -24,6 +26,7 @@ class Command extends BaseCommand {
await shim.attachFileToNote(note, localFilePath);
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -2,9 +2,11 @@ const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
class Command extends BaseCommand {
usage() {
return 'cat <note>';
}
@@ -14,7 +16,9 @@ class Command extends BaseCommand {
}
options() {
return [['-v, --verbose', _('Displays the complete information about note.')]];
return [
['-v, --verbose', _('Displays the complete information about note.')],
];
}
async action(args) {
@@ -26,13 +30,10 @@ class Command extends BaseCommand {
const content = args.options.verbose ? await Note.serialize(item) : await Note.serializeForEdit(item);
this.stdout(content);
app()
.gui()
.showConsole();
app()
.gui()
.maximizeConsole();
app().gui().showConsole();
app().gui().maximizeConsole();
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -4,33 +4,36 @@ const { app } = require('./app.js');
const Setting = require('lib/models/Setting.js');
class Command extends BaseCommand {
usage() {
return 'config [name] [value]';
}
description() {
return _('Gets or sets a config value. If [value] is not provided, it will show the value of [name]. If neither [name] nor [value] is provided, it will list the current configuration.');
return _("Gets or sets a config value. If [value] is not provided, it will show the value of [name]. If neither [name] nor [value] is provided, it will list the current configuration.");
}
options() {
return [['-v, --verbose', _('Also displays unset and hidden config variables.')]];
return [
['-v, --verbose', _('Also displays unset and hidden config variables.')],
];
}
async action(args) {
const verbose = args.options.verbose;
const renderKeyValue = name => {
const renderKeyValue = (name) => {
const md = Setting.settingMetadata(name);
let value = Setting.value(name);
if (typeof value === 'object' || Array.isArray(value)) value = JSON.stringify(value);
if (md.secure && value) value = '********';
if (md.secure) value = '********';
if (Setting.isEnum(name)) {
return _('%s = %s (%s)', name, value, Setting.enumOptionsDoc(name));
} else {
return _('%s = %s', name, value);
}
};
}
if (!args.name && !args.value) {
let keys = Setting.keys(!verbose, 'cli');
@@ -40,23 +43,15 @@ class Command extends BaseCommand {
if (!verbose && !value) continue;
this.stdout(renderKeyValue(keys[i]));
}
app()
.gui()
.showConsole();
app()
.gui()
.maximizeConsole();
app().gui().showConsole();
app().gui().maximizeConsole();
return;
}
if (args.name && !args.value) {
this.stdout(renderKeyValue(args.name));
app()
.gui()
.showConsole();
app()
.gui()
.maximizeConsole();
app().gui().showConsole();
app().gui().maximizeConsole();
return;
}
@@ -69,6 +64,7 @@ class Command extends BaseCommand {
await Setting.saveAll();
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -2,9 +2,11 @@ const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
class Command extends BaseCommand {
usage() {
return 'cp <note> [notebook]';
}
@@ -31,6 +33,7 @@ class Command extends BaseCommand {
Note.updateGeolocation(newNote.id);
}
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -2,10 +2,12 @@ const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const { time } = require('lib/time-utils.js');
class Command extends BaseCommand {
usage() {
return 'done <note>';
}
@@ -33,6 +35,7 @@ class Command extends BaseCommand {
async action(args) {
await Command.handleAction(this, args, true);
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,9 +1,12 @@
const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const Tag = require('lib/models/Tag.js');
class Command extends BaseCommand {
usage() {
return 'dump';
}
@@ -16,7 +19,7 @@ class Command extends BaseCommand {
return true;
}
async action() {
async action(args) {
let items = [];
let folders = await Folder.all();
for (let i = 0; i < folders.length; i++) {
@@ -32,9 +35,10 @@ class Command extends BaseCommand {
}
items = items.concat(tags);
this.stdout(JSON.stringify(items));
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,21 +1,20 @@
const { BaseCommand } = require('./base-command.js');
const { _ } = require('lib/locale.js');
const { cliUtils } = require('./cli-utils.js');
const EncryptionService = require('lib/services/EncryptionService');
const DecryptionWorker = require('lib/services/DecryptionWorker');
const MasterKey = require('lib/models/MasterKey');
const BaseItem = require('lib/models/BaseItem');
const Setting = require('lib/models/Setting.js');
const { shim } = require('lib/shim');
const pathUtils = require('lib/path-utils.js');
const imageType = require('image-type');
const readChunk = require('read-chunk');
class Command extends BaseCommand {
usage() {
return 'e2ee <command> [path]';
}
description() {
return _('Manages E2EE configuration. Commands are `enable`, `disable`, `decrypt`, `status`, `decrypt-file` and `target-status`.');
return _('Manages E2EE configuration. Commands are `enable`, `disable`, `decrypt`, `status` and `target-status`.');
}
options() {
@@ -23,7 +22,6 @@ class Command extends BaseCommand {
// This is here mostly for testing - shouldn't be used
['-p, --password <password>', 'Use this password as master password (For security reasons, it is not recommended to use this option).'],
['-v, --verbose', 'More verbose output for the `target-status` command'],
['-o, --output <directory>', 'Output directory'],
];
}
@@ -32,33 +30,13 @@ class Command extends BaseCommand {
const options = args.options;
const askForMasterKey = async error => {
const masterKeyId = error.masterKeyId;
const password = await this.prompt(_('Enter master password:'), { type: 'string', secure: true });
if (!password) {
this.stdout(_('Operation cancelled'));
return false;
}
Setting.setObjectKey('encryption.passwordCache', masterKeyId, password);
await EncryptionService.instance().loadMasterKeysFromSettings();
return true;
};
if (args.command === 'enable') {
const password = options.password ? options.password.toString() : await this.prompt(_('Enter master password:'), { type: 'string', secure: true });
if (!password) {
this.stdout(_('Operation cancelled'));
return;
}
const password2 = await this.prompt(_('Confirm master password:'), { type: 'string', secure: true });
if (!password2) {
this.stdout(_('Operation cancelled'));
return;
}
if (password !== password2) {
this.stdout(_('Passwords do not match!'));
return;
}
await EncryptionService.instance().generateMasterKeyAndEnableEncryption(password);
return;
}
@@ -81,8 +59,14 @@ class Command extends BaseCommand {
break;
} catch (error) {
if (error.code === 'masterKeyNotLoaded') {
const ok = await askForMasterKey(error);
if (!ok) return;
const masterKeyId = error.masterKeyId;
const password = await this.prompt(_('Enter master password:'), { type: 'string', secure: true });
if (!password) {
this.stdout(_('Operation cancelled'));
return;
}
Setting.setObjectKey('encryption.passwordCache', masterKeyId, password);
await EncryptionService.instance().loadMasterKeysFromSettings();
continue;
}
@@ -101,49 +85,21 @@ class Command extends BaseCommand {
return;
}
if (args.command === 'decrypt-file') {
while (true) {
try {
const outputDir = options.output ? options.output : require('os').tmpdir();
let outFile = `${outputDir}/${pathUtils.filename(args.path)}.${Date.now()}.bin`;
await EncryptionService.instance().decryptFile(args.path, outFile);
const buffer = await readChunk(outFile, 0, 64);
const detectedType = imageType(buffer);
if (detectedType) {
const newOutFile = `${outFile}.${detectedType.ext}`;
await shim.fsDriver().move(outFile, newOutFile);
outFile = newOutFile;
}
this.stdout(outFile);
break;
} catch (error) {
if (error.code === 'masterKeyNotLoaded') {
const ok = await askForMasterKey(error);
if (!ok) return;
continue;
}
throw error;
}
}
return;
}
if (args.command === 'target-status') {
const fs = require('fs-extra');
const pathUtils = require('lib/path-utils.js');
const fsDriver = new (require('lib/fs-driver-node.js').FsDriverNode)();
const targetPath = args.path;
if (!targetPath) throw new Error('Please specify the sync target path.');
const dirPaths = function(targetPath) {
let paths = [];
fs.readdirSync(targetPath).forEach(path => {
fs.readdirSync(targetPath).forEach((path) => {
paths.push(path);
});
return paths;
};
}
let itemCount = 0;
let resourceCount = 0;
@@ -158,7 +114,7 @@ class Command extends BaseCommand {
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
const fullPath = `${targetPath}/${path}`;
const fullPath = targetPath + '/' + path;
const stat = await fs.stat(fullPath);
// this.stdout(fullPath);
@@ -168,7 +124,7 @@ class Command extends BaseCommand {
for (let j = 0; j < resourcePaths.length; j++) {
const resourcePath = resourcePaths[j];
resourceCount++;
const fullResourcePath = `${fullPath}/${resourcePath}`;
const fullResourcePath = fullPath + '/' + resourcePath;
const isEncrypted = await EncryptionService.instance().fileIsEncrypted(fullResourcePath);
if (isEncrypted) {
encryptedResourceCount++;
@@ -202,9 +158,9 @@ class Command extends BaseCommand {
}
}
this.stdout(`Encrypted items: ${encryptedItemCount}/${itemCount}`);
this.stdout(`Encrypted resources: ${encryptedResourceCount}/${resourceCount}`);
this.stdout(`Other items (never encrypted): ${otherItemCount}`);
this.stdout('Encrypted items: ' + encryptedItemCount + '/' + itemCount);
this.stdout('Encrypted resources: ' + encryptedResourceCount + '/' + resourceCount);
this.stdout('Other items (never encrypted): ' + otherItemCount);
if (options.verbose) {
this.stdout('');
@@ -227,6 +183,7 @@ class Command extends BaseCommand {
return;
}
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -3,11 +3,15 @@ const { BaseCommand } = require('./base-command.js');
const { uuid } = require('lib/uuid.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const Setting = require('lib/models/Setting.js');
const BaseModel = require('lib/BaseModel.js');
const { cliUtils } = require('./cli-utils.js');
const { time } = require('lib/time-utils.js');
class Command extends BaseCommand {
usage() {
return 'edit <note>';
}
@@ -17,19 +21,20 @@ class Command extends BaseCommand {
}
async action(args) {
let watcher = null;
let tempFilePath = null;
const onFinishedEditing = async () => {
if (tempFilePath) fs.removeSync(tempFilePath);
};
}
const textEditorPath = () => {
if (Setting.value('editor')) return Setting.value('editor');
if (process.env.EDITOR) return process.env.EDITOR;
throw new Error(_('No text editor is defined. Please set it using `config editor <editor-path>`'));
};
}
try {
try {
// -------------------------------------------------------------------------
// Load note or create it if it doesn't exist
// -------------------------------------------------------------------------
@@ -60,7 +65,7 @@ class Command extends BaseCommand {
const originalContent = await Note.serializeForEdit(note);
tempFilePath = `${Setting.value('tempDir')}/${uuid.create()}.md`;
tempFilePath = Setting.value('tempDir') + '/' + uuid.create() + '.md';
editorArgs.push(tempFilePath);
await fs.writeFile(tempFilePath, originalContent);
@@ -71,30 +76,18 @@ class Command extends BaseCommand {
this.logger().info('Disabling fullscreen...');
app()
.gui()
.showModalOverlay(_('Starting to edit note. Close the editor to get back to the prompt.'));
await app()
.gui()
.forceRender();
const termState = app()
.gui()
.termSaveState();
app().gui().showModalOverlay(_('Starting to edit note. Close the editor to get back to the prompt.'));
await app().gui().forceRender();
const termState = app().gui().termSaveState();
const spawnSync = require('child_process').spawnSync;
const spawnSync = require('child_process').spawnSync;
const result = spawnSync(editorPath, editorArgs, { stdio: 'inherit' });
if (result.error) this.stdout(_('Error opening note in editor: %s', result.error.message));
app()
.gui()
.termRestoreState(termState);
app()
.gui()
.hideModalOverlay();
app()
.gui()
.forceRender();
app().gui().termRestoreState(termState);
app().gui().hideModalOverlay();
app().gui().forceRender();
// -------------------------------------------------------------------------
// Save the note and clean up
@@ -114,11 +107,13 @@ class Command extends BaseCommand {
});
await onFinishedEditing();
} catch (error) {
} catch(error) {
await onFinishedEditing();
throw error;
}
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -3,6 +3,7 @@ const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
class Command extends BaseCommand {
usage() {
return 'exit';
}
@@ -15,9 +16,10 @@ class Command extends BaseCommand {
return ['gui'];
}
async action() {
async action(args) {
await app().exit();
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,10 +1,13 @@
const { BaseCommand } = require('./base-command.js');
const { Database } = require('lib/database.js');
const { app } = require('./app.js');
const Setting = require('lib/models/Setting.js');
const { _ } = require('lib/locale.js');
const { ReportService } = require('lib/services/report.js');
const fs = require('fs-extra');
class Command extends BaseCommand {
usage() {
return 'export-sync-status';
}
@@ -17,20 +20,17 @@ class Command extends BaseCommand {
return true;
}
async action() {
async action(args) {
const service = new ReportService();
const csv = await service.basicItemList({ format: 'csv' });
const filePath = `${Setting.value('profileDir')}/syncReport-${new Date().getTime()}.csv`;
const filePath = Setting.value('profileDir') + '/syncReport-' + (new Date()).getTime() + '.csv';
await fs.writeFileSync(filePath, csv);
this.stdout(`Sync status exported to ${filePath}`);
this.stdout('Sync status exported to ' + filePath);
app()
.gui()
.showConsole();
app()
.gui()
.maximizeConsole();
app().gui().showConsole();
app().gui().maximizeConsole();
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,10 +1,14 @@
const { BaseCommand } = require('./base-command.js');
const InteropService = require('lib/services/InteropService.js');
const BaseModel = require('lib/BaseModel.js');
const Note = require('lib/models/Note.js');
const { reg } = require('lib/registry.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const fs = require('fs-extra');
class Command extends BaseCommand {
usage() {
return 'export <path>';
}
@@ -15,14 +19,17 @@ class Command extends BaseCommand {
options() {
const service = new InteropService();
const formats = service
.modules()
const formats = service.modules()
.filter(m => m.type === 'exporter')
.map(m => m.format + (m.description ? ` (${m.description})` : ''));
.map(m => m.format + (m.description ? ' (' + m.description + ')' : ''));
return [['--format <format>', _('Destination format: %s', formats.join(', '))], ['--note <note>', _('Exports only the given note.')], ['--notebook <notebook>', _('Exports only the given notebook.')]];
return [
['--format <format>', _('Destination format: %s', formats.join(', '))],
['--note <note>', _('Exports only the given note.')],
['--notebook <notebook>', _('Exports only the given notebook.')],
];
}
async action(args) {
let exportOptions = {};
exportOptions.path = args.path;
@@ -30,20 +37,25 @@ class Command extends BaseCommand {
exportOptions.format = args.options.format ? args.options.format : 'jex';
if (args.options.note) {
const notes = await app().loadItems(BaseModel.TYPE_NOTE, args.options.note, { parent: app().currentFolder() });
if (!notes.length) throw new Error(_('Cannot find "%s".', args.options.note));
exportOptions.sourceNoteIds = notes.map(n => n.id);
exportOptions.sourceNoteIds = notes.map((n) => n.id);
} else if (args.options.notebook) {
const folders = await app().loadItems(BaseModel.TYPE_FOLDER, args.options.notebook);
if (!folders.length) throw new Error(_('Cannot find "%s".', args.options.notebook));
exportOptions.sourceFolderIds = folders.map(n => n.id);
exportOptions.sourceFolderIds = folders.map((n) => n.id);
}
const service = new InteropService();
const result = await service.export(exportOptions);
result.warnings.map(w => this.stdout(w));
result.warnings.map((w) => this.stdout(w));
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -2,9 +2,11 @@ const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
class Command extends BaseCommand {
usage() {
return 'geoloc <note>';
}
@@ -21,10 +23,9 @@ class Command extends BaseCommand {
const url = Note.geolocationUrl(item);
this.stdout(url);
app()
.gui()
.showConsole();
app().gui().showConsole();
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,10 +1,14 @@
const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { renderCommandHelp } = require('./help-utils.js');
const { Database } = require('lib/database.js');
const Setting = require('lib/models/Setting.js');
const { wrap } = require('lib/string-utils.js');
const { _ } = require('lib/locale.js');
const { cliUtils } = require('./cli-utils.js');
class Command extends BaseCommand {
usage() {
return 'help [command]';
}
@@ -24,7 +28,7 @@ class Command extends BaseCommand {
output.push(command);
}
output.sort((a, b) => (a.name() < b.name() ? -1 : +1));
output.sort((a, b) => a.name() < b.name() ? -1 : +1);
return output;
}
@@ -33,40 +37,34 @@ class Command extends BaseCommand {
const stdoutWidth = app().commandStdoutMaxWidth();
if (args.command === 'shortcuts' || args.command === 'keymap') {
this.stdout(_('For information on how to customise the shortcuts please visit %s', 'https://joplinapp.org/terminal/#shortcuts'));
this.stdout(_('For information on how to customise the shortcuts please visit %s', 'https://joplin.cozic.net/terminal/#shortcuts'));
this.stdout('');
if (
app()
.gui()
.isDummy()
) {
if (app().gui().isDummy()) {
throw new Error(_('Shortcuts are not available in CLI mode.'));
}
const keymap = app()
.gui()
.keymap();
const keymap = app().gui().keymap();
let rows = [];
for (let i = 0; i < keymap.length; i++) {
const item = keymap[i];
const keys = item.keys.map(k => (k === ' ' ? '(SPACE)' : k));
const keys = item.keys.map((k) => k === ' ' ? '(SPACE)' : k);
rows.push([keys.join(', '), item.command]);
}
cliUtils.printArray(this.stdout.bind(this), rows);
} else if (args.command === 'all') {
const commands = this.allCommands();
const output = commands.map(c => renderCommandHelp(c));
const output = commands.map((c) => renderCommandHelp(c));
this.stdout(output.join('\n\n'));
} else if (args.command) {
const command = app().findCommandByName(args['command']);
if (!command) throw new Error(_('Cannot find "%s".', args.command));
this.stdout(renderCommandHelp(command, stdoutWidth));
} else {
const commandNames = this.allCommands().map(a => a.name());
const commandNames = this.allCommands().map((a) => a.name());
this.stdout(_('Type `help [command]` for more information about a command; or type `help all` for the complete usage information.'));
this.stdout('');
@@ -84,13 +82,10 @@ class Command extends BaseCommand {
this.stdout(_('For the list of keyboard shortcuts and config options, type `help keymap`'));
}
app()
.gui()
.showConsole();
app()
.gui()
.maximizeConsole();
app().gui().showConsole();
app().gui().maximizeConsole();
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,11 +1,17 @@
const { BaseCommand } = require('./base-command.js');
const InteropService = require('lib/services/InteropService.js');
const BaseModel = require('lib/BaseModel.js');
const Note = require('lib/models/Note.js');
const { filename, basename, fileExtension } = require('lib/path-utils.js');
const { importEnex } = require('lib/import-enex');
const { cliUtils } = require('./cli-utils.js');
const { reg } = require('lib/registry.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const fs = require('fs-extra');
class Command extends BaseCommand {
usage() {
return 'import <path> [notebook]';
}
@@ -16,14 +22,14 @@ class Command extends BaseCommand {
options() {
const service = new InteropService();
const formats = service
.modules()
.filter(m => m.type === 'importer')
.map(m => m.format);
const formats = service.modules().filter(m => m.type === 'importer').map(m => m.format);
return [['--format <format>', _('Source format: %s', ['auto'].concat(formats).join(', '))], ['-f, --force', _('Do not ask for confirmation.')]];
return [
['--format <format>', _('Source format: %s', (['auto'].concat(formats)).join(', '))],
['-f, --force', _('Do not ask for confirmation.')],
];
}
async action(args) {
let folder = await app().loadItem(BaseModel.TYPE_FOLDER, args.notebook);
@@ -38,7 +44,7 @@ class Command extends BaseCommand {
// onProgress/onError supported by Enex import only
importOptions.onProgress = progressState => {
importOptions.onProgress = (progressState) => {
let line = [];
line.push(_('Found: %d.', progressState.loaded));
line.push(_('Created: %d.', progressState.created));
@@ -50,21 +56,20 @@ class Command extends BaseCommand {
cliUtils.redraw(lastProgress);
};
importOptions.onError = error => {
importOptions.onError = (error) => {
let s = error.trace ? error.trace : error.toString();
this.stdout(s);
};
app()
.gui()
.showConsole();
app().gui().showConsole();
this.stdout(_('Importing notes...'));
const service = new InteropService();
const result = await service.import(importOptions);
result.warnings.map(w => this.stdout(w));
result.warnings.map((w) => this.stdout(w));
cliUtils.redrawDone();
if (lastProgress) this.stdout(_('The notes have been imported: %s', lastProgress));
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -10,6 +10,7 @@ const { time } = require('lib/time-utils.js');
const { cliUtils } = require('./cli-utils.js');
class Command extends BaseCommand {
usage() {
return 'ls [note-pattern]';
}
@@ -21,9 +22,16 @@ class Command extends BaseCommand {
enabled() {
return false;
}
options() {
return [['-n, --limit <num>', _('Displays only the first top <num> notes.')], ['-s, --sort <field>', _('Sorts the item by <field> (eg. title, updated_time, created_time).')], ['-r, --reverse', _('Reverses the sorting order.')], ['-t, --type <type>', _('Displays only the items of the specific type(s). Can be `n` for notes, `t` for to-dos, or `nt` for notes and to-dos (eg. `-tt` would display only the to-dos, while `-ttd` would display notes and to-dos.')], ['-f, --format <format>', _('Either "text" or "json"')], ['-l, --long', _('Use long list format. Format is ID, NOTE_COUNT (for notebook), DATE, TODO_CHECKED (for to-dos), TITLE')]];
return [
['-n, --limit <num>', _('Displays only the first top <num> notes.')],
['-s, --sort <field>', _('Sorts the item by <field> (eg. title, updated_time, created_time).')],
['-r, --reverse', _('Reverses the sorting order.')],
['-t, --type <type>', _('Displays only the items of the specific type(s). Can be `n` for notes, `t` for to-dos, or `nt` for notes and to-dos (eg. `-tt` would display only the to-dos, while `-ttd` would display notes and to-dos.')],
['-f, --format <format>', _('Either "text" or "json"')],
['-l, --long', _('Use long list format. Format is ID, NOTE_COUNT (for notebook), DATE, TODO_CHECKED (for to-dos), TITLE')],
];
}
async action(args) {
@@ -85,19 +93,19 @@ class Command extends BaseCommand {
row.push(await Folder.noteCount(item.id));
}
row.push(time.formatMsToLocal(item.user_updated_time));
row.push(time.unixMsToLocalDateTime(item.user_updated_time));
}
let title = item.title;
if (!shortIdShown && (seenTitles.indexOf(item.title) >= 0 || !item.title)) {
title += ` (${BaseModel.shortId(item.id)})`;
title += ' (' + BaseModel.shortId(item.id) + ')';
} else {
seenTitles.push(item.title);
}
if (hasTodos) {
if (item.is_todo) {
row.push(sprintf('[%s]', item.todo_completed ? 'X' : ' '));
row.push(sprintf('[%s]', !!item.todo_completed ? 'X' : ' '));
} else {
row.push(' ');
}
@@ -110,7 +118,9 @@ class Command extends BaseCommand {
cliUtils.printArray(this.stdout.bind(this), rows);
}
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -2,8 +2,10 @@ const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const Folder = require('lib/models/Folder.js');
const { reg } = require('lib/registry.js');
class Command extends BaseCommand {
usage() {
return 'mkbook <new-notebook>';
}
@@ -13,9 +15,10 @@ class Command extends BaseCommand {
}
async action(args) {
let folder = await Folder.save({ title: args['new-notebook'] }, { userSideValidation: true });
let folder = await Folder.save({ title: args['new-notebook'] }, { userSideValidation: true });
app().switchCurrentFolder(folder);
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -4,6 +4,7 @@ const { _ } = require('lib/locale.js');
const Note = require('lib/models/Note.js');
class Command extends BaseCommand {
usage() {
return 'mknote <new-note>';
}
@@ -25,6 +26,7 @@ class Command extends BaseCommand {
app().switchCurrentFolder(app().currentFolder());
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -4,6 +4,7 @@ const { _ } = require('lib/locale.js');
const Note = require('lib/models/Note.js');
class Command extends BaseCommand {
usage() {
return 'mktodo <new-todo>';
}
@@ -26,6 +27,7 @@ class Command extends BaseCommand {
app().switchCurrentFolder(app().currentFolder());
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -6,6 +6,7 @@ const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
class Command extends BaseCommand {
usage() {
return 'mv <note> [notebook]';
}
@@ -17,7 +18,7 @@ class Command extends BaseCommand {
async action(args) {
const pattern = args['note'];
const destination = args['notebook'];
const folder = await Folder.loadByField('title', destination);
if (!folder) throw new Error(_('Cannot find "%s".', destination));
@@ -28,6 +29,7 @@ class Command extends BaseCommand {
await Note.moveToFolder(notes[i].id, folder.id);
}
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -6,6 +6,7 @@ const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
class Command extends BaseCommand {
usage() {
return 'ren <item> <name>';
}
@@ -34,6 +35,7 @@ class Command extends BaseCommand {
await Note.save(newItem);
}
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,10 +1,14 @@
const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseItem = require('lib/models/BaseItem.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const BaseModel = require('lib/BaseModel.js');
const { cliUtils } = require('./cli-utils.js');
class Command extends BaseCommand {
usage() {
return 'rmbook <notebook>';
}
@@ -14,7 +18,9 @@ class Command extends BaseCommand {
}
options() {
return [['-f, --force', _('Deletes the notebook without asking for confirmation.')]];
return [
['-f, --force', _('Deletes the notebook without asking for confirmation.')],
];
}
async action(args) {
@@ -28,6 +34,7 @@ class Command extends BaseCommand {
await Folder.delete(folder.id);
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,10 +1,14 @@
const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseItem = require('lib/models/BaseItem.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const BaseModel = require('lib/BaseModel.js');
const { cliUtils } = require('./cli-utils.js');
class Command extends BaseCommand {
usage() {
return 'rmnote <note-pattern>';
}
@@ -14,7 +18,9 @@ class Command extends BaseCommand {
}
options() {
return [['-f, --force', _('Deletes the notes without asking for confirmation.')]];
return [
['-f, --force', _('Deletes the notes without asking for confirmation.')],
];
}
async action(args) {
@@ -26,9 +32,10 @@ class Command extends BaseCommand {
const ok = force ? true : await this.prompt(notes.length > 1 ? _('%d notes match this pattern. Delete them?', notes.length) : _('Delete note?'), { booleanAnswerDefault: 'n' });
if (!ok) return;
let ids = notes.map(n => n.id);
let ids = notes.map((n) => n.id);
await Note.batchDelete(ids);
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,10 +1,15 @@
const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const { sprintf } = require('sprintf-js');
const { time } = require('lib/time-utils.js');
const { uuid } = require('lib/uuid.js');
class Command extends BaseCommand {
usage() {
return 'search <pattern> [notebook]';
}
@@ -44,7 +49,37 @@ class Command extends BaseCommand {
type: 'SEARCH_SELECT',
id: searchId,
});
// let fields = Note.previewFields();
// fields.push('body');
// const notes = await Note.previews(folder ? folder.id : null, {
// fields: fields,
// anywherePattern: '*' + pattern + '*',
// });
// const fragmentLength = 50;
// let parents = {};
// for (let i = 0; i < notes.length; i++) {
// const note = notes[i];
// const parent = parents[note.parent_id] ? parents[note.parent_id] : await Folder.load(note.parent_id);
// parents[note.parent_id] = parent;
// const idx = note.body.indexOf(pattern);
// let line = '';
// if (idx >= 0) {
// let fragment = note.body.substr(Math.max(0, idx - fragmentLength / 2), fragmentLength);
// fragment = fragment.replace(/\n/g, ' ');
// line = sprintf('%s: %s / %s: %s', BaseModel.shortId(note.id), parent.title, note.title, fragment);
// } else {
// line = sprintf('%s: %s / %s', BaseModel.shortId(note.id), parent.title, note.title);
// }
// this.stdout(line);
// }
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,57 +0,0 @@
const { BaseCommand } = require('./base-command.js');
const { _ } = require('lib/locale.js');
const Setting = require('lib/models/Setting.js');
const { Logger } = require('lib/logger.js');
const { shim } = require('lib/shim');
class Command extends BaseCommand {
usage() {
return 'server <command>';
}
description() {
return `${_('Start, stop or check the API server. To specify on which port it should run, set the api.port config variable. Commands are (%s).', ['start', 'stop', 'status'].join('|'))} This is an experimental feature - use at your own risks! It is recommended that the server runs off its own separate profile so that no two CLI instances access that profile at the same time. Use --profile to specify the profile path.`;
}
async action(args) {
const command = args.command;
const ClipperServer = require('lib/ClipperServer');
const stdoutFn = (s) => this.stdout(s);
const clipperLogger = new Logger();
clipperLogger.addTarget('file', { path: `${Setting.value('profileDir')}/log-clipper.txt` });
clipperLogger.addTarget('console', { console: {
info: stdoutFn,
warn: stdoutFn,
error: stdoutFn,
}});
ClipperServer.instance().setDispatch(() => {});
ClipperServer.instance().setLogger(clipperLogger);
const pidPath = `${Setting.value('profileDir')}/clipper-pid.txt`;
const runningOnPort = await ClipperServer.instance().isRunning();
if (command === 'start') {
if (runningOnPort) {
this.stdout(_('Server is already running on port %d', runningOnPort));
} else {
await shim.fsDriver().writeFile(pidPath, process.pid.toString(), 'utf-8');
await ClipperServer.instance().start(); // Never exit
}
} else if (command === 'status') {
this.stdout(runningOnPort ? _('Server is running on port %d', runningOnPort) : _('Server is not running.'));
} else if (command === 'stop') {
if (!runningOnPort) {
this.stdout(_('Server is not running.'));
return;
}
const pid = await shim.fsDriver().readFile(pidPath);
if (!pid) return;
process.kill(pid, 'SIGTERM');
}
}
}
module.exports = Command;

View File

@@ -3,9 +3,12 @@ const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const { Database } = require('lib/database.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const BaseItem = require('lib/models/BaseItem.js');
class Command extends BaseCommand {
usage() {
return 'set <note> <name> [value]';
}
@@ -16,7 +19,7 @@ class Command extends BaseCommand {
for (let i = 0; i < fields.length; i++) {
const f = fields[i];
if (f.name === 'id') continue;
s.push(`${f.name} (${Database.enumName('fieldType', f.type)})`);
s.push(f.name + ' (' + Database.enumName('fieldType', f.type) + ')');
}
return _('Sets the property <name> of the given <note> to the given [value]. Possible properties are:\n\n%s', s.join(', '));
@@ -39,16 +42,10 @@ class Command extends BaseCommand {
type_: notes[i].type_,
};
newNote[propName] = propValue;
const timestamp = Date.now();
await Note.save(newNote, {
autoTimestamp: false, // No auto-timestamp because user may have provided them
updated_time: timestamp,
created_time: timestamp,
});
await Note.save(newNote);
}
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,10 +1,12 @@
const { BaseCommand } = require('./base-command.js');
const { Database } = require('lib/database.js');
const { app } = require('./app.js');
const Setting = require('lib/models/Setting.js');
const { _ } = require('lib/locale.js');
const { ReportService } = require('lib/services/report.js');
class Command extends BaseCommand {
usage() {
return 'status';
}
@@ -13,7 +15,7 @@ class Command extends BaseCommand {
return _('Displays summary about the notes and notebooks.');
}
async action() {
async action(args) {
let service = new ReportService();
let report = await service.status(Setting.value('sync.target'));
@@ -22,7 +24,7 @@ class Command extends BaseCommand {
if (i > 0) this.stdout('');
this.stdout(`# ${section.title}`);
this.stdout('# ' + section.title);
this.stdout('');
for (let n in section.body) {
@@ -32,13 +34,10 @@ class Command extends BaseCommand {
}
}
app()
.gui()
.showConsole();
app()
.gui()
.maximizeConsole();
app().gui().showConsole();
app().gui().maximizeConsole();
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -3,7 +3,7 @@ const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const { OneDriveApiNodeUtils } = require('./onedrive-api-node-utils.js');
const Setting = require('lib/models/Setting.js');
const ResourceFetcher = require('lib/services/ResourceFetcher');
const BaseItem = require('lib/models/BaseItem.js');
const { Synchronizer } = require('lib/synchronizer.js');
const { reg } = require('lib/registry.js');
const { cliUtils } = require('./cli-utils.js');
@@ -13,6 +13,7 @@ const fs = require('fs-extra');
const SyncTargetRegistry = require('lib/SyncTargetRegistry');
class Command extends BaseCommand {
constructor() {
super();
this.syncTargetId_ = null;
@@ -29,7 +30,9 @@ class Command extends BaseCommand {
}
options() {
return [['--target <target>', _('Sync to provided target (defaults to sync.target config value)')]];
return [
['--target <target>', _('Sync to provided target (defaults to sync.target config value)')],
];
}
static lockFile(filePath) {
@@ -62,25 +65,21 @@ class Command extends BaseCommand {
const syncTarget = reg.syncTarget(this.syncTargetId_);
const syncTargetMd = SyncTargetRegistry.idToMetadata(this.syncTargetId_);
if (this.syncTargetId_ === 3 || this.syncTargetId_ === 4) {
// OneDrive
if (this.syncTargetId_ === 3 || this.syncTargetId_ === 4) { // OneDrive
this.oneDriveApiUtils_ = new OneDriveApiNodeUtils(syncTarget.api());
const auth = await this.oneDriveApiUtils_.oauthDance({
log: (...s) => {
return this.stdout(...s);
},
log: (...s) => { return this.stdout(...s); }
});
this.oneDriveApiUtils_ = null;
Setting.setValue(`sync.${this.syncTargetId_}.auth`, auth ? JSON.stringify(auth) : null);
Setting.setValue('sync.' + this.syncTargetId_ + '.auth', auth ? JSON.stringify(auth) : null);
if (!auth) {
this.stdout(_('Authentication was not completed (did not receive an authentication token).'));
return false;
}
return true;
} else if (syncTargetMd.name === 'dropbox') {
// Dropbox
} else if (syncTargetMd.name === 'dropbox') { // Dropbox
const api = await syncTarget.api();
const loginUrl = api.loginUrl();
this.stdout(_('To allow Joplin to synchronise with Dropbox, please follow the steps below:'));
@@ -93,7 +92,7 @@ class Command extends BaseCommand {
}
const response = await api.execAuthToken(authCode);
Setting.setValue(`sync.${this.syncTargetId_}.auth`, response.access_token);
Setting.setValue('sync.' + this.syncTargetId_ + '.auth', response.access_token);
api.setAuthToken(response.access_token);
return true;
}
@@ -117,8 +116,9 @@ class Command extends BaseCommand {
this.releaseLockFn_ = null;
// Lock is unique per profile/database
const lockFilePath = `${require('os').tmpdir()}/synclock_${md5(escape(Setting.value('profileDir')))}`; // https://github.com/pvorb/node-md5/issues/41
if (!(await fs.pathExists(lockFilePath))) await fs.writeFile(lockFilePath, 'synclock');
// TODO: use SQLite database to do lock?
const lockFilePath = require('os').tmpdir() + '/synclock_' + md5(escape(Setting.value('profileDir'))); // https://github.com/pvorb/node-md5/issues/41
if (!await fs.pathExists(lockFilePath)) await fs.writeFile(lockFilePath, 'synclock');
try {
if (await Command.isLocked(lockFilePath)) throw new Error(_('Synchronisation is already in progress.'));
@@ -147,26 +147,22 @@ class Command extends BaseCommand {
const syncTarget = reg.syncTarget(this.syncTargetId_);
if (!(await syncTarget.isAuthenticated())) {
app()
.gui()
.showConsole();
app()
.gui()
.maximizeConsole();
if (!await syncTarget.isAuthenticated()) {
app().gui().showConsole();
app().gui().maximizeConsole();
const authDone = await this.doAuth();
if (!authDone) return cleanUp();
}
const sync = await syncTarget.synchronizer();
let options = {
onProgress: report => {
onProgress: (report) => {
let lines = Synchronizer.reportToLines(report);
if (lines.length) cliUtils.redraw(lines.join(' '));
},
onMessage: msg => {
onMessage: (msg) => {
cliUtils.redrawDone();
this.stdout(msg);
},
@@ -178,7 +174,7 @@ class Command extends BaseCommand {
this.stdout(_('Starting synchronisation...'));
const contextKey = `sync.${this.syncTargetId_}.context`;
const contextKey = 'sync.' + this.syncTargetId_ + '.context';
let context = Setting.value(contextKey);
context = context ? JSON.parse(context) : {};
@@ -195,15 +191,6 @@ class Command extends BaseCommand {
}
}
// When using the tool in command line mode, the ResourceFetcher service is
// not going to be running in the background, so the resources need to be
// explicitely downloaded below.
if (!app().hasGui()) {
this.stdout(_('Downloading resources...'));
await ResourceFetcher.instance().fetchAll();
await ResourceFetcher.instance().waitForAllFinished();
}
await app().refreshCurrentFolder();
} catch (error) {
cleanUp();
@@ -241,6 +228,7 @@ class Command extends BaseCommand {
cancellable() {
return true;
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -3,25 +3,19 @@ const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const Tag = require('lib/models/Tag.js');
const BaseModel = require('lib/BaseModel.js');
const { time } = require('lib/time-utils.js');
class Command extends BaseCommand {
usage() {
return 'tag <tag-command> [tag] [note]';
}
description() {
return _('<tag-command> can be "add", "remove" or "list" to assign or remove [tag] from [note], or to list the notes associated with [tag]. The command `tag list` can be used to list all the tags (use -l for long option).');
return _('<tag-command> can be "add", "remove" or "list" to assign or remove [tag] from [note], or to list the notes associated with [tag]. The command `tag list` can be used to list all the tags.');
}
options() {
return [['-l, --long', _('Use long list format. Format is ID, NOTE_COUNT (for notebook), DATE, TODO_CHECKED (for to-dos), TITLE')]];
}
async action(args) {
let tag = null;
let options = args.options;
if (args.tag) tag = await app().loadItem(BaseModel.TYPE_TAG, args.tag);
let notes = [];
if (args.note) {
@@ -47,38 +41,16 @@ class Command extends BaseCommand {
} else if (command == 'list') {
if (tag) {
let notes = await Tag.notes(tag.id);
notes.map(note => {
let line = '';
if (options.long) {
line += BaseModel.shortId(note.id);
line += ' ';
line += time.formatMsToLocal(note.user_updated_time);
line += ' ';
}
if (note.is_todo) {
line += '[';
if (note.todo_completed) {
line += 'X';
} else {
line += ' ';
}
line += '] ';
} else {
line += ' ';
}
line += note.title;
this.stdout(line);
});
notes.map((note) => { this.stdout(note.title); });
} else {
let tags = await Tag.all();
tags.map(tag => {
this.stdout(tag.title);
});
tags.map((tag) => { this.stdout(tag.title); });
}
} else {
throw new Error(_('Invalid command: "%s"', command));
}
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -2,10 +2,12 @@ const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const { time } = require('lib/time-utils.js');
class Command extends BaseCommand {
usage() {
return 'todo <todo-command> <note-pattern>';
}
@@ -37,11 +39,12 @@ class Command extends BaseCommand {
}
} else if (action == 'clear') {
toSave.is_todo = 0;
}
}
await Note.save(toSave);
}
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -1,9 +1,15 @@
const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const Folder = require('lib/models/Folder.js');
const Note = require('lib/models/Note.js');
const { time } = require('lib/time-utils.js');
const CommandDone = require('./command-done.js');
class Command extends BaseCommand {
usage() {
return 'undone <note>';
}
@@ -15,6 +21,7 @@ class Command extends BaseCommand {
async action(args) {
await CommandDone.handleAction(this, args, false);
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -2,8 +2,10 @@ const { BaseCommand } = require('./base-command.js');
const { app } = require('./app.js');
const { _ } = require('lib/locale.js');
const BaseModel = require('lib/BaseModel.js');
const Folder = require('lib/models/Folder.js');
class Command extends BaseCommand {
usage() {
return 'use <notebook>';
}
@@ -12,6 +14,10 @@ class Command extends BaseCommand {
return _('Switches to [notebook] - all further operations will happen within this notebook.');
}
autocomplete() {
return { data: autocompleteFolders };
}
compatibleUis() {
return ['cli'];
}
@@ -21,6 +27,7 @@ class Command extends BaseCommand {
if (!folder) throw new Error(_('Cannot find "%s".', args['notebook']));
app().switchCurrentFolder(folder);
}
}
module.exports = Command;
module.exports = Command;

View File

@@ -3,6 +3,7 @@ const Setting = require('lib/models/Setting.js');
const { _ } = require('lib/locale.js');
class Command extends BaseCommand {
usage() {
return 'version';
}
@@ -11,10 +12,11 @@ class Command extends BaseCommand {
return _('Displays version information');
}
async action() {
async action(args) {
const p = require('./package.json');
this.stdout(_('%s %s (%s)', p.name, p.version, Setting.value('env')));
}
}
module.exports = Command;
module.exports = Command;

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +1,7 @@
const TextWidget = require('tkwidgets/TextWidget.js');
class ConsoleWidget extends TextWidget {
constructor() {
super();
this.lines_ = [];
@@ -15,7 +16,7 @@ class ConsoleWidget extends TextWidget {
}
get lastLine() {
return this.lines_.length ? this.lines_[this.lines_.length - 1] : '';
return this.lines_.length ? this.lines_[this.lines_.length-1] : '';
}
addLine(line) {
@@ -39,12 +40,13 @@ class ConsoleWidget extends TextWidget {
if (this.lines_.length > this.maxLines_) {
this.lines_.splice(0, this.lines_.length - this.maxLines_);
}
this.text = this.lines_.join('\n');
this.text = this.lines_.join("\n");
this.updateText_ = false;
}
super.render();
}
}
module.exports = ConsoleWidget;
module.exports = ConsoleWidget;

View File

@@ -5,6 +5,7 @@ const ListWidget = require('tkwidgets/ListWidget.js');
const _ = require('lib/locale.js')._;
class FolderListWidget extends ListWidget {
constructor() {
super();
@@ -19,19 +20,21 @@ class FolderListWidget extends ListWidget {
this.updateItems_ = false;
this.trimItemTitle = false;
this.itemRenderer = item => {
this.itemRenderer = (item) => {
let output = [];
if (item === '-') {
output.push('-'.repeat(this.innerWidth));
} else if (item.type_ === Folder.modelType()) {
output.push(' '.repeat(this.folderDepth(this.folders, item.id)) + Folder.displayTitle(item));
} else if (item.type_ === Tag.modelType()) {
output.push(`[${Folder.displayTitle(item)}]`);
output.push('[' + Folder.displayTitle(item) + ']');
} else if (item.type_ === BaseModel.TYPE_SEARCH) {
output.push(_('Search:'));
output.push(item.title);
}
// if (item && item.id) output.push(item.id.substr(0, 5));
return output.join(' ');
};
}
@@ -44,6 +47,7 @@ class FolderListWidget extends ListWidget {
output++;
folderId = folder.parent_id;
}
throw new Error('unreachable');
}
get selectedFolderId() {
@@ -52,7 +56,7 @@ class FolderListWidget extends ListWidget {
set selectedFolderId(v) {
this.selectedFolderId_ = v;
this.updateIndexFromSelectedItemId();
this.updateIndexFromSelectedItemId()
this.invalidate();
}
@@ -62,7 +66,7 @@ class FolderListWidget extends ListWidget {
set selectedSearchId(v) {
this.selectedSearchId_ = v;
this.updateIndexFromSelectedItemId();
this.updateIndexFromSelectedItemId()
this.invalidate();
}
@@ -72,7 +76,7 @@ class FolderListWidget extends ListWidget {
set selectedTagId(v) {
this.selectedTagId_ = v;
this.updateIndexFromSelectedItemId();
this.updateIndexFromSelectedItemId()
this.invalidate();
}
@@ -81,8 +85,9 @@ class FolderListWidget extends ListWidget {
}
set notesParentType(v) {
//if (this.notesParentType_ === v) return;
this.notesParentType_ = v;
this.updateIndexFromSelectedItemId();
this.updateIndexFromSelectedItemId()
this.invalidate();
}
@@ -93,7 +98,7 @@ class FolderListWidget extends ListWidget {
set searches(v) {
this.searches_ = v;
this.updateItems_ = true;
this.updateIndexFromSelectedItemId();
this.updateIndexFromSelectedItemId()
this.invalidate();
}
@@ -104,7 +109,7 @@ class FolderListWidget extends ListWidget {
set tags(v) {
this.tags_ = v;
this.updateItems_ = true;
this.updateIndexFromSelectedItemId();
this.updateIndexFromSelectedItemId()
this.invalidate();
}
@@ -115,37 +120,17 @@ class FolderListWidget extends ListWidget {
set folders(v) {
this.folders_ = v;
this.updateItems_ = true;
this.updateIndexFromSelectedItemId();
this.updateIndexFromSelectedItemId()
this.invalidate();
}
folderHasChildren_(folders, folderId) {
for (let i = 0; i < folders.length; i++) {
let folder = folders[i];
if (folder.parent_id === folderId) return true;
}
return false;
}
render() {
if (this.updateItems_) {
this.logger().debug('Rebuilding items...', this.notesParentType, this.selectedJoplinItemId, this.selectedSearchId);
const wasSelectedItemId = this.selectedJoplinItemId;
const previousParentType = this.notesParentType;
let newItems = [];
const orderFolders = parentId => {
for (let i = 0; i < this.folders.length; i++) {
const f = this.folders[i];
const folderParentId = f.parent_id ? f.parent_id : '';
if (folderParentId === parentId) {
newItems.push(f);
if (this.folderHasChildren_(this.folders, f.id)) orderFolders(f.id);
}
}
};
orderFolders('');
let newItems = this.folders.slice();
if (this.tags.length) {
if (newItems.length) newItems.push('-');
@@ -160,7 +145,7 @@ class FolderListWidget extends ListWidget {
this.items = newItems;
this.notesParentType = previousParentType;
this.updateIndexFromSelectedItemId(wasSelectedItemId);
this.updateIndexFromSelectedItemId(wasSelectedItemId)
this.updateItems_ = false;
}
@@ -172,7 +157,7 @@ class FolderListWidget extends ListWidget {
if (this.notesParentType === 'Folder') return this.selectedFolderId;
if (this.notesParentType === 'Tag') return this.selectedTagId;
if (this.notesParentType === 'Search') return this.selectedSearchId;
throw new Error(`Unknown parent type: ${this.notesParentType}`);
throw new Error('Unknown parent type: ' + this.notesParentType);
}
get selectedJoplinItem() {
@@ -186,6 +171,7 @@ class FolderListWidget extends ListWidget {
const index = this.itemIndexByKey('id', itemId);
this.currentIndex = index >= 0 ? index : 0;
}
}
module.exports = FolderListWidget;
module.exports = FolderListWidget;

View File

@@ -2,16 +2,17 @@ const Note = require('lib/models/Note.js');
const ListWidget = require('tkwidgets/ListWidget.js');
class NoteListWidget extends ListWidget {
constructor() {
super();
this.selectedNoteId_ = 0;
this.updateIndexFromSelectedNoteId_ = false;
this.itemRenderer = note => {
this.itemRenderer = (note) => {
let label = Note.displayTitle(note); // + ' ' + note.id;
if (note.is_todo) {
label = `[${note.todo_completed ? 'X' : ' '}] ${label}`;
label = '[' + (note.todo_completed ? 'X' : ' ') + '] ' + label;
}
return label;
};
@@ -31,6 +32,7 @@ class NoteListWidget extends ListWidget {
super.render();
}
}
module.exports = NoteListWidget;
module.exports = NoteListWidget;

View File

@@ -2,6 +2,7 @@ const Note = require('lib/models/Note.js');
const TextWidget = require('tkwidgets/TextWidget.js');
class NoteMetadataWidget extends TextWidget {
constructor() {
super();
this.noteId_ = 0;
@@ -29,6 +30,7 @@ class NoteMetadataWidget extends TextWidget {
this.text = this.note_ ? await Note.minimalSerializeForDisplay(this.note_) : '';
}
}
}
module.exports = NoteMetadataWidget;
module.exports = NoteMetadataWidget;

View File

@@ -3,6 +3,7 @@ const TextWidget = require('tkwidgets/TextWidget.js');
const { _ } = require('lib/locale.js');
class NoteWidget extends TextWidget {
constructor() {
super();
this.noteId_ = 0;
@@ -43,11 +44,11 @@ class NoteWidget extends TextWidget {
} else if (this.noteId_) {
this.doAsync('loadNote', async () => {
this.note_ = await Note.load(this.noteId_);
if (this.note_ && this.note_.encryption_applied) {
this.text = _('One or more items are currently encrypted and you may need to supply a master password. To do so please type `e2ee decrypt`. If you have already supplied the password, the encrypted items are being decrypted in the background and will be available soon.');
} else {
this.text = this.note_ ? `${this.note_.title}\n\n${this.note_.body}` : '';
this.text = this.note_ ? this.note_.title + "\n\n" + this.note_.body : '';
}
if (this.lastLoadedNoteId_ !== this.noteId_) this.scrollTop = 0;
@@ -58,6 +59,7 @@ class NoteWidget extends TextWidget {
this.scrollTop = 0;
}
}
}
module.exports = NoteWidget;
module.exports = NoteWidget;

View File

@@ -5,6 +5,7 @@ const stripAnsi = require('strip-ansi');
const { handleAutocompletion } = require('../autocompletion.js');
class StatusBarWidget extends BaseWidget {
constructor() {
super();
@@ -74,7 +75,7 @@ class StatusBarWidget extends BaseWidget {
super.render();
const doSaveCursor = !this.promptActive;
if (doSaveCursor) this.term.saveCursor();
this.innerClear();
@@ -84,15 +85,16 @@ class StatusBarWidget extends BaseWidget {
// On Windows, bgBlueBright is fine and looks dark enough (Windows is probably in the wrong though)
// For now, just don't use any colour at all.
// const textStyle = this.promptActive ? (s) => s : chalk.bgBlueBright.white;
// const textStyle = (s) => s;
const textStyle = this.promptActive ? s => s : chalk.gray;
//const textStyle = this.promptActive ? (s) => s : chalk.bgBlueBright.white;
//const textStyle = (s) => s;
const textStyle = this.promptActive ? (s) => s : chalk.gray;
this.term.drawHLine(this.absoluteInnerX, this.absoluteInnerY, this.innerWidth, textStyle(' '));
this.term.moveTo(this.absoluteInnerX, this.absoluteInnerY);
if (this.promptActive) {
this.term.write(textStyle(this.promptState_.promptString));
if (this.inputEventEmitter_) {
@@ -111,8 +113,8 @@ class StatusBarWidget extends BaseWidget {
history: this.history,
default: this.promptState_.initialText,
autoComplete: handleAutocompletion,
autoCompleteHint: true,
autoCompleteMenu: true,
autoCompleteHint : true,
autoCompleteMenu : true,
};
if ('cursorPosition' in this.promptState_) options.cursorPosition = this.promptState_.cursorPosition;
@@ -151,15 +153,19 @@ class StatusBarWidget extends BaseWidget {
// Only callback once everything has been cleaned up and reset
resolveFn(resolveResult);
});
} else {
for (let i = 0; i < this.items_.length; i++) {
const s = this.items_[i].substr(0, this.innerWidth - 1);
this.term.write(textStyle(s));
}
}
if (doSaveCursor) this.term.restoreCursor();
}
}
module.exports = StatusBarWidget;

View File

@@ -1,7 +1,10 @@
const fs = require('fs-extra');
const { wrap } = require('lib/string-utils.js');
const Setting = require('lib/models/Setting.js');
const { _ } = require('lib/locale.js');
const { fileExtension, basename, dirname } = require('lib/path-utils.js');
const { _, setLocale, languageCode } = require('lib/locale.js');
const rootDir = dirname(dirname(__dirname));
const MAX_WIDTH = 78;
const INDENT = ' ';
@@ -13,14 +16,14 @@ function renderTwoColumnData(options, baseIndent, width) {
let option = options[i];
const flag = option[0];
const indent = baseIndent + INDENT + ' '.repeat(optionColWidth + 2);
let r = wrap(option[1], indent, width);
r = r.substr(flag.length + (baseIndent + INDENT).length);
r = baseIndent + INDENT + flag + r;
output.push(r);
}
return output.join('\n');
return output.join("\n");
}
function renderCommandHelp(cmd, width = null) {
@@ -41,7 +44,7 @@ function renderCommandHelp(cmd, width = null) {
}
if (cmd.name() === 'config') {
const renderMetadata = md => {
const renderMetadata = (md) => {
let desc = [];
if (md.label) {
@@ -60,17 +63,17 @@ function renderCommandHelp(cmd, width = null) {
if ('value' in md) {
if (md.type === Setting.TYPE_STRING) {
defaultString = md.value ? `"${md.value}"` : null;
defaultString = md.value ? '"' + md.value + '"' : null;
} else if (md.type === Setting.TYPE_INT) {
defaultString = (md.value ? md.value : 0).toString();
} else if (md.type === Setting.TYPE_BOOL) {
defaultString = md.value === true ? 'true' : 'false';
defaultString = (md.value === true ? 'true' : 'false');
}
}
if (defaultString !== null) desc.push(_('Default: %s', defaultString));
return [md.key, desc.join('\n')];
return [md.key, desc.join("\n")];
};
output.push('');
@@ -80,7 +83,7 @@ function renderCommandHelp(cmd, width = null) {
let keysValues = [];
const keys = Setting.keys(true, 'cli');
for (let i = 0; i < keys.length; i++) {
if (keysValues.length) keysValues.push(['', '']);
if (keysValues.length) keysValues.push(['','']);
const md = Setting.settingMetadata(keys[i]);
if (!md.label) continue;
keysValues.push(renderMetadata(md));
@@ -88,8 +91,8 @@ function renderCommandHelp(cmd, width = null) {
output.push(renderTwoColumnData(keysValues, baseIndent, width));
}
return output.join('\n');
return output.join("\n");
}
function getOptionColWidth(options) {
@@ -101,4 +104,4 @@ function getOptionColWidth(options) {
return output;
}
module.exports = { renderCommandHelp };
module.exports = { renderCommandHelp };

View File

@@ -1,15 +1,12 @@
#!/usr/bin/env node
// Use njstrace to find out what Node.js might be spending time on
// var njstrace = require('njstrace').inject();
// Make it possible to require("/lib/...") without specifying full path
require('app-module-path').addPath(__dirname);
const compareVersion = require('compare-version');
const nodeVersion = process && process.versions && process.versions.node ? process.versions.node : '0.0.0';
if (compareVersion(nodeVersion, '8.0.0') < 0) {
console.error(`Joplin requires Node 8+. Detected version ${nodeVersion}`);
console.error('Joplin requires Node 8+. Detected version ' + nodeVersion);
process.exit(1);
}
@@ -22,7 +19,6 @@ const Tag = require('lib/models/Tag.js');
const NoteTag = require('lib/models/NoteTag.js');
const MasterKey = require('lib/models/MasterKey');
const Setting = require('lib/models/Setting.js');
const Revision = require('lib/models/Revision.js');
const { Logger } = require('lib/logger.js');
const { FsDriverNode } = require('lib/fs-driver-node.js');
const { shimInit } = require('lib/shim-init-node.js');
@@ -44,7 +40,6 @@ BaseItem.loadClass('Resource', Resource);
BaseItem.loadClass('Tag', Tag);
BaseItem.loadClass('NoteTag', NoteTag);
BaseItem.loadClass('MasterKey', MasterKey);
BaseItem.loadClass('Revision', Revision);
Setting.setConstant('appId', 'net.cozic.joplin-cli');
Setting.setConstant('appType', 'cli');
@@ -53,25 +48,25 @@ shimInit();
const application = app();
if (process.platform === 'win32') {
var rl = require('readline').createInterface({
if (process.platform === "win32") {
var rl = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
output: process.stdout
});
rl.on('SIGINT', function() {
process.emit('SIGINT');
rl.on("SIGINT", function () {
process.emit("SIGINT");
});
}
process.stdout.on('error', function(err) {
process.stdout.on('error', function( err ) {
// https://stackoverflow.com/questions/12329816/error-write-epipe-when-piping-node-output-to-head#15884508
if (err.code == 'EPIPE') {
if (err.code == "EPIPE") {
process.exit(0);
}
});
application.start(process.argv).catch(error => {
application.start(process.argv).catch((error) => {
if (error.code == 'flagError') {
console.error(error.message);
console.error(_('Type `joplin help` for usage information.'));
@@ -81,4 +76,4 @@ application.start(process.argv).catch(error => {
}
process.exit(1);
});
});

View File

@@ -1,11 +1,13 @@
const { _ } = require('lib/locale.js');
const { netUtils } = require('lib/net-utils.js');
const http = require('http');
const urlParser = require('url');
const http = require("http");
const urlParser = require("url");
const FormData = require('form-data');
const enableServerDestroy = require('server-destroy');
class OneDriveApiNodeUtils {
constructor(api) {
this.api_ = api;
this.oauthServer_ = null;
@@ -44,9 +46,9 @@ class OneDriveApiNodeUtils {
const port = await netUtils.findAvailablePort(this.possibleOAuthDancePorts(), 0);
if (!port) throw new Error(_('All potential ports are in use - please report the issue at %s', 'https://github.com/laurent22/joplin'));
let authCodeUrl = this.api().authCodeUrl(`http://localhost:${port}`);
let authCodeUrl = this.api().authCodeUrl('http://localhost:' + port);
return new Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
this.oauthServer_ = http.createServer();
let errorMessage = null;
@@ -54,7 +56,7 @@ class OneDriveApiNodeUtils {
const url = urlParser.parse(request.url, true);
if (url.pathname === '/auth') {
response.writeHead(302, { Location: authCodeUrl });
response.writeHead(302, { 'Location': authCodeUrl });
response.end();
return;
}
@@ -62,10 +64,10 @@ class OneDriveApiNodeUtils {
const query = url.query;
const writeResponse = (code, message) => {
response.writeHead(code, { 'Content-Type': 'text/html' });
response.writeHead(code, {"Content-Type": "text/html"});
response.write(this.makePage(message));
response.end();
};
}
// After the response has been received, don't destroy the server right
// away or the browser might display a connection reset error (even
@@ -75,24 +77,21 @@ class OneDriveApiNodeUtils {
this.oauthServer_.destroy();
this.oauthServer_ = null;
}, 1000);
};
}
if (!query.code) return writeResponse(400, '"code" query parameter is missing');
this.api()
.execTokenRequest(query.code, `http://localhost:${port.toString()}`)
.then(() => {
writeResponse(200, _('The application has been authorised - you may now close this browser tab.'));
targetConsole.log('');
targetConsole.log(_('The application has been successfully authorised.'));
waitAndDestroy();
})
.catch(error => {
writeResponse(400, error.message);
targetConsole.log('');
targetConsole.log(error.message);
waitAndDestroy();
});
this.api().execTokenRequest(query.code, 'http://localhost:' + port.toString()).then(() => {
writeResponse(200, _('The application has been authorised - you may now close this browser tab.'));
targetConsole.log('');
targetConsole.log(_('The application has been successfully authorised.'));
waitAndDestroy();
}).catch((error) => {
writeResponse(400, error.message);
targetConsole.log('');
targetConsole.log(error.message);
waitAndDestroy();
});
});
this.oauthServer_.on('close', () => {
@@ -114,9 +113,10 @@ class OneDriveApiNodeUtils {
targetConsole.log(_('Please open the following URL in your browser to authenticate the application. The application will create a directory in "Apps/Joplin" and will only read and write files in this directory. It will have no access to any files outside this directory nor to any other personal data. No data will be shared with any third party.'));
targetConsole.log('');
targetConsole.log(`http://127.0.0.1:${port}/auth`);
targetConsole.log('http://127.0.0.1:' + port + '/auth');
});
}
}
module.exports = { OneDriveApiNodeUtils };
module.exports = { OneDriveApiNodeUtils };

View File

@@ -5,6 +5,5 @@ BUILD_DIR="$ROOT_DIR/build"
rsync -a --exclude "node_modules/" "$ROOT_DIR/app/" "$BUILD_DIR/"
rsync -a --delete "$ROOT_DIR/../ReactNativeClient/lib/" "$BUILD_DIR/lib/"
rsync -a --delete "$ROOT_DIR/../ReactNativeClient/locales/" "$BUILD_DIR/locales/"
cp "$ROOT_DIR/package.json" "$BUILD_DIR"
chmod 755 "$BUILD_DIR/main.js"

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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