1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-12-29 23:48:19 +02:00

Compare commits

..

8 Commits

Author SHA1 Message Date
Laurent Cozic
84a793270d move back to test 2021-05-21 15:15:48 +02:00
Laurent Cozic
5f8b73350d other tdsts 2021-05-21 15:09:08 +02:00
Laurent Cozic
a733cb0394 services 2021-05-21 13:44:57 +02:00
Laurent Cozic
7da4cb0d80 sync tests 2021-05-21 13:22:50 +02:00
Laurent Cozic
3233082b4c move more 2021-05-21 13:14:45 +02:00
Laurent Cozic
c782f5e981 move 2021-05-21 13:01:43 +02:00
Laurent Cozic
db51e2dd4b cli setup 2021-05-21 12:42:19 +02:00
Laurent Cozic
f00f3d7f04 test move 2021-05-21 12:33:33 +02:00
108 changed files with 1005 additions and 2753 deletions

View File

@@ -83,9 +83,6 @@ packages/app-cli/tests/MdToHtml.js.map
packages/app-cli/tests/MdToMd.d.ts
packages/app-cli/tests/MdToMd.js
packages/app-cli/tests/MdToMd.js.map
packages/app-cli/tests/services/keychain/KeychainService.d.ts
packages/app-cli/tests/services/keychain/KeychainService.js
packages/app-cli/tests/services/keychain/KeychainService.js.map
packages/app-cli/tests/services/plugins/PluginService.d.ts
packages/app-cli/tests/services/plugins/PluginService.js
packages/app-cli/tests/services/plugins/PluginService.js.map
@@ -104,9 +101,6 @@ packages/app-cli/tests/services/plugins/api/JoplinWorkspace.js.map
packages/app-cli/tests/services/plugins/sandboxProxy.d.ts
packages/app-cli/tests/services/plugins/sandboxProxy.js
packages/app-cli/tests/services/plugins/sandboxProxy.js.map
packages/app-cli/tests/testUtils.d.ts
packages/app-cli/tests/testUtils.js
packages/app-cli/tests/testUtils.js.map
packages/app-desktop/ElectronAppWrapper.d.ts
packages/app-desktop/ElectronAppWrapper.js
packages/app-desktop/ElectronAppWrapper.js.map
@@ -1172,6 +1166,9 @@ packages/lib/services/keychain/KeychainServiceDriver.node.js.map
packages/lib/services/keychain/KeychainServiceDriverBase.d.ts
packages/lib/services/keychain/KeychainServiceDriverBase.js
packages/lib/services/keychain/KeychainServiceDriverBase.js.map
packages/lib/services/keychain/keychainService.test.d.ts
packages/lib/services/keychain/keychainService.test.js
packages/lib/services/keychain/keychainService.test.js.map
packages/lib/services/plugins/BasePluginRunner.d.ts
packages/lib/services/plugins/BasePluginRunner.js
packages/lib/services/plugins/BasePluginRunner.js.map

9
.gitignore vendored
View File

@@ -69,9 +69,6 @@ packages/app-cli/tests/MdToHtml.js.map
packages/app-cli/tests/MdToMd.d.ts
packages/app-cli/tests/MdToMd.js
packages/app-cli/tests/MdToMd.js.map
packages/app-cli/tests/services/keychain/KeychainService.d.ts
packages/app-cli/tests/services/keychain/KeychainService.js
packages/app-cli/tests/services/keychain/KeychainService.js.map
packages/app-cli/tests/services/plugins/PluginService.d.ts
packages/app-cli/tests/services/plugins/PluginService.js
packages/app-cli/tests/services/plugins/PluginService.js.map
@@ -90,9 +87,6 @@ packages/app-cli/tests/services/plugins/api/JoplinWorkspace.js.map
packages/app-cli/tests/services/plugins/sandboxProxy.d.ts
packages/app-cli/tests/services/plugins/sandboxProxy.js
packages/app-cli/tests/services/plugins/sandboxProxy.js.map
packages/app-cli/tests/testUtils.d.ts
packages/app-cli/tests/testUtils.js
packages/app-cli/tests/testUtils.js.map
packages/app-desktop/ElectronAppWrapper.d.ts
packages/app-desktop/ElectronAppWrapper.js
packages/app-desktop/ElectronAppWrapper.js.map
@@ -1158,6 +1152,9 @@ packages/lib/services/keychain/KeychainServiceDriver.node.js.map
packages/lib/services/keychain/KeychainServiceDriverBase.d.ts
packages/lib/services/keychain/KeychainServiceDriverBase.js
packages/lib/services/keychain/KeychainServiceDriverBase.js.map
packages/lib/services/keychain/keychainService.test.d.ts
packages/lib/services/keychain/keychainService.test.js
packages/lib/services/keychain/keychainService.test.js.map
packages/lib/services/plugins/BasePluginRunner.d.ts
packages/lib/services/plugins/BasePluginRunner.js
packages/lib/services/plugins/BasePluginRunner.js.map

View File

@@ -9,8 +9,6 @@ version: '3'
services:
db:
image: postgres:13.1
volumes:
- ./data/postgres:/var/lib/postgresql/data
ports:
- "5432:5432"
restart: unless-stopped

View File

@@ -108,12 +108,11 @@
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Defines whether the command should be enabled or disabled, which in turns
affects the enabled state of any associated button or menu item.</p>
<p>Defines whether the command should be enabled or disabled, which in turns affects
the enabled state of any associated button or menu item.</p>
</div>
<p>The condition should be expressed as a &quot;when-clause&quot; (as in Visual Studio
Code). It&#39;s a simple boolean expression that evaluates to <code>true</code> or
<code>false</code>. It supports the following operators:</p>
<p>The condition should be expressed as a &quot;when-clause&quot; (as in Visual Studio Code). It&#39;s a simple boolean expression that evaluates to
<code>true</code> or <code>false</code>. It supports the following operators:</p>
<table>
<thead>
<tr>
@@ -143,17 +142,7 @@
<td>&quot;oneNoteSelected &amp;&amp; !inConflictFolder&quot;</td>
</tr>
</tbody></table>
<p>Joplin, unlike VSCode, also supports parenthesis, which allows creating
more complex expressions such as <code>cond1 || (cond2 &amp;&amp; cond3)</code>. Only one
level of parenthesis is possible (nested ones aren&#39;t supported).</p>
<p>Currently the supported context variables aren&#39;t documented, but you can
find the list below:</p>
<ul>
<li>[Global When
Clauses](<a href="https://github.com/laurent22/joplin/blob/dev/packages/lib/services/commands/stateToWhenClauseContext.ts">https://github.com/laurent22/joplin/blob/dev/packages/lib/services/commands/stateToWhenClauseContext.ts</a>).</li>
<li>[Desktop app When
Clauses](<a href="https://github.com/laurent22/joplin/blob/dev/packages/app-desktop/services/commands/stateToWhenClauseContext.ts">https://github.com/laurent22/joplin/blob/dev/packages/app-desktop/services/commands/stateToWhenClauseContext.ts</a>).</li>
</ul>
<p>Currently the supported context variables aren&#39;t documented, but you can <a href="https://github.com/laurent22/joplin/blob/dev/packages/lib/services/commands/stateToWhenClauseContext.ts">find the list here</a>.</p>
<p>Note: Commands are enabled by default unless you use this property.</p>
</div>
</section>

View File

@@ -721,11 +721,6 @@ async function fetchAllNotes() {
<td></td>
</tr>
<tr>
<td>share_id</td>
<td>text</td>
<td></td>
</tr>
<tr>
<td>body_html</td>
<td>text</td>
<td>Note body, in HTML format</td>
@@ -846,11 +841,6 @@ async function fetchAllNotes() {
<td>int</td>
<td></td>
</tr>
<tr>
<td>share_id</td>
<td>text</td>
<td></td>
</tr>
</tbody>
</table>
<h2>GET /folders<a name="get-folders" href="#get-folders" class="heading-anchor">🔗</a></h2>
@@ -947,11 +937,6 @@ async function fetchAllNotes() {
<td>int</td>
<td></td>
</tr>
<tr>
<td>share_id</td>
<td>text</td>
<td></td>
</tr>
</tbody>
</table>
<h2>GET /resources<a name="get-resources" href="#get-resources" class="heading-anchor">🔗</a></h2>

View File

@@ -405,46 +405,6 @@ https://github.com/laurent22/joplin/blob/dev/readme/changelog.md
<p><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;business=E8JMYD2LQ8MMA&amp;lc=GB&amp;item_name=Joplin+Development&amp;currency_code=EUR&amp;bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted"><img src="https://joplinapp.org/images/badges/Donate-PayPal-green.svg" alt="Donate using PayPal"></a> <a href="https://github.com/sponsors/laurent22/"><img src="https://joplinapp.org/images/badges/GitHub-Badge.svg" alt="Sponsor on GitHub"></a> <a href="https://www.patreon.com/joplin"><img src="https://joplinapp.org/images/badges/Patreon-Badge.svg" alt="Become a patron"></a> <a href="https://joplinapp.org/donate/#donations"><img src="https://joplinapp.org/images/badges/Donate-IBAN.svg" alt="Donate using IBAN"></a></p>
<hr>
<h1>Joplin changelog<a name="joplin-changelog" href="#joplin-changelog" class="heading-anchor">🔗</a></h1>
<h2><a href="https://github.com/laurent22/joplin/releases/tag/v2.0.2">v2.0.2</a> (Pre-release) - 2021-05-21T18:07:48Z<a name="v2-0-2-https-github-com-laurent22-joplin-releases-tag-v2-0-2-pre-release-2021-05-21t18-07-48z" href="#v2-0-2-https-github-com-laurent22-joplin-releases-tag-v2-0-2-pre-release-2021-05-21t18-07-48z" class="heading-anchor">🔗</a></h2>
<ul>
<li>New: Add Share Notebook menu item (6f2f241)</li>
<li>New: Add classnames to DOM elements for theming purposes (<a href="https://github.com/laurent22/joplin/issues/4933">#4933</a> by <a href="https://github.com/ajilderda">@ajilderda</a>)</li>
<li>Improved: Allow unsharing a note (f7d164b)</li>
<li>Improved: Displays error info when Joplin Server fails (3f0586e)</li>
<li>Improved: Handle too large items for Joplin Server (d29624c)</li>
<li>Improved: Import SVG as images when importing ENEX files (<a href="https://github.com/laurent22/joplin/issues/4968">#4968</a>)</li>
<li>Improved: Import linked local files when importing Markdown files (<a href="https://github.com/laurent22/joplin/issues/4966">#4966</a>) (<a href="https://github.com/laurent22/joplin/issues/4433">#4433</a> by <a href="https://github.com/JackGruber">@JackGruber</a>)</li>
<li>Improved: Improved usability when plugin repository cannot be connected to (<a href="https://github.com/laurent22/joplin/issues/4462">#4462</a>)</li>
<li>Improved: Made sync more reliable by making it skip items that time out, and improved sync status screen (15fe119)</li>
<li>Improved: Pass custom CSS property to all export handlers and renderers (bd08041)</li>
<li>Improved: Regression: It was no longer possible to add list items in an empty note (6577f4f)</li>
<li>Improved: Regression: Pasting plain text in Rich Text editor was broken (9e9bf63)</li>
<li>Fixed: Fixed issue with empty panels being created by plugins (<a href="https://github.com/laurent22/joplin/issues/4926">#4926</a>)</li>
<li>Fixed: Fixed pasting HTML in Rich Text editor, and improved pasting plain text (2226b79)</li>
<li>Fixed: Improved importing Evernote notes that contain codeblocks (<a href="https://github.com/laurent22/joplin/issues/4965">#4965</a>)</li>
<li>Fixed: Prevent cursor from jumping to top of page when pasting image (<a href="https://github.com/laurent22/joplin/issues/4591">#4591</a>)</li>
</ul>
<h2><a href="https://github.com/laurent22/joplin/releases/tag/v2.0.1">v2.0.1</a> (Pre-release) - 2021-05-15T13:22:58Z<a name="v2-0-1-https-github-com-laurent22-joplin-releases-tag-v2-0-1-pre-release-2021-05-15t13-22-58z" href="#v2-0-1-https-github-com-laurent22-joplin-releases-tag-v2-0-1-pre-release-2021-05-15t13-22-58z" class="heading-anchor">🔗</a></h2>
<ul>
<li>New: Add support for sharing notebooks with Joplin Server (<a href="https://github.com/laurent22/joplin/issues/4772">#4772</a>)</li>
<li>New: Add new date format YYMMDD (<a href="https://github.com/laurent22/joplin/issues/4954">#4954</a> by Helmut K. C. Tessarek)</li>
<li>New: Added button to skip an application update (a31b402)</li>
<li>Fixed: Display proper error message when JEX file is corrupted (<a href="https://github.com/laurent22/joplin/issues/4958">#4958</a>)</li>
<li>Fixed: Show or hide completed todos in search results based on user settings (<a href="https://github.com/laurent22/joplin/issues/4951">#4951</a>) (<a href="https://github.com/laurent22/joplin/issues/4581">#4581</a> by <a href="https://github.com/JackGruber">@JackGruber</a>)</li>
<li>Fixed: Solve &quot;Resource Id not provided&quot; error (<a href="https://github.com/laurent22/joplin/issues/4943">#4943</a>) (<a href="https://github.com/laurent22/joplin/issues/4891">#4891</a> by <a href="https://github.com/Subhra264">@Subhra264</a>)</li>
</ul>
<h2><a href="https://github.com/laurent22/joplin/releases/tag/v1.8.5">v1.8.5</a> - 2021-05-10T11:58:14Z<a name="v1-8-5-https-github-com-laurent22-joplin-releases-tag-v1-8-5-2021-05-10t11-58-14z" href="#v1-8-5-https-github-com-laurent22-joplin-releases-tag-v1-8-5-2021-05-10t11-58-14z" class="heading-anchor">🔗</a></h2>
<ul>
<li>Fixed: Fixed pasting of text and images from Word on Windows (<a href="https://github.com/laurent22/joplin/issues/4916">#4916</a>)</li>
<li>Security: Filter out NOSCRIPT tags that could be used to cause an XSS (found by <a href="https://twitter.com/jubairfolder">Jubair Rehman Yousafzai</a>) (9c20d59)</li>
</ul>
<h2><a href="https://github.com/laurent22/joplin/releases/tag/v1.8.4">v1.8.4</a> (Pre-release) - 2021-05-09T18:05:05Z<a name="v1-8-4-https-github-com-laurent22-joplin-releases-tag-v1-8-4-pre-release-2021-05-09t18-05-05z" href="#v1-8-4-https-github-com-laurent22-joplin-releases-tag-v1-8-4-pre-release-2021-05-09t18-05-05z" class="heading-anchor">🔗</a></h2>
<ul>
<li>Improved: Improve display of release notes for new versions (f76f99b)</li>
<li>Fixed: Ensure that image paths that contain spaces are pasted correctly in the Rich Text editor (<a href="https://github.com/laurent22/joplin/issues/4916">#4916</a>)</li>
<li>Fixed: Make sure sync startup operations are cleared after startup (<a href="https://github.com/laurent22/joplin/issues/4919">#4919</a>)</li>
<li>Security: Apply npm audit security fixes (0b67446)</li>
</ul>
<h2><a href="https://github.com/laurent22/joplin/releases/tag/v1.8.3">v1.8.3</a> (Pre-release) - 2021-05-04T10:38:16Z<a name="v1-8-3-https-github-com-laurent22-joplin-releases-tag-v1-8-3-pre-release-2021-05-04t10-38-16z" href="#v1-8-3-https-github-com-laurent22-joplin-releases-tag-v1-8-3-pre-release-2021-05-04t10-38-16z" class="heading-anchor">🔗</a></h2>
<ul>
<li>New: Add &quot;id&quot; and &quot;due&quot; search filters (<a href="https://github.com/laurent22/joplin/issues/4898">#4898</a> by <a href="https://github.com/JackGruber">@JackGruber</a>)</li>

View File

@@ -1,443 +0,0 @@
<!doctype html>
<html>
<!--
!!! WARNING !!!
This file was auto-generated from readme/changelog_android.md and any manual change
made to it will be overwritten. To make a change to this file please modify
the source Markdown file:
https://github.com/laurent22/joplin/blob/dev/readme/changelog_android.md
-->
<head>
<title>Joplin Android app changelog | Joplin</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://joplinapp.org/css/bootstrap.min.css">
<link rel="shortcut icon" type="image/x-icon" href="https://joplinapp.org/favicon.ico">
<!-- <link rel="stylesheet" href="https://joplinapp.org/css/fontawesome-all.min.css"> -->
<link rel="stylesheet" href="https://joplinapp.org/css/fork-awesome.min.css">
<script src="https://joplinapp.org/js/jquery-3.2.1.slim.min.js"></script>
<style>
body {
background-color: #F1F1F1;
color: #333333;
}
.root {
overflow: hidden;
}
a[href^="mailto:"] {
word-break: break-all;
}
table {
margin-bottom: 1em;
}
td, th {
padding: .8em;
border: 1px solid #ccc;
}
.page-markdown table pre,
.page-markdown table blockquote {
margin-bottom: 0;
}
.page-markdown table pre,
.page-markdown table blockquote {
margin-bottom: 0;
}
.page-markdown table pre {
background-color: rgba(0,0,0,0);
border: none;
margin: 0;
padding: 0;
}
h1, h2 {
border-bottom: 1px solid #eaecef;
padding-bottom: 0.3em;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
font-weight: 600;
font-size: 2em;
margin-bottom: 16px;
}
h2 {
font-size: 1.6em;
}
h3 {
font-size: 1.3em;
}
code {
color: black;
background-color: #eee;
border: 1px solid #ccc;
font-size: .85em;
/* word-break: break-all; */
}
pre code {
border: none;
}
pre {
font-size: .85em;
}
blockquote {
font-size: 1em;
color: #555;
};
#toc ul {
margin-bottom: 10px;
}
#toc > ul > li {
margin-bottom: 10px;
}
#toc {
padding-bottom: 1em;
}
.title {
display: flex;
align-items: center;
}
.title-icon {
display: flex;
height: 1em;
}
.title-text {
display: flex;
font-weight: normal;
margin-bottom: .2em;
margin-left: .5em;
}
.sub-title {
font-weight: normal;
}
.container {
background-color: white;
padding: 0;
box-shadow: 0 10px 20px #888888;
}
table.screenshots {
margin-top: 2em;
margin-bottom: 2em;
}
table.screenshots th {
height: 3em;
text-align: center;
}
table.screenshots th,
table.screenshots td {
border: 1px solid #C2C2C2;
}
img[align="left"] {
margin-right: 10px;
margin-bottom: 10px;
}
.mobile-screenshot {
height: 40em;
padding: 1em;
}
.cli-screenshot-wrapper {
background-color: black;
vertical-align: top;
padding: 1em 2em 1em 1em;
}
.cli-screenshot {
font-family: "Monaco", "Inconsolata", "CONSOLAS", "Deja Vu Sans Mono", "Droid Sans Mono", "Andale Mono", monospace;
background-color: black;
color: white;
border: none;
}
.cli-screenshot .prompt {
color: #48C2F0;
}
.top-screenshot {
margin-top: 2em;
text-align: center;
}
.header {
position: relative;
padding-left: 2em;
padding-right: 2em;
padding-top: 1em;
padding-bottom: 1em;
color: white;
background-color: #2B2B3D;
}
.header a h1 {
color: white;
}
.header a:hover {
text-decoration: none;
}
.content {
padding-left: 2em;
padding-right: 2em;
padding-bottom: 2em;
padding-top: 2em;
}
.forkme {
position: absolute;
right: 0;
top:0;
}
.nav-wrapper {
position: relative;
width: inherit;
}
.nav {
background-color: black;
display: flex;
flex-direction: row;
align-items: center;
}
.nav.sticky {
position:fixed;
top: 0;
width: inherit;
box-shadow: 0 0 10px #000000;
}
.nav a {
color: white;
display: inline-block;
padding: .6em .9em .6em .9em;
}
.nav ul {
padding-left: 2em;
margin-bottom: 0;
display: table-cell;
display: flex;
width: 100%;
/* For GSoC: */
min-width: 470px;
}
.nav ul li {
display: inline-block;
padding: 0;
}
.nav li.selected {
background-color: #222;
font-weight: bold;
}
.nav-right {
display: flex;
text-align: right;
vertical-align: middle;
line-height: 0;
margin-right: 10px;
}
.nav-right .share-btn {
display: none;
}
.nav-right .small-share-btn {
display: none;
}
.footer {
padding: 2em;
border-top: 1px solid #d4d4d4;
margin-top: 2em;
color: gray;
font-size: .9em;
}
a.heading-anchor {
display: inline-block;
opacity: 0;
width: 1.3em;
font-size: 0.7em;
margin-left: 0.4em;
line-height: 1em;
text-decoration: none;
transition: opacity 0.3s;
}
a.heading-anchor:hover,
h1:hover a.heading-anchor,
h2:hover a.heading-anchor,
h3:hover a.heading-anchor,
h4:hover a.heading-anchor,
h5:hover a.heading-anchor,
h6:hover a.heading-anchor {
opacity: 1;
}
@media (min-width: 992px) {
.content{
display: flex;
}
#toc{
display: block!important;
align-self: flex-start;
width: 300px;
position: sticky; top: 20px; left: 0;
}
.main{
width: calc(100% - 300px);
}
}
.bottom-links {
display: flex;
justify-content: center;
border-top: 1px solid #d4d4d4;
margin-top: 30px;
padding-top: 25px;
}
@media all and (min-width: 400px) {
.nav-right .share-btn {
display: inline-block;
}
.nav-right .small-share-btn {
display: none;
}
}
</style>
</head>
<body>
<div class="container root page-changelog_android">
<div class="header">
<a class="forkme" href="https://github.com/laurent22/joplin"><img src="https://joplinapp.org/images/ForkMe.png"/></a>
<a href="https://joplinapp.org"><h1 class="title"><img class="title-icon" src="https://joplinapp.org/images/Icon512.png"><span class="title-text">Joplin</span></h1></a>
<p class="sub-title">An open source note taking and to-do application with synchronisation capabilities</p>
</div>
<div class="nav-wrapper">
<div class="nav">
<ul>
<li class=""><a href="https:&#x2F;&#x2F;joplinapp.org/" title="Home"><i class="fa fa-home"></i></a></li>
<li><a href="https://discourse.joplinapp.org" title="Forum">Forum</a></li>
<li><a class="gsoc" href="https://joplinapp.org/gsoc2021/index/" title="Google Summer of Code 2021">GSoC 2021</a></li>
</ul>
<div class="nav-right">
<iframe class="share-btn share-btn-github" src="https://ghbtns.com/github-btn.html?user=laurent22&repo=joplin&type=star&count=true" frameborder="0" scrolling="0" width="115px" height="20px"></iframe>
</div>
</div>
</div>
<div class="content">
<div id="toc"><ul>
<li>
<p>Applications</p>
<ul>
<li><a href="https://joplinapp.org/desktop/">Desktop application</a></li>
<li><a href="https://joplinapp.org/mobile/">Mobile applications</a></li>
<li><a href="https://joplinapp.org/terminal/">Terminal application</a></li>
<li><a href="https://joplinapp.org/clipper/">Web Clipper</a></li>
</ul>
</li>
<li>
<p>Support</p>
<ul>
<li><a href="https://discourse.joplinapp.org">Joplin Forum</a></li>
<li><a href="https://joplinapp.org/markdown/">Markdown Guide</a></li>
<li><a href="https://joplinapp.org/e2ee/">How to enable end-to-end encryption</a></li>
<li><a href="https://joplinapp.org/conflict/">What is a conflict?</a></li>
<li><a href="https://joplinapp.org/debugging/">How to enable debug mode</a></li>
<li><a href="https://joplinapp.org/rich_text_editor/">About the Rich Text editor limitations</a></li>
<li><a href="https://joplinapp.org/faq/">FAQ</a></li>
</ul>
</li>
<li>
<p>Joplin API - Get Started</p>
<ul>
<li><a href="https://joplinapp.org/api/overview/">Joplin API Overview</a></li>
<li><a href="https://joplinapp.org/api/get_started/plugins/">Plugin development</a></li>
<li><a href="https://joplinapp.org/api/tutorials/toc_plugin/">Plugin tutorial</a></li>
</ul>
</li>
<li>
<p>Joplin API - References</p>
<ul>
<li><a href="https://joplinapp.org/api/references/plugin_api/classes/joplin.html">Plugin API</a></li>
<li><a href="https://joplinapp.org/api/references/rest_api/">Data API</a></li>
<li><a href="https://joplinapp.org/api/references/plugin_manifest/">Plugin manifest</a></li>
<li><a href="https://joplinapp.org/api/references/plugin_loading_rules/">Plugin loading rules</a></li>
<li><a href="https://joplinapp.org/api/references/plugin_theming/">Plugin theming</a></li>
</ul>
</li>
<li>
<p>Development</p>
<ul>
<li><a href="https://github.com/laurent22/joplin/blob/dev/BUILD.md">How to build the apps</a></li>
<li><a href="https://joplinapp.org/spec/e2ee/">End-to-end encryption spec</a></li>
<li><a href="https://joplinapp.org/spec/history/">Note History spec</a></li>
<li><a href="https://joplinapp.org/spec/sync_lock/">Sync Lock spec</a></li>
<li><a href="https://joplinapp.org/spec/plugins/">Plugin Architecture spec</a></li>
<li><a href="https://joplinapp.org/spec/search_sorting/">Search Sorting spec</a></li>
<li><a href="https://joplinapp.org/spec/server_file_url_format/">Server: File URL Format</a></li>
<li><a href="https://joplinapp.org/spec/server_delta_sync/">Server: Delta Sync</a></li>
<li><a href="https://joplinapp.org/spec/server_sharing/">Server: Sharing</a></li>
</ul>
</li>
<li>
<p>Google Summer of Code 2021</p>
<ul>
<li><a href="https://joplinapp.org/gsoc2021/index/">Google Summer of Code 2021</a></li>
<li><a href="https://joplinapp.org/gsoc2021/pull_request_guidelines/">How to submit a GSoC pull request</a></li>
<li><a href="https://joplinapp.org/gsoc2021/ideas/">Project Ideas</a></li>
</ul>
</li>
<li>
<p>About</p>
<ul>
<li><a href="https://joplinapp.org/changelog/">Changelog (Desktop App)</a></li>
<li><a href="https://joplinapp.org/changelog_cli/">Changelog (CLI App)</a></li>
<li><a href="https://joplinapp.org/changelog_server/">Changelog (Server)</a></li>
<li><a href="https://joplinapp.org/stats/">Stats</a></li>
<li><a href="https://joplinapp.org/donate/">Donate</a></li>
</ul>
</li>
</ul>
</div>
<div class="main">
<p><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;business=E8JMYD2LQ8MMA&amp;lc=GB&amp;item_name=Joplin+Development&amp;currency_code=EUR&amp;bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted"><img src="https://joplinapp.org/images/badges/Donate-PayPal-green.svg" alt="Donate using PayPal"></a> <a href="https://github.com/sponsors/laurent22/"><img src="https://joplinapp.org/images/badges/GitHub-Badge.svg" alt="Sponsor on GitHub"></a> <a href="https://www.patreon.com/joplin"><img src="https://joplinapp.org/images/badges/Patreon-Badge.svg" alt="Become a patron"></a> <a href="https://joplinapp.org/donate/#donations"><img src="https://joplinapp.org/images/badges/Donate-IBAN.svg" alt="Donate using IBAN"></a></p>
<hr>
<h1>Joplin Android app changelog<a name="joplin-android-app-changelog" href="#joplin-android-app-changelog" class="heading-anchor">🔗</a></h1>
<div class="bottom-links">
<a href="https://github.com/laurent22/joplin/blob/dev/readme/changelog_android.md">
<i class="fa fa-github"></i> Improve this doc
</a>
</div>
<script>
function stickyHeader() {
return; // Disabled
if ($(window).scrollTop() > 179) {
$('.nav').addClass('sticky');
} else {
$('.nav').removeClass('sticky');
}
}
$(window).scroll(function() {
stickyHeader();
});
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-103586105-1', 'auto');
ga('send', 'pageview');
</script>
</div></div>
<div class="footer">
Copyright (C) 2016-2021 Laurent Cozic
</div>
</body>
</html>

View File

@@ -405,16 +405,6 @@ https://github.com/laurent22/joplin/blob/dev/readme/changelog_server.md
<p><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;business=E8JMYD2LQ8MMA&amp;lc=GB&amp;item_name=Joplin+Development&amp;currency_code=EUR&amp;bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted"><img src="https://joplinapp.org/images/badges/Donate-PayPal-green.svg" alt="Donate using PayPal"></a> <a href="https://github.com/sponsors/laurent22/"><img src="https://joplinapp.org/images/badges/GitHub-Badge.svg" alt="Sponsor on GitHub"></a> <a href="https://www.patreon.com/joplin"><img src="https://joplinapp.org/images/badges/Patreon-Badge.svg" alt="Become a patron"></a> <a href="https://joplinapp.org/donate/#donations"><img src="https://joplinapp.org/images/badges/Donate-IBAN.svg" alt="Donate using IBAN"></a></p>
<hr>
<h1>Joplin Server Changelog<a name="joplin-server-changelog" href="#joplin-server-changelog" class="heading-anchor">🔗</a></h1>
<h2><a href="https://github.com/laurent22/joplin/releases/tag/server-v2.0.1">server-v2.0.1</a> (Pre-release) - 2021-05-14T13:55:45Z<a name="server-v2-0-1-https-github-com-laurent22-joplin-releases-tag-server-v2-0-1-pre-release-2021-05-14t13-55-45z" href="#server-v2-0-1-https-github-com-laurent22-joplin-releases-tag-server-v2-0-1-pre-release-2021-05-14t13-55-45z" class="heading-anchor">🔗</a></h2>
<ul>
<li>New: Add support for sharing notes via a link (ccbc329)</li>
<li>New: Add support for sharing a folder (#4772)</li>
<li>New: Added log page to view latest changes to files (874f301)</li>
<li>Fixed: Prevent new user password from being hashed twice (76c143e)</li>
<li>Fixed: Fixed crash when rendering note with links to non-existing resources or notes (07484de)</li>
<li>Fixed: Fixed error handling when no session is provided (63a5bfa)</li>
<li>Fixed: Fixed uploading empty file to the API (#4402)</li>
</ul>
<h2><a href="https://github.com/laurent22/joplin/releases/tag/server-v1.7.2">server-v1.7.2</a> - 2021-01-24T19:11:10Z<a name="server-v1-7-2-https-github-com-laurent22-joplin-releases-tag-server-v1-7-2-2021-01-24t19-11-10z" href="#server-v1-7-2-https-github-com-laurent22-joplin-releases-tag-server-v1-7-2-2021-01-24t19-11-10z" class="heading-anchor">🔗</a></h2>
<ul>
<li>Fixed: Fixed password hashing when changing password</li>

View File

@@ -424,19 +424,19 @@ https://github.com/laurent22/joplin/blob/dev/README.md
<tbody>
<tr>
<td>Windows (32 and 64-bit)</td>
<td><a href='https://github.com/laurent22/joplin/releases/download/v1.8.5/Joplin-Setup-1.8.5.exe'><img alt='Get it on Windows' width="134px" src='https://joplinapp.org/images/BadgeWindows.png'/></a></td>
<td><a href='https://github.com/laurent22/joplin/releases/download/v1.7.11/Joplin-Setup-1.7.11.exe'><img alt='Get it on Windows' width="134px" src='https://joplinapp.org/images/BadgeWindows.png'/></a></td>
</tr>
<tr>
<td>macOS</td>
<td><a href='https://github.com/laurent22/joplin/releases/download/v1.8.5/Joplin-1.8.5.dmg'><img alt='Get it on macOS' width="134px" src='https://joplinapp.org/images/BadgeMacOS.png'/></a></td>
<td><a href='https://github.com/laurent22/joplin/releases/download/v1.7.11/Joplin-1.7.11.dmg'><img alt='Get it on macOS' width="134px" src='https://joplinapp.org/images/BadgeMacOS.png'/></a></td>
</tr>
<tr>
<td>Linux</td>
<td><a href='https://github.com/laurent22/joplin/releases/download/v1.8.5/Joplin-1.8.5.AppImage'><img alt='Get it on Linux' width="134px" src='https://joplinapp.org/images/BadgeLinux.png'/></a></td>
<td><a href='https://github.com/laurent22/joplin/releases/download/v1.7.11/Joplin-1.7.11.AppImage'><img alt='Get it on Linux' width="134px" src='https://joplinapp.org/images/BadgeLinux.png'/></a></td>
</tr>
</tbody>
</table>
<p><strong>On Windows</strong>, you may also use the <a href='https://github.com/laurent22/joplin/releases/download/v1.8.5/JoplinPortable.exe'>Portable version</a>. The <a href="https://en.wikipedia.org/wiki/Portable_application">portable application</a> allows installing the software on a portable device such as a USB key. Simply copy the file JoplinPortable.exe in any directory on that USB key ; the application will then create a directory called &quot;JoplinProfile&quot; next to the executable file.</p>
<p><strong>On Windows</strong>, you may also use the <a href='https://github.com/laurent22/joplin/releases/download/v1.7.11/JoplinPortable.exe'>Portable version</a>. The <a href="https://en.wikipedia.org/wiki/Portable_application">portable application</a> allows installing the software on a portable device such as a USB key. Simply copy the file JoplinPortable.exe in any directory on that USB key ; the application will then create a directory called &quot;JoplinProfile&quot; next to the executable file.</p>
<p><strong>On Linux</strong>, the recommended way is to use the following installation script as it will handle the desktop icon too:</p>
<pre><code style="word-break: break-all">wget -O - https://raw.githubusercontent.com/laurent22/joplin/dev/Joplin_install_and_update.sh | bash</code></pre>
<h2>Mobile applications<a name="mobile-applications" href="#mobile-applications" class="heading-anchor">🔗</a></h2>
@@ -662,7 +662,7 @@ Joplin is also capable of exporting to a number of other formats including HTML
&quot;s3:DeleteObject&quot;,
&quot;s3:DeleteObjectVersion&quot;,
&quot;s3:PutObject&quot;
],
]
&quot;Resource&quot;: [
&quot;arn:aws:s3:::joplin-bucket&quot;,
&quot;arn:aws:s3:::joplin-bucket/*&quot;
@@ -692,7 +692,7 @@ Joplin is also capable of exporting to a number of other formats including HTML
<ul>
<li><strong>Windows</strong>: &gt;= 8. Make sure the Action Center is enabled on Windows. Task bar balloon for Windows &lt; 8. Growl as fallback. Growl takes precedence over Windows balloons.</li>
<li><strong>macOS</strong>: &gt;= 10.8 or Growl if earlier.</li>
<li><strong>Linux</strong>: <code>notify-send</code> tool, delivered through packages <code>notify-osd</code>, <code>libnotify-bin</code> or <code>libnotify-tools</code>. GNOME should have this by default, but install <code>libnotify-tools</code> if using KDE Plasma.</li>
<li><strong>Linux</strong>: <code>notify-osd</code> or <code>libnotify-bin</code> installed (Ubuntu should have this by default). Growl otherwise</li>
</ul>
<p>See <a href="https://github.com/mikaelbr/node-notifier/blob/master/DECISION_FLOW.md">documentation and flow chart for reporter choice</a></p>
<p>On mobile, the alarms will be displayed using the built-in notification system.</p>
@@ -989,49 +989,49 @@ Eg. <code>:search -- &quot;-tag:tag1&quot;</code>.</p>
<td>Arabic</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/ar.po">ar</a></td>
<td><a href="mailto:Whaell@protonmail.com">Whaell O</a></td>
<td>96%</td>
<td>99%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/es/basque_country.png" alt=""></td>
<td>Basque</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/eu.po">eu</a></td>
<td>juan.abasolo@ehu.eus</td>
<td>30%</td>
<td>31%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/ba.png" alt=""></td>
<td>Bosnian (Bosna i Hercegovina)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/bs_BA.po">bs_BA</a></td>
<td><a href="mailto:dervis.t@pm.me">Derviš T.</a></td>
<td>75%</td>
<td>74%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/bg.png" alt=""></td>
<td>Bulgarian (България)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/bg_BG.po">bg_BG</a></td>
<td></td>
<td>58%</td>
<td>60%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/es/catalonia.png" alt=""></td>
<td>Catalan</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/ca.po">ca</a></td>
<td>jmontane, 2019</td>
<td>83%</td>
<td>85%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/hr.png" alt=""></td>
<td>Croatian (Hrvatska)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/hr_HR.po">hr_HR</a></td>
<td><a href="mailto:mail@milotype.de">Milo Ivir</a></td>
<td>96%</td>
<td>99%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/cz.png" alt=""></td>
<td>Czech (Česká republika)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/cs_CZ.po">cs_CZ</a></td>
<td><a href="mailto:lukas@aiya.cz">Lukas Helebrandt</a></td>
<td>86%</td>
<td>89%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/dk.png" alt=""></td>
@@ -1045,14 +1045,14 @@ Eg. <code>:search -- &quot;-tag:tag1&quot;</code>.</p>
<td>Deutsch (Deutschland)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/de_DE.po">de_DE</a></td>
<td><a href="mailto:atalanttore@googlemail.com">Atalanttore</a></td>
<td>95%</td>
<td>98%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/ee.png" alt=""></td>
<td>Eesti Keel (Eesti)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/et_EE.po">et_EE</a></td>
<td></td>
<td>57%</td>
<td>58%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/gb.png" alt=""></td>
@@ -1073,203 +1073,203 @@ Eg. <code>:search -- &quot;-tag:tag1&quot;</code>.</p>
<td>Español (España)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/es_ES.po">es_ES</a></td>
<td><a href="mailto:mario.campo@gmail.com">Mario Campo</a></td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/esperanto.png" alt=""></td>
<td>Esperanto</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/eo.po">eo</a></td>
<td>Marton Paulo</td>
<td>33%</td>
<td>34%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/fi.png" alt=""></td>
<td>Finnish (Suomi)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/fi_FI.po">fi_FI</a></td>
<td>mrkaato</td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/fr.png" alt=""></td>
<td>Français (France)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/fr_FR.po">fr_FR</a></td>
<td>Laurent Cozic</td>
<td>99%</td>
<td>95%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/es/galicia.png" alt=""></td>
<td>Galician (España)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/gl_ES.po">gl_ES</a></td>
<td><a href="mailto:marcoslansgarza@gmail.com">Marcos Lans</a></td>
<td>38%</td>
<td>39%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/id.png" alt=""></td>
<td>Indonesian (Indonesia)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/id_ID.po">id_ID</a></td>
<td><a href="mailto:42007357+eresytter@users.noreply.github.com">eresytter</a></td>
<td>93%</td>
<td>96%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/it.png" alt=""></td>
<td>Italiano (Italia)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/it_IT.po">it_IT</a></td>
<td><a href="mailto:mailfilledwithspam@gmail.com">Alessandro Bernardello</a></td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/hu.png" alt=""></td>
<td>Magyar (Magyarország)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/hu_HU.po">hu_HU</a></td>
<td><a href="mailto:mail@szokesandor.hu">Szőke Sándor</a></td>
<td>88%</td>
<td>91%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/be.png" alt=""></td>
<td>Nederlands (België, Belgique, Belgien)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/nl_BE.po">nl_BE</a></td>
<td></td>
<td>92%</td>
<td>95%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/nl.png" alt=""></td>
<td>Nederlands (Nederland)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/nl_NL.po">nl_NL</a></td>
<td><a href="mailto:metbril@users.noreply.github.com">MetBril</a></td>
<td>95%</td>
<td>98%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/no.png" alt=""></td>
<td>Norwegian (Norge, Noreg)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/nb_NO.po">nb_NO</a></td>
<td><a href="mailto:code@mxe.no">Mats Estensen</a></td>
<td>76%</td>
<td>78%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/ir.png" alt=""></td>
<td>Persian</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/fa.po">fa</a></td>
<td><a href="mailto:kourox@protonmail.com">Kourosh Firoozbakht</a></td>
<td>71%</td>
<td>74%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/pl.png" alt=""></td>
<td>Polski (Polska)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/pl_PL.po">pl_PL</a></td>
<td><a href="mailto:hello.konhi@gmail.com">konhi</a></td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/br.png" alt=""></td>
<td>Português (Brasil)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/pt_BR.po">pt_BR</a></td>
<td><a href="mailto:nicolas.suzuki@pm.me">Nicolas Suzuki</a></td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/pt.png" alt=""></td>
<td>Português (Portugal)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/pt_PT.po">pt_PT</a></td>
<td><a href="mailto:dcaveiro@yahoo.com">Diogo Caveiro</a></td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/ro.png" alt=""></td>
<td>Română</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/ro.po">ro</a></td>
<td><a href="mailto:cristi.duluta@gmail.com">Cristi Duluta</a></td>
<td>66%</td>
<td>68%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/si.png" alt=""></td>
<td>Slovenian (Slovenija)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/sl_SI.po">sl_SI</a></td>
<td><a href="mailto:martin.korelic@protonmail.com">Martin Korelič</a></td>
<td>96%</td>
<td>99%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/se.png" alt=""></td>
<td>Svenska</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/sv.po">sv</a></td>
<td><a href="mailto:jonatan@autistici.org">Jonatan Nyberg</a></td>
<td>61%</td>
<td>63%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/th.png" alt=""></td>
<td>Thai (ประเทศไทย)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/th_TH.po">th_TH</a></td>
<td></td>
<td>45%</td>
<td>47%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/vi.png" alt=""></td>
<td>Tiếng Việt</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/vi.po">vi</a></td>
<td></td>
<td>73%</td>
<td>75%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/tr.png" alt=""></td>
<td>Türkçe (Türkiye)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/tr_TR.po">tr_TR</a></td>
<td><a href="mailto:arda@kilicdagi.com">Arda Kılıçdağı</a></td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/ua.png" alt=""></td>
<td>Ukrainian (Україна)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/uk_UA.po">uk_UA</a></td>
<td><a href="mailto:vandreykiv@gmail.com">Vyacheslav Andreykiv</a></td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/gr.png" alt=""></td>
<td>Ελληνικά (Ελλάδα)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/el_GR.po">el_GR</a></td>
<td><a href="mailto:xaris@tuta.io">Harris Arvanitis</a></td>
<td>97%</td>
<td>85%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/ru.png" alt=""></td>
<td>Русский (Россия)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/ru_RU.po">ru_RU</a></td>
<td><a href="mailto:thesermanarm@gmail.com">Sergey Segeda</a></td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/rs.png" alt=""></td>
<td>српски језик (Србија)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/sr_RS.po">sr_RS</a></td>
<td></td>
<td>71%</td>
<td>73%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/cn.png" alt=""></td>
<td>中文 (简体)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/zh_CN.po">zh_CN</a></td>
<td><a href="mailto:zyangmath@gmail.com">Yang Zhang</a></td>
<td>94%</td>
<td>97%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/tw.png" alt=""></td>
<td>中文 (繁體)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/zh_TW.po">zh_TW</a></td>
<td><a href="mailto:yaozeye@yahoo.co.jp">Yaoze Ye</a></td>
<td>92%</td>
<td>95%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/jp.png" alt=""></td>
<td>日本語 (日本)</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/ja_JP.po">ja_JP</a></td>
<td><a href="mailto:genneko217@gmail.com">genneko</a></td>
<td>97%</td>
<td>98%</td>
</tr>
<tr>
<td><img src="https://joplinapp.org/images/flags/country-4x3/kr.png" alt=""></td>
<td>한국어</td>
<td><a href="https://github.com/laurent22/joplin/blob/dev/packages/tools/locales/ko.po">ko</a></td>
<td><a href="mailto:potatogim@potatogim.net">Ji-Hyeon Gim</a></td>
<td>96%</td>
<td>97%</td>
</tr>
</tbody>
</table>

View File

@@ -101,10 +101,15 @@
"default": "",
"description": "Joplin Server URL. Attention: If you change this location, make sure you copy all your content to it before syncing, otherwise all files will be removed! See the FAQ for more details: https://joplinapp.org/faq/"
},
"sync.9.directory": {
"type": "string",
"default": "Apps/Joplin",
"description": "Joplin Server Directory"
},
"sync.9.username": {
"type": "string",
"default": "",
"description": "Joplin Server email"
"description": "Joplin Server username"
},
"sync.9.password": {
"type": "string",
@@ -597,11 +602,6 @@
"default": -1,
"$comment": "private"
},
"sync.userId": {
"type": "string",
"default": "",
"$comment": "private"
},
"style.zoom": {
"type": "integer",
"default": 100,
@@ -633,7 +633,7 @@
},
"autoUpdateEnabled": {
"type": "boolean",
"default": true,
"default": false,
"description": "Automatically update the application"
},
"autoUpdate.includePreReleases": {
@@ -726,6 +726,12 @@
"description": "Enable spell checking in Markdown editor? (WARNING BETA feature). Spell checker in the Markdown editor was previously unstable (cursor location was not stable, sometimes edits would not be saved or reflected in the viewer, etc.) however it appears to be more reliable now. If you notice any issue, please report it on GitHub or the Joplin Forum (Help -> Joplin Forum)",
"$comment": "private"
},
"image.noresizing": {
"type": "boolean",
"default": false,
"description": "Do not resize images",
"$comment": "private"
},
"net.customCertificates": {
"type": "string",
"default": "",

File diff suppressed because it is too large Load Diff

View File

@@ -33,7 +33,8 @@ module.exports = {
'<rootDir>/node_modules/',
'<rootDir>/tests/support/',
'<rootDir>/build/',
'<rootDir>/tests/testUtils.js',
'<rootDir>/tests/test-utils.js',
'<rootDir>/tests/test-utils-synchronizer.js',
'<rootDir>/tests/tmp/',
'<rootDir>/tests/test data/',
],

View File

@@ -7,8 +7,8 @@ import Setting from '@joplin/lib/models/Setting';
import * as fs from 'fs-extra';
import Note from '@joplin/lib/models/Note';
import Folder from '@joplin/lib/models/Folder';
import { newPluginScript } from '@joplin/lib/testing/test-utils';
import { expectNotThrow, setupDatabaseAndSynchronizer, switchClient, expectThrow, createTempDir, supportDir } from '@joplin/lib/testing/test-utils';
import { newPluginScript } from '../../testUtils';
const testPluginDir = `${supportDir}/plugins`;

View File

@@ -1,7 +1,7 @@
import Setting from '@joplin/lib/models/Setting';
import { waitForFolderCount, setupDatabaseAndSynchronizer, switchClient, afterEachCleanUp } from '@joplin/lib/testing/test-utils';
import PluginService from '@joplin/lib/services/plugins/PluginService';
const { waitForFolderCount, newPluginService, newPluginScript, setupDatabaseAndSynchronizer, switchClient, afterEachCleanUp } = require('@joplin/lib/testing/test-utils');
import Folder from '@joplin/lib/models/Folder';
import { newPluginScript, newPluginService } from '../../../testUtils';
describe('JoplinSettings', () => {
@@ -16,7 +16,7 @@ describe('JoplinSettings', () => {
});
test('should listen to setting change event', async () => {
const service = newPluginService();
const service = new newPluginService() as PluginService;
const pluginScript = newPluginScript(`
joplin.plugins.register({
@@ -68,7 +68,7 @@ describe('JoplinSettings', () => {
});
test('should allow registering multiple settings', async () => {
const service = newPluginService();
const service = new newPluginService() as PluginService;
const pluginScript = newPluginScript(`
joplin.plugins.register({

View File

@@ -1,6 +1,6 @@
import KeymapService from '@joplin/lib/services/KeymapService';
import { setupDatabaseAndSynchronizer, switchClient, afterEachCleanUp } from '@joplin/lib/testing/test-utils';
import { newPluginScript, newPluginService } from '../../../testUtils';
import PluginService from '@joplin/lib/services/plugins/PluginService';
const { newPluginService, newPluginScript, setupDatabaseAndSynchronizer, switchClient, afterEachCleanUp } = require('@joplin/lib/testing/test-utils');
describe('JoplinViewMenuItem', () => {
@@ -15,7 +15,7 @@ describe('JoplinViewMenuItem', () => {
});
test('should register commands with the keymap service', async () => {
const service = newPluginService();
const service = new newPluginService() as PluginService;
KeymapService.instance().initialize();

View File

@@ -1,9 +1,8 @@
import Setting from '@joplin/lib/models/Setting';
import { setupDatabaseAndSynchronizer, switchClient, afterEachCleanUp } from '@joplin/lib/testing/test-utils';
import { newPluginService, newPluginScript, setupDatabaseAndSynchronizer, switchClient, afterEachCleanUp } from '@joplin/lib/testing/test-utils';
import Note from '@joplin/lib/models/Note';
import Folder from '@joplin/lib/models/Folder';
import ItemChange from '@joplin/lib/models/ItemChange';
import { newPluginScript, newPluginService } from '../../../testUtils';
describe('JoplinWorkspace', () => {

View File

@@ -1,5 +1,6 @@
import sandboxProxy, { Target } from '@joplin/lib/services/plugins/sandboxProxy';
import { setupDatabaseAndSynchronizer, switchClient } from '@joplin/lib/testing/test-utils';
const { setupDatabaseAndSynchronizer, switchClient } = require('@joplin/lib/testing/test-utils.js');
describe('services_plugins_sandboxProxy', function() {

View File

@@ -1,41 +0,0 @@
import PluginService from '@joplin/lib/services/plugins/PluginService';
import PluginRunner from '../app/services/plugins/PluginRunner';
export interface PluginServiceOptions {
getState?(): Record<string, any>;
}
export function newPluginService(appVersion = '1.4', options: PluginServiceOptions = null): PluginService {
options = options || {};
const runner = new PluginRunner();
const service = new PluginService();
service.initialize(
appVersion,
{
joplin: {},
},
runner,
{
dispatch: () => {},
getState: options.getState ? options.getState : () => {},
}
);
return service;
}
export function newPluginScript(script: string) {
return `
/* joplin-manifest:
{
"id": "org.joplinapp.plugins.PluginTest",
"manifest_version": 1,
"app_min_version": "1.4",
"name": "JS Bundle test",
"version": "1.0.0"
}
*/
${script}
`;
}

View File

@@ -2,7 +2,7 @@ import * as React from 'react';
import { useRef, useState, useEffect } from 'react';
import useWindowResizeEvent from './utils/useWindowResizeEvent';
import setLayoutItemProps from './utils/setLayoutItemProps';
import useLayoutItemSizes, { LayoutItemSizes, itemSize, calculateMaxSizeAvailableForItem, itemMinWidth, itemMinHeight } from './utils/useLayoutItemSizes';
import useLayoutItemSizes, { LayoutItemSizes, itemSize } from './utils/useLayoutItemSizes';
import validateLayout from './utils/validateLayout';
import { Size, LayoutItem } from './utils/types';
import { canMove, MoveDirection } from './utils/movements';
@@ -11,6 +11,9 @@ import { StyledWrapperRoot, StyledMoveOverlay, MoveModeRootWrapper, MoveModeRoot
import { Resizable } from 're-resizable';
const EventEmitter = require('events');
const itemMinWidth = 20;
const itemMinHeight = 20;
interface onResizeEvent {
layout: LayoutItem;
}
@@ -32,7 +35,7 @@ function itemVisible(item: LayoutItem, moveMode: boolean) {
return item.visible !== false;
}
function renderContainer(item: LayoutItem, parent: LayoutItem | null, sizes: LayoutItemSizes, resizedItemMaxSize: Size | null, onResizeStart: Function, onResize: Function, onResizeStop: Function, children: any[], isLastChild: boolean, moveMode: boolean): any {
function renderContainer(item: LayoutItem, parent: LayoutItem | null, sizes: LayoutItemSizes, onResizeStart: Function, onResize: Function, onResizeStop: Function, children: any[], isLastChild: boolean, moveMode: boolean): any {
const style: any = {
display: itemVisible(item, moveMode) ? 'flex' : 'none',
flexDirection: item.direction,
@@ -65,8 +68,6 @@ function renderContainer(item: LayoutItem, parent: LayoutItem | null, sizes: Lay
enable={enable}
minWidth={'minWidth' in item ? item.minWidth : itemMinWidth}
minHeight={'minHeight' in item ? item.minHeight : itemMinHeight}
maxWidth={resizedItemMaxSize?.width}
maxHeight={resizedItemMaxSize?.height}
>
{children}
</Resizable>
@@ -113,7 +114,6 @@ function ResizableLayout(props: Props) {
key: item.key,
initialWidth: sizes[item.key].width,
initialHeight: sizes[item.key].height,
maxSize: calculateMaxSizeAvailableForItem(item, parent, sizes),
});
}
@@ -143,7 +143,6 @@ function ResizableLayout(props: Props) {
setResizedItem(null);
}
const resizedItemMaxSize = item.key === resizedItem?.key ? resizedItem.maxSize : null;
if (!item.children) {
const size = itemSize(item, parent, sizes, false);
@@ -156,7 +155,7 @@ function ResizableLayout(props: Props) {
const wrapper = renderItemWrapper(comp, item, parent, size, props.moveMode);
return renderContainer(item, parent, sizes, resizedItemMaxSize, onResizeStart, onResize, onResizeStop, [wrapper], isLastChild, props.moveMode);
return renderContainer(item, parent, sizes, onResizeStart, onResize, onResizeStop, [wrapper], isLastChild, props.moveMode);
} else {
const childrenComponents = [];
for (let i = 0; i < item.children.length; i++) {
@@ -164,7 +163,7 @@ function ResizableLayout(props: Props) {
childrenComponents.push(renderLayoutItem(child, item, sizes, isVisible && itemVisible(child, props.moveMode), i === item.children.length - 1));
}
return renderContainer(item, parent, sizes, resizedItemMaxSize, onResizeStart, onResize, onResizeStop, childrenComponents, isLastChild, props.moveMode);
return renderContainer(item, parent, sizes, onResizeStart, onResize, onResizeStop, childrenComponents, isLastChild, props.moveMode);
}
}

View File

@@ -1,4 +1,4 @@
import useLayoutItemSizes, { itemSize, calculateMaxSizeAvailableForItem } from './useLayoutItemSizes';
import useLayoutItemSizes, { itemSize } from './useLayoutItemSizes';
import { LayoutItem, LayoutItemDirection } from './types';
import { renderHook } from '@testing-library/react-hooks';
import validateLayout from './validateLayout';
@@ -138,219 +138,4 @@ describe('useLayoutItemSizes', () => {
expect(itemSize(parent.children[1], parent, sizes, false)).toEqual({ width: 95, height: 50 });
});
test('should decrease size of the largest item if the total size would be larger than the container', () => {
const layout: LayoutItem = validateLayout({
key: 'root',
width: 200,
height: 100,
direction: LayoutItemDirection.Row,
children: [
{
key: 'col1',
width: 110,
},
{
key: 'col2',
width: 100,
},
{
key: 'col3',
minWidth: 50,
},
],
});
const { result } = renderHook(() => useLayoutItemSizes(layout));
const sizes = result.current;
expect(sizes.col1.width).toBe(50);
expect(sizes.col2.width).toBe(100);
expect(sizes.col3.width).toBe(50);
});
test('should not allow a minWidth of 0, should still make space for the item', () => {
const layout: LayoutItem = validateLayout({
key: 'root',
width: 200,
height: 100,
direction: LayoutItemDirection.Row,
children: [
{
key: 'col1',
width: 210,
},
{
key: 'col2',
minWidth: 0,
},
],
});
const { result } = renderHook(() => useLayoutItemSizes(layout));
const sizes = result.current;
expect(sizes.col1.width).toBe(160);
expect(sizes.col2.width).toBe(40); // default minWidth is 40
});
test('should ignore invisible items when counting remaining size', () => {
const layout: LayoutItem = validateLayout({
key: 'root',
width: 200,
height: 100,
direction: LayoutItemDirection.Row,
children: [
{
key: 'col1',
width: 110,
visible: false,
},
{
key: 'col2',
width: 100,
},
{
key: 'col3',
minWidth: 50,
},
],
});
const { result } = renderHook(() => useLayoutItemSizes(layout));
const sizes = result.current;
expect(sizes.col1.width).toBe(0);
expect(sizes.col2.width).toBe(100);
expect(sizes.col3.width).toBe(100);
});
test('should ignore invisible items when selecting largest child', () => {
const layout: LayoutItem = validateLayout({
key: 'root',
width: 200,
height: 100,
direction: LayoutItemDirection.Row,
children: [
{
key: 'col1',
width: 110,
visible: false,
},
{
key: 'col2',
width: 100,
},
{
key: 'col3',
width: 110,
},
{
key: 'col4',
minWidth: 50,
},
],
});
const { result } = renderHook(() => useLayoutItemSizes(layout));
const sizes = result.current;
expect(sizes.col1.width).toBe(0);
expect(sizes.col2.width).toBe(100);
expect(sizes.col3.width).toBe(50);
expect(sizes.col4.width).toBe(50);
});
});
describe('calculateMaxSizeAvailableForItem', () => {
test('should give maximum available space this item can take up during resizing', () => {
const layout: LayoutItem = validateLayout({
key: 'root',
width: 200,
height: 100,
direction: LayoutItemDirection.Row,
children: [
{
key: 'col1',
width: 50,
},
{
key: 'col2',
width: 70,
},
{
key: 'col3',
},
],
});
const { result } = renderHook(() => useLayoutItemSizes(layout));
const sizes = result.current;
const maxSize1 = calculateMaxSizeAvailableForItem(layout.children[0], layout, sizes);
const maxSize2 = calculateMaxSizeAvailableForItem(layout.children[1], layout, sizes);
// maxSize = totalSize - ( [size of items with set size, except for the current item] + [minimum size of items with no set size] )
expect(maxSize1.width).toBe(90); // 90 = layout.width - (col2.width + col3.minWidth(=40) )
expect(maxSize2.width).toBe(110); // 110 = layout.width - (col1.width + col3.minWidth(=40) )
});
test('should respect minimum sizes', () => {
const layout: LayoutItem = validateLayout({
key: 'root',
width: 200,
height: 100,
direction: LayoutItemDirection.Row,
children: [
{
key: 'col1',
width: 50,
},
{
key: 'col2',
width: 70,
},
{
key: 'col3',
minWidth: 60,
},
],
});
const { result } = renderHook(() => useLayoutItemSizes(layout));
const sizes = result.current;
const maxSize1 = calculateMaxSizeAvailableForItem(layout.children[0], layout, sizes);
const maxSize2 = calculateMaxSizeAvailableForItem(layout.children[1], layout, sizes);
// maxSize = totalSize - ( [size of items with set size, except for the current item] + [minimum size of items with no set size] )
expect(maxSize1.width).toBe(70); // 70 = layout.width - (col2.width + col3.minWidth)
expect(maxSize2.width).toBe(90); // 90 = layout.width - (col1.width + col3.minWidth)
});
test('should not allow a minWidth of 0, should still leave space for the item', () => {
const layout: LayoutItem = validateLayout({
key: 'root',
width: 200,
height: 100,
direction: LayoutItemDirection.Row,
children: [
{
key: 'col1',
width: 50,
},
{
key: 'col2',
minWidth: 0,
},
],
});
const { result } = renderHook(() => useLayoutItemSizes(layout));
const sizes = result.current;
const maxSize1 = calculateMaxSizeAvailableForItem(layout.children[0], layout, sizes);
// maxSize = totalSize - ( [size of items with set size, except for the current item] + [minimum size of items with no set size] )
expect(maxSize1.width).toBe(160); // 160 = layout.width - col2.minWidth(=40)
});
});

View File

@@ -3,9 +3,6 @@ import { LayoutItem, Size } from './types';
const dragBarThickness = 5;
export const itemMinWidth = 40;
export const itemMinHeight = 40;
export interface LayoutItemSizes {
[key: string]: Size;
}
@@ -20,8 +17,8 @@ export function itemSize(item: LayoutItem, parent: LayoutItem | null, sizes: Lay
const bottomGap = !isContainer && (item.resizableBottom || parentResizableBottom) ? dragBarThickness : 0;
return {
width: sizes[item.key].width - rightGap,
height: sizes[item.key].height - bottomGap,
width: ('width' in item ? item.width : sizes[item.key].width) - rightGap,
height: ('height' in item ? item.height : sizes[item.key].height) - bottomGap,
};
}
@@ -41,10 +38,6 @@ function calculateChildrenSizes(item: LayoutItem, parent: LayoutItem | null, siz
const noWidthChildren: any[] = [];
const noHeightChildren: any[] = [];
// The minimum space required for items with no defined size
let noWidthChildrenMinWidth = 0;
let noHeightChildrenMinHeight = 0;
for (const child of item.children) {
let w = 'width' in child ? child.width : null;
let h = 'height' in child ? child.height : null;
@@ -54,43 +47,10 @@ function calculateChildrenSizes(item: LayoutItem, parent: LayoutItem | null, siz
}
sizes[child.key] = { width: w, height: h };
if (w !== null) remainingSize.width -= w;
if (h !== null) remainingSize.height -= h;
if (w === null) {
noWidthChildren.push({ item: child, parent: item });
noWidthChildrenMinWidth += child.minWidth || itemMinWidth;
}
if (h === null) {
noHeightChildren.push({ item: child, parent: item });
noHeightChildrenMinHeight += child.minHeight || itemMinHeight;
}
}
while (remainingSize.width < noWidthChildrenMinWidth) {
// There is not enough space, the widest item will be made smaller
let widestChild = item.children[0].key;
for (const child of item.children) {
if (!child.visible) continue;
if (sizes[child.key].width > sizes[widestChild].width) widestChild = child.key;
}
const dw = Math.abs(remainingSize.width - noWidthChildrenMinWidth);
sizes[widestChild].width -= dw;
remainingSize.width += dw;
}
while (remainingSize.height < noHeightChildrenMinHeight) {
// There is not enough space, the tallest item will be made smaller
let tallestChild = item.children[0].key;
for (const child of item.children) {
if (!child.visible) continue;
if (sizes[child.key].height > sizes[tallestChild].height) tallestChild = child.key;
}
const dh = Math.abs(remainingSize.height - noHeightChildrenMinHeight);
sizes[tallestChild].height -= dh;
remainingSize.height += dh;
if (w === null) noWidthChildren.push({ item: child, parent: item });
if (h === null) noHeightChildren.push({ item: child, parent: item });
}
if (noWidthChildren.length) {
@@ -117,24 +77,6 @@ function calculateChildrenSizes(item: LayoutItem, parent: LayoutItem | null, siz
return sizes;
}
// Gives the maximum available space for this item that it can take up during resizing
// availableSize = totalSize - ( [size of items with set size, except for the current item] + [minimum size of items with no set size] )
export function calculateMaxSizeAvailableForItem(item: LayoutItem, parent: LayoutItem, sizes: LayoutItemSizes): Size {
const availableSize: Size = { ...sizes[parent.key] };
for (const sibling of parent.children) {
if (!sibling.visible) continue;
availableSize.width -= 'width' in sibling ? sizes[sibling.key].width : (sibling.minWidth || itemMinWidth);
availableSize.height -= 'height' in sibling ? sizes[sibling.key].height : (sibling.minHeight || itemMinHeight);
}
availableSize.width += sizes[item.key].width;
availableSize.height += sizes[item.key].height;
return availableSize;
}
export default function useLayoutItemSizes(layout: LayoutItem, makeAllVisible: boolean = false) {
return useMemo(() => {
let sizes: LayoutItemSizes = {};

View File

@@ -1,6 +1,6 @@
{
"name": "@joplin/app-desktop",
"version": "2.0.2",
"version": "2.0.1",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View File

@@ -1,6 +1,6 @@
{
"name": "@joplin/app-desktop",
"version": "2.0.2",
"version": "2.0.1",
"description": "Joplin for Desktop",
"main": "main.js",
"private": true,

View File

@@ -26,12 +26,12 @@ if [ "$RESET_ALL" == "1" ]; then
echo "config keychain.supported 0" >> "$CMD_FILE"
echo "config sync.target 9" >> "$CMD_FILE"
echo "config sync.9.path http://api-joplincloud.local:22300" >> "$CMD_FILE"
echo "config sync.9.path http://localhost:22300" >> "$CMD_FILE"
echo "config sync.9.username $USER_EMAIL" >> "$CMD_FILE"
echo "config sync.9.password 123456" >> "$CMD_FILE"
if [ "$1" == "1" ]; then
curl --data '{"action": "createTestUsers"}' -H 'Content-Type: application/json' http://api-joplincloud.local:22300/api/debug
curl --data '{"action": "createTestUsers"}' http://localhost:22300/api/debug
echo 'mkbook "shared"' >> "$CMD_FILE"
echo 'mkbook "other"' >> "$CMD_FILE"

View File

@@ -4905,11 +4905,6 @@
"resolved": "https://registry.npmjs.org/jetifier/-/jetifier-1.6.6.tgz",
"integrity": "sha512-JNAkmPeB/GS2tCRqUzRPsTOHpGDah7xP18vGJfIjZC+W2sxEHbxgJxetIjIqhjQ3yYbYNEELkM/spKLtwoOSUQ=="
},
"joplin-rn-alarm-notification": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/joplin-rn-alarm-notification/-/joplin-rn-alarm-notification-1.0.3.tgz",
"integrity": "sha512-HZGDrLmYf6aMVgzk02w4DS9CjaTogE1hnOLdMDsrWkZzRskO6g3bZw+Bwlc63cCX4ZLZeeWIaABzHoWKAbLzpQ=="
},
"js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -7102,6 +7097,11 @@
"prop-types": "^15.5.10"
}
},
"react-native-alarm-notification": {
"version": "1.7.1",
"resolved": "https://registry.npmjs.org/react-native-alarm-notification/-/react-native-alarm-notification-1.7.1.tgz",
"integrity": "sha512-cvfSqCCfw48NyeFTEL5WOF/tkeWLNI7X1mVoEQ/9aY+2fuBtkCfZUoJ7vvOOHeryPbDJrlDNpRWTi3erLphZ+w=="
},
"react-native-camera": {
"version": "3.40.0",
"resolved": "https://registry.npmjs.org/react-native-camera/-/react-native-camera-3.40.0.tgz",

View File

@@ -3,11 +3,8 @@ import { _ } from './locale';
const { rtrimSlashes } = require('./path-utils.js');
import JoplinError from './JoplinError';
import { Env } from './models/Setting';
import Logger from './Logger';
const { stringify } = require('query-string');
const logger = Logger.create('JoplinServerApi');
interface Options {
baseUrl(): string;
username(): string;
@@ -77,7 +74,7 @@ export default class JoplinServerApi {
public static connectionErrorMessage(error: any) {
const msg = error && error.message ? error.message : 'Unknown error';
return _('Could not connect to Joplin Cloud. Please check the Synchronisation options in the config screen. Full error was:\n\n%s', msg);
return _('Could not connect to Joplin Server. Please check the Synchronisation options in the config screen. Full error was:\n\n%s', msg);
}
private requestToCurl_(url: string, options: any) {
@@ -136,78 +133,71 @@ export default class JoplinServerApi {
url += stringify(query);
}
try {
if (this.debugRequests_) {
logger.debug(this.requestToCurl_(url, fetchOptions));
}
let response: any = null;
let response: any = null;
if (options.source == 'file' && (method == 'POST' || method == 'PUT')) {
if (fetchOptions.path) {
const fileStat = await shim.fsDriver().stat(fetchOptions.path);
if (fileStat) fetchOptions.headers['Content-Length'] = `${fileStat.size}`;
}
response = await shim.uploadBlob(url, fetchOptions);
} else if (options.target == 'string') {
if (typeof body === 'string') fetchOptions.headers['Content-Length'] = `${shim.stringByteLength(body)}`;
response = await shim.fetch(url, fetchOptions);
} else {
// file
response = await shim.fetchBlob(url, fetchOptions);
}
const responseText = await response.text();
if (this.debugRequests_) {
logger.debug('Response', responseText);
}
// Creates an error object with as much data as possible as it will appear in the log, which will make debugging easier
const newError = (message: string, code: number = 0) => {
// Gives a shorter response for error messages. Useful for cases where a full HTML page is accidentally loaded instead of
// JSON. That way the error message will still show there's a problem but without filling up the log or screen.
const shortResponseText = (`${responseText}`).substr(0, 1024);
// return new JoplinError(`${method} ${path}: ${message} (${code}): ${shortResponseText}`, code);
return new JoplinError(message, code, `${method} ${path}: ${message} (${code}): ${shortResponseText}`);
};
let responseJson_: any = null;
const loadResponseJson = async () => {
if (!responseText) return null;
if (responseJson_) return responseJson_;
responseJson_ = JSON.parse(responseText);
if (!responseJson_) throw newError('Cannot parse JSON response', response.status);
return responseJson_;
};
if (!response.ok) {
if (options.target === 'file') throw newError('fetchBlob error', response.status);
let json = null;
try {
json = await loadResponseJson();
} catch (error) {
// Just send back the plain text in newErro()
}
if (json && json.error) {
throw newError(`${json.error}`, json.code ? json.code : response.status);
}
throw newError('Unknown error', response.status);
}
if (options.responseFormat === 'text') return responseText;
const output = await loadResponseJson();
return output;
} catch (error) {
if (error.code !== 404) {
logger.warn(this.requestToCurl_(url, fetchOptions));
logger.warn(error);
}
throw error;
if (this.debugRequests_) {
console.info('Joplin API Call', `${method} ${url}`, headers, options);
console.info(this.requestToCurl_(url, fetchOptions));
}
if (options.source == 'file' && (method == 'POST' || method == 'PUT')) {
if (fetchOptions.path) {
const fileStat = await shim.fsDriver().stat(fetchOptions.path);
if (fileStat) fetchOptions.headers['Content-Length'] = `${fileStat.size}`;
}
response = await shim.uploadBlob(url, fetchOptions);
} else if (options.target == 'string') {
if (typeof body === 'string') fetchOptions.headers['Content-Length'] = `${shim.stringByteLength(body)}`;
response = await shim.fetch(url, fetchOptions);
} else {
// file
response = await shim.fetchBlob(url, fetchOptions);
}
const responseText = await response.text();
if (this.debugRequests_) {
console.info('Joplin API Response', responseText);
}
// Creates an error object with as much data as possible as it will appear in the log, which will make debugging easier
const newError = (message: string, code: number = 0) => {
// Gives a shorter response for error messages. Useful for cases where a full HTML page is accidentally loaded instead of
// JSON. That way the error message will still show there's a problem but without filling up the log or screen.
const shortResponseText = (`${responseText}`).substr(0, 1024);
// return new JoplinError(`${method} ${path}: ${message} (${code}): ${shortResponseText}`, code);
return new JoplinError(message, code, `${method} ${path}: ${message} (${code}): ${shortResponseText}`);
};
let responseJson_: any = null;
const loadResponseJson = async () => {
if (!responseText) return null;
if (responseJson_) return responseJson_;
responseJson_ = JSON.parse(responseText);
if (!responseJson_) throw newError('Cannot parse JSON response', response.status);
return responseJson_;
};
if (!response.ok) {
if (options.target === 'file') throw newError('fetchBlob error', response.status);
let json = null;
try {
json = await loadResponseJson();
} catch (error) {
// Just send back the plain text in newErro()
}
if (json && json.error) {
throw newError(`${json.error}`, json.code ? json.code : response.status);
}
throw newError('Unknown error', response.status);
}
if (options.responseFormat === 'text') return responseText;
const output = await loadResponseJson();
return output;
}
}

View File

@@ -27,7 +27,7 @@ export default class SyncTargetJoplinServer extends BaseSyncTarget {
}
public static label() {
return `${_('Joplin Cloud')} (Beta)`;
return `${_('Joplin Server')} (Beta)`;
}
public async isAuthenticated() {

View File

@@ -1,8 +1,17 @@
const { afterEachCleanUp } = require('./testing/test-utils.js');
const { shimInit } = require('./shim-init-node.js');
const shim = require('./shim').default;
const sharp = require('sharp');
shimInit(sharp, null);
let keytar;
try {
keytar = shim.platformSupportsKeyChain() ? require('keytar') : null;
} catch (error) {
console.error('Cannot load keytar - keychain support will be disabled', error);
keytar = null;
}
shimInit(sharp, keytar);
global.afterEach(async () => {
await afterEachCleanUp();

View File

@@ -472,7 +472,7 @@ class Setting extends BaseModel {
return settings['sync.target'] == SyncTargetRegistry.nameToId('joplinServer');
},
public: true,
label: () => _('Joplin Cloud URL'),
label: () => _('Joplin Server URL'),
description: () => emptyDirWarning,
storage: SettingStorage.File,
},
@@ -487,7 +487,7 @@ class Setting extends BaseModel {
// return value ? ltrimSlashes(rtrimSlashes(value)) : '';
// },
// public: true,
// label: () => _('Joplin Cloud Directory'),
// label: () => _('Joplin Server Directory'),
// storage: SettingStorage.File,
// },
'sync.9.username': {
@@ -498,7 +498,7 @@ class Setting extends BaseModel {
return settings['sync.target'] == SyncTargetRegistry.nameToId('joplinServer');
},
public: true,
label: () => _('Joplin Cloud email'),
label: () => _('Joplin Server email'),
storage: SettingStorage.File,
},
'sync.9.password': {
@@ -509,7 +509,7 @@ class Setting extends BaseModel {
return settings['sync.target'] == SyncTargetRegistry.nameToId('joplinServer');
},
public: true,
label: () => _('Joplin Cloud password'),
label: () => _('Joplin Server password'),
secure: true,
},

View File

@@ -4059,6 +4059,24 @@
"verror": "1.10.0"
}
},
"keytar": {
"version": "7.7.0",
"resolved": "https://registry.npmjs.org/keytar/-/keytar-7.7.0.tgz",
"integrity": "sha512-YEY9HWqThQc5q5xbXbRwsZTh2PJ36OSYRjSv3NN2xf5s5dpLTjEZnC2YikR29OaVybf9nQ0dJ/80i40RS97t/A==",
"dev": true,
"requires": {
"node-addon-api": "^3.0.0",
"prebuild-install": "^6.0.0"
},
"dependencies": {
"node-addon-api": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.0.tgz",
"integrity": "sha512-kcwSAWhPi4+QzAtsL2+2s/awvDo2GKLsvMCwNRxb5BUshteXU8U97NCyvQDsGKs/m0He9WcG4YWew/BnuLx++w==",
"dev": true
}
}
},
"kind-of": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",

View File

@@ -21,6 +21,7 @@
"@types/fs-extra": "^9.0.6",
"jest": "^26.6.3",
"sharp": "^0.26.2",
"keytar": "^7.0.0",
"typescript": "^4.0.5",
"clean-html": "^1.5.0"
},

View File

@@ -1,7 +1,8 @@
import KeychainService from '@joplin/lib/services/keychain/KeychainService';
import shim from '@joplin/lib/shim';
import Setting from '@joplin/lib/models/Setting';
import { db, setupDatabaseAndSynchronizer, switchClient } from '@joplin/lib/testing/test-utils';
import KeychainService from '../../services/keychain/KeychainService';
import shim from '../../shim';
import Setting from '../../models/Setting';
const { db, setupDatabaseAndSynchronizer, switchClient } = require('../../testing/test-utils.js');
function describeIfCompatible(name: string, fn: any, elseFn: any) {
if (['win32', 'darwin'].includes(shim.platformName())) {

View File

@@ -48,8 +48,10 @@ export interface Command {
* Currently the supported context variables aren't documented, but you can
* find the list below:
*
* - [Global When Clauses](https://github.com/laurent22/joplin/blob/dev/packages/lib/services/commands/stateToWhenClauseContext.ts)
* - [Desktop app When Clauses](https://github.com/laurent22/joplin/blob/dev/packages/app-desktop/services/commands/stateToWhenClauseContext.ts)
* - [Global When
* Clauses](https://github.com/laurent22/joplin/blob/dev/packages/lib/services/commands/stateToWhenClauseContext.ts).
* - [Desktop app When
* Clauses](https://github.com/laurent22/joplin/blob/dev/packages/app-desktop/services/commands/stateToWhenClauseContext.ts).
*
* Note: Commands are enabled by default unless you use this property.
*/

View File

@@ -13,6 +13,8 @@ import KeymapService from '../services/KeymapService';
import KvStore from '../services/KvStore';
import KeychainServiceDriver from '../services/keychain/KeychainServiceDriver.node';
import KeychainServiceDriverDummy from '../services/keychain/KeychainServiceDriver.dummy';
import PluginRunner from '../../app-cli/app/services/plugins/PluginRunner';
import PluginService from '../services/plugins/PluginService';
import FileApiDriverJoplinServer from '../file-api-driver-joplinServer';
import OneDriveApi from '../onedrive-api';
import SyncTargetOneDrive from '../SyncTargetOneDrive';
@@ -764,6 +766,45 @@ async function createTempDir() {
return tempDirPath;
}
interface PluginServiceOptions {
getState?(): Record<string, any>;
}
function newPluginService(appVersion = '1.4', options: PluginServiceOptions = null): PluginService {
options = options || {};
const runner = new PluginRunner();
const service = new PluginService();
service.initialize(
appVersion,
{
joplin: {},
},
runner,
{
dispatch: () => {},
getState: options.getState ? options.getState : () => {},
}
);
return service;
}
function newPluginScript(script: string) {
return `
/* joplin-manifest:
{
"id": "org.joplinapp.plugins.PluginTest",
"manifest_version": 1,
"app_min_version": "1.4",
"name": "JS Bundle test",
"version": "1.0.0"
}
*/
${script}
`;
}
async function waitForFolderCount(count: number) {
const timeout = 2000;
const startTime = Date.now();
@@ -860,4 +901,4 @@ class TestApp extends BaseApplication {
}
}
export { supportDir, waitForFolderCount, afterAllCleanUp, exportDir, synchronizerStart, afterEachCleanUp, syncTargetName, setSyncTargetName, syncDir, createTempDir, isNetworkSyncTarget, kvStore, expectThrow, logger, expectNotThrow, resourceService, resourceFetcher, tempFilePath, allSyncTargetItemsEncrypted, msleep, setupDatabase, revisionService, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync, checkThrow, encryptionService, loadEncryptionMasterKey, fileContentEqual, decryptionWorker, currentClientId, id, ids, sortedIds, at, createNTestNotes, createNTestFolders, createNTestTags, TestApp };
export { supportDir, waitForFolderCount, afterAllCleanUp, exportDir, newPluginService, newPluginScript, synchronizerStart, afterEachCleanUp, syncTargetName, setSyncTargetName, syncDir, createTempDir, isNetworkSyncTarget, kvStore, expectThrow, logger, expectNotThrow, resourceService, resourceFetcher, tempFilePath, allSyncTargetItemsEncrypted, msleep, setupDatabase, revisionService, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync, checkThrow, encryptionService, loadEncryptionMasterKey, fileContentEqual, decryptionWorker, currentClientId, id, ids, sortedIds, at, createNTestNotes, createNTestFolders, createNTestTags, TestApp };

View File

@@ -38,16 +38,11 @@ function credentialFile(filename) {
});
}
exports.credentialFile = credentialFile;
function readCredentialFile(filename, defaultValue = '') {
function readCredentialFile(filename) {
return __awaiter(this, void 0, void 0, function* () {
try {
const filePath = yield credentialFile(filename);
const r = yield fs.readFile(filePath);
return r.toString();
}
catch (error) {
return defaultValue;
}
const filePath = yield credentialFile(filename);
const r = yield fs.readFile(filePath);
return r.toString();
});
}
exports.readCredentialFile = readCredentialFile;

View File

@@ -24,12 +24,8 @@ export async function credentialFile(filename: string) {
return output;
}
export async function readCredentialFile(filename: string, defaultValue: string = '') {
try {
const filePath = await credentialFile(filename);
const r = await fs.readFile(filePath);
return r.toString();
} catch (error) {
return defaultValue;
}
export async function readCredentialFile(filename: string) {
const filePath = await credentialFile(filename);
const r = await fs.readFile(filePath);
return r.toString();
}

View File

@@ -6,5 +6,4 @@ db-*.sqlite
*.pid
logs/
tests/temp/
temp/
.env
temp/

View File

@@ -1,9 +1,4 @@
{
"verbose": true,
"watch": [
"dist/",
"../renderer",
"../lib",
"src/views"
]
"watch": ["dist/", "../renderer", "../lib"]
}

View File

@@ -1,6 +1,6 @@
{
"name": "@joplin/server",
"version": "2.0.4",
"version": "2.0.1",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -1389,15 +1389,6 @@
"integrity": "sha512-9fq4jZVhPNW8r+UYKnxF1e2HkDWOWKM5bC2/7c9wPV835I0aOrVbS/Hw/pWPk2uKrNXQqg9Z959Kz+IYDd5p3w==",
"dev": true
},
"@types/nodemailer": {
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.1.tgz",
"integrity": "sha512-8081UY/0XTTDpuGqCnDc8IY+Q3DSg604wB3dBH0CaZlj4nZWHWuxtZ3NRZ9c9WUrz1Vfm6wioAUnqL3bsh49uQ==",
"dev": true,
"requires": {
"@types/node": "*"
}
},
"@types/normalize-package-data": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.0.tgz",
@@ -5967,19 +5958,6 @@
"minimist": "^1.2.5"
}
},
"moment": {
"version": "2.29.1",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.29.1.tgz",
"integrity": "sha512-kHmoybcPV8Sqy59DwNDY3Jefr64lK/by/da0ViFcuA4DH0vQg5Q6Ze5VimxkfQNSC+Mls/Kx53s7TjP1RhFEDQ=="
},
"moment-timezone": {
"version": "0.5.33",
"resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.33.tgz",
"integrity": "sha512-PTc2vcT8K9J5/9rDEPe5czSIKgLoGsH8UNpA4qZTVw0Vd/Uz19geE9abbIOQKaAQFcnQ3v5YEXrbSc5BpshH+w==",
"requires": {
"moment": ">= 2.9.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
@@ -6067,14 +6045,6 @@
"integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==",
"dev": true
},
"node-cron": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.0.tgz",
"integrity": "sha512-DDwIvvuCwrNiaU7HEivFDULcaQualDv7KoNlB/UU1wPW0n1tDEmBJKhEIE6DlF2FuoOHcNbLJ8ITL2Iv/3AWmA==",
"requires": {
"moment-timezone": "^0.5.31"
}
},
"node-env-file": {
"version": "0.1.8",
"resolved": "https://registry.npmjs.org/node-env-file/-/node-env-file-0.1.8.tgz",
@@ -6178,11 +6148,6 @@
}
}
},
"nodemailer": {
"version": "6.6.0",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.6.0.tgz",
"integrity": "sha512-ikSMDU1nZqpo2WUPE0wTTw/NGGImTkwpJKDIFPZT+YvvR9Sj+ze5wzu95JHkBMglQLoG2ITxU21WukCC/XsFkg=="
},
"nodemon": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.6.tgz",

View File

@@ -1,9 +1,9 @@
{
"name": "@joplin/server",
"version": "2.0.4",
"version": "2.0.1",
"private": true,
"scripts": {
"start-dev": "nodemon --config nodemon.json --ext ts,js,mustache,css,tsx dist/app.js --env dev",
"start-dev": "nodemon --config nodemon.json dist/app.js --env dev",
"start": "node dist/app.js",
"generateTypes": "rm -f db-buildTypes.sqlite && npm run start -- --migrate-db --env buildTypes && node dist/tools/generateTypes.js && mv db-buildTypes.sqlite schema.sqlite",
"tsc": "tsc --project tsconfig.json",
@@ -30,13 +30,11 @@
"mustache": "^3.1.0",
"nanoid": "^2.1.1",
"node-env-file": "^0.1.8",
"nodemailer": "^6.6.0",
"nodemon": "^2.0.6",
"pg": "^8.5.1",
"pretty-bytes": "^5.6.0",
"query-string": "^6.8.3",
"sqlite3": "^4.1.0",
"node-cron": "^3.0.0",
"yargs": "^14.0.0"
},
"devDependencies": {
@@ -48,7 +46,6 @@
"@types/koa": "^2.0.49",
"@types/markdown-it": "^12.0.0",
"@types/mustache": "^0.8.32",
"@types/nodemailer": "^6.4.1",
"@types/yargs": "^13.0.2",
"jest": "^26.6.3",
"jsdom": "^16.4.0",

Binary file not shown.

View File

@@ -7,7 +7,7 @@ import { argv } from 'yargs';
import Logger, { LoggerWrapper, TargetType } from '@joplin/lib/Logger';
import config, { initConfig, runningInDocker, EnvVariables } from './config';
import { createDb, dropDb } from './tools/dbTools';
import { dropTables, connectDb, disconnectDb, migrateDb, waitForConnection, sqliteDefaultDir } from './db';
import { dropTables, connectDb, disconnectDb, migrateDb, waitForConnection, sqliteFilePath } from './db';
import { AppContext, Env } from './utils/types';
import FsDriverNode from '@joplin/lib/fs-driver-node';
import routeHandler from './middleware/routeHandler';
@@ -26,14 +26,12 @@ const env: Env = argv.env as Env || Env.Prod;
const envVariables: Record<Env, EnvVariables> = {
dev: {
SQLITE_DATABASE: `${sqliteDefaultDir}/db-dev.sqlite`,
SQLITE_DATABASE: 'dev',
},
buildTypes: {
SQLITE_DATABASE: `${sqliteDefaultDir}/db-buildTypes.sqlite`,
},
prod: {
SQLITE_DATABASE: `${sqliteDefaultDir}/db-prod.sqlite`,
SQLITE_DATABASE: 'buildTypes',
},
prod: {}, // Actually get the env variables from the environment
};
let appLogger_: LoggerWrapper = null;
@@ -69,21 +67,10 @@ function markPasswords(o: Record<string, any>): Record<string, any> {
return output;
}
async function getEnvFilePath(env: Env, argv: any): Promise<string> {
if (argv.envFile) return argv.envFile;
if (env === Env.Dev) {
const envFilePath = `${require('os').homedir()}/joplin-credentials/server.env`;
if (await fs.pathExists(envFilePath)) return envFilePath;
}
return '';
}
async function main() {
const envFilePath = await getEnvFilePath(env, argv);
if (envFilePath) nodeEnvFile(envFilePath);
if (argv.envFile) {
nodeEnvFile(argv.envFile);
}
if (!envVariables[env]) throw new Error(`Invalid env: ${env}`);
@@ -104,8 +91,6 @@ async function main() {
});
Logger.initializeGlobalLogger(globalLogger);
if (envFilePath) appLogger().info(`Env variables were loaded from: ${envFilePath}`);
const pidFile = argv.pidfile as string;
if (pidFile) {
@@ -130,10 +115,9 @@ async function main() {
appLogger().info(`Starting server (${env}) on port ${config().port} and PID ${process.pid}...`);
appLogger().info('Running in Docker:', runningInDocker());
appLogger().info('Public base URL:', config().baseUrl);
appLogger().info('API base URL:', config().apiBaseUrl);
appLogger().info('User content base URL:', config().userContentBaseUrl);
appLogger().info('Log dir:', config().logDir);
appLogger().info('DB Config:', markPasswords(config().database));
if (config().database.client === 'sqlite3') appLogger().info('DB file:', sqliteFilePath(config().database.name));
appLogger().info('Trying to connect to database...');
const connectionCheck = await waitForConnection(config().database);
@@ -145,7 +129,7 @@ async function main() {
const appContext = app.context as AppContext;
await setupAppContext(appContext, env, connectionCheck.connection, appLogger);
await initializeJoplinUtils(config(), appContext.models, appContext.services.mustache);
await initializeJoplinUtils(config(), appContext.models);
appLogger().info('Migrating database...');
await migrateDb(appContext.db);
@@ -160,7 +144,7 @@ async function main() {
// }
// }
appLogger().info(`Call this for testing: \`curl ${config().apiBaseUrl}/api/ping\``);
appLogger().info(`Call this for testing: \`curl ${config().baseUrl}/api/ping\``);
// const tree: any = {
// '000000000000000000000000000000F1': {},

View File

@@ -1,12 +1,9 @@
import { rtrimSlashes } from '@joplin/lib/path-utils';
import { Config, DatabaseConfig, DatabaseConfigClient, MailerConfig, RouteType } from './utils/types';
import { Config, DatabaseConfig, DatabaseConfigClient } from './utils/types';
import * as pathUtils from 'path';
export interface EnvVariables {
APP_BASE_URL?: string;
USER_CONTENT_BASE_URL?: string;
API_BASE_URL?: string;
APP_PORT?: string;
DB_CLIENT?: string;
RUNNING_IN_DOCKER?: string;
@@ -17,16 +14,6 @@ export interface EnvVariables {
POSTGRES_HOST?: string;
POSTGRES_PORT?: string;
MAILER_ENABLED?: string;
MAILER_HOST?: string;
MAILER_PORT?: string;
MAILER_SECURE?: string;
MAILER_AUTH_USER?: string;
MAILER_AUTH_PASSWORD?: string;
MAILER_NOREPLY_NAME?: string;
MAILER_NOREPLY_EMAIL?: string;
// This must be the full path to the database file
SQLITE_DATABASE?: string;
}
@@ -65,24 +52,11 @@ function databaseConfigFromEnv(runningInDocker: boolean, env: EnvVariables): Dat
return {
client: DatabaseConfigClient.SQLite,
name: env.SQLITE_DATABASE,
name: env.SQLITE_DATABASE || 'prod',
asyncStackTraces: true,
};
}
function mailerConfigFromEnv(env: EnvVariables): MailerConfig {
return {
enabled: env.MAILER_ENABLED !== '0',
host: env.MAILER_HOST || '',
port: Number(env.MAILER_PORT || 587),
secure: !!Number(env.MAILER_SECURE) || true,
authUser: env.MAILER_AUTH_USER || '',
authPassword: env.MAILER_AUTH_PASSWORD || '',
noReplyName: env.MAILER_NOREPLY_NAME || '',
noReplyEmail: env.MAILER_NOREPLY_EMAIL || '',
};
}
function baseUrlFromEnv(env: any, appPort: number): string {
if (env.APP_BASE_URL) {
return rtrimSlashes(env.APP_BASE_URL);
@@ -99,7 +73,6 @@ export function initConfig(env: EnvVariables, overrides: any = null) {
const rootDir = pathUtils.dirname(__dirname);
const viewDir = `${pathUtils.dirname(__dirname)}/src/views`;
const appPort = env.APP_PORT ? Number(env.APP_PORT) : 22300;
const baseUrl = baseUrlFromEnv(env, appPort);
config_ = {
rootDir: rootDir,
@@ -108,29 +81,12 @@ export function initConfig(env: EnvVariables, overrides: any = null) {
tempDir: `${rootDir}/temp`,
logDir: `${rootDir}/logs`,
database: databaseConfigFromEnv(runningInDocker_, env),
mailer: mailerConfigFromEnv(env),
port: appPort,
baseUrl,
apiBaseUrl: env.API_BASE_URL ? env.API_BASE_URL : baseUrl,
userContentBaseUrl: env.USER_CONTENT_BASE_URL ? env.USER_CONTENT_BASE_URL : baseUrl,
baseUrl: baseUrlFromEnv(env, appPort),
...overrides,
};
}
export function baseUrl(type: RouteType): string {
if (type === RouteType.Web) return config().baseUrl;
if (type === RouteType.Api) return config().apiBaseUrl;
if (type === RouteType.UserContent) return config().userContentBaseUrl;
throw new Error(`Unknown type: ${type}`);
}
// User content URL is not supported for now so only show the URL if the
// user content is hosted on the same domain. Needs to get cookie working
// across domains to get user content url working.
export function showItemUrls(config: Config): boolean {
return config.userContentBaseUrl === config.baseUrl;
}
function config(): Config {
if (!config_) throw new Error('Config has not been initialized!');
return config_;

View File

@@ -17,7 +17,7 @@ require('pg').types.setTypeParser(20, function(val: any) {
const logger = Logger.create('db');
const migrationDir = `${__dirname}/migrations`;
export const sqliteDefaultDir = pathUtils.dirname(__dirname);
const sqliteDbDir = pathUtils.dirname(__dirname);
export const defaultAdminEmail = 'admin@localhost';
export const defaultAdminPassword = 'admin';
@@ -47,11 +47,15 @@ export interface ConnectionCheckResult {
connection: DbConnection;
}
export function sqliteFilePath(name: string): string {
return `${sqliteDbDir}/db-${name}.sqlite`;
}
export function makeKnexConfig(dbConfig: DatabaseConfig): KnexDatabaseConfig {
const connection: DbConfigConnection = {};
if (dbConfig.client === 'sqlite3') {
connection.filename = dbConfig.name;
connection.filename = sqliteFilePath(dbConfig.name);
} else {
connection.database = dbConfig.name;
connection.host = dbConfig.host;
@@ -214,11 +218,6 @@ export enum ItemType {
User,
}
export enum EmailSender {
NoReply = 1,
Support = 2,
}
export enum ChangeType {
Create = 1,
Update = 2,
@@ -278,8 +277,6 @@ export interface User extends WithDates, WithUuid {
is_admin?: number;
max_item_size?: number;
can_share?: number;
email_confirmed?: number;
must_set_password?: number;
}
export interface Session extends WithDates, WithUuid {
@@ -373,25 +370,6 @@ export interface Change extends WithDates, WithUuid {
user_id?: Uuid;
}
export interface Email extends WithDates {
id?: number;
recipient_name?: string;
recipient_email?: string;
recipient_id?: Uuid;
sender_id?: EmailSender;
subject?: string;
body?: string;
sent_time?: number;
sent_success?: number;
error?: string;
}
export interface Token extends WithDates {
id?: number;
value?: string;
user_id?: Uuid;
}
export const databaseSchema: DatabaseTables = {
users: {
id: { type: 'string' },
@@ -403,8 +381,6 @@ export const databaseSchema: DatabaseTables = {
created_time: { type: 'string' },
max_item_size: { type: 'number' },
can_share: { type: 'number' },
email_confirmed: { type: 'number' },
must_set_password: { type: 'number' },
},
sessions: {
id: { type: 'string' },
@@ -509,26 +485,5 @@ export const databaseSchema: DatabaseTables = {
previous_item: { type: 'string' },
user_id: { type: 'string' },
},
emails: {
id: { type: 'number' },
recipient_name: { type: 'string' },
recipient_email: { type: 'string' },
recipient_id: { type: 'string' },
sender_id: { type: 'number' },
subject: { type: 'string' },
body: { type: 'string' },
sent_time: { type: 'string' },
sent_success: { type: 'number' },
error: { type: 'string' },
updated_time: { type: 'string' },
created_time: { type: 'string' },
},
tokens: {
id: { type: 'number' },
value: { type: 'string' },
user_id: { type: 'string' },
updated_time: { type: 'string' },
created_time: { type: 'string' },
},
};
// AUTO-GENERATED-TYPES

View File

@@ -19,7 +19,7 @@ async function handleChangeAdminPasswordNotification(ctx: AppContext) {
ctx.owner.id,
'change_admin_password',
NotificationLevel.Important,
_('The default admin password is insecure and has not been changed! [Change it now](%s)', ctx.models.user().profileUrl())
_('The default admin password is insecure and has not been changed! [Change it now](%s)', await ctx.models.user().profileUrl())
);
} else {
await notificationModel.markAsRead(ctx.owner.id, 'change_admin_password');

View File

@@ -1,6 +1,15 @@
import { routeResponseFormat, Response, RouteResponseFormat, execRequest } from '../utils/routeUtils';
import { AppContext, Env } from '../utils/types';
import { isView, View } from '../services/MustacheService';
import MustacheService, { isView, View } from '../services/MustacheService';
import config from '../config';
let mustache_: MustacheService = null;
function mustache(): MustacheService {
if (!mustache_) {
mustache_ = new MustacheService(config().viewDir, config().baseUrl);
}
return mustache_;
}
export default async function(ctx: AppContext) {
ctx.appLogger().info(`${ctx.request.method} ${ctx.path}`);
@@ -12,7 +21,7 @@ export default async function(ctx: AppContext) {
ctx.response = responseObject.response;
} else if (isView(responseObject)) {
ctx.response.status = 200;
ctx.response.body = await ctx.services.mustache.renderView(responseObject, {
ctx.response.body = await mustache().renderView(responseObject, {
notifications: ctx.notifications || [],
hasNotifications: !!ctx.notifications && !!ctx.notifications.length,
owner: ctx.owner,
@@ -35,9 +44,7 @@ export default async function(ctx: AppContext) {
const responseFormat = routeResponseFormat(ctx);
if (error.code === 'invalidOrigin') {
ctx.response.body = error.message;
} else if (responseFormat === RouteResponseFormat.Html) {
if (responseFormat === RouteResponseFormat.Html) {
ctx.response.set('Content-Type', 'text/html');
const view: View = {
name: 'error',
@@ -48,7 +55,7 @@ export default async function(ctx: AppContext) {
owner: ctx.owner,
},
};
ctx.response.body = await ctx.services.mustache.renderView(view);
ctx.response.body = await mustache().renderView(view);
} else { // JSON
ctx.response.set('Content-Type', 'application/json');
const r: any = { error: error.message };

View File

@@ -1,47 +0,0 @@
import { Knex } from 'knex';
import { DbConnection } from '../db';
export async function up(db: DbConnection): Promise<any> {
await db.schema.alterTable('users', function(table: Knex.CreateTableBuilder) {
table.integer('email_confirmed').defaultTo(0).notNullable();
table.integer('must_set_password').defaultTo(0).notNullable();
});
await db.schema.createTable('emails', function(table: Knex.CreateTableBuilder) {
table.increments('id').unique().primary().notNullable();
table.text('recipient_name', 'mediumtext').defaultTo('').notNullable();
table.text('recipient_email', 'mediumtext').defaultTo('').notNullable();
table.string('recipient_id', 32).defaultTo(0).notNullable();
table.integer('sender_id').notNullable();
table.string('subject', 128).notNullable();
table.text('body').notNullable();
table.bigInteger('sent_time').defaultTo(0).notNullable();
table.integer('sent_success').defaultTo(0).notNullable();
table.text('error').defaultTo('').notNullable();
table.bigInteger('updated_time').notNullable();
table.bigInteger('created_time').notNullable();
});
await db.schema.createTable('tokens', function(table: Knex.CreateTableBuilder) {
table.increments('id').unique().primary().notNullable();
table.string('value', 32).notNullable();
table.string('user_id', 32).defaultTo('').notNullable();
table.bigInteger('updated_time').notNullable();
table.bigInteger('created_time').notNullable();
});
await db.schema.alterTable('emails', function(table: Knex.CreateTableBuilder) {
table.index(['sent_time']);
table.index(['sent_success']);
});
await db('users').update({ email_confirmed: 1 });
await db.schema.alterTable('tokens', function(table: Knex.CreateTableBuilder) {
table.index(['value', 'user_id']);
});
}
export async function down(_db: DbConnection): Promise<any> {
}

View File

@@ -97,10 +97,7 @@ export default abstract class BaseModel<T> {
}
if (mainTable) {
output = output.map(f => {
if (f.includes(`${mainTable}.`)) return f;
return `${mainTable}.${f}`;
});
output = output.map(f => `${mainTable}.${f}`);
}
return output;
@@ -275,10 +272,10 @@ export default abstract class BaseModel<T> {
return this.db(this.tableName).select(options.fields || this.defaultFields).where({ id: id }).first();
}
public async delete(id: string | string[] | number | number[], options: DeleteOptions = {}): Promise<void> {
public async delete(id: string | string[], options: DeleteOptions = {}): Promise<void> {
if (!id) throw new Error('id cannot be empty');
const ids = (typeof id === 'string' || typeof id === 'number') ? [id] : id;
const ids = typeof id === 'string' ? [id] : id;
if (!ids.length) throw new Error('no id provided');

View File

@@ -68,7 +68,7 @@ export default class ChangeModel extends BaseModel<Change> {
return results;
}
private changesForUserQuery(userId: Uuid, count: boolean): Knex.QueryBuilder {
private changesForUserQuery(userId: Uuid): Knex.QueryBuilder {
// When need to get:
//
// - All the CREATE and DELETE changes associated with the user
@@ -78,8 +78,15 @@ export default class ChangeModel extends BaseModel<Change> {
// UPDATE changes do not have the user_id set because they are specific
// to the item, not to a particular user.
const query = this
return this
.db('changes')
.select([
'id',
'item_id',
'item_name',
'type',
'updated_time',
])
.where(function() {
void this.whereRaw('((type = ? OR type = ?) AND user_id = ?)', [ChangeType.Create, ChangeType.Delete, userId])
// Need to use a RAW query here because Knex has a "not a
@@ -89,20 +96,6 @@ export default class ChangeModel extends BaseModel<Change> {
// https://github.com/knex/knex/issues/1851
.orWhereRaw('type = ? AND item_id IN (SELECT item_id FROM user_items WHERE user_id = ?)', [ChangeType.Update, userId]);
});
if (count) {
void query.countDistinct('id', { as: 'total' });
} else {
void query.select([
'id',
'item_id',
'item_name',
'type',
'updated_time',
]);
}
return query;
}
public async allByUser(userId: Uuid, pagination: Pagination = null): Promise<PaginatedChanges> {
@@ -113,9 +106,9 @@ export default class ChangeModel extends BaseModel<Change> {
...pagination,
};
const query = this.changesForUserQuery(userId, false);
const countQuery = this.changesForUserQuery(userId, true);
const itemCount = (await countQuery.first()).total;
const query = this.changesForUserQuery(userId);
const countQuery = query.clone();
const itemCount = (await countQuery.countDistinct('id', { as: 'total' }))[0].total;
void query
.orderBy(pagination.order[0].by, pagination.order[0].dir)
@@ -147,7 +140,7 @@ export default class ChangeModel extends BaseModel<Change> {
if (!changeAtCursor) throw new ErrorResyncRequired();
}
const query = this.changesForUserQuery(userId, false);
const query = this.changesForUserQuery(userId);
// If a cursor was provided, apply it to the query.
if (changeAtCursor) {

View File

@@ -1,33 +0,0 @@
import { Uuid, Email, EmailSender } from '../db';
import BaseModel from './BaseModel';
export interface EmailToSend {
sender_id: EmailSender;
recipient_email: string;
subject: string;
body: string;
recipient_name?: string;
recipient_id?: Uuid;
}
export default class EmailModel extends BaseModel<Email> {
public get tableName(): string {
return 'emails';
}
protected hasUuid(): boolean {
return false;
}
public async push(email: EmailToSend) {
EmailModel.eventEmitter.emit('saved');
return super.save({ ...email });
}
public async needToBeSent(): Promise<Email[]> {
return this.db(this.tableName).where('sent_time', '=', 0);
}
}

View File

@@ -130,16 +130,4 @@ describe('ItemModel', function() {
}
});
test('should count items', async function() {
const { user: user1 } = await createUserAndSession(1, true);
await createItemTree(user1.id, '', {
'000000000000000000000000000000F1': {
'00000000000000000000000000000001': null,
},
});
expect(await models().item().childrenCount(user1.id)).toBe(2);
});
});

View File

@@ -349,18 +349,13 @@ export default class ItemModel extends BaseModel<Item> {
}
private childrenQuery(userId: Uuid, pathQuery: string = '', count: boolean = false, options: LoadOptions = {}): Knex.QueryBuilder {
private childrenQuery(userId: Uuid, pathQuery: string = '', options: LoadOptions = {}): Knex.QueryBuilder {
const query = this
.db('user_items')
.leftJoin('items', 'user_items.item_id', 'items.id')
.select(this.selectFields(options, ['id', 'name', 'updated_time'], 'items'))
.where('user_items.user_id', '=', userId);
if (count) {
void query.countDistinct('items.id', { as: 'total' });
} else {
void query.select(this.selectFields(options, ['id', 'name', 'updated_time'], 'items'));
}
if (pathQuery) {
// We support /* as a prefix only. Anywhere else would have
// performance issue or requires a revert index.
@@ -381,14 +376,14 @@ export default class ItemModel extends BaseModel<Item> {
public async children(userId: Uuid, pathQuery: string = '', pagination: Pagination = null, options: LoadOptions = {}): Promise<PaginatedItems> {
pagination = pagination || defaultPagination();
const query = this.childrenQuery(userId, pathQuery, false, options);
const query = this.childrenQuery(userId, pathQuery, options);
return paginateDbQuery(query, pagination, 'items');
}
public async childrenCount(userId: Uuid, pathQuery: string = ''): Promise<number> {
const query = this.childrenQuery(userId, pathQuery, true);
const r = await query.first();
return r ? r.total : 0;
const query = this.childrenQuery(userId, pathQuery);
const r = await query.countDistinct('items.id', { as: 'total' });
return r[0].total;
}
private async joplinItemPath(jopId: string): Promise<Item[]> {

View File

@@ -1,30 +0,0 @@
import { createUserAndSession, beforeAllDb, afterAllTests, beforeEachDb, models } from '../utils/testing/testUtils';
describe('TokenModel', function() {
beforeAll(async () => {
await beforeAllDb('TokenModel');
});
afterAll(async () => {
await afterAllTests();
});
beforeEach(async () => {
await beforeEachDb();
});
test('should delete old tokens', async function() {
const { user: user1 } = await createUserAndSession(1);
await models().token().generate(user1.id);
const [token1, token2] = await models().token().all();
await models().token().save({ id: token1.id, created_time: Date.now() - 2629746000 });
await models().token().deleteExpiredTokens();
const tokens = await models().token().all();
expect(tokens.length).toBe(1);
expect(tokens[0].id).toBe(token2.id);
});
});

View File

@@ -1,62 +0,0 @@
import { Token, Uuid } from '../db';
import { ErrorForbidden } from '../utils/errors';
import uuidgen from '../utils/uuidgen';
import BaseModel from './BaseModel';
export default class TokenModel extends BaseModel<Token> {
private tokenTtl_: number = 7 * 24 * 60 * 1000;
public get tableName(): string {
return 'tokens';
}
protected hasUuid(): boolean {
return false;
}
public async generate(userId: Uuid): Promise<string> {
const token = await this.save({
value: uuidgen(32),
user_id: userId,
});
return token.value;
}
public async checkToken(userId: string, tokenValue: string): Promise<void> {
if (!(await this.isValid(userId, tokenValue))) throw new ErrorForbidden('Invalid or expired token');
}
private async byUser(userId: string, tokenValue: string): Promise<Token> {
return this
.db(this.tableName)
.select(['id'])
.where('user_id', '=', userId)
.where('value', '=', tokenValue)
.first();
}
public async isValid(userId: string, tokenValue: string): Promise<boolean> {
const token = await this.byUser(userId, tokenValue);
return !!token;
}
public async deleteExpiredTokens() {
const cutOffDate = Date.now() - this.tokenTtl_;
await this.db(this.tableName).where('created_time', '<', cutOffDate).delete();
}
public async deleteByValue(userId: Uuid, value: string) {
const token = await this.byUser(userId, value);
if (token) await this.delete(token.id);
}
public async allByUserId(userId: Uuid): Promise<Token[]> {
return this
.db(this.tableName)
.select(this.defaultFields)
.where('user_id', '=', userId);
}
}

View File

@@ -1,5 +1,5 @@
import { createUserAndSession, beforeAllDb, afterAllTests, beforeEachDb, models, checkThrowAsync, createItem } from '../utils/testing/testUtils';
import { EmailSender, User } from '../db';
import { User } from '../db';
import { ErrorUnprocessableEntity } from '../utils/errors';
describe('UserModel', function() {
@@ -68,22 +68,4 @@ describe('UserModel', function() {
expect((await models().userItem().all()).length).toBe(0);
});
test('should push an email when creating a new user', async function() {
const { user: user1 } = await createUserAndSession(1);
const { user: user2 } = await createUserAndSession(2);
const emails = await models().email().all();
expect(emails.length).toBe(2);
expect(emails.find(e => e.recipient_email === user1.email)).toBeTruthy();
expect(emails.find(e => e.recipient_email === user2.email)).toBeTruthy();
const email = emails[0];
expect(email.subject.trim()).toBeTruthy();
expect(email.body.includes('/confirm?token=')).toBeTruthy();
expect(email.sender_id).toBe(EmailSender.NoReply);
expect(email.sent_success).toBe(0);
expect(email.sent_time).toBe(0);
expect(email.error).toBe('');
});
});

View File

@@ -1,7 +1,7 @@
import BaseModel, { AclAction, SaveOptions, ValidateOptions } from './BaseModel';
import { EmailSender, Item, User, Uuid } from '../db';
import { Item, User } from '../db';
import * as auth from '../utils/auth';
import { ErrorUnprocessableEntity, ErrorForbidden, ErrorPayloadTooLarge, ErrorNotFound } from '../utils/errors';
import { ErrorUnprocessableEntity, ErrorForbidden, ErrorPayloadTooLarge } from '../utils/errors';
import { ModelType } from '@joplin/lib/BaseModel';
import { _ } from '@joplin/lib/locale';
import prettyBytes = require('pretty-bytes');
@@ -134,14 +134,10 @@ export default class UserModel extends BaseModel<User> {
return !!s[0].length && !!s[1].length;
}
public profileUrl(): string {
public async profileUrl(): Promise<string> {
return `${this.baseUrl}/users/me`;
}
public confirmUrl(userId: Uuid, validationToken: string): string {
return `${this.baseUrl}/users/${userId}/confirm?token=${validationToken}`;
}
public async delete(id: string): Promise<void> {
const shares = await this.models().share().sharesByUser(id);
@@ -155,13 +151,6 @@ export default class UserModel extends BaseModel<User> {
}, 'UserModel::delete');
}
public async confirmEmail(userId: Uuid, token: string) {
await this.models().token().checkToken(userId, token);
const user = await this.models().user().load(userId);
if (!user) throw new ErrorNotFound('No such user');
await this.save({ id: user.id, email_confirmed: 1 });
}
// Note that when the "password" property is provided, it is going to be
// hashed automatically. It means that it is not safe to do:
//
@@ -171,30 +160,8 @@ export default class UserModel extends BaseModel<User> {
// Because the password would be hashed twice.
public async save(object: User, options: SaveOptions = {}): Promise<User> {
const user = { ...object };
if (user.password) user.password = auth.hashPassword(user.password);
const isNew = await this.isNew(object, options);
return this.withTransaction(async () => {
const savedUser = await super.save(user, options);
if (isNew) {
const validationToken = await this.models().token().generate(savedUser.id);
const validationUrl = encodeURI(this.confirmUrl(savedUser.id, validationToken));
await this.models().email().push({
sender_id: EmailSender.NoReply,
recipient_id: savedUser.id,
recipient_email: savedUser.email,
recipient_name: savedUser.full_name || '',
subject: 'Verify your email',
body: `Click this: ${validationUrl}`,
});
}
return savedUser;
});
return super.save(user, options);
}
}

View File

@@ -63,11 +63,9 @@ import SessionModel from './SessionModel';
import ChangeModel from './ChangeModel';
import NotificationModel from './NotificationModel';
import ShareModel from './ShareModel';
import EmailModel from './EmailModel';
import ItemResourceModel from './ItemResourceModel';
import ShareUserModel from './ShareUserModel';
import KeyValueModel from './KeyValueModel';
import TokenModel from './TokenModel';
export class Models {
@@ -87,18 +85,10 @@ export class Models {
return new UserModel(this.db_, newModelFactory, this.baseUrl_);
}
public email() {
return new EmailModel(this.db_, newModelFactory, this.baseUrl_);
}
public userItem() {
return new UserItemModel(this.db_, newModelFactory, this.baseUrl_);
}
public token() {
return new TokenModel(this.db_, newModelFactory, this.baseUrl_);
}
public itemResource() {
return new ItemResourceModel(this.db_, newModelFactory, this.baseUrl_);
}

View File

@@ -2,11 +2,10 @@ import config from '../../config';
import { createTestUsers } from '../../tools/debugTools';
import { bodyFields } from '../../utils/requestUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { SubPath } from '../../utils/routeUtils';
import { AppContext } from '../../utils/types';
const router = new Router(RouteType.Api);
const router = new Router();
router.public = true;

View File

@@ -1,7 +1,6 @@
import { ErrorNotFound } from '../../utils/errors';
import { bodyFields } from '../../utils/requestUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { SubPath } from '../../utils/routeUtils';
import { AppContext } from '../../utils/types';
@@ -15,7 +14,7 @@ const supportedEvents: Record<string, Function> = {
},
};
const router = new Router(RouteType.Api);
const router = new Router();
router.post('api/events', async (_path: SubPath, ctx: AppContext) => {
const event = await bodyFields<Event>(ctx.req);

View File

@@ -2,7 +2,6 @@ import { Item, Uuid } from '../../db';
import { formParse } from '../../utils/requestUtils';
import { respondWithItemContent, SubPath } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import * as fs from 'fs-extra';
import { ErrorMethodNotAllowed, ErrorNotFound } from '../../utils/errors';
@@ -11,7 +10,7 @@ import { requestDeltaPagination, requestPagination } from '../../models/utils/pa
import { AclAction } from '../../models/BaseModel';
import { safeRemove } from '../../utils/fileUtils';
const router = new Router(RouteType.Api);
const router = new Router();
// Note about access control:
//

View File

@@ -1,7 +1,6 @@
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
const router = new Router(RouteType.Api);
const router = new Router();
router.public = true;

View File

@@ -1,12 +1,11 @@
import { SubPath } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { ErrorForbidden } from '../../utils/errors';
import { AppContext } from '../../utils/types';
import { bodyFields } from '../../utils/requestUtils';
import { User } from '../../db';
const router = new Router(RouteType.Api);
const router = new Router();
router.public = true;

View File

@@ -2,11 +2,10 @@ import { ErrorBadRequest, ErrorNotFound } from '../../utils/errors';
import { bodyFields } from '../../utils/requestUtils';
import { SubPath } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import { AclAction } from '../../models/BaseModel';
const router = new Router(RouteType.Api);
const router = new Router();
router.patch('api/share_users/:id', async (path: SubPath, ctx: AppContext) => {
const shareUserModel = ctx.models.shareUser();

View File

@@ -3,7 +3,6 @@ import { Share, ShareType } from '../../db';
import { bodyFields, ownerRequired } from '../../utils/requestUtils';
import { SubPath } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import { AclAction } from '../../models/BaseModel';
@@ -12,7 +11,7 @@ interface ShareApiInput extends Share {
note_id?: string;
}
const router = new Router(RouteType.Api);
const router = new Router();
router.public = true;

View File

@@ -2,13 +2,12 @@ import { User } from '../../db';
import { bodyFields } from '../../utils/requestUtils';
import { SubPath } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import { ErrorNotFound } from '../../utils/errors';
import { AclAction } from '../../models/BaseModel';
import uuidgen from '../../utils/uuidgen';
const router = new Router(RouteType.Api);
const router = new Router();
async function fetchUser(path: SubPath, ctx: AppContext): Promise<User> {
const user = await ctx.models.user().load(path.id);
@@ -31,9 +30,8 @@ router.post('api/users', async (_path: SubPath, ctx: AppContext) => {
const user = await postedUserFromContext(ctx);
// We set a random password because it's required, but user will have to
// set it after clicking on the confirmation link.
// set it by clicking on the confirmation link.
user.password = uuidgen();
user.must_set_password = 1;
const output = await ctx.models.user().save(user);
return ctx.models.user().toApiOutput(output);
});

View File

@@ -1,10 +1,10 @@
import { SubPath, Response, ResponseType, redirect } from '../utils/routeUtils';
import { SubPath, Response, ResponseType } from '../utils/routeUtils';
import Router from '../utils/Router';
import { ErrorNotFound, ErrorForbidden } from '../utils/errors';
import { dirname, normalize } from 'path';
import { pathExists } from 'fs-extra';
import * as fs from 'fs-extra';
import { AppContext, RouteType } from '../utils/types';
import { AppContext } from '../utils/types';
import { localFileFromUrl } from '../utils/joplinUtils';
const { mime } = require('@joplin/lib/mime-utils.js');
@@ -44,22 +44,13 @@ async function findLocalFile(path: string): Promise<string> {
return localPath;
}
const router = new Router(RouteType.Web);
const router = new Router();
router.public = true;
// Used to serve static files, so it needs to be public because for example the
// login page, which is public, needs access to the CSS files.
router.get('', async (path: SubPath, ctx: AppContext) => {
// Redirect to either /login or /home when trying to access the root
if (!path.id && !path.link) {
if (ctx.owner) {
return redirect(ctx, 'home');
} else {
return redirect(ctx, 'login');
}
}
const localPath = await findLocalFile(path.raw);
let mimeType: string = mime.fromFilename(localPath);

View File

@@ -1,16 +1,14 @@
import { SubPath } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import { changeTypeToString } from '../../db';
import { PaginationOrderDir } from '../../models/utils/pagination';
import { formatDateTime } from '../../utils/time';
import defaultView from '../../utils/defaultView';
import { View } from '../../services/MustacheService';
import { makeTablePagination, Table, Row, makeTableView } from '../../utils/views/table';
import config, { showItemUrls } from '../../config';
import { makeTablePagination, Table, Row, makeTableView, tablePartials } from '../../utils/views/table';
const router = new Router(RouteType.Web);
const router = new Router();
router.get('changes', async (_path: SubPath, ctx: AppContext) => {
const pagination = makeTablePagination(ctx.query, 'updated_time', PaginationOrderDir.DESC);
@@ -42,7 +40,7 @@ router.get('changes', async (_path: SubPath, ctx: AppContext) => {
{
value: change.item_name,
stretch: true,
url: showItemUrls(config()) ? (items.find(i => i.id === change.item_id) ? ctx.models.item().itemContentUrl(change.item_id) : '') : null,
url: items.find(i => i.id === change.item_id) ? ctx.models.item().itemContentUrl(change.item_id) : '',
},
{
value: changeTypeToString(change.type),
@@ -59,6 +57,7 @@ router.get('changes', async (_path: SubPath, ctx: AppContext) => {
const view: View = defaultView('changes');
view.content.changeTable = makeTableView(table),
view.cssFiles = ['index/changes'];
view.partials = view.partials.concat(tablePartials());
return view;
});

View File

@@ -1,12 +1,11 @@
import { SubPath } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import { contextSessionId } from '../../utils/requestUtils';
import { ErrorMethodNotAllowed } from '../../utils/errors';
import defaultView from '../../utils/defaultView';
const router: Router = new Router(RouteType.Web);
const router: Router = new Router();
router.get('home', async (_path: SubPath, ctx: AppContext) => {
contextSessionId(ctx);

View File

@@ -1,18 +1,17 @@
import { SubPath, redirect, respondWithItemContent } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import { formParse } from '../../utils/requestUtils';
import { ErrorNotFound } from '../../utils/errors';
import config, { showItemUrls } from '../../config';
import config from '../../config';
import { formatDateTime } from '../../utils/time';
import defaultView from '../../utils/defaultView';
import { View } from '../../services/MustacheService';
import { makeTablePagination, makeTableView, Row, Table } from '../../utils/views/table';
import { makeTablePagination, makeTableView, Row, Table, tablePartials } from '../../utils/views/table';
import { PaginationOrderDir } from '../../models/utils/pagination';
const prettyBytes = require('pretty-bytes');
const router = new Router(RouteType.Web);
const router = new Router();
router.get('items', async (_path: SubPath, ctx: AppContext) => {
const pagination = makeTablePagination(ctx.query, 'name', PaginationOrderDir.ASC);
@@ -47,7 +46,7 @@ router.get('items', async (_path: SubPath, ctx: AppContext) => {
{
value: item.name,
stretch: true,
url: showItemUrls(config()) ? `${config().userContentBaseUrl}/items/${item.id}/content` : null,
url: `${config().baseUrl}/items/${item.id}/content`,
},
{
value: prettyBytes(item.content_size),
@@ -68,6 +67,7 @@ router.get('items', async (_path: SubPath, ctx: AppContext) => {
view.content.itemTable = makeTableView(table),
view.content.postUrl = `${config().baseUrl}/items`;
view.cssFiles = ['index/items'];
view.partials = view.partials.concat(tablePartials());
return view;
});
@@ -76,7 +76,7 @@ router.get('items/:id/content', async (path: SubPath, ctx: AppContext) => {
const item = await itemModel.loadWithContent(path.id);
if (!item) throw new ErrorNotFound();
return respondWithItemContent(ctx.response, item, item.content);
}, RouteType.UserContent);
});
router.post('items', async (_path: SubPath, ctx: AppContext) => {
const body = await formParse(ctx.req);

View File

@@ -1,6 +1,5 @@
import { SubPath, redirect } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import { formParse } from '../../utils/requestUtils';
import config from '../../config';
@@ -10,11 +9,11 @@ import { View } from '../../services/MustacheService';
function makeView(error: any = null): View {
const view = defaultView('login');
view.content.error = error;
view.navbar = false;
view.partials = ['errorBanner'];
return view;
}
const router: Router = new Router(RouteType.Web);
const router: Router = new Router();
router.public = true;

View File

@@ -1,11 +1,10 @@
import { SubPath, redirect } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import config from '../../config';
import { contextSessionId } from '../../utils/requestUtils';
const router = new Router(RouteType.Web);
const router = new Router();
router.post('logout', async (_path: SubPath, ctx: AppContext) => {
const sessionId = contextSessionId(ctx, false);

View File

@@ -1,12 +1,11 @@
import { SubPath } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import { bodyFields } from '../../utils/requestUtils';
import { ErrorNotFound } from '../../utils/errors';
import { Notification } from '../../db';
const router = new Router(RouteType.Web);
const router = new Router();
router.patch('notifications/:id', async (path: SubPath, ctx: AppContext) => {
const fields: Notification = await bodyFields(ctx.req);

View File

@@ -1,6 +1,5 @@
import { SubPath, ResponseType, Response } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext } from '../../utils/types';
import { ErrorNotFound } from '../../utils/errors';
import { Item, Share } from '../../db';
@@ -19,7 +18,7 @@ async function renderItem(context: AppContext, item: Item, share: Share): Promis
};
}
const router: Router = new Router(RouteType.Web);
const router: Router = new Router();
router.public = true;

View File

@@ -1,7 +1,7 @@
import { User } from '../../db';
import routeHandler from '../../middleware/routeHandler';
import { ErrorForbidden } from '../../utils/errors';
import { execRequest, execRequestC } from '../../utils/testing/apiUtils';
import { execRequest } from '../../utils/testing/apiUtils';
import { beforeAllDb, afterAllTests, beforeEachDb, koaAppContext, createUserAndSession, models, parseHtml, checkContextError, expectHttpError } from '../../utils/testing/testUtils';
export async function postUser(sessionId: string, email: string, password: string): Promise<User> {
@@ -153,76 +153,6 @@ describe('index_users', function() {
expect(result).toContain(user2.email);
});
test('should allow user to set a password for new accounts', async function() {
const { user: user1 } = await createUserAndSession(1);
const { user: user2 } = await createUserAndSession(2);
const email = (await models().email().all()).find(e => e.recipient_id === user1.id);
const matches = email.body.match(/\/(users\/.*)(\?token=)(.{32})/);
const path = matches[1];
const token = matches[3];
// Check that the token is valid
expect(await models().token().isValid(user1.id, token)).toBe(true);
// Check that we can't set the password without the token
{
const context = await execRequestC('', 'POST', path, {
password: 'newpassword',
password2: 'newpassword',
});
const sessionId = context.cookies.get('sessionId');
expect(sessionId).toBeFalsy();
}
// Check that we can't set the password with someone else's token
{
const token2 = (await models().token().allByUserId(user2.id))[0].value;
const context = await execRequestC('', 'POST', path, {
password: 'newpassword',
password2: 'newpassword',
token: token2,
});
const sessionId = context.cookies.get('sessionId');
expect(sessionId).toBeFalsy();
}
const context = await execRequestC('', 'POST', path, {
password: 'newpassword',
password2: 'newpassword',
token: token,
});
// Check that the user has been logged in
const sessionId = context.cookies.get('sessionId');
const session = await models().session().load(sessionId);
expect(session.user_id).toBe(user1.id);
// Check that the password has been set
const loggedInUser = await models().user().login(user1.email, 'newpassword');
expect(loggedInUser.id).toBe(user1.id);
// Check that the token has been cleared
expect(await models().token().isValid(user1.id, token)).toBe(false);
// Check that a notification has been created
const notification = (await models().notification().all())[0];
expect(notification.key).toBe('passwordSet');
});
// test('should handle invalid email validation', async function() {
// await createUserAndSession(1);
// const email = (await models().email().all())[0];
// const matches = email.body.match(/\/(users\/.*)(\?token=)(.{32})/);
// const path = matches[1];
// const token = matches[3];
// // Valid path but invalid token
// await expectHttpError(async () => execRequest(null, 'GET', path, null, { query: { token: 'invalid' } }), ErrorNotFound.httpCode);
// // Valid token but invalid path
// await expectHttpError(async () => execRequest(null, 'GET', 'users/abcd1234/confirm', null, { query: { token } }), ErrorNotFound.httpCode);
// });
test('should apply ACL', async function() {
const { user: admin, session: adminSession } = await createUserAndSession(1, true);
const { user: user1, session: session1 } = await createUserAndSession(2, false);

View File

@@ -1,27 +1,15 @@
import { SubPath, redirect } from '../../utils/routeUtils';
import Router from '../../utils/Router';
import { RouteType } from '../../utils/types';
import { AppContext, HttpMethod } from '../../utils/types';
import { bodyFields, formParse } from '../../utils/requestUtils';
import { formParse } from '../../utils/requestUtils';
import { ErrorForbidden, ErrorUnprocessableEntity } from '../../utils/errors';
import { NotificationLevel, User } from '../../db';
import { User } from '../../db';
import config from '../../config';
import { View } from '../../services/MustacheService';
import defaultView from '../../utils/defaultView';
import { AclAction } from '../../models/BaseModel';
const prettyBytes = require('pretty-bytes');
function checkPassword(fields: SetPasswordFormData, required: boolean): string {
if (fields.password) {
if (fields.password !== fields.password2) throw new ErrorUnprocessableEntity('Passwords do not match');
return fields.password;
} else {
if (required) throw new ErrorUnprocessableEntity('Password is required');
}
return '';
}
function makeUser(isNew: boolean, fields: any): User {
const user: User = {};
@@ -31,20 +19,16 @@ function makeUser(isNew: boolean, fields: any): User {
if ('max_item_size' in fields) user.max_item_size = fields.max_item_size;
user.can_share = fields.can_share ? 1 : 0;
const password = checkPassword(fields, false);
if (password) user.password = password;
if (fields.password) {
if (fields.password !== fields.password2) throw new ErrorUnprocessableEntity('Passwords do not match');
user.password = fields.password;
}
if (!isNew) user.id = fields.id;
return user;
}
function defaultUser(): User {
return {
can_share: 1,
};
}
function userIsNew(path: SubPath): boolean {
return path.id === 'new';
}
@@ -53,7 +37,7 @@ function userIsMe(path: SubPath): boolean {
return path.id === 'me';
}
const router = new Router(RouteType.Web);
const router = new Router();
router.get('users', async (_path: SubPath, ctx: AppContext) => {
const userModel = ctx.models.user();
@@ -79,7 +63,6 @@ router.get('users/:id', async (path: SubPath, ctx: AppContext, user: User = null
const userId = userIsMe(path) ? owner.id : path.id;
user = !isNew ? user || await userModel.load(userId) : null;
if (isNew && !user) user = defaultUser();
await userModel.checkIfAllowed(ctx.owner, AclAction.Read, user);
@@ -100,63 +83,11 @@ router.get('users/:id', async (path: SubPath, ctx: AppContext, user: User = null
view.content.error = error;
view.content.postUrl = postUrl;
view.content.showDeleteButton = !isNew && !!owner.is_admin && owner.id !== user.id;
view.partials.push('errorBanner');
return view;
});
router.publicSchemas.push('users/:id/confirm');
router.get('users/:id/confirm', async (path: SubPath, ctx: AppContext, error: Error = null) => {
const userId = path.id;
const token = ctx.query.token;
if (token) await ctx.models.user().confirmEmail(userId, token);
const user = await ctx.models.user().load(userId);
const view: View = {
...defaultView('users/confirm'),
content: {
user,
error,
token,
postUrl: ctx.models.user().confirmUrl(userId, token),
},
navbar: false,
};
return view;
});
interface SetPasswordFormData {
token: string;
password: string;
password2: string;
}
router.post('users/:id/confirm', async (path: SubPath, ctx: AppContext) => {
const userId = path.id;
try {
const fields = await bodyFields<SetPasswordFormData>(ctx.req);
await ctx.models.token().checkToken(userId, fields.token);
const password = checkPassword(fields, true);
await ctx.models.user().save({ id: userId, password });
await ctx.models.token().deleteByValue(userId, fields.token);
const session = await ctx.models.session().createUserSession(userId);
ctx.cookies.set('sessionId', session.id);
await ctx.models.notification().add(userId, 'passwordSet', NotificationLevel.Normal, 'Welcome to Joplin Cloud! Your password has been set successfully.');
return redirect(ctx, `${config().baseUrl}/home`);
} catch (error) {
const endPoint = router.findEndPoint(HttpMethod.GET, 'users/:id/confirm');
return endPoint.handler(path, ctx, error);
}
});
router.alias(HttpMethod.POST, 'users/:id', 'users');
router.post('users', async (path: SubPath, ctx: AppContext) => {
@@ -193,7 +124,7 @@ router.post('users', async (path: SubPath, ctx: AppContext) => {
} catch (error) {
if (error instanceof ErrorForbidden) throw error;
const endPoint = router.findEndPoint(HttpMethod.GET, 'users/:id');
return endPoint.handler(path, ctx, user, error);
return endPoint(path, ctx, user, error);
}
});

View File

@@ -0,0 +1,45 @@
import { Models } from '../models/factory';
import { Config } from '../utils/types';
import MustacheService from './MustacheService';
export default class BaseApplication {
private appName_: string;
private config_: Config = null;
private models_: Models = null;
private mustache_: MustacheService = null;
private rootDir_: string;
protected get mustache(): MustacheService {
return this.mustache_;
}
protected get config(): Config {
return this.config_;
}
protected get models(): Models {
return this.models_;
}
public get rootDir(): string {
return this.rootDir_;
}
public get appBaseUrl(): string {
return `${this.config.baseUrl}/apps/${this.appName_}`;
}
public initBase_(appName: string, config: Config, models: Models) {
this.appName_ = appName;
this.rootDir_ = `${config.rootDir}/src/apps/${appName}`;
this.config_ = config;
this.models_ = models;
this.mustache_ = new MustacheService(`${this.rootDir}/views`, `${config.baseUrl}/apps/${appName}`);
}
public async localFileFromUrl(_url: string): Promise<string> {
return null;
}
}

View File

@@ -1,96 +0,0 @@
import Logger from '@joplin/lib/Logger';
import { Models } from '../models/factory';
import { msleep } from '../utils/time';
import { Config, Env } from '../utils/types';
const logger = Logger.create('BaseService');
export default class BaseService {
private env_: Env;
private models_: Models;
private config_: Config;
protected enabled_: boolean = true;
private destroyed_: boolean = false;
protected maintenanceInterval_: number = 10000;
private scheduledMaintenances_: boolean[] = [];
private maintenanceInProgress_: boolean = false;
public constructor(env: Env, models: Models, config: Config) {
this.env_ = env;
this.models_ = models;
this.config_ = config;
this.scheduleMaintenance = this.scheduleMaintenance.bind(this);
}
public async destroy() {
if (this.destroyed_) throw new Error('Already destroyed');
this.destroyed_ = true;
this.scheduledMaintenances_ = [];
while (this.maintenanceInProgress_) {
await msleep(500);
}
}
protected get models(): Models {
return this.models_;
}
protected get env(): Env {
return this.env_;
}
protected get config(): Config {
return this.config_;
}
public get enabled(): boolean {
return this.enabled_;
}
public get maintenanceInProgress(): boolean {
return !!this.scheduledMaintenances_.length;
}
protected async scheduleMaintenance() {
if (this.destroyed_) return;
// Every time a maintenance is scheduled we push a task to this array.
// Whenever the maintenance actually runs, that array is cleared. So it
// means, that if new tasks are pushed to the array while the
// maintenance is runing, it will run again once it's finished, so as to
// process any item that might have been added.
this.scheduledMaintenances_.push(true);
if (this.scheduledMaintenances_.length !== 1) return;
while (this.scheduledMaintenances_.length) {
await msleep(this.env === Env.Dev ? 2000 : this.maintenanceInterval_);
if (this.destroyed_) return;
const itemCount = this.scheduledMaintenances_.length;
await this.runMaintenance();
this.scheduledMaintenances_.splice(0, itemCount);
}
}
private async runMaintenance() {
this.maintenanceInProgress_ = true;
try {
await this.maintenance();
} catch (error) {
logger.error('Could not run maintenance', error);
}
this.maintenanceInProgress_ = false;
}
protected async maintenance() {
throw new Error('Not implemented');
}
public async runInBackground() {
await this.runMaintenance();
}
}

View File

@@ -1,12 +0,0 @@
import BaseService from './BaseService';
const cron = require('node-cron');
export default class CronService extends BaseService {
public async runInBackground() {
cron.schedule('0 */6 * * *', async () => {
await this.models.token().deleteExpiredTokens();
});
}
}

View File

@@ -1,122 +0,0 @@
import Logger from '@joplin/lib/Logger';
import UserModel from '../models/UserModel';
import BaseService from './BaseService';
import Mail = require('nodemailer/lib/mailer');
import { createTransport } from 'nodemailer';
import { Email, EmailSender } from '../db';
import { errorToString } from '../utils/errors';
const logger = Logger.create('EmailService');
interface Participant {
name: string;
email: string;
}
export default class EmailService extends BaseService {
private transport_: any;
private async transport(): Promise<Mail> {
if (!this.transport_) {
this.transport_ = createTransport({
host: this.config.mailer.host,
port: this.config.mailer.port,
secure: this.config.mailer.secure,
auth: {
user: this.config.mailer.authUser,
pass: this.config.mailer.authPassword,
},
});
try {
await this.transport_.verify();
} catch (error) {
this.enabled_ = false;
this.transport_ = null;
error.message = `Could not initialize transporter. Service will be disabled: ${error.message}`;
throw error;
}
}
return this.transport_;
}
private senderInfo(senderId: EmailSender): Participant {
if (senderId === EmailSender.NoReply) {
return {
name: this.config.mailer.noReplyName,
email: this.config.mailer.noReplyEmail,
};
}
throw new Error(`Invalid sender ID: ${senderId}`);
}
private escapeEmailField(f: string): string {
return f.replace(/[\n\r"<>]/g, '');
}
private formatNameAndEmail(email: string, name: string = ''): string {
if (!email) throw new Error('Email is required');
const output: string[] = [];
if (name) output.push(`"${this.escapeEmailField(name)}"`);
output.push((name ? '<' : '') + this.escapeEmailField(email) + (name ? '>' : ''));
return output.join(' ');
}
protected async maintenance() {
if (!this.enabled_) return;
logger.info('Starting maintenance...');
const startTime = Date.now();
try {
const emails = await this.models.email().needToBeSent();
const transport = await this.transport();
for (const email of emails) {
const sender = this.senderInfo(email.sender_id);
const mailOptions: Mail.Options = {
from: this.formatNameAndEmail(sender.email, sender.name),
to: this.formatNameAndEmail(email.recipient_email, email.recipient_name),
subject: email.subject,
text: email.body,
};
const emailToSave: Email = {
id: email.id,
sent_time: Date.now(),
};
try {
await transport.sendMail(mailOptions);
emailToSave.sent_success = 1;
emailToSave.error = '';
} catch (error) {
emailToSave.sent_success = 0;
emailToSave.error = errorToString(error);
}
await this.models.email().save(emailToSave);
}
} catch (error) {
logger.error('Could not run maintenance:', error);
}
logger.info(`Maintenance completed in ${Date.now() - startTime}ms`);
}
public async runInBackground() {
if (!this.config.mailer.host || !this.config.mailer.enabled) {
this.enabled_ = false;
logger.info('Service will be disabled because mailer config is not set or is explicitly disabled');
return;
}
UserModel.eventEmitter.on('created', this.scheduleMaintenance);
await super.runInBackground();
}
}

View File

@@ -1,9 +1,6 @@
import * as Mustache from 'mustache';
import * as fs from 'fs-extra';
import config from '../config';
import { filename } from '@joplin/lib/path-utils';
import { NotificationView } from '../utils/types';
import { User } from '../db';
export interface RenderOptions {
partials?: any;
@@ -14,21 +11,12 @@ export interface RenderOptions {
export interface View {
name: string;
path: string;
navbar?: boolean;
content?: any;
partials?: string[];
cssFiles?: string[];
jsFiles?: string[];
}
interface GlobalParams {
baseUrl?: string;
prefersDarkEnabled?: boolean;
notifications?: NotificationView[];
hasNotifications?: boolean;
owner?: User;
}
export function isView(o: any): boolean {
if (typeof o !== 'object' || !o) return false;
return 'path' in o && 'name' in o;
@@ -39,27 +27,12 @@ export default class MustacheService {
private viewDir_: string;
private baseAssetUrl_: string;
private prefersDarkEnabled_: boolean = true;
private partials_: Record<string, string> = {};
public constructor(viewDir: string, baseAssetUrl: string) {
this.viewDir_ = viewDir;
this.baseAssetUrl_ = baseAssetUrl;
}
public async loadPartials() {
const files = await fs.readdir(this.partialDir);
for (const f of files) {
const name = filename(f);
const templateContent = await this.loadTemplateContent(`${this.partialDir}/${f}`);
this.partials_[name] = templateContent;
}
}
public get partialDir(): string {
return `${this.viewDir_}/partials`;
}
public get prefersDarkEnabled(): boolean {
return this.prefersDarkEnabled_;
}
@@ -72,7 +45,7 @@ export default class MustacheService {
return `${config().layoutDir}/default.mustache`;
}
private get defaultLayoutOptions(): GlobalParams {
private get defaultLayoutOptions(): any {
return {
baseUrl: config().baseUrl,
prefersDarkEnabled: this.prefersDarkEnabled_,
@@ -91,9 +64,17 @@ export default class MustacheService {
return output;
}
public async renderView(view: View, globalParams: GlobalParams = null): Promise<string> {
public async renderView(view: View, globalParams: any = null): Promise<string> {
const partials = view.partials || [];
const cssFiles = this.resolvesFilePaths('css', view.cssFiles || []);
const jsFiles = this.resolvesFilePaths('js', view.jsFiles || []);
const partialContents: any = {};
for (const partialName of partials) {
const filePath = `${this.viewDir_}/partials/${partialName}.mustache`;
partialContents[partialName] = await this.loadTemplateContent(filePath);
}
const filePath = `${this.viewDir_}/${view.path}.mustache`;
globalParams = {
@@ -107,20 +88,19 @@ export default class MustacheService {
...view.content,
global: globalParams,
},
this.partials_
partialContents
);
const layoutView: any = {
const layoutView: any = Object.assign({}, {
global: globalParams,
pageName: view.name,
contentHtml: contentHtml,
cssFiles: cssFiles,
jsFiles: jsFiles,
navbar: view.navbar,
...view.content,
};
});
return Mustache.render(await this.loadTemplateContent(this.defaultLayoutPath), layoutView, this.partials_);
return Mustache.render(await this.loadTemplateContent(this.defaultLayoutPath), layoutView, partialContents);
}
}

View File

@@ -1,4 +1,3 @@
import config from '../config';
import { shareFolderWithUser } from '../utils/testing/shareApiUtils';
import { createUserAndSession, beforeAllDb, afterAllTests, beforeEachDb, models, updateNote, msleep } from '../utils/testing/testUtils';
import { Env } from '../utils/types';
@@ -24,7 +23,7 @@ describe('ShareService', function() {
const { user: user1, session: session1 } = await createUserAndSession(1);
const { user: user2, session: session2 } = await createUserAndSession(2);
const service = new ShareService(Env.Dev, models(), config());
const service = new ShareService(Env.Dev, models());
void service.runInBackground();
await shareFolderWithUser(session1.id, session2.id, '000000000000000000000000000000F2', {

View File

@@ -1,27 +1,73 @@
import Logger from '@joplin/lib/Logger';
import ChangeModel from '../models/ChangeModel';
import BaseService from './BaseService';
import { Models } from '../models/factory';
import { Env } from '../utils/types';
const logger = Logger.create('ShareService');
export default class ShareService extends BaseService {
export default class ShareService {
private env_: Env;
private models_: Models;
private maintenanceScheduled_: boolean = false;
private maintenanceInProgress_: boolean = false;
private scheduleMaintenanceTimeout_: any = null;
public constructor(env: Env, models: Models) {
this.env_ = env;
this.models_ = models;
this.scheduleMaintenance = this.scheduleMaintenance.bind(this);
}
public async destroy() {
if (this.scheduleMaintenanceTimeout_) {
clearTimeout(this.scheduleMaintenanceTimeout_);
this.scheduleMaintenanceTimeout_ = null;
}
}
public get models(): Models {
return this.models_;
}
public get env(): Env {
return this.env_;
}
public get maintenanceInProgress(): boolean {
return this.maintenanceInProgress_;
}
private async scheduleMaintenance() {
if (this.maintenanceScheduled_) return;
this.maintenanceScheduled_ = true;
this.scheduleMaintenanceTimeout_ = setTimeout(() => {
this.maintenanceScheduled_ = false;
void this.maintenance();
}, this.env === Env.Dev ? 2000 : 10000);
}
private async maintenance() {
if (this.maintenanceInProgress_) return;
protected async maintenance() {
logger.info('Starting maintenance...');
const startTime = Date.now();
this.maintenanceInProgress_ = true;
try {
await this.models.share().updateSharedItems3();
} catch (error) {
logger.error('Could not update share items:', error);
}
this.maintenanceInProgress_ = false;
logger.info(`Maintenance completed in ${Date.now() - startTime}ms`);
}
public async runInBackground() {
ChangeModel.eventEmitter.on('saved', this.scheduleMaintenance);
await super.runInBackground();
await this.maintenance();
}
}

View File

@@ -1,11 +1,5 @@
import CronService from './CronService';
import EmailService from './EmailService';
import MustacheService from './MustacheService';
import ShareService from './ShareService';
export interface Services {
share: ShareService;
email: EmailService;
cron: CronService;
mustache: MustacheService;
}

View File

@@ -1,4 +1,4 @@
import { connectDb, disconnectDb, migrateDb } from '../db';
import { connectDb, disconnectDb, migrateDb, sqliteFilePath } from '../db';
import * as fs from 'fs-extra';
import { DatabaseConfig } from '../utils/types';
@@ -33,7 +33,7 @@ export async function createDb(config: DatabaseConfig, options: CreateDbOptions
await execCommand(cmd.join(' '), { env: { PGPASSWORD: config.password } });
} else if (config.client === 'sqlite3') {
const filePath = config.name;
const filePath = sqliteFilePath(config.name);
if (await fs.pathExists(filePath)) {
if (options.dropIfExists) {
@@ -71,6 +71,6 @@ export async function dropDb(config: DatabaseConfig, options: DropDbOptions = nu
throw error;
}
} else if (config.client === 'sqlite3') {
await fs.remove(config.name);
await fs.remove(sqliteFilePath(config.name));
}
}

View File

@@ -31,8 +31,6 @@ const config = {
'main.shares': 'WithDates, WithUuid',
'main.share_users': 'WithDates, WithUuid',
'main.user_items': 'WithDates',
'main.emails': 'WithDates',
'main.tokens': 'WithDates',
},
};
@@ -43,8 +41,6 @@ const propertyTypes: Record<string, string> = {
'shares.type': 'ShareType',
'items.content': 'Buffer',
'share_users.status': 'ShareUserStatus',
'emails.sender_id': 'EmailSender',
'emails.sent_time': 'number',
};
function insertContentIntoFile(filePath: string, markerOpen: string, markerClose: string, contentToInsert: string): void {

View File

@@ -1,12 +1,7 @@
import { ErrorMethodNotAllowed, ErrorNotFound } from './errors';
import { HttpMethod, RouteType } from './types';
import { HttpMethod } from './types';
import { RouteResponseFormat, RouteHandler } from './routeUtils';
interface RouteInfo {
handler: RouteHandler;
type?: RouteType;
}
export default class Router {
// When the router is public, we do not check that a valid session is
@@ -14,71 +9,59 @@ export default class Router {
// not logged in, can access any route of this router. End points that
// should not be publicly available should call ownerRequired(ctx);
public public: boolean = false;
public publicSchemas: string[] = [];
public responseFormat: RouteResponseFormat = null;
private routes_: Record<string, Record<string, RouteInfo>> = {};
private routes_: Record<string, Record<string, RouteHandler>> = {};
private aliases_: Record<string, Record<string, string>> = {};
private type_: RouteType;
public constructor(type: RouteType) {
this.type_ = type;
}
public findEndPoint(method: HttpMethod, schema: string): RouteInfo {
public findEndPoint(method: HttpMethod, schema: string): RouteHandler {
if (this.aliases_[method]?.[schema]) { return this.findEndPoint(method, this.aliases_[method]?.[schema]); }
if (!this.routes_[method]) { throw new ErrorMethodNotAllowed(`Not allowed: ${method} ${schema}`); }
const endPoint = this.routes_[method][schema];
if (!endPoint) { throw new ErrorNotFound(`Not found: ${method} ${schema}`); }
let endPointInfo = endPoint;
let endPointFn = endPoint;
for (let i = 0; i < 1000; i++) {
if (typeof endPointInfo === 'string') {
endPointInfo = this.routes_[method]?.[endPointInfo];
if (typeof endPointFn === 'string') {
endPointFn = this.routes_[method]?.[endPointFn];
} else {
const output = { ...endPointInfo };
if (!output.type) output.type = this.type_;
return output;
return endPointFn;
}
}
throw new ErrorNotFound(`Could not resolve: ${method} ${schema}`);
}
public isPublic(schema: string): boolean {
return this.public || this.publicSchemas.includes(schema);
}
public alias(method: HttpMethod, path: string, target: string) {
if (!this.aliases_[method]) { this.aliases_[method] = {}; }
this.aliases_[method][path] = target;
}
public get(path: string, handler: RouteHandler, type: RouteType = null) {
public get(path: string, handler: RouteHandler) {
if (!this.routes_.GET) { this.routes_.GET = {}; }
this.routes_.GET[path] = { handler, type };
this.routes_.GET[path] = handler;
}
public post(path: string, handler: RouteHandler, type: RouteType = null) {
public post(path: string, handler: RouteHandler) {
if (!this.routes_.POST) { this.routes_.POST = {}; }
this.routes_.POST[path] = { handler, type };
this.routes_.POST[path] = handler;
}
public patch(path: string, handler: RouteHandler, type: RouteType = null) {
public patch(path: string, handler: RouteHandler) {
if (!this.routes_.PATCH) { this.routes_.PATCH = {}; }
this.routes_.PATCH[path] = { handler, type };
this.routes_.PATCH[path] = handler;
}
public del(path: string, handler: RouteHandler, type: RouteType = null) {
public del(path: string, handler: RouteHandler) {
if (!this.routes_.DELETE) { this.routes_.DELETE = {}; }
this.routes_.DELETE[path] = { handler, type };
this.routes_.DELETE[path] = handler;
}
public put(path: string, handler: RouteHandler, type: RouteType = null) {
public put(path: string, handler: RouteHandler) {
if (!this.routes_.PUT) { this.routes_.PUT = {}; }
this.routes_.PUT[path] = { handler, type };
this.routes_.PUT[path] = handler;
}
}

View File

@@ -6,6 +6,9 @@ export default function(name: string): View {
name: name,
path: `index/${name}`,
content: {},
navbar: true,
partials: [
'navbar',
'notifications',
],
};
}

View File

@@ -26,8 +26,8 @@ export class ErrorMethodNotAllowed extends ApiError {
export class ErrorNotFound extends ApiError {
public static httpCode: number = 404;
public constructor(message: string = 'Not Found', code: string = undefined) {
super(message, ErrorNotFound.httpCode, code);
public constructor(message: string = 'Not Found') {
super(message, ErrorNotFound.httpCode);
Object.setPrototypeOf(this, ErrorNotFound.prototype);
}
}
@@ -86,10 +86,3 @@ export class ErrorPayloadTooLarge extends ApiError {
Object.setPrototypeOf(this, ErrorPayloadTooLarge.prototype);
}
}
export function errorToString(error: Error): string {
const msg: string[] = [];
msg.push(error.message ? error.message : 'Unknown error');
if (error.stack) msg.push(error.stack);
return msg.join(': ');
}

View File

@@ -1,5 +1,5 @@
import JoplinDatabase from '@joplin/lib/JoplinDatabase';
// import Logger from '@joplin/lib/Logger';
import Logger from '@joplin/lib/Logger';
import BaseModel, { ModelType } from '@joplin/lib/BaseModel';
import BaseItem from '@joplin/lib/models/BaseItem';
import Note from '@joplin/lib/models/Note';
@@ -24,7 +24,7 @@ import Setting from '@joplin/lib/models/Setting';
import { Models } from '../models/factory';
import MustacheService from '../services/MustacheService';
// const logger = Logger.create('JoplinUtils');
const logger = Logger.create('JoplinUtils');
export interface FileViewerResponse {
body: any;
@@ -55,16 +55,15 @@ let baseUrl_: string = null;
export const resourceDirName = '.resource';
export async function initializeJoplinUtils(config: Config, models: Models, mustache: MustacheService) {
export async function initializeJoplinUtils(config: Config, models: Models) {
models_ = models;
baseUrl_ = config.baseUrl;
mustache_ = mustache;
const filePath = `${config.tempDir}/joplin.sqlite`;
await fs.remove(filePath);
db_ = new JoplinDatabase(new DatabaseDriverNode());
// db_.setLogger(logger as Logger);
db_.setLogger(logger as Logger);
await db_.open({ name: filePath });
BaseModel.setDb(db_);
@@ -79,8 +78,8 @@ export async function initializeJoplinUtils(config: Config, models: Models, must
BaseItem.loadClass('MasterKey', MasterKey);
BaseItem.loadClass('Revision', Revision);
// mustache_ = new MustacheService(config.viewDir, config.baseUrl);
// mustache_.prefersDarkEnabled = false;
mustache_ = new MustacheService(config.viewDir, config.baseUrl);
mustache_.prefersDarkEnabled = false;
}
export function linkedResourceIds(body: string): string[] {
@@ -211,7 +210,7 @@ async function renderNote(share: Share, note: NoteEntity, resourceInfos: Resourc
};
`,
},
}, { prefersDarkEnabled: false });
});
return {
body: bodyHtml,

View File

@@ -22,8 +22,6 @@ export async function formParse(req: any): Promise<FormParseResult> {
return output;
}
// Note that for Formidable to work, the content-type must be set in the
// headers
return new Promise((resolve: Function, reject: Function) => {
const form = formidable({ multiples: true });
form.parse(req, (error: any, fields: any, files: any) => {
@@ -38,8 +36,29 @@ export async function formParse(req: any): Promise<FormParseResult> {
}
export async function bodyFields<T>(req: any/* , filter:string[] = null*/): Promise<T> {
// Formidable needs the content-type to be 'application/json' so on our side
// we explicitely set it to that. However save the previous value so that it
// can be restored.
let previousContentType = null;
if (req.headers['content-type'] !== 'application/json') {
previousContentType = req.headers['content-type'];
req.headers['content-type'] = 'application/json';
}
const form = await formParse(req);
if (previousContentType) req.headers['content-type'] = previousContentType;
return form.fields as T;
// if (filter) {
// const output:BodyFields = {};
// Object.keys(form.fields).forEach(f => {
// if (filter.includes(f)) output[f] = form.fields[f];
// });
// return output;
// } else {
// return form.fields;
// }
}
export function ownerRequired(ctx: AppContext) {

View File

@@ -1,4 +1,4 @@
import { isValidOrigin, parseSubPath, splitItemPath } from './routeUtils';
import { parseSubPath, splitItemPath } from './routeUtils';
import { ItemAddressingType } from '../db';
describe('routeUtils', function() {
@@ -41,46 +41,4 @@ describe('routeUtils', function() {
}
});
it('should check the request origin', async function() {
const testCases: any[] = [
[
'https://example.com', // Request origin
'https://example.com', // Config base URL
true,
],
[
// Apache ProxyPreserveHost somehow converts https:// to http://
// but in this context it's valid as only the domain matters.
'http://example.com',
'https://example.com',
true,
],
[
// With Apache ProxyPreserveHost, the request might be eg
// https://example.com/joplin/api/ping but the origin part, as
// forwarded by Apache will be https://example.com/api/ping
// (without /joplin). In that case the request is valid anyway
// since we only care about the domain.
'https://example.com',
'https://example.com/joplin',
true,
],
[
'https://bad.com',
'https://example.com',
false,
],
[
'http://bad.com',
'https://example.com',
false,
],
];
for (const testCase of testCases) {
const [requestOrigin, configBaseUrl, expected] = testCase;
expect(isValidOrigin(requestOrigin, configBaseUrl)).toBe(expected);
}
});
});

View File

@@ -1,9 +1,7 @@
import { baseUrl } from '../config';
import { Item, ItemAddressingType } from '../db';
import { ErrorBadRequest, ErrorForbidden, ErrorNotFound } from './errors';
import Router from './Router';
import { AppContext, HttpMethod } from './types';
import { URL } from 'url';
const { ltrimSlashes, rtrimSlashes } = require('@joplin/lib/path-utils');
@@ -153,12 +151,6 @@ export function parseSubPath(basePath: string, p: string, rawPath: string = null
return output;
}
export function isValidOrigin(requestOrigin: string, endPointBaseUrl: string): boolean {
const host1 = (new URL(requestOrigin)).host;
const host2 = (new URL(endPointBaseUrl)).host;
return host1 === host2;
}
export function routeResponseFormat(context: AppContext): RouteResponseFormat {
// const rawPath = context.path;
// if (match && match.route.responseFormat) return match.route.responseFormat;
@@ -174,15 +166,14 @@ export async function execRequest(routes: Routers, ctx: AppContext) {
const match = findMatchingRoute(ctx.path, routes);
if (!match) throw new ErrorNotFound();
const endPoint = match.route.findEndPoint(ctx.request.method as HttpMethod, match.subPath.schema);
if (ctx.URL && !isValidOrigin(ctx.URL.origin, baseUrl(endPoint.type))) throw new ErrorNotFound('Invalid origin', 'invalidOrigin');
const routeHandler = match.route.findEndPoint(ctx.request.method as HttpMethod, match.subPath.schema);
// This is a generic catch-all for all private end points - if we
// couldn't get a valid session, we exit now. Individual end points
// might have additional permission checks depending on the action.
if (!match.route.isPublic(match.subPath.schema) && !ctx.owner) throw new ErrorForbidden();
if (!match.route.public && !ctx.owner) throw new ErrorForbidden();
return endPoint.handler(match.subPath, ctx);
return routeHandler(match.subPath, ctx);
}
// In a path such as "/api/files/SOME_ID/content" we want to find:

View File

@@ -2,32 +2,22 @@ import { LoggerWrapper } from '@joplin/lib/Logger';
import config from '../config';
import { DbConnection } from '../db';
import newModelFactory, { Models } from '../models/factory';
import { AppContext, Config, Env } from './types';
import { AppContext, Env } from './types';
import routes from '../routes/routes';
import ShareService from '../services/ShareService';
import { Services } from '../services/types';
import EmailService from '../services/EmailService';
import CronService from '../services/CronService';
import MustacheService from '../services/MustacheService';
async function setupServices(env: Env, models: Models, config: Config): Promise<Services> {
const output: Services = {
share: new ShareService(env, models, config),
email: new EmailService(env, models, config),
cron: new CronService(env, models, config),
mustache: new MustacheService(config.viewDir, config.baseUrl),
function setupServices(env: Env, models: Models): Services {
return {
share: new ShareService(env, models),
};
await output.mustache.loadPartials();
return output;
}
export default async function(appContext: AppContext, env: Env, dbConnection: DbConnection, appLogger: ()=> LoggerWrapper) {
appContext.env = env;
appContext.db = dbConnection;
appContext.models = newModelFactory(appContext.db, config().baseUrl);
appContext.services = await setupServices(env, appContext.models, config());
appContext.services = setupServices(env, appContext.models);
appContext.appLogger = appLogger;
appContext.routes = { ...routes };

View File

@@ -1,9 +1,5 @@
import { AppContext } from './types';
export default async function startServices(appContext: AppContext) {
const services = appContext.services;
void services.share.runInBackground();
void services.email.runInBackground();
void services.cron.runInBackground();
export default function startServices(appContext: AppContext) {
void appContext.services.share.runInBackground();
}

View File

@@ -1,4 +1,4 @@
import { User, Session, DbConnection, connectDb, disconnectDb, truncateTables, Item, Uuid } from '../../db';
import { User, Session, DbConnection, connectDb, disconnectDb, truncateTables, sqliteFilePath, Item, Uuid } from '../../db';
import { createDb } from '../../tools/dbTools';
import modelFactory from '../../models/factory';
import { AppContext, Env } from '../types';
@@ -9,7 +9,6 @@ import FakeRequest from './koa/FakeRequest';
import FakeResponse from './koa/FakeResponse';
import * as httpMocks from 'node-mocks-http';
import * as crypto from 'crypto';
import * as path from 'path';
import * as fs from 'fs-extra';
import * as jsdom from 'jsdom';
import setupAppContext from '../setupAppContext';
@@ -18,11 +17,10 @@ import { putApi } from './apiUtils';
import { FolderEntity, NoteEntity, ResourceEntity } from '@joplin/lib/services/database/types';
import { ModelType } from '@joplin/lib/BaseModel';
import { initializeJoplinUtils } from '../joplinUtils';
import MustacheService from '../../services/MustacheService';
// Takes into account the fact that this file will be inside the /dist directory
// when it runs.
const packageRootDir = path.dirname(path.dirname(path.dirname(__dirname)));
const packageRootDir = `${__dirname}/../../..`;
let db_: DbConnection = null;
@@ -56,9 +54,9 @@ function initGlobalLogger() {
Logger.initializeGlobalLogger(globalLogger);
}
let createdDbPath_: string = null;
let createdDbName_: string = null;
export async function beforeAllDb(unitName: string) {
createdDbPath_ = `${packageRootDir}/db-test-${unitName}.sqlite`;
createdDbName_ = unitName;
const tempDir = `${packageRootDir}/temp/test-${unitName}`;
await fs.mkdirp(tempDir);
@@ -68,7 +66,7 @@ export async function beforeAllDb(unitName: string) {
// initConfig({
// DB_CLIENT: 'pg',
// POSTGRES_DATABASE: unitName,
// POSTGRES_DATABASE: createdDbName_,
// POSTGRES_USER: 'joplin',
// POSTGRES_PASSWORD: 'joplin',
// }, {
@@ -76,7 +74,7 @@ export async function beforeAllDb(unitName: string) {
// });
initConfig({
SQLITE_DATABASE: createdDbPath_,
SQLITE_DATABASE: createdDbName_,
}, {
tempDir: tempDir,
});
@@ -86,10 +84,7 @@ export async function beforeAllDb(unitName: string) {
await createDb(config().database, { dropIfExists: true });
db_ = await connectDb(config().database);
const mustache = new MustacheService(config().viewDir, config().baseUrl);
await mustache.loadPartials();
await initializeJoplinUtils(config(), models(), mustache);
await initializeJoplinUtils(config(), models());
}
export async function afterAllTests() {
@@ -103,9 +98,10 @@ export async function afterAllTests() {
tempDir_ = null;
}
if (createdDbPath_) {
await fs.remove(createdDbPath_);
createdDbPath_ = null;
if (createdDbName_) {
const filePath = sqliteFilePath(createdDbName_);
await fs.remove(filePath);
createdDbName_ = null;
}
}

View File

@@ -36,8 +36,6 @@ export enum DatabaseConfigClient {
export interface DatabaseConfig {
client: DatabaseConfigClient;
// For Postgres, this is the actual database name. For SQLite, this is the
// path to the SQLite file.
name: string;
host?: string;
port?: number;
@@ -46,31 +44,17 @@ export interface DatabaseConfig {
asyncStackTraces?: boolean;
}
export interface MailerConfig {
enabled: boolean;
host: string;
port: number;
secure: boolean;
authUser: string;
authPassword: string;
noReplyName: string;
noReplyEmail: string;
}
export interface Config {
port: number;
rootDir: string;
viewDir: string;
layoutDir: string;
// Note that, for now, nothing is being logged to file. Log is just printed
// Not that, for now, nothing is being logged to file. Log is just printed
// to stdout, which is then handled by Docker own log mechanism
logDir: string;
tempDir: string;
baseUrl: string;
apiBaseUrl: string;
userContentBaseUrl: string;
database: DatabaseConfig;
mailer: MailerConfig;
baseUrl: string;
}
export enum HttpMethod {
@@ -81,10 +65,4 @@ export enum HttpMethod {
HEAD = 'HEAD',
}
export enum RouteType {
Web = 1,
Api = 2,
UserContent = 3,
}
export type KoaNext = ()=> Promise<void>;

View File

@@ -7,10 +7,10 @@
{{/stack}}
</div>
{{#owner}}
<p><a href="{{{global.baseUrl}}}/home">Go to home page</a></p>
<p><a href="{{{global.baseUrl}}}/home">Back to home page</a></p>
{{/owner}}
{{^owner}}
<p><a href="{{{global.baseUrl}}}/login">Go to login page</a></p>
<p><a href="{{{global.baseUrl}}}/login">Back to login page</a></p>
{{/owner}}
</div>
</div>

View File

@@ -1,17 +1,17 @@
{{#itemTable}}
{{>table}}
{{/itemTable}}
<form id="item_form" action="{{{postUrl}}}" method="POST" class="block">
<input type="submit" name="delete_all_button" class="button is-danger" value="Delete all" />
</form>
{{#itemTable}}
{{>table}}
{{/itemTable}}
<script>
onDocumentReady(function() {
document.getElementById("item_form").addEventListener('submit', function(event) {
if (event.submitter.getAttribute('name') === 'delete_all_button') {
const response = prompt('This will DELETE all your notes, and it cannot be undone. If you wish to continue, please type "confirm".');
if (response !== 'confirm') event.preventDefault();
const ok = confirm('Delete all items?');
if (!ok) event.preventDefault();
}
});
});

View File

@@ -1,33 +0,0 @@
<section class="section">
<div class="container">
<h1 class="title">Welcome to Joplin!</h1>
<h2 class="subtitle">Please enter your password to start using your account.</h2>
<form action="{{postUrl}}" method="POST">
<input class="input" type="hidden" name="token" value="{{token}}"/>
<div class="field">
<label class="label">Email</label>
<div class="control">
<input class="input" type="email" disabled value="{{user.email}}"/>
</div>
</div>
<div class="field">
<label class="label">Password</label>
<div class="control">
<input class="input" type="password" name="password"/>
</div>
</div>
<div class="field">
<label class="label">Repeat password</label>
<div class="control">
<input class="input" type="password" name="password2"/>
</div>
</div>
{{> errorBanner}}
<div class="control">
<button class="button is-primary">Save password</button>
</div>
</form>
</div>
</section>

View File

@@ -1,8 +1,8 @@
{{#error}}
<div class="notification is-danger">
<strong>{{message}}</strong>
{{#stack}}
<strong>{{error.message}}</strong>
{{#error.stack}}
<pre>{{.}}</pre>
{{/stack}}
{{/error.stack}}
</div>
{{/error}}

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