Compare commits

...

131 Commits

Author SHA1 Message Date
Licaon_Kter
c54759e766 Remove gradle property unused in Java 17
Signed-off-by: Licaon_Kter <licaon-kter@users.noreply.github.com>
2024-03-22 23:17:45 +05:00
Ammar Ahmed
f15446b1d6 mobile: bump version code 2024-03-21 11:45:03 +05:00
Ammar Ahmed
aa2a8ab6f4 mobile: ignore beta updates on gh release 2024-03-21 10:17:34 +05:00
Ammar Ahmed
8e59ff1318 mobile: release v2.6.18 2024-03-21 10:11:37 +05:00
Abdullah Atta
ad99c87f72 web: bump version to 2.6.17 2024-03-21 10:07:11 +05:00
Abdullah Atta
ba776b5854 global: update lockfiles 2024-03-21 10:07:02 +05:00
Abdullah Atta
e526145e48 web: fix cannot read property integration of undefined 2024-03-21 10:02:08 +05:00
Abdullah Atta
45c5e65bf6 core: add more sanity checks 2024-03-21 09:42:38 +05:00
Abdullah Atta
87bec4e2ab core: add sanity checks to handle cannot read properties of undefined (reading 'hash') error 2024-03-21 09:37:18 +05:00
Abdullah Atta
433e67a6dc web: fix pull failed error on downloading attachments 2024-03-21 09:12:55 +05:00
Ammar Ahmed
6acba51b88 mobile: fix app lock shows on session expired dialog 2024-03-21 07:46:49 +05:00
Abdullah Atta
cf1322952d web: handle errors during attachment downloading 2024-03-15 09:25:10 +05:00
Abdullah Atta
b5ac9dd430 web: make opfs safer by allowing only 1 operation at a time 2024-03-15 09:01:35 +05:00
Abdullah Atta
a3b590bcb7 core: add more login tests 2024-03-12 07:19:59 +05:00
Ammar Ahmed
d4f7e3ef07 mobile: add changelog 2024-03-06 15:31:33 +05:00
Abdullah Atta
16119f6958 setup: optimize bootstrap script 2024-03-06 13:40:42 +05:00
Abdullah Atta
e39c2583a5 setup: only run npm rebuild if required 2024-03-06 13:40:41 +05:00
Abdullah Atta
eecff009dd setup: run npm rebuild after bootstrap 2024-03-06 13:40:41 +05:00
Abdullah Atta
d9ed61a7da setup: ignore scripts during bootstrap 2024-03-06 13:40:41 +05:00
Abdullah Atta
58db265702 setup: use 1 thread on CI 2024-03-06 13:40:41 +05:00
Abdullah Atta
bd39f0cbf8 core: fix e.metadata.hash is not defined 2024-03-06 13:29:59 +05:00
Abdullah Atta
255015108a core: update lockfile 2024-03-06 13:01:00 +05:00
Abdullah Atta
b80f366f8d core: run patch-package after install 2024-03-06 13:00:34 +05:00
Ammar Ahmed
c845c7fce6 mobile: release v2.6.17 2024-03-06 12:59:23 +05:00
Ammar Ahmed
6e7b7ce0e1 mobile: ask user to save recovery key after changing password 2024-03-06 12:33:38 +05:00
Abdullah Atta
9b728902d4 web: bump version to 2.6.16 2024-03-06 12:03:06 +05:00
Abdullah Atta
9a1f54c41a desktop: set proxy on startup 2024-03-06 11:43:50 +05:00
Abdullah Atta
b3251eb016 core: fix login gets stuck on error 2024-03-06 11:28:45 +05:00
Abdullah Atta
f4064b7939 core: patch signalr to exclude electron renderer process as node 2024-03-06 11:28:27 +05:00
Abdullah Atta
f014f08ff4 web: fix export to html test snapshot 2024-03-05 15:41:53 +05:00
Abdullah Atta
dee1cf4b5a web: fix locked note status not updating in list 2024-03-05 15:38:01 +05:00
Abdullah Atta
f35a3d8fa3 web: clear editor on unlocking the note 2024-03-05 15:37:45 +05:00
Abdullah Atta
ca9a8d14fa core: fix sync tests 2024-03-05 15:03:18 +05:00
Abdullah Atta
35c35fa9d7 core: update test snapshots 2024-03-05 14:51:41 +05:00
Abdullah Atta
09fff95d58 editor: fix marks.filter is not a function error on pressing Enter 2024-03-05 14:27:29 +05:00
Abdullah Atta
287307a1ba core: move to json protocol for signalr 2024-03-05 14:23:44 +05:00
Abdullah Atta
d628e62302 web: fix app hangs when downloading logs 2024-03-05 14:18:54 +05:00
Ammar Ahmed
a070bc46ad mobile: check backup was successful 2024-03-05 14:16:35 +05:00
Ammar Ahmed
9027c44511 mobile: request backup before changing password 2024-03-05 14:16:35 +05:00
Abdullah Atta
722aa7b9c6 mobile: update database sync api to use new sync options 2024-03-05 14:16:35 +05:00
Abdullah Atta
a4e777b24b web: update database sync api to use new sync options 2024-03-05 14:16:35 +05:00
Abdullah Atta
af7120e953 web: create backup before changing password 2024-03-05 14:16:35 +05:00
Abdullah Atta
d5adc3bbac web: refactor backup verification logic 2024-03-05 14:16:35 +05:00
Abdullah Atta
aa3d778ad1 core: reduce unnecessary syncing during password change 2024-03-05 14:16:35 +05:00
Abdullah Atta
3465a816c6 web: rename to markdown shortcuts 2024-03-05 13:42:39 +05:00
Ammar Ahmed
3d1726c5aa mobile: toggle markdown shortcuts 2024-03-05 13:42:39 +05:00
Muhammad Ali
488de2d583 web: add setting for toggling markdown in editor 2024-03-05 13:42:39 +05:00
Abdullah Atta
c415b114a6 web: template not disabling when copying as markdown 2024-03-05 13:32:54 +05:00
Abdullah Atta
da36784e9c core: fix content inside span not converting to markdown 2024-03-05 13:32:54 +05:00
Muhammad Ali
78fafdc272 editor: convert google docs checklists on paste 2024-03-05 13:32:54 +05:00
Muhammad Ali
7d57055f73 editor: fix new lines from google docs not being preserved on paste (#3988)
* editor: handle <br> directly under root element

* editor: fix pasting from google docs

---------

Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-03-05 12:14:19 +05:00
Ammar Ahmed
b84cc747cb mobile: restore backup with encryption key 2024-03-04 15:56:12 +05:00
Abdullah Atta
9a4f3ccbad web: allow using encryption key to restore backup 2024-03-04 15:56:12 +05:00
Abdullah Atta
68de3cc928 core: allow using encryption key to decrypt backup 2024-03-04 15:56:12 +05:00
Ammar Ahmed
6e135cdd36 mobile: sort reminders 2024-03-04 15:27:42 +05:00
Abdullah Atta
696116ac85 web: add support for sorting reminders 2024-03-04 15:27:42 +05:00
Abdullah Atta
08a13ff35a core: add support for group options for reminders 2024-03-04 15:27:42 +05:00
Abdullah Atta
af1cea81dc theme: use radio focus color from theme 2024-03-04 15:27:42 +05:00
Muhammad Ali
2c22a7ca90 core: add support for sorting reminders by due date 2024-03-04 15:27:42 +05:00
Muhammad Ali
6fd6bd0375 desktop: add proxy settings (#4196) 2024-03-04 15:16:59 +05:00
Muhammad Ali
1a96dc965a desktop: add support for viewing and removing custom dictionary words (#4362)
Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-03-04 13:47:24 +05:00
Muhammad Ali
9550350f25 desktop: add menu item to copy images in editor (#4373) 2024-03-04 13:27:46 +05:00
Muhammad Ali
0ed605a5b9 editor: fix column toolbar position when table is scrolled horizontally (#4366) 2024-03-04 13:25:46 +05:00
Abdullah Atta
18910d931c config: add .nx to .gitignore 2024-03-04 13:24:25 +05:00
Muhammad Ali
87648b7d8b editor: fix katex math not being rendered correctly (#4353)
Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-03-04 13:23:27 +05:00
Muhammad Ali
7e7a1aeecb editor: add support for toggling highlight/background color (#4330) 2024-03-04 13:22:25 +05:00
Muhammad Ali
cb353358b7 web: fix editor text not selectable from margins (#4292)
Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-03-04 13:20:40 +05:00
Muhammad Ali
ba1619711b desktop: fix app autostart in appimage (#4223) 2024-03-04 12:40:51 +05:00
Ammar Ahmed
b3cc9475ad mobile: fix attachment search 2024-03-01 08:22:14 +05:00
Abdullah Atta
ee5c4077fe docs: improve skiff pages import guide 2024-02-13 01:07:14 +05:00
Abdullah Atta
47bbfc618e docs: add guide for migrating from skiff pages 2024-02-12 10:49:40 +05:00
Abdullah Atta
b377329a8b core: fix attachment mime type on read 2024-02-02 16:02:20 +05:00
Abdullah Atta
ae8bcf3865 ci: fix you may only define one of branches and branches-ignore for a single event
Signed-off-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-01-31 12:46:32 +05:00
Abdullah Atta
2f67611829 ci: add workflows for v3 beta publishing 2024-01-31 12:41:08 +05:00
Ammar Ahmed
058c612f4f ci: update default build tools version android
Signed-off-by: Ammar Ahmed <40239442+ammarahm-ed@users.noreply.github.com>
2024-01-30 11:41:20 +05:00
Ammar Ahmed
be8df90ccb iOS Publish Workflow (#4194)
Signed-off-by: Ammar Ahmed <40239442+ammarahm-ed@users.noreply.github.com>
2024-01-30 11:32:48 +05:00
Abdullah Atta
aa730b5b93 web: fix title only txt exports 2024-01-30 00:29:46 +05:00
Abdullah Atta
34bbcf6387 web: add feature highlights for v2.6.15 2024-01-29 23:33:15 +05:00
Abdullah Atta
33c3c78e2f desktop: get rid of configuration.win.signingHashAlgorithms should be an array 2024-01-29 23:27:45 +05:00
Ammar Ahmed
bf144dcda4 mobile: add ExportOptions.plist 2024-01-29 23:23:48 +05:00
Ammar Ahmed
284ebdb86f ci: @notesnook/ios
Signed-off-by: Ammar Ahmed <40239442+ammarahm-ed@users.noreply.github.com>
2024-01-29 23:23:01 +05:00
Abdullah Atta
9dac4cf7f4 desktop: set signing has to sha256 2024-01-29 23:22:29 +05:00
Abdullah Atta
fb973a5514 ci: run build job no matter what 2024-01-29 23:22:29 +05:00
Abdullah Atta
f9226510f9 desktop: use full path for FilesCatalog 2024-01-29 23:22:29 +05:00
Abdullah Atta
5c0a964699 ci: add inputs to disable build for specific platforms 2024-01-29 23:22:29 +05:00
Abdullah Atta
41ffaab3dc ci: install azurecodesigning module 2024-01-29 23:22:29 +05:00
Abdullah Atta
764c721f1d desktop: add windows code signing 2024-01-29 23:22:29 +05:00
Ammar Ahmed
3d267f91ef mobile: bump version code 2024-01-29 19:55:41 +05:00
Ammar Ahmed
f10f28a7f8 mobile: release v2.6.15 2024-01-29 19:32:14 +05:00
Ammar Ahmed
8d04f89a18 mobile: remove progress bar 2024-01-29 19:06:01 +05:00
Ammar Ahmed
9d1374dcd4 editor: fix progress not showing in image on mobile 2024-01-29 19:05:49 +05:00
Abdullah Atta
094a65e514 editor: hide progress on image if 0 2024-01-29 18:26:44 +05:00
Ammar Ahmed
372da979e1 mobile: support ignoring edits 2024-01-29 18:26:44 +05:00
Abdullah Atta
d3371326f2 editor: add progress indicator to image 2024-01-29 18:26:44 +05:00
Abdullah Atta
57452bd0e6 core: allow setting custom date edited 2024-01-29 18:26:44 +05:00
Abdullah Atta
993b8460bf web: do not update dateEdited if ignoring edits 2024-01-29 18:26:44 +05:00
Abdullah Atta
081201aa42 editor: add support for ignoring edits 2024-01-29 18:26:44 +05:00
Abdullah Atta
270e6778d1 editor: optimize image loading when fast scrolling 2024-01-29 16:23:59 +05:00
Abdullah Atta
2074320583 editor: revoke blob urls on image unmount 2024-01-29 16:09:05 +05:00
Abdullah Atta
cd90030616 web: fix note title in toolbar not changing 2024-01-29 15:45:13 +05:00
Abdullah Atta
807bd683b7 web: do not show success prompt on unlock cancel 2024-01-29 15:36:01 +05:00
Abdullah Atta
35929026a4 web: monograph.notesnook.com > monogr.ph 2024-01-29 15:22:22 +05:00
Ammar Ahmed
41eb94ee47 mobile: fix exporting locked notes 2024-01-29 11:02:32 +05:00
Ammar Ahmed
ba51e110ad mobile: fix opening webclips 2024-01-29 11:02:32 +05:00
Ammar Ahmed
ecad06d249 mobile: disable rtl mode 2024-01-29 11:02:32 +05:00
Abdullah Atta
19a151f637 editor: fix image query matching all images in editor 2024-01-28 17:17:45 +05:00
Ammar Ahmed
7c4a6f1e17 global: update deps 2024-01-27 23:06:24 +05:00
Ammar Ahmed
bc88e953d1 mobile: make sure tools render in toolbar 2024-01-27 23:05:30 +05:00
Ammar Ahmed
7d89ec676a mobile: fix attachments not loading when added from share ext 2024-01-27 22:50:41 +05:00
Ammar Ahmed
c8f8bcca93 mobile: organize bulk exports 2024-01-27 21:23:29 +05:00
Abdullah Atta
9fa904e849 web: fix exporting of single note 2024-01-27 21:23:29 +05:00
Abdullah Atta
05cc947cb4 web: fix pdf exports 2024-01-27 21:23:29 +05:00
alihamuh
a20a683b17 web: code refactoring 2024-01-27 21:23:29 +05:00
alihamuh
5fc43c931e web: added directory paths for exports 2024-01-27 21:23:29 +05:00
Abdullah Atta
0879c3b4d6 core: fix formatting of single spaced paragarphs in markdown exports (#4186)
* core: update showdown library to support single spaced paragraphs

* core: add tests

* core: update showdown library
2024-01-27 18:59:35 +05:00
Abdullah Atta
2eded71de3 core: fix restored attachments not syncing 2024-01-27 16:06:04 +05:00
Abdullah Atta
9e30ee50b8 core: add logs 2024-01-27 16:06:04 +05:00
Abdullah Atta
08621a5873 core: try to preserve mime type on backup restore 2024-01-27 16:06:04 +05:00
Abdullah Atta
17f5bd28ba web: do not overwrite filename & mimetype on attachment reupload 2024-01-27 16:06:04 +05:00
Ammar Ahmed
4558c0b2eb mobile: fix downloading attachments from editor 2024-01-27 16:06:04 +05:00
Abdullah Atta
a442677e91 editor: fix loading of images that have wrong mime type 2024-01-27 16:06:04 +05:00
Abdullah Atta
95666bee36 editor: remove attachment progress once it reaches 100 2024-01-27 16:06:04 +05:00
Abdullah Atta
c4232ac95a web: do not send hash when updating attachment 2024-01-27 16:06:04 +05:00
Abdullah Atta
0283037289 mobile: changes related to download cancellation 2024-01-27 16:06:04 +05:00
Abdullah Atta
b6fd0df715 web: get rid of all attachment loading logic 2024-01-27 16:06:04 +05:00
Abdullah Atta
f53fb58024 editor: eagerly load image/webclip instead of waiting on client 2024-01-27 16:06:04 +05:00
Abdullah Atta
21d452308d core: simplify download cancellation 2024-01-27 16:06:04 +05:00
Ammar Ahmed
823608cca1 mobile: daily trash cleanup 2024-01-27 16:05:28 +05:00
alihamuh
f3a0b998e4 web: added daily trash interval option 2024-01-27 16:05:28 +05:00
theProton
a47a38b16b web: fix incorrect title on scrolling note (#4137)
Signed-off-by: Parthiv-M <parthivmenon.dev@gmail.com>
2024-01-27 11:44:58 +05:00
Ammar Ahmed
a184c53dd5 mobile: fix loading empty conent in editor on tablets 2024-01-26 23:02:06 +05:00
185 changed files with 3278 additions and 1689 deletions

View File

@@ -1,4 +1,4 @@
name: Publish @notesnook/mobile
name: Publish @notesnook/android
on: workflow_dispatch
@@ -33,13 +33,14 @@ jobs:
- name: Sign app bundle for Playstore release
id: sign_app
uses: r0adkll/sign-android-release@v1
uses: r0adkll/sign-android-release@master
with:
releaseDirectory: apps/mobile/native/android/app/build/outputs/bundle/release
signingKeyBase64: ${{ secrets.SIGNING_KEY }}
alias: ${{ secrets.ALIAS }}
keyStorePassword: ${{ secrets.KEY_PASSWORD }}
keyPassword: ${{ secrets.KEY_PASSWORD }}
env:
BUILD_TOOLS_VERSION: "33.0.0"
- name: Publish to Playstore
@@ -65,6 +66,7 @@ jobs:
alias: ${{ secrets.PUBLIC_ALIAS }}
keyStorePassword: ${{ secrets.PUBLIC_KEY_PASSWORD }}
keyPassword: ${{ secrets.PUBLIC_KEY_PASSWORD }}
env:
BUILD_TOOLS_VERSION: "33.0.0"
- name: Rename apk files

View File

@@ -18,6 +18,21 @@ on:
required: true
default: true
description: "Publish on GitHub releases?"
build-windows:
type: boolean
required: true
default: true
description: "Build for Windows?"
build-linux:
type: boolean
required: true
default: true
description: "Build for Linux?"
build-mac:
type: boolean
required: true
default: true
description: "Build for macOS?"
jobs:
build:
@@ -71,6 +86,7 @@ jobs:
build-macos:
name: Build for macOS
needs: build
if: inputs.build-mac
runs-on: macos-12
steps:
@@ -163,6 +179,7 @@ jobs:
build-linux:
name: Build for Linux
needs: build
if: inputs.build-linux
runs-on: ubuntu-22.04
steps:
@@ -221,12 +238,22 @@ jobs:
build-windows:
name: Build for Windows
needs: build
if: inputs.build-windows
runs-on: windows-latest
steps:
- name: Check out Git repository
uses: actions/checkout@v3
- name: Setup .NET Core SDK
uses: actions/setup-dotnet@v2
with:
dotnet-version: 6.0.x
- name: Install AzureCodeSigning
run: Install-Module -Name AzureCodeSigning -RequiredVersion 0.3.0 -Force -Repository PSGallery
shell: pwsh
- name: Setup Node
uses: ./.github/actions/setup-node-with-cache
@@ -247,6 +274,9 @@ jobs:
- name: Publish
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
run: |
if ($${{ inputs.publish-github }} -eq $true) {
yarn electron-builder --win --publish always

67
.github/workflows/ios.publish.yml vendored Normal file
View File

@@ -0,0 +1,67 @@
name: Publish @notesnook/ios
on: workflow_dispatch
jobs:
build:
runs-on: macos-13
timeout-minutes: 60
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Node
uses: ./.github/actions/setup-node-with-cache
- name: Install node modules
run: |
npm ci --ignore-scripts --prefer-offline --no-audit
npm run bootstrap -- --scope=mobile
- name: Build packages
run: npx nx run @notesnook/mobile:build
- name: Install Pods
run: npm run prepare:ios
- name: Build iOS App
uses: yukiarrr/ios-build-action@v1.11.2
with:
bundle-identifier: org.streetwriters.notesnook
scheme: Notesnook
configuration: "Release"
export-options: apps/mobile/native/ios/ExportOptions.plist
project-path: apps/mobile/native/ios/Notesnook.xcodeproj
workspace-path: apps/mobile/native/ios/Notesnook.xcworkspace
update-targets: |
Notesnook
Make Note
NotesWidgetExtension
disable-targets: Notesnook-tvOS,Notesnook-tvOSTests,NotesnookTests
code-signing-identity: Apple Distribution
team-id: ${{ secrets.APPLE_TEAM_ID }}
p12-base64: ${{ secrets.APPLE_CERTIFICATE_P12 }}
certificate-password: ${{ secrets.APPLE_CERTIFICATE_P12_PASSWORD }}
app-store-connect-api-key-issuer-id: ${{ secrets.API_KEY_ISSUER_ID }}
app-store-connect-api-key-id: ${{ secrets.APPSTORE_KEY_ID }}
app-store-connect-api-key-base64: ${{ secrets.APPSTORE_CONNECT_API_KEY_BASE64 }}
output-path: Notesnook.ipa
mobileprovision-base64: |
${{ secrets.APPLE_MOBILE_PROVISION_APP }}
${{ secrets.APPLE_MOBILE_PROVISION_SHARE }}
${{ secrets.APPLE_MOBILE_PROVISION_WIDGET }}
- name: 'Upload app to TestFlight'
uses: apple-actions/upload-testflight-build@v1
with:
app-path: Notesnook.ipa
issuer-id: ${{ secrets.API_KEY_ISSUER_ID }}
api-key-id: ${{ secrets.API_KEY_ID }}
api-private-key: ${{ secrets.API_KEY }}
- name: Upload to Github
uses: actions/upload-artifact@v2
with:
name: Notesnook.ipa
path: Notesnook.ipa

View File

@@ -1,10 +1,11 @@
name: Publish @notesnook/web Beta
on:
on:
workflow_dispatch:
push:
branches:
- master
- '!v3-beta'
paths-ignore:
- "apps/mobile/**"
- "packages/editor-mobile/**"
@@ -22,6 +23,7 @@ on:
- synchronize
branches:
- master
- '!v3-beta'
paths-ignore:
- "apps/mobile/**"
- "packages/editor-mobile/**"

View File

@@ -0,0 +1,40 @@
name: Publish @notesnook/web v3 Beta
on:
workflow_dispatch:
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node
uses: ./.github/actions/setup-node-with-cache
- name: Install packages
run: |
npm ci --ignore-scripts --prefer-offline --no-audit
npm run bootstrap -- --scope=web
- name: Setup environment
run: |
echo "NX_CLOUD_ACCESS_TOKEN=${{ secrets.NX_CLOUD_ACCESS_TOKEN }}" >> $GITHUB_ENV
echo "CLOUDFLARE_ACCOUNT_ID=${{ secrets.CLOUDFLARE_ACCOUNT_ID }}" >> $GITHUB_ENV
echo "CLOUDFLARE_API_TOKEN=${{ secrets.CLOUDFLARE_API_TOKEN }}" >> $GITHUB_ENV
- name: Generate beta build
run: npm run build:beta:web
- name: Publish to Cloudflare Pages
uses: unlike-ltd/github-actions-cloudflare-pages@v0.1.1
id: pages
with:
cloudflare-api-token: ${{ secrets.CLOUDFLARE_API_TOKEN }}
cloudflare-account-id: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
cloudflare-project-name: notesnook-v3-app
directory: ./apps/web/build
github-token: ${{ secrets.GITHUB_TOKEN }}
github-environment: ${{ (github.ref == 'refs/heads/master' && 'beta') || 'preview' }}

3
.gitignore vendored
View File

@@ -9,4 +9,5 @@ nx-cloud.env
.env.local
.nyc_output
site
node_modules.backup
node_modules.backup
.nx

View File

@@ -1,12 +1,12 @@
{
"name": "@notesnook/desktop",
"version": "2.6.14",
"version": "2.6.17",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@notesnook/desktop",
"version": "2.6.14",
"version": "2.6.17",
"hasInstallScript": true,
"license": "GPL-3.0-or-later",
"dependencies": {

View File

@@ -2,7 +2,7 @@
"name": "@notesnook/desktop",
"productName": "Notesnook",
"description": "Your private note taking space",
"version": "2.6.14",
"version": "2.6.17",
"appAppleId": "1544027013",
"private": true,
"main": "./dist/index.js",
@@ -135,6 +135,10 @@
]
}
],
"signingHashAlgorithms": [
"sha256"
],
"sign": "./sign.js",
"icon": "assets/icons/app.ico"
},
"portable": {

60
apps/desktop/sign.js Normal file
View File

@@ -0,0 +1,60 @@
/*
This file is part of the Notesnook project (https://notesnook.com/)
Copyright (C) 2023 Streetwriters (Private) Limited
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const { writeFileSync, rmSync, readFileSync } = require("fs");
const { execSync } = require("child_process");
const { relative, join } = require("path");
module.exports = async function (configuration) {
const Endpoint = "https://weu.codesigning.azure.net";
const CodeSigningAccountName = "Notesnook";
const CertificateProfileName = "Notesnook";
const FileDigest = configuration.hash.toUpperCase();
const TimestampRfc3161 = "http://timestamp.acs.microsoft.com";
const TimestampDigest = configuration.hash.toUpperCase();
const Description = "The Notesnook app";
const DescriptionUrl = "https://notesnook.com/";
const FilesCatalog = createCatalog(configuration.path);
const command = `Invoke-AzureCodeSigning -Endpoint "${Endpoint}" -CodeSigningAccountName "${CodeSigningAccountName}" -CertificateProfileName "${CertificateProfileName}" -FileDigest "${FileDigest}" -TimestampRfc3161 "${TimestampRfc3161}" -TimestampDigest "${TimestampDigest}" -Description "${Description}" -DescriptionUrl "${DescriptionUrl}" -FilesCatalog "${FilesCatalog}"`;
console.debug("Signing", configuration.path, "using command", command);
psexec(command);
console.debug("Signed", configuration.path);
deleteCatalog();
};
function createCatalog(path) {
writeFileSync("_catalog", relative(__dirname, path));
return join(__dirname, "_catalog");
}
function deleteCatalog() {
rmSync("_catalog");
}
function psexec(cmd) {
return execSync(cmd, {
env: process.env,
stdio: "inherit",
shell: "pwsh"
});
}

View File

@@ -54,6 +54,14 @@ export const osIntegrationRouter = t.router({
config.zoomFactor = factor;
}),
proxyRules: t.procedure.query(() => config.proxyRules),
setProxyRules: t.procedure
.input(z.string().optional())
.mutation(({ input: proxyRules }) => {
globalThis.window?.webContents.session.setProxy({ proxyRules });
config.proxyRules = proxyRules || "";
}),
privacyMode: t.procedure.query(() => config.privacyMode),
setPrivacyMode: t.procedure
.input(z.object({ enabled: z.boolean() }))

View File

@@ -118,5 +118,13 @@ export const spellCheckerRouter = t.router({
.mutation(({ input: { enabled } }) => {
globalThis.window?.webContents.session.setSpellCheckerEnabled(enabled);
config.isSpellCheckerEnabled = enabled;
})
}),
words: t.procedure.query(() =>
globalThis.window?.webContents.session.listWordsInSpellCheckerDictionary()
),
deleteWord: t.procedure.input(z.string()).mutation(({ input: word }) => {
globalThis.window?.webContents.session.removeWordFromSpellCheckerDictionary(
word
);
})
});

View File

@@ -112,6 +112,7 @@ async function createWindow() {
mainWindow.webContents.session.setSpellCheckerDictionaryDownloadURL(
"http://dictionaries.notesnook.com/"
);
mainWindow.webContents.session.setProxy({ proxyRules: config.proxyRules });
mainWindow.once("closed", () => {
globalThis.window = null;

View File

@@ -25,7 +25,11 @@ Type=Application
Version=${app.getVersion()}
Name=${app.getName()}
Comment=${app.getName()} startup script
Exec=${process.execPath}${hidden ? " --hidden" : ""}
Exec=${
process.env.APPIMAGE
? `${process.env.APPIMAGE}${hidden ? " --hidden" : ""}`
: `${process.execPath}${hidden ? " --hidden" : ""}`
}
StartupNotify=false
Terminal=false`;

View File

@@ -41,7 +41,8 @@ export const config = {
isSpellCheckerEnabled: true,
zoomFactor: 1,
theme: nativeTheme.themeSource,
automaticUpdates: true
automaticUpdates: true,
proxyRules: ""
};
type ConfigKey = keyof typeof config;

View File

@@ -131,6 +131,17 @@ function setupMenu() {
);
}
if (params.mediaType === "image")
menu.append(
new MenuItem({
id: "copy-image",
label: "Copy Image",
click() {
globalThis.window?.webContents.copyImageAt(params.x, params.y);
}
})
);
if (params.isEditable)
menu.append(
new MenuItem({

View File

@@ -17,13 +17,12 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import "@azure/core-asynciterator-polyfill";
import SettingsService from "./services/settings";
import {
THEME_COMPATIBILITY_VERSION,
useThemeEngineStore
} from "@notesnook/theme";
import React, { useEffect } from "react";
import { View } from "react-native";
import { I18nManager, View } from "react-native";
import "react-native-gesture-handler";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { SafeAreaProvider } from "react-native-safe-area-context";
@@ -32,11 +31,16 @@ import { withErrorBoundry } from "./components/exception-handler";
import GlobalSafeAreaProvider from "./components/globalsafearea";
import { useAppEvents } from "./hooks/use-app-events";
import { ApplicationHolder } from "./navigation";
import { themeTrpcClient } from "./screens/settings/theme-selector";
import Notifications from "./services/notifications";
import SettingsService from "./services/settings";
import { TipManager } from "./services/tip-manager";
import { useThemeStore } from "./stores/use-theme-store";
import { useUserStore } from "./stores/use-user-store";
import { themeTrpcClient } from "./screens/settings/theme-selector";
I18nManager.allowRTL(false);
I18nManager.forceRTL(false);
I18nManager.swapLeftAndRightInRTL(false);
SettingsService.checkOrientation();
const App = () => {

View File

@@ -34,7 +34,8 @@ import { useAttachmentStore } from "../../stores/use-attachment-store";
import { db } from "../database";
import Storage from "../database/storage";
import { cacheDir, copyFileAsync, releasePermissions } from "./utils";
import { createCacheDir } from "./io";
import { createCacheDir, exists } from "./io";
import { IOS_APPGROUPID } from "../../utils/constants";
export const FileDownloadStatus = {
Success: 1,
@@ -181,7 +182,9 @@ export default async function downloadAttachment(
silent: false,
cache: false,
throwError: false,
groupId: undefined
groupId: undefined,
base64: false,
text: false
}
) {
await createCacheDir();
@@ -212,10 +215,17 @@ export default async function downloadAttachment(
options.groupId || attachment.metadata.hash,
attachment.metadata.hash
);
if (
!(await RNFetchBlob.fs.exists(`${cacheDir}/${attachment.metadata.hash}`))
)
if (!(await exists(attachment.metadata.hash))) {
return;
}
if (options.base64 || options.text) {
return await db.attachments.read(
attachment.metadata.hash,
options.base64 ? "base64" : "text"
);
}
let filename = getFileNameWithExtension(
attachment.metadata.filename,
@@ -233,7 +243,8 @@ export default async function downloadAttachment(
mime: attachment.metadata.type,
fileName: options.cache ? undefined : filename,
uri: options.cache ? undefined : folder.uri,
chunkSize: attachment.chunkSize
chunkSize: attachment.chunkSize,
appGroupId: IOS_APPGROUPID
};
let fileUri = await Sodium.decryptFile(

View File

@@ -36,9 +36,13 @@ export async function readEncrypted(filename, key, cipherData) {
}
const attachment = db.attachments.attachment(filename);
const isPng = /(png)/g.test(attachment?.metadata.type);
const isJpeg = /(jpeg|jpg)/g.test(attachment?.metadata.type);
console.log("decrypting....");
const isPng = !attachment.metadata.type
? false
: /(png)/g.test(attachment?.metadata.type);
const isJpeg = !attachment.metadata.type
? false
: /(jpeg|jpg)/g.test(attachment?.metadata.type);
let output = await Sodium.decryptFile(
key,
{

View File

@@ -48,7 +48,7 @@ import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
import { formatBytes } from "@notesnook/common";
const Actions = ({ attachment, setAttachments, fwdRef }) => {
const Actions = ({ attachment, setAttachments, fwdRef, close }) => {
const { colors } = useThemeColors();
const contextId = attachment.metadata.hash;
const [filename, setFilename] = useState(attachment.metadata.filename);
@@ -64,7 +64,7 @@ const Actions = ({ attachment, setAttachments, fwdRef }) => {
name: "Download",
onPress: async () => {
if (currentProgress) {
await db.fs.cancel(attachment.metadata.hash, "download");
await db.fs.cancel(attachment.metadata.hash);
useAttachmentStore.getState().remove(attachment.metadata.hash);
}
downloadAttachment(attachment.metadata.hash, false);
@@ -117,7 +117,7 @@ const Actions = ({ attachment, setAttachments, fwdRef }) => {
});
}
setAttachments([...db.attachments.all]);
setAttachments();
setLoading({
name: null
});
@@ -140,7 +140,7 @@ const Actions = ({ attachment, setAttachments, fwdRef }) => {
filename: value
});
setFilename(value);
setAttachments([...db.attachments.all]);
setAttachments();
}
},
positiveText: "Rename"
@@ -152,8 +152,8 @@ const Actions = ({ attachment, setAttachments, fwdRef }) => {
name: "Delete",
onPress: async () => {
await db.attachments.remove(attachment.metadata.hash, false);
setAttachments([...db.attachments.all]);
eSendEvent(eCloseSheet, contextId);
setAttachments();
close();
},
icon: "delete-outline"
}
@@ -362,8 +362,13 @@ const Actions = ({ attachment, setAttachments, fwdRef }) => {
Actions.present = (attachment, set, context) => {
presentSheet({
context: context,
component: (ref) => (
<Actions fwdRef={ref} setAttachments={set} attachment={attachment} />
component: (ref, close) => (
<Actions
fwdRef={ref}
setAttachments={set}
close={close}
attachment={attachment}
/>
)
});
};

View File

@@ -132,7 +132,7 @@ export const AttachmentItem = ({
activeOpacity={0.9}
onPress={() => {
if (encryption || !pressable) return;
db.fs.cancel(attachment.metadata.hash, currentProgress.type);
db.fs.cancel(attachment.metadata.hash);
setCurrentProgress(null);
}}
style={{

View File

@@ -49,7 +49,7 @@ export const AttachmentDialog = ({ note }) => {
const { height } = useSettingStore((state) => state.dimensions);
const [attachments, setAttachments] = useState(
note
? db.attachments.ofNote(note.id, "all")
? db.attachments.ofNote(note?.id, "all")
: [...(db.attachments.all || [])]
);
@@ -59,8 +59,8 @@ export const AttachmentDialog = ({ note }) => {
const [currentFilter, setCurrentFilter] = useState("all");
const onChangeText = (text) => {
const attachments = note
? db.attachments.ofNote(note.id, "all")
const attachments = note?.id
? db.attachments.ofNote(note?.id, "all")
: [...(db.attachments.all || [])];
attachmentSearchValue.current = text;
@@ -68,7 +68,7 @@ export const AttachmentDialog = ({ note }) => {
!attachmentSearchValue.current ||
attachmentSearchValue.current === ""
) {
setAttachments([...attachments]);
setAttachments(filterAttachments(currentFilter));
}
clearTimeout(searchTimer.current);
searchTimer.current = setTimeout(() => {
@@ -77,13 +77,16 @@ export const AttachmentDialog = ({ note }) => {
attachmentSearchValue.current
);
if (results.length === 0) return;
setAttachments(results);
setAttachments(filterAttachments(currentFilter, results));
}, 300);
};
const renderItem = ({ item }) => (
<AttachmentItem
setAttachments={setAttachments}
setAttachments={() => {
setAttachments(filterAttachments(currentFilter));
}}
attachment={item}
context="attachments-list"
/>
@@ -133,11 +136,13 @@ export const AttachmentDialog = ({ note }) => {
}
];
const filterAttachments = (type) => {
const attachments = note
? db.attachments.ofNote(note.id, "all")
const filterAttachments = (type, _attachments) => {
const attachments = _attachments
? _attachments
: note
? db.attachments.ofNote(note?.id, "all")
: [...(db.attachments.all || [])];
isDocument;
switch (type) {
case "all":
return attachments;

View File

@@ -26,12 +26,15 @@ import {
ToastEvent
} from "../../services/event-manager";
import { useUserStore } from "../../stores/use-user-store";
import { eCloseSheet } from "../../utils/events";
import { eCloseSheet, eOpenRecoveryKeyDialog } from "../../utils/events";
import DialogHeader from "../dialog/dialog-header";
import { Button } from "../ui/button";
import Input from "../ui/input";
import { Notice } from "../ui/notice";
import Seperator from "../ui/seperator";
import { Dialog } from "../dialog";
import BackupService from "../../services/backup";
import { sleep } from "../../utils/time";
export const ChangePassword = () => {
const passwordInputRef = useRef();
@@ -64,6 +67,9 @@ export const ChangePassword = () => {
}
setLoading(true);
try {
const result = await BackupService.run(false, "change-password-dialog");
if (!result) throw new Error("Failed to create backup");
await db.user.clearSessions();
await db.user.changePassword(oldPassword.current, password.current);
ToastEvent.show({
@@ -73,6 +79,8 @@ export const ChangePassword = () => {
});
setLoading(false);
eSendEvent(eCloseSheet);
await sleep(300);
eSendEvent(eOpenRecoveryKeyDialog);
} catch (e) {
setLoading(false);
ToastEvent.show({
@@ -92,6 +100,7 @@ export const ChangePassword = () => {
padding: 12
}}
>
<Dialog context="change-password-dialog" />
<DialogHeader
title="Change password"
paragraph="Enter your old and new passwords"
@@ -129,7 +138,14 @@ export const ChangePassword = () => {
/>
<Notice
text="Changing password is a non-undoable process. You will be logged out from all your devices. Please make sure you do not close the app while your password is changing and have good internet connection."
text={`Changing password is an irreversible process. You will be logged out from all your devices. Please make sure you do not close the app while your password is changing and have good internet connection.`}
type="alert"
/>
<View style={{ height: 10 }} />
<Notice
text={`Once your password is changed, please make sure to save the new account recovery key.`}
type="alert"
/>

View File

@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { useThemeColors } from "@notesnook/theme";
import React, { useEffect, useState } from "react";
import { Modal, View } from "react-native";
import { View } from "react-native";
import { db } from "../../common/database";
import { MMKV } from "../../common/database/mmkv";
import BiometricService from "../../services/biometrics";
@@ -37,6 +37,7 @@ import { eLoginSessionExpired, eUserLoggedIn } from "../../utils/events";
import { SIZE } from "../../utils/size";
import { sleep } from "../../utils/time";
import { Dialog } from "../dialog";
import BaseDialog from "../dialog/base-dialog";
import { presentDialog } from "../dialog/functions";
import SheetProvider from "../sheet-provider";
import { Toast } from "../toast";
@@ -46,7 +47,6 @@ import Input from "../ui/input";
import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
import { LoginSteps, useLogin } from "./use-login";
import BaseDialog from "../dialog/base-dialog";
function getObfuscatedEmail(email) {
if (!email) return "";
@@ -69,6 +69,9 @@ export const SessionExpired = () => {
eSendEvent(eUserLoggedIn, true);
setVisible(false);
setFocused(false);
useUserStore.setState({
disableAppLockRequests: false
});
},
true
);
@@ -84,6 +87,9 @@ export const SessionExpired = () => {
MMKV.clearStore();
clearAllStores();
setVisible(false);
useUserStore.setState({
disableAppLockRequests: false
});
} catch (e) {
ToastEvent.show({
heading: e.message,
@@ -127,6 +133,9 @@ export const SessionExpired = () => {
email.current = user.email;
setFocused(false);
setVisible(true);
useUserStore.setState({
disableAppLockRequests: true
});
}
}, [email]);
@@ -142,6 +151,9 @@ export const SessionExpired = () => {
await sleep(300);
passwordInputRef.current?.focus();
setFocused(true);
useUserStore.setState({
disableAppLockRequests: true
});
}}
enableSheetKeyboardHandler={true}
visible={true}

View File

@@ -40,7 +40,10 @@ import { Button } from "../ui/button";
export const Dialog = ({ context = "global" }) => {
const { colors } = useThemeColors();
const [visible, setVisible] = useState(false);
const [inputValue, setInputValue] = useState(null);
const [checked, setChecked] = useState(false);
const values = useRef({
inputValue: undefined
});
const inputRef = useRef();
const [dialogInfo, setDialogInfo] = useState({
title: "",
@@ -76,7 +79,8 @@ export const Dialog = ({ context = "global" }) => {
if (dialogInfo.positivePress) {
inputRef.current?.blur();
let result = await dialogInfo.positivePress(
inputValue || dialogInfo.defaultValue
values.current.inputValue || dialogInfo.defaultValue,
checked
);
if (result === false) {
return;
@@ -91,14 +95,16 @@ export const Dialog = ({ context = "global" }) => {
if (!data.context) data.context = "global";
if (data.context !== context) return;
setDialogInfo(data);
setChecked(false);
values.current.inputValue = data.defaultValue;
setVisible(true);
setInputValue(data.defaultValue);
},
[context]
);
const hide = () => {
setInputValue(null);
setChecked(false);
values.current.inputValue = undefined;
setVisible(false);
};
@@ -106,7 +112,6 @@ export const Dialog = ({ context = "global" }) => {
if (dialogInfo.onClose) {
await dialogInfo.onClose();
}
hide();
};
@@ -159,7 +164,7 @@ export const Dialog = ({ context = "global" }) => {
fwdRef={inputRef}
autoCapitalize="none"
onChangeText={(value) => {
setInputValue(value);
values.current.inputValue = value;
}}
testID="input-value"
secureTextEntry={dialogInfo.secureTextEntry}
@@ -176,10 +181,10 @@ export const Dialog = ({ context = "global" }) => {
<>
<Button
onPress={() => {
setInputValue(!inputValue);
setChecked(!checked);
}}
icon={
inputValue
checked
? "check-circle-outline"
: "checkbox-blank-circle-outline"
}
@@ -187,9 +192,10 @@ export const Dialog = ({ context = "global" }) => {
justifyContent: "flex-start"
}}
height={35}
iconSize={20}
width="100%"
title={dialogInfo.check.info}
type={inputValue ? dialogInfo.check.type : "gray"}
type={checked ? dialogInfo.check.type : "gray"}
/>
</>
) : null}

View File

@@ -101,7 +101,7 @@ export const SectionHeader = React.memo(
alignItems: "center"
}}
>
{index === 0 && (
{index === 0 ? (
<>
<Button
onPress={() => {
@@ -109,7 +109,6 @@ export const SectionHeader = React.memo(
component: <Sort screen={screen} type={type} />
});
}}
hidden={screen === "Reminders"}
tooltipText="Change sorting of items in list"
fwdRef={sortRef}
title={groupBy}
@@ -160,7 +159,7 @@ export const SectionHeader = React.memo(
size={SIZE.lg - 2}
/>
</>
)}
) : null}
</View>
</View>
);

View File

@@ -101,6 +101,7 @@ const SheetProvider = ({ context = "global" }) => {
setVisible(false);
setData(null);
}}
keyboardHandlerDisabled={data?.keyboardHandlerDisabled}
bottomPadding={!data.noBottomPadding}
enableGesturesInScrollView={
typeof data.enableGesturesInScrollView === "undefined"

View File

@@ -43,6 +43,7 @@ import Paragraph from "../../ui/typography/paragraph";
import { eSendEvent } from "../../../services/event-manager";
import { eCloseSheet } from "../../../utils/events";
import { requestInAppReview } from "../../../services/app-review";
import { Dialog } from "../../dialog";
const ExportNotesSheet = ({ notes, update }) => {
const { colors } = useThemeColors();
@@ -157,6 +158,8 @@ const ExportNotesSheet = ({ notes, update }) => {
</>
) : null}
<Dialog context="export-notes" />
<View style={styles.buttonContainer}>
{!exporting && !complete ? (
actions.map((item) => (
@@ -346,7 +349,8 @@ ExportNotesSheet.present = (notes, allNotes) => {
notes={allNotes ? db.notes.all : notes}
update={update}
/>
)
),
keyboardHandlerDisabled: true
});
};

View File

@@ -37,7 +37,7 @@ import Heading from "../../ui/typography/heading";
import Paragraph from "../../ui/typography/paragraph";
import { requestInAppReview } from "../../../services/app-review";
const PublishNoteSheet = ({ note: item, update }) => {
const PublishNoteSheet = ({ note: item }) => {
const { colors } = useThemeColors();
const actionSheetRef = useRef();
@@ -48,8 +48,7 @@ const PublishNoteSheet = ({ note: item, update }) => {
const [note, setNote] = useState(item);
const [publishing, setPublishing] = useState(false);
const publishUrl =
note &&
`https://monograph.notesnook.com/${db?.monographs.monograph(note?.id)}`;
note && `https://monogr.ph/${db?.monographs.monograph(note?.id)}`;
const isPublished = note && db?.monographs.isPublished(note?.id);
const pwdInput = useRef();
const passwordValue = useRef();

View File

@@ -17,17 +17,19 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { getFormattedDate } from "@notesnook/common";
import { EVENTS } from "@notesnook/core/dist/common";
import { useThemeColors } from "@notesnook/theme";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { ActivityIndicator, Platform, View } from "react-native";
import { FlatList } from "react-native-actions-sheet";
import RNFetchBlob from "react-native-blob-util";
import DocumentPicker, {
DocumentPickerResponse
} from "react-native-document-picker";
import DocumentPicker from "react-native-document-picker";
import * as ScopedStorage from "react-native-scoped-storage";
import { unzip } from "react-native-zip-archive";
import { db } from "../../../common/database";
import storage from "../../../common/database/storage";
import { cacheDir, copyFileAsync } from "../../../common/filesystem/utils";
import {
ToastEvent,
eSubscribeEvent,
@@ -35,7 +37,6 @@ import {
} from "../../../services/event-manager";
import SettingsService from "../../../services/settings";
import { initialize } from "../../../stores";
import { useThemeColors } from "@notesnook/theme";
import { eCloseRestoreDialog, eOpenRestoreDialog } from "../../../utils/events";
import { SIZE } from "../../../utils/size";
import { Dialog } from "../../dialog";
@@ -46,9 +47,6 @@ import { Button } from "../../ui/button";
import Seperator from "../../ui/seperator";
import SheetWrapper from "../../ui/sheet";
import Paragraph from "../../ui/typography/paragraph";
import { getFormattedDate } from "@notesnook/common";
import { unzip } from "react-native-zip-archive";
import { cacheDir, copyFileAsync } from "../../../common/filesystem/utils";
const RestoreDataSheet = () => {
const [visible, setVisible] = useState(false);
@@ -184,7 +182,7 @@ const RestoreDataComponent = ({ close, setRestoring, restoring }) => {
title: "Encrypted backup",
input: true,
inputPlaceholder: "Password",
paragraph: "Please enter password of this backup file to restore it",
paragraph: "Please enter password of this backup file",
positiveText: "Restore",
secureTextEntry: true,
onClose: () => {
@@ -192,10 +190,17 @@ const RestoreDataComponent = ({ close, setRestoring, restoring }) => {
resolve(undefined);
},
negativeText: "Cancel",
positivePress: async (password) => {
resolve(password);
positivePress: async (password, isEncryptionKey) => {
resolve({
value: password,
isEncryptionKey
});
resolved = true;
return true;
},
check: {
info: "Use encryption key",
type: "transparent"
}
});
});
@@ -235,8 +240,8 @@ const RestoreDataComponent = ({ close, setRestoring, restoring }) => {
}
};
const restoreBackup = async (backup, password) => {
await db.backup.import(backup, password);
const restoreBackup = async (backup, password, key) => {
await db.backup.import(backup, password, key);
await db.initCollections();
initialize();
ToastEvent.show({
@@ -279,6 +284,7 @@ const RestoreDataComponent = ({ close, setRestoring, restoring }) => {
}
let password;
let key;
console.log(`Found ${backupFiles?.length} files to restore from backup`);
for (const path of backupFiles) {
@@ -289,10 +295,16 @@ const RestoreDataComponent = ({ close, setRestoring, restoring }) => {
if (parsed.encrypted && !password) {
console.log("Backup is encrypted...", "requesting password");
password = await withPassword();
if (!password) throw new Error("Failed to decrypt backup");
const { value, isEncryptionKey } = await withPassword();
if (isEncryptionKey) {
key = value;
} else {
password = value;
}
if (!password && !key) throw new Error("Failed to decrypt backup");
}
await db.backup.import(parsed, password);
await db.backup.import(parsed, password, key);
console.log("Imported", path);
}
// Remove files from cache
@@ -323,10 +335,19 @@ const RestoreDataComponent = ({ close, setRestoring, restoring }) => {
async function restoreFromNNBackup(backup) {
try {
if (backup.data.iv && backup.data.salt) {
const password = await withPassword();
if (password) {
const { value, isEncryptionKey } = await withPassword();
let key;
let password;
if (isEncryptionKey) {
key = value;
} else {
password = value;
}
if (key || password) {
try {
await restoreBackup(backup, password);
await restoreBackup(backup, password, key);
close();
setRestoring(false);
} catch (e) {

View File

@@ -88,10 +88,14 @@ const Sort = ({ type, screen }) => {
? groupOptions.groupBy === "abc" ||
groupOptions.sortBy === "title"
? "A - Z"
: groupOptions.sortBy === "dueDate"
? "Earliest first"
: "Old - New"
: groupOptions.groupBy === "abc" ||
groupOptions.sortBy === "title"
? "Z - A"
: groupOptions.sortBy === "dueDate"
? "Latest first"
: "New - Old"
}
icon={
@@ -142,6 +146,7 @@ const Sort = ({ type, screen }) => {
/>
) : (
Object.keys(SORT).map((item) =>
(item === "dueDate" && screen !== "Reminders") ||
(item === "title" && groupOptions.groupBy !== "none") ||
((screen !== "Tags" || screen !== "Reminders") &&
item === "dateModified") ||

View File

@@ -37,11 +37,11 @@ const SheetWrapper = ({
onOpen,
closeOnTouchBackdrop = true,
onHasReachedTop,
keyboardMode,
overlay,
overlayOpacity = 0.3,
enableGesturesInScrollView = false,
bottomPadding = true
bottomPadding = true,
keyboardHandlerDisabled
}) => {
const localRef = useRef(null);
const { colors } = useThemeColors("sheet");
@@ -121,8 +121,9 @@ const SheetWrapper = ({
initialOffsetFromBottom={1}
onPositionChanged={onHasReachedTop}
closeOnTouchBackdrop={closeOnTouchBackdrop}
keyboardMode={keyboardMode}
keyboardHandlerEnabled={sheetKeyboardHandler}
keyboardHandlerEnabled={
keyboardHandlerDisabled ? false : sheetKeyboardHandler
}
closeOnPressBack={closeOnTouchBackdrop}
indicatorColor={colors.secondary.background}
onOpen={_onOpen}

View File

@@ -550,15 +550,6 @@ export const useActions = ({ close = () => null, item }) => {
}
async function exportNote() {
if (item.locked) {
ToastEvent.show({
heading: "Note is locked",
type: "error",
message: "Locked notes cannot be exported",
context: "local"
});
return;
}
ExportNotesSheet.present([item]);
}

View File

@@ -623,15 +623,20 @@ export const useAppEvents = () => {
}, [loading, onUserUpdated]);
const initializeDatabase = useCallback(async () => {
if (!db.isInitialized) {
RNBootSplash.hide({ fade: true });
DatabaseLogger.info("Initializing database");
await db.init();
try {
if (!db.isInitialized) {
RNBootSplash.hide({ fade: true });
DatabaseLogger.info("Initializing database");
await db.init();
}
if (IsDatabaseMigrationRequired()) return;
initialize();
setLoading(false);
Walkthrough.init();
} catch (e) {
DatabaseLogger.error(e);
ToastEvent.error(e, "Error initializing database", "global");
}
if (IsDatabaseMigrationRequired()) return;
initialize();
setLoading(false);
Walkthrough.init();
}, [IsDatabaseMigrationRequired]);
useEffect(() => {

View File

@@ -31,7 +31,8 @@
"url": "^0.11.0",
"validator": "^13.5.2",
"zustand": "^3.6.0",
"katex": "0.16.2"
"katex": "0.16.2",
"@readme/data-urls": "3.0.0"
},
"sideEffects": false
}

View File

@@ -45,6 +45,7 @@ import { EditorProps, useEditorType } from "./tiptap/types";
import { useEditor } from "./tiptap/use-editor";
import { useEditorEvents } from "./tiptap/use-editor-events";
import { editorController } from "./tiptap/utils";
import { useThemeColors } from "@notesnook/theme";
const style: ViewStyle = {
height: "100%",
@@ -93,35 +94,6 @@ const Editor = React.memo(
get: () => editor
}));
const onMediaDownloaded = useCallback(
({
hash,
groupId,
src,
attachmentType
}: {
hash: string;
groupId: string;
src: string;
attachmentType: string;
}) => {
if (groupId !== editor.note.current?.id) return;
editorController.current.markImageLoaded(hash);
if (attachmentType === "webclip") {
editor.commands.updateWebclip({
hash: hash,
src: src
});
} else {
editor.commands.updateImage({
hash: hash,
dataurl: src
});
}
},
[editor.commands, editor.note]
);
const onError = useCallback(() => {
renderKey.current =
renderKey.current === `editor-0` ? `editor-1` : `editor-0`;
@@ -130,16 +102,11 @@ const Editor = React.memo(
}, [editor]);
useEffect(() => {
const sub = [
eSubscribeEvent("webview_reset", onError),
EV.subscribe(EVENTS.mediaAttachmentDownloaded, onMediaDownloaded)
];
const sub = [eSubscribeEvent("webview_reset", onError)];
return () => {
sub.forEach((s) => s.unsubscribe());
EV.unsubscribe(EVENTS.mediaAttachmentDownloaded, onMediaDownloaded);
};
}, [onError, onMediaDownloaded]);
}, [onError]);
useLayoutEffect(() => {
setImmediate(() => {
@@ -210,6 +177,7 @@ export default Editor;
const ReadonlyButton = ({ editor }: { editor: useEditorType }) => {
const readonly = useEditorStore((state) => state.readonly);
const keyboard = useKeyboard();
const { colors } = useThemeColors();
const onPress = async () => {
if (editor.note.current) {
@@ -225,7 +193,7 @@ const ReadonlyButton = ({ editor }: { editor: useEditorType }) => {
name="pencil-lock"
type="grayBg"
onPress={onPress}
color="accent"
color={colors.primary.accent}
customStyle={{
position: "absolute",
bottom: 60,

View File

@@ -17,10 +17,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import type {
Attachment,
AttachmentProgress
} from "@notesnook/editor/dist/extensions/attachment/index";
import type { Attachment } from "@notesnook/editor/dist/extensions/attachment/index";
import type { ImageAttributes } from "@notesnook/editor/dist/extensions/image/index";
import { createRef, RefObject } from "react";
import { Platform } from "react-native";
@@ -203,11 +200,16 @@ typeof globalThis.statusBar !== "undefined" && statusBar.current.set({date:"",sa
);
};
setAttachmentProgress = async (attachmentProgress: AttachmentProgress) => {
setAttachmentProgress = async (attachmentProgress: Partial<Attachment>) => {
await this.doAsync(
`editor && editor.commands.setAttachmentProgress(${JSON.stringify(
`editor && editor.commands.updateAttachment(${JSON.stringify(
attachmentProgress
)})`
)}, {
preventUpdate: true,
query: (attachment) => {
return attachment.hash === "${attachmentProgress.hash}";
}
})`
);
};

View File

@@ -36,5 +36,6 @@ export const EventTypes = {
contentchange: "editor-event:content-change",
reminders: "editor-event:reminders",
previewAttachment: "editor-event:preview-attachment",
copyToClipboard: "editor-events:copy-to-clipboard"
copyToClipboard: "editor-events:copy-to-clipboard",
getAttachmentData: "editor-events:get-attachment-data"
};

View File

@@ -53,6 +53,7 @@ export type Settings = {
dateFormat: string;
timeFormat: string;
fontScale: number;
markdownShortcuts: boolean;
};
export type EditorProps = {
@@ -97,6 +98,7 @@ export type SavePayload = {
type?: Content["type"];
sessionId?: string | null;
sessionHistoryId?: number;
ignoreEdit: boolean;
};
export type AppState = {

View File

@@ -66,6 +66,7 @@ import { EditorMessage, EditorProps, useEditorType } from "./types";
import { EditorEvents, editorState } from "./utils";
import { useNoteStore } from "../../../stores/use-notes-store";
import SettingsService from "../../../services/settings";
import downloadAttachment from "../../../common/filesystem/download-attachment";
const publishNote = async (editor: useEditorType) => {
const user = useUserStore.getState().user;
@@ -127,6 +128,8 @@ const showActionsheet = async (editor: useEditorType) => {
}
};
type ContentMessage = { html: string; ignoreEdit: boolean };
export const useEditorEvents = (
editor: useEditorType,
{ readonly: editorPropReadonly, noHeader, noToolbar }: Partial<EditorProps>
@@ -154,6 +157,9 @@ export const useEditorEvents = (
const defaultFontFamily = useSettingStore(
(state) => state.settings.defaultFontFamily
);
const markdownShortcuts = useSettingStore(
(state) => state.settings.markdownShortcuts
);
const tools = useDragState((state) => state.data);
@@ -199,7 +205,8 @@ export const useEditorEvents = (
fontFamily: SettingsService.get().defaultFontFamily,
dateFormat: db.settings?.getDateFormat(),
timeFormat: db.settings?.getTimeFormat(),
fontScale
fontScale,
markdownShortcuts
});
}, [
fullscreen,
@@ -219,7 +226,8 @@ export const useEditorEvents = (
dateFormat,
timeFormat,
loading,
fontScale
fontScale,
markdownShortcuts
]);
const onBackPress = useCallback(async () => {
@@ -330,14 +338,16 @@ export const useEditorEvents = (
if (editorMessage.type === EventTypes.content) {
editor.saveContent({
type: editorMessage.type,
content: editorMessage.value as string,
content: (editorMessage.value as ContentMessage).html,
ignoreEdit: (editorMessage.value as ContentMessage).ignoreEdit,
forSessionId: editorMessage.sessionId
});
} else if (editorMessage.type === EventTypes.title) {
editor.saveContent({
type: editorMessage.type,
title: editorMessage.value as string,
forSessionId: editorMessage.sessionId
forSessionId: editorMessage.sessionId,
ignoreEdit: false
});
}
@@ -416,6 +426,44 @@ export const useEditorEvents = (
break;
}
case EventTypes.getAttachmentData: {
const attachment = (editorMessage.value as any)
.attachment as Attachment;
console.log(
"Getting attachment data:",
attachment.hash,
attachment.type
);
downloadAttachment(attachment.hash, true, {
base64: attachment.type === "image",
text: attachment.type === "web-clip",
silent: true,
groupId: editor.note.current?.id,
cache: true
} as any)
.then((data: any) => {
console.log(
"Got attachment data:",
!!data,
(editorMessage.value as any).resolverId
);
editor.postMessage(EditorEvents.attachmentData, {
resolverId: (editorMessage.value as any).resolverId,
data
});
})
.catch(() => {
console.log("Error downloading attachment data");
editor.postMessage(EditorEvents.attachmentData, {
resolverId: (editorMessage.value as any).resolverId,
data: undefined
});
});
break;
}
case EventTypes.pro:
if (editor.state.current?.isFocused) {
editor.state.current.isFocused = true;

View File

@@ -78,7 +78,6 @@ export const useEditor = (
const saveCount = useRef(0);
const lastContentChangeTime = useRef<number>(0);
const lock = useRef(false);
const loadedImages = useRef<{ [name: string]: boolean }>({});
const lockedSessionId = useRef<string>();
const loadingState = useRef<string>();
@@ -129,12 +128,9 @@ export const useEditor = (
const reset = useCallback(
async (resetState = true, resetContent = true) => {
currentNote.current?.id &&
db.fs?.cancel(currentNote.current.id, "download");
currentNote.current?.id && db.fs?.cancel(currentNote.current.id);
currentNote.current = null;
loadedImages.current = {};
currentContent.current = null;
clearTimeout(timers.current["loading-images"]);
sessionHistoryId.current = undefined;
saveCount.current = 0;
loadingState.current = undefined;
@@ -166,7 +162,8 @@ export const useEditor = (
data,
type,
sessionId: currentSessionId,
sessionHistoryId: currentSessionHistoryId
sessionHistoryId: currentSessionHistoryId,
ignoreEdit
}: SavePayload) => {
if (
readonly ||
@@ -198,6 +195,12 @@ export const useEditor = (
};
noteData.title = title;
if (ignoreEdit) {
console.log("Ignoring edits...");
noteData.dateEdited = note?.dateEdited;
}
if (data) {
noteData.content = {
data: data,
@@ -287,58 +290,6 @@ export const useEditor = (
}
}, []);
const getMediaToLoad = (previousContent?: string) => {
if (!currentNote.current?.id) return [];
const previousAttachments =
previousContent?.matchAll(/data-hash="(.+?)"/gm) || [];
const attachments =
currentContent.current?.data?.matchAll(/data-hash="(.+?)"/gm) || [];
const media: string[] = [];
const oldMatches = Array.from(previousAttachments).map((match) => match[1]);
const matches = Array.from(attachments).map((match) => match[1]);
for (let i = 0; i < matches.length; i++) {
const currentHash = matches[i];
const oldHash = oldMatches[i];
if (currentHash !== oldHash) {
media.push(currentHash);
loadedImages.current[currentHash] = false;
}
}
return media;
};
const markImageLoaded = (hash: string) => {
const attachment = loadedImages.current[hash];
if (typeof attachment === "boolean") {
loadedImages.current[hash] = true;
}
};
const loadImages = useCallback((previousContent?: string) => {
if (!currentNote.current?.id) return;
const timerId = "loading-images";
clearTimeout(timers.current[timerId]);
timers.current[timerId] = setTimeout(() => {
if (!currentNote.current?.id) return;
if (currentNote.current?.content?.isPreview) {
db.content?.downloadMedia(
currentNote.current?.id,
currentNote.current.content,
true
);
} else {
const media = getMediaToLoad(previousContent);
if (media.length > 0) {
db.attachments?.downloadMedia(currentNote.current?.id, media);
}
}
}, 1000);
}, []);
const loadNote = useCallback(
async (
item: Omit<NoteType, "type"> & {
@@ -408,13 +359,13 @@ export const useEditor = (
await commands.setStatus(getFormattedDate(item.dateEdited), "Saved");
await postMessage(EditorEvents.title, item.title);
loadingState.current = currentContent.current?.data;
if (currentContent.current?.data) {
await postMessage(
EditorEvents.html,
currentContent.current?.data,
10000
);
}
await postMessage(
EditorEvents.html,
currentContent.current?.data || "",
10000
);
loadingState.current = undefined;
useEditorStore.getState().setReadonly(item.readonly);
await commands.setTags(currentNote.current);
@@ -425,18 +376,9 @@ export const useEditor = (
}
}, 300);
overlay(false);
loadImages();
}
},
[
commands,
isDefaultEditor,
loadContent,
loadImages,
overlay,
postMessage,
reset
]
[commands, isDefaultEditor, loadContent, overlay, postMessage, reset]
);
const lockNoteWithVault = useCallback((note: NoteType) => {
@@ -466,8 +408,6 @@ export const useEditor = (
lock.current = true;
const previousContent = currentContent.current?.data;
if (data.type === "tiptap") {
if (!currentNote.current.locked && isContentEncrypted) {
lockNoteWithVault(note);
@@ -500,18 +440,8 @@ export const useEditor = (
}
lock.current = false;
if (data.type === "tiptap") {
loadImages(previousContent);
db.eventManager.subscribe(
EVENTS.syncCompleted,
() => {
loadImages(previousContent);
},
true
);
}
},
[loadImages, lockNoteWithVault, postMessage, commands]
[lockNoteWithVault, postMessage, commands]
);
useEffect(() => {
@@ -531,12 +461,14 @@ export const useEditor = (
title,
content,
type,
forSessionId
forSessionId,
ignoreEdit
}: {
title?: string;
content?: string;
type: string;
forSessionId: string;
ignoreEdit: boolean;
}) => {
if (lock.current || lockedSessionId.current === forSessionId) return;
lastContentChangeTime.current = Date.now();
@@ -567,7 +499,8 @@ export const useEditor = (
type: "tiptap",
sessionId: forSessionId,
id: noteId,
sessionHistoryId: sessionHistoryId.current
sessionHistoryId: sessionHistoryId.current,
ignoreEdit
};
withTimer(
noteId || "newnote",
@@ -585,7 +518,7 @@ export const useEditor = (
}
saveNote(params);
},
150
ignoreEdit ? 0 : 150
);
},
[withTimer, onChange, saveNote]
@@ -689,7 +622,6 @@ export const useEditor = (
saveContent,
onContentChanged,
editorId: editorId,
markImageLoaded,
overlay,
postMessage
};

View File

@@ -50,7 +50,8 @@ export const EditorEvents: { [name: string]: string } = {
titleplaceholder: "native:titleplaceholder",
logger: "native:logger",
status: "native:status",
keyboardShown: "native:keyboardShown"
keyboardShown: "native:keyboardShown",
attachmentData: "native:attachment-data"
};
export function randId(prefix: string) {

View File

@@ -115,7 +115,7 @@ export const EditorWrapper = ({ width }) => {
style={{ height: 1, padding: 0, width: 1, position: "absolute" }}
blurOnSubmit={false}
/>
<ProgressBar />
{/* <ProgressBar /> */}
<Editor key="editor" withController={true} />
</KeyboardAvoidingViewIOS>
)}

View File

@@ -69,10 +69,10 @@ export const TrashIntervalPicker = createSettingsPicker({
db.settings.setTrashCleanupInterval(item);
},
formatValue: (item) => {
return item === -1 ? "Never" : item + " days";
return item === -1 ? "Never" : item === 1 ? "Daily" : item + " days";
},
getItemKey: (item) => item.toString(),
options: [-1, 7, 30, 365],
options: [-1, 1, 7, 30, 365],
compareValue: (current, item) => current === item,
premium: true
});

View File

@@ -584,6 +584,13 @@ export const settingsGroups: SettingSection[] = [
component: "title-format",
description: "Customize the formatting for new note title",
type: "component"
},
{
id: "toggle-markdown",
name: "Markdown shortcuts",
property: "markdownShortcuts",
description: "Toggle markdown in the editor",
type: "switch"
}
]
}

View File

@@ -65,7 +65,11 @@ const PLACEHOLDER_DATA = (trashCleanupInterval = 7) => ({
paragraph:
trashCleanupInterval === -1
? "Set automatic trash cleanup interval from Settings > Behaviour > Clean trash interval."
: `Items in the trash will be permanently deleted after after ${trashCleanupInterval} days.`,
: `Trash gets automatically cleaned up ${
trashCleanupInterval === 1
? "daily."
: `after ${trashCleanupInterval} days.`
}`,
button: null,
loading: "Loading trash items"
});

View File

@@ -213,10 +213,12 @@ async function run(progress, context) {
RNFetchBlob.fs.unlink(zipSourceFolder).catch(console.log);
updateNextBackupTime();
let showBackupCompleteSheet = SettingsService.get().showBackupCompleteSheet;
let showBackupCompleteSheet =
progress && SettingsService.get().showBackupCompleteSheet;
if (context) return path;
await sleep(300);
if (showBackupCompleteSheet) {
presentBackupCompleteSheet(backupFilePath);
} else {
@@ -233,7 +235,7 @@ async function run(progress, context) {
return path;
} catch (e) {
await sleep(300);
eSendEvent(eCloseSheet);
progress && eSendEvent(eCloseSheet);
ToastEvent.error(e, "Backup failed!");
return null;
}

View File

@@ -18,17 +18,19 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { decode, EntityLevel } from "entities";
import { zipSync } from "fflate";
import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import RNHTMLtoPDF from "react-native-html-to-pdf-lite";
import * as ScopedStorage from "react-native-scoped-storage";
import RNFetchBlob from "react-native-blob-util";
import { zip } from "react-native-zip-archive";
import { DatabaseLogger, db } from "../common/database/index";
import Storage from "../common/database/storage";
import { convertNoteToText } from "../utils/note-to-text";
import { sleep } from "../utils/time";
import { sanitizeFilename } from "@notesnook/common";
import { presentDialog } from "../components/dialog/functions";
import { useSettingStore } from "../stores/use-setting-store";
import BiometicService from "./biometrics";
import { ToastEvent } from "./event-manager";
const MIMETypes = {
txt: "text/plain",
@@ -99,8 +101,8 @@ async function save(path, data, fileName, extension) {
return uri || path;
}
async function makeHtml(note) {
let html = await db.notes.note(note.id).export("html");
async function makeHtml(note, content) {
let html = await db.notes.note(note.id).export("html", content);
html = decode(html, {
level: EntityLevel.HTML
});
@@ -111,23 +113,25 @@ async function makeHtml(note) {
*
* @param {"txt" | "pdf" | "md" | "html" | "md-frontmatter"} type
*/
async function exportAs(type, note, bulk) {
async function exportAs(type, note, bulk, content) {
let data;
switch (type) {
case "html":
{
data = await makeHtml(note);
data = await makeHtml(note, content);
}
break;
case "md":
data = await db.notes.note(note.id).export("md");
data = await db.notes.note(note.id).export("md", content);
break;
case "md-frontmatter":
data = await db.notes.note(note.id).export("md-frontmatter");
data = await db.notes
.note(note.id)
.export("md-frontmatter", content?.data);
break;
case "pdf":
{
let html = await makeHtml(note);
let html = await makeHtml(note, content);
let fileName = sanitizeFilename(note.title + Date.now(), {
replacement: "_"
});
@@ -153,21 +157,84 @@ async function exportAs(type, note, bulk) {
}
break;
case "txt":
data = await convertNoteToText(note);
{
data = await db.notes?.note(note.id).export("txt", content);
}
break;
}
return data;
}
async function unlockVault() {
let biometry = await BiometicService.isBiometryAvailable();
let fingerprint = await BiometicService.hasInternetCredentials("nn_vault");
if (biometry && fingerprint) {
let credentials = await BiometicService.getCredentials(
"Unlock vault",
"Unlock vault to export locked notes"
);
if (credentials) {
return db.vault.unlock(credentials.password);
}
}
useSettingStore.getState().setSheetKeyboardHandler(false);
return new Promise((resolve) => {
setImmediate(() => {
presentDialog({
context: "export-notes",
input: true,
secureTextEntry: true,
positiveText: "Unlock",
title: "Unlock vault",
paragraph: "Some exported notes are locked, Unlock to export them",
inputPlaceholder: "Enter password",
positivePress: async (value) => {
const unlocked = await db.vault.unlock(value);
if (!unlocked) {
ToastEvent.show({
heading: "Invalid password",
message: "Please enter a valid password",
type: "error",
context: "local"
});
return false;
}
resolve(unlocked);
useSettingStore.getState().setSheetKeyboardHandler(true);
return true;
},
onClose: () => {
resolve(false);
useSettingStore.getState().setSheetKeyboardHandler(true);
}
});
});
});
}
/**
*
* @param {"txt" | "pdf" | "md" | "html" | "md-frontmatter"} type
*/
async function exportNote(note, type) {
let content;
if (note.locked) {
try {
let unlocked = await unlockVault();
if (!unlocked) return null;
const unlockedNote = await db.vault.open(note.id);
content = unlockedNote.content;
} catch (e) {
DatabaseLogger.error(e);
}
}
let path = await getPath(FolderNames[type]);
if (!path) return;
let result = await exportAs(type, note);
let result = await exportAs(type, note, false, content);
if (!result) return null;
let fileName = sanitizeFilename(note.title + Date.now(), {
replacement: "_"
@@ -195,11 +262,6 @@ function copyFileAsync(source, dest) {
});
}
function zipsync(results) {
let data = zipSync(results);
return Buffer.from(data.buffer).toString("base64");
}
function getUniqueFileName(fileName, results) {
const chunks = fileName.split(".");
const ext = chunks.pop();
@@ -221,19 +283,108 @@ async function bulkExport(notes, type, callback) {
let path = await getPath(FolderNames[type]);
if (!path) return;
const exportCacheFolder =
RNFetchBlob.fs.dirs.CacheDir + `/export_${Date.now()}`;
await RNFetchBlob.fs.mkdir(exportCacheFolder).catch((e) => console.log(e));
const mkdir = async (dir) => {
const folder = `${exportCacheFolder}/${dir}`;
if (!(await RNFetchBlob.fs.exists(folder))) {
await RNFetchBlob.fs.mkdir(folder);
}
};
const writeFile = async (path, result) => {
const cacheFilePath = exportCacheFolder + path;
await RNFetchBlob.fs.writeFile(
cacheFilePath,
result,
type === "pdf" ? "base64" : "utf8"
);
};
const results = {};
for (var i = 0; i < notes.length; i++) {
try {
await sleep(1);
let note = notes[i];
if (note.locked) continue;
let result = await exportAs(type, note);
let content;
if (note.locked) {
try {
let unlocked = !db.vault.unlocked ? await unlockVault() : true;
if (!unlocked) {
continue;
}
const unlockedNote = await db.vault.open(note.id);
content = unlockedNote.content;
} catch (e) {
DatabaseLogger.error(e);
continue;
}
}
let result = await exportAs(type, note, true, content);
let fileName = sanitizeFilename(note.title, {
replacement: "_"
});
if (result) {
results[getUniqueFileName(fileName + `.${type}`, results)] =
Buffer.from(result, type === "pdf" ? "base64" : "utf-8");
const notebooks = [
...(db.relations
?.to({ id: note.id, type: "note" }, "notebook")
.map((notebook) => ({
title: notebook.title
})) || []),
...(note.notebooks || []).map((ref) => {
const notebook = db.notebooks?.notebook(ref.id);
const topics = notebook?.topics.all || [];
return {
title: notebook?.title,
topics: ref.topics
.map((topicId) => topics.find((topic) => topic.id === topicId))
.filter(Boolean)
};
})
];
for (const notebook of notebooks) {
results[notebook.title] = results[notebook.title] || {};
await mkdir(notebook.title);
if (notebook.topics && notebook.topics.length) {
for (const topic of notebook.topics) {
results[notebook.title][topic.title] =
results[notebook.title][topic.title] || {};
await mkdir(`${notebook.title}/${topic.title}`);
const exportedNoteName = getUniqueFileName(
fileName + `.${type}`,
results[notebook.title][topic.title]
);
results[notebook.title][topic.title][exportedNoteName] = true;
writeFile(
`/${notebook.title}/${topic.title}/${exportedNoteName}`,
result
);
}
} else {
const exportedNoteName = getUniqueFileName(
fileName + `.${type}`,
results[notebook.title]
);
results[notebook.title][exportedNoteName] = true;
writeFile(`/${notebook.title}/${exportedNoteName}`, result);
}
}
if (!notebooks.length) {
const exportedNoteName = getUniqueFileName(
fileName + `.${type}`,
results
);
results[exportedNoteName] = true;
writeFile(`/${exportedNoteName}`, result);
}
}
callback(`${i + 1}/${notes.length}`);
} catch (e) {
@@ -244,26 +395,24 @@ async function bulkExport(notes, type, callback) {
try {
callback("zipping");
await sleep(1);
const zipped = zipsync(results);
const zipOutputPath =
Platform.OS === "ios"
? path + `/${fileName}`
: RNFetchBlob.fs.dirs.CacheDir + `/${fileName}`;
await zip(exportCacheFolder, zipOutputPath);
callback("saving to disk");
await sleep(1);
if (Platform.OS === "ios") {
RNFetchBlob.fs.writeFile(path + `/${fileName}`, zipped, "base64");
} else {
const templFile = RNFetchBlob.fs.dirs.CacheDir + `/${fileName}`;
await RNFetchBlob.fs.writeFile(templFile, zipped, "base64");
if (Platform.OS === "android") {
const file = await ScopedStorage.createFile(
path,
fileName,
"application/zip"
);
path = file.uri;
await copyFileAsync("file://" + templFile, path);
await RNFetchBlob.fs.unlink(templFile);
await copyFileAsync("file://" + zipOutputPath, path);
await RNFetchBlob.fs.unlink(zipOutputPath);
callback();
}
RNFetchBlob.fs.unlink(exportCacheFolder);
} catch (e) {
DatabaseLogger.error(e);
}

View File

@@ -262,7 +262,7 @@ const onEvent = async ({ type, detail }: Event) => {
if (status.isInternetReachable) {
try {
if (!globalThis["IS_MAIN_APP_RUNNING" as never]) {
await db.sync(false, false);
await db.sync({ type: "send", force: false });
} else {
console.log("main app running, skipping sync");
}
@@ -904,7 +904,7 @@ async function pinNote(id: string) {
const note = db.notes?.note(id as string) as any;
let text = await convertNoteToText(note as any, false);
if (!text) text = "";
let html = text.replace(/\n/g, "<br />");
const html = text.replace(/\n/g, "<br />");
Notifications.displayNotification({
title: note.title,
message: note.headline || text,

View File

@@ -79,7 +79,11 @@ const run = async (
try {
await BackgroundSync.doInBackground(async () => {
try {
await db.sync(full, forced, lastSyncTime);
await db.sync({
type: full ? "full" : "send",
force: forced,
lastSyncTime
});
} catch (e) {
error = e;
}

View File

@@ -68,8 +68,7 @@ export const useAttachmentStore = create<AttachmentStore>((set, get) => ({
if (!progress) return;
editorController.current?.commands.setAttachmentProgress({
hash: hash,
progress: 100,
type: progress[hash]?.type || "download"
progress: 100
});
progress[hash] = null;
set({ progress: { ...progress } });
@@ -80,10 +79,11 @@ export const useAttachmentStore = create<AttachmentStore>((set, get) => ({
progress[hash] = { sent, total, hash, recieved, type };
const progressPercentage =
type === "upload" ? sent / total : recieved / total;
editorController.current?.commands.setAttachmentProgress({
hash: hash,
progress: Math.round(Math.max(progressPercentage * 100, 0)),
type: type
//@ts-ignore
progress: Math.round(Math.max(progressPercentage * 100, 0))
});
set({ progress: { ...progress } });
},

View File

@@ -32,7 +32,10 @@ export const useReminderStore = create<ReminderStore>((set) => ({
reminders: [],
setReminders: () => {
set({
reminders: groupReminders((db.reminders?.all as Reminder[]) || [])
reminders: groupReminders(
(db.reminders?.all as Reminder[]) || [],
db.settings?.getGroupOptions("reminders")
)
});
},
cleareReminders: () => set({ reminders: [] })

View File

@@ -74,6 +74,7 @@ export type Settings = {
colorScheme: "dark" | "light";
lighTheme: ThemeDefinition;
darkTheme: ThemeDefinition;
markdownShortcuts?: boolean;
};
type DimensionsType = {
@@ -154,7 +155,8 @@ export const defaultSettings: SettingStore["settings"] = {
defaultFontSize: 16,
colorScheme: "light",
lighTheme: ThemeLight,
darkTheme: ThemeDark
darkTheme: ThemeDark,
markdownShortcuts: true
};
export const useSettingStore = create<SettingStore>((set, get) => ({

View File

@@ -41,7 +41,8 @@ export const SORT = {
dateModified: "Date modified",
dateEdited: "Date edited",
dateCreated: "Date created",
title: "Title"
title: "Title",
dueDate: "Due date"
};
export const itemSkus = [

View File

@@ -36,7 +36,7 @@ function confirmDeleteAllNotes(items, type, context) {
}?`,
positiveText: "Delete",
negativeText: "Cancel",
positivePress: (value) => {
positivePress: (_inputValue, value) => {
setTimeout(() => {
resolve({ delete: true, deleteNotes: value });
});

View File

@@ -61,7 +61,10 @@ export const getGithubVersion = async () => {
if (!res?.ok) return null;
const data = (await res?.json()) as GithubRelease[];
const versions = data?.filter((tag) => tag.tag_name.endsWith("android"));
const versions = data?.filter(
(tag) =>
tag.tag_name.endsWith("android") && !tag.tag_name.endsWith("beta-android")
);
const latestVersion = versions[0];
const version = latestVersion.tag_name.replace("-android", "");
return {

View File

@@ -21,7 +21,7 @@ import Sodium from "@ammarahmed/react-native-sodium";
import { isImage } from "@notesnook/core/dist/utils/filename";
import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import { db } from "../common/database";
import { DatabaseLogger, db } from "../common/database";
import { IOS_APPGROUPID } from "./constants";
const santizeUri = (uri) => {
@@ -57,6 +57,7 @@ export async function attachFile(uri, hash, type, filename, options) {
return true;
} catch (e) {
if (Platform.OS === "ios") RNFetchBlob.fs.unlink(uri).catch(console.log);
DatabaseLogger.error(e, "Attach file error");
console.log("attach file error: ", e);
return false;
}
@@ -107,26 +108,31 @@ async function createNotes(bundle) {
uri: uri,
type: "cache"
});
await attachFile(uri, hash, file.type, file.name, {
const attached = await attachFile(uri, hash, file.type, file.name, {
type: "cache",
id: id,
appGroupId: IOS_APPGROUPID
});
let content = ``;
if (isImage(file.type)) {
content = `<img data-hash="${hash}" data-mime="${file.type}" data-filename="${file.name}" />`;
} else {
content = `<p><span data-hash="${hash}" data-mime="${file.type}" data-filename="${file.name}" data-size="${file.size}" /></p>`;
if (attached) {
if (isImage(file.type)) {
content = `<img data-hash="${hash}" data-mime="${file.type}" data-filename="${file.name}" />`;
} else {
content = `<p><span data-hash="${hash}" data-mime="${file.type}" data-filename="${file.name}" data-size="${file.size}" /></p>`;
}
const rawContent = await db.content.raw(
db.notes.note(id).data?.contentId
);
await db.notes.add({
id: id,
content: {
type: "tiptap",
data: rawContent?.data ? rawContent?.data + content : content
},
sessionId: sessionId
});
}
const rawContent = await db.content.raw(db.notes.note(id).data?.contentId);
await db.notes.add({
id: id,
content: {
type: "tiptap",
data: rawContent?.data ? rawContent?.data + content : content
},
sessionId: sessionId
});
}
}

View File

@@ -111,7 +111,7 @@ android {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
multiDexEnabled true
versionCode 2074
versionCode 2090
versionName getNpmVersion()
testBuildType System.getProperty('testBuildType', 'debug')
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'

View File

@@ -5,7 +5,7 @@
<!-- Customize your theme here. -->
<item name="android:windowDisablePreview">true</item>
<item name="android:editTextBackground">@drawable/edit_text</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:datePickerDialogTheme">@style/DialogDatePicker.Theme</item>
</style>
@@ -20,6 +20,7 @@
<style name="BootTheme" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@color/bootsplash_background</item>
<item name="windowSplashScreenAnimatedIcon">@mipmap/bootsplash_logo_dark</item>
<item name="android:navigationBarColor">@color/bootsplash_background</item>
<item name="postSplashScreenTheme">@style/AppTheme</item>
</style>
@@ -31,6 +32,7 @@
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:editTextBackground">@drawable/edit_text</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
</style>
<style name="DialogDatePicker.Theme" parent="Theme.AppCompat.Light.Dialog">

View File

@@ -5,7 +5,7 @@
<!-- Customize your theme here. -->
<item name="android:windowDisablePreview">true</item>
<item name="android:editTextBackground">@drawable/edit_text</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:datePickerDialogTheme">@style/DialogDatePicker.Theme</item>
</style>
@@ -20,6 +20,7 @@
<style name="BootTheme" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@color/bootsplash_background</item>
<item name="windowSplashScreenAnimatedIcon">@mipmap/bootsplash_logo</item>
<item name="android:navigationBarColor">@color/bootsplash_background</item>
<item name="postSplashScreenTheme">@style/AppTheme</item>
</style>
@@ -31,6 +32,7 @@
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:editTextBackground">@drawable/edit_text</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
</style>
<style name="DialogDatePicker.Theme" parent="Theme.AppCompat.Light.Dialog">

View File

@@ -10,7 +10,7 @@
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.jvmargs=-Xmx4096m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
@@ -47,4 +47,4 @@ hermesEnabled=true
# v8.android.tools.dir=/home/ammarahm-ed/Repos/notesnook-mobile/node_modules/v8-android-jit-nointl/dist/tools/android
# fdroid
fdroidBuild=false
fdroidBuild=false

View File

@@ -1,3 +1,3 @@
- Bug fixes and performance improvements
- Minor bug fixes
Thank you for using Notesnook!

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>provisioningProfiles</key>
<dict>
<key>org.streetwriters.notesnook</key>
<string>Notesnook App Distribution 2024</string>
<key>org.streetwriters.notesnook.notewidget</key>
<string>Notesnook Widget Distribution 2024</string>
<key>org.streetwriters.notesnook.share</key>
<string>Notesnook Share Distribution 2024</string>
</dict>
</dict>
</plist>

View File

@@ -14,13 +14,13 @@
2D02E4BD1E0B4A84006451C7 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
2D02E4BF1E0B4AB3006451C7 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };
2DCD954D1E0B4F2C00145EB5 /* NotesnookTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* NotesnookTests.m */; };
6510626F27042891009661C3 /* OpenSans-Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 6552012F27019F7700A43C51 /* OpenSans-Regular.ttf */; };
6510627627042895009661C3 /* OpenSans-SemiBold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 6552012E27019F6E00A43C51 /* OpenSans-SemiBold.ttf */; };
6510E6D72877215700DACAA9 /* build.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 6510E6D62877215700DACAA9 /* build.bundle */; };
6515C42F2580AA3000E83E39 /* StoreKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6515C42E2580AA2F00E83E39 /* StoreKit.framework */; };
6517B7C12B6838EB0079FF37 /* OpenSans-Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 6517B7BE2B6838EB0079FF37 /* OpenSans-Regular.ttf */; };
6517B7C22B6838EB0079FF37 /* OpenSans-SemiBold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 6517B7BF2B6838EB0079FF37 /* OpenSans-SemiBold.ttf */; };
6517B7C32B6838EB0079FF37 /* OpenSans-Bold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 6517B7C02B6838EB0079FF37 /* OpenSans-Bold.ttf */; };
6529A13E279BC4C70048D4A8 /* BootSplash.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6529A13D279BC4C70048D4A8 /* BootSplash.storyboard */; };
6593E4A3281C345400492C50 /* AppDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 6593E4A2281C345400492C50 /* AppDelegate.mm */; };
659670B22A2754FD00C5D2AF /* OpenSans-Bold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 659670B12A2754FD00C5D2AF /* OpenSans-Bold.ttf */; };
659BE46725E11A5100E05671 /* notesnook-text.png in Resources */ = {isa = PBXBuildFile; fileRef = 659BE46625E11A5100E05671 /* notesnook-text.png */; };
65AA857925E6DDEC00772A01 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 65AA857825E6DDEC00772A01 /* WidgetKit.framework */; };
65AA857B25E6DDEC00772A01 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 65AA857A25E6DDEC00772A01 /* SwiftUI.framework */; };
@@ -110,12 +110,12 @@
4C4AF691C324D95337F2FB0A /* libPods-Make Note.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Make Note.a"; sourceTree = BUILT_PRODUCTS_DIR; };
6510E6D62877215700DACAA9 /* build.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; name = build.bundle; path = "../../../../packages/editor-mobile/build.bundle"; sourceTree = "<group>"; };
6515C42E2580AA2F00E83E39 /* StoreKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = StoreKit.framework; path = System/Library/Frameworks/StoreKit.framework; sourceTree = SDKROOT; };
6517B7BE2B6838EB0079FF37 /* OpenSans-Regular.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; name = "OpenSans-Regular.ttf"; path = "../../../../packages/editor-mobile/public/fonts/OpenSans-Regular.ttf"; sourceTree = "<group>"; };
6517B7BF2B6838EB0079FF37 /* OpenSans-SemiBold.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; name = "OpenSans-SemiBold.ttf"; path = "../../../../packages/editor-mobile/public/fonts/OpenSans-SemiBold.ttf"; sourceTree = "<group>"; };
6517B7C02B6838EB0079FF37 /* OpenSans-Bold.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; name = "OpenSans-Bold.ttf"; path = "../../../../packages/editor-mobile/public/fonts/OpenSans-Bold.ttf"; sourceTree = "<group>"; };
6529A13D279BC4C70048D4A8 /* BootSplash.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = BootSplash.storyboard; path = Notesnook/BootSplash.storyboard; sourceTree = "<group>"; };
6529D2B0257B4A2900B49BC3 /* NotesnookDebug.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; name = NotesnookDebug.entitlements; path = Notesnook/NotesnookDebug.entitlements; sourceTree = "<group>"; };
6552012E27019F6E00A43C51 /* OpenSans-SemiBold.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; name = "OpenSans-SemiBold.ttf"; path = "../android/app/src/main/assets/fonts/OpenSans-SemiBold.ttf"; sourceTree = "<group>"; };
6552012F27019F7700A43C51 /* OpenSans-Regular.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; name = "OpenSans-Regular.ttf"; path = "../android/app/src/main/assets/fonts/OpenSans-Regular.ttf"; sourceTree = "<group>"; };
6593E4A2281C345400492C50 /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = Notesnook/AppDelegate.mm; sourceTree = "<group>"; };
659670B12A2754FD00C5D2AF /* OpenSans-Bold.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; name = "OpenSans-Bold.ttf"; path = "../android/app/src/main/assets/fonts/OpenSans-Bold.ttf"; sourceTree = "<group>"; };
659BE46625E11A5100E05671 /* notesnook-text.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "notesnook-text.png"; path = "Notesnook/Images.xcassets/notesnook-text.png"; sourceTree = "<group>"; };
65A7F34F255689AD00699170 /* Notesnook.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; name = Notesnook.entitlements; path = Notesnook/Notesnook.entitlements; sourceTree = "<group>"; };
65AA857725E6DDEC00772A01 /* NotesWidgetExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = NotesWidgetExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -293,13 +293,13 @@
83CBB9F61A601CBA00E9B192 = {
isa = PBXGroup;
children = (
6517B7C02B6838EB0079FF37 /* OpenSans-Bold.ttf */,
6517B7BE2B6838EB0079FF37 /* OpenSans-Regular.ttf */,
6517B7BF2B6838EB0079FF37 /* OpenSans-SemiBold.ttf */,
65C400DD2A80B68D00AA3DF5 /* MaterialCommunityIcons.ttf */,
65C149862A61151B005C40F1 /* extension.bundle */,
6510E6D62877215700DACAA9 /* build.bundle */,
65EC5B71272A7EE200FB3748 /* NotesWidgetExtensionDebug.entitlements */,
6552012F27019F7700A43C51 /* OpenSans-Regular.ttf */,
659670B12A2754FD00C5D2AF /* OpenSans-Bold.ttf */,
6552012E27019F6E00A43C51 /* OpenSans-SemiBold.ttf */,
65D145C429DC30470056FE7D /* MaterialCommunityIcons.ttf */,
13B07FAE1A68108700A75B9A /* Notesnook */,
832341AE1AAA6A7D00B99B32 /* Libraries */,
@@ -542,12 +542,12 @@
buildActionMask = 2147483647;
files = (
65C400DE2A80B68D00AA3DF5 /* MaterialCommunityIcons.ttf in Resources */,
6510626F27042891009661C3 /* OpenSans-Regular.ttf in Resources */,
659670B22A2754FD00C5D2AF /* OpenSans-Bold.ttf in Resources */,
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
6517B7C32B6838EB0079FF37 /* OpenSans-Bold.ttf in Resources */,
6517B7C22B6838EB0079FF37 /* OpenSans-SemiBold.ttf in Resources */,
6529A13E279BC4C70048D4A8 /* BootSplash.storyboard in Resources */,
6510E6D72877215700DACAA9 /* build.bundle in Resources */,
6510627627042895009661C3 /* OpenSans-SemiBold.ttf in Resources */,
6517B7C12B6838EB0079FF37 /* OpenSans-Regular.ttf in Resources */,
659BE46725E11A5100E05671 /* notesnook-text.png in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -997,7 +997,7 @@
CODE_SIGN_IDENTITY = "Apple Development";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 2066;
CURRENT_PROJECT_VERSION = 2090;
DEVELOPMENT_TEAM = 53CWBG3QUC;
ENABLE_BITCODE = NO;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64;
@@ -1071,7 +1071,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 2.6.15;
MARKETING_VERSION = 2.6.18;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
@@ -1102,7 +1102,7 @@
CODE_SIGN_IDENTITY = "Apple Development";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 2066;
CURRENT_PROJECT_VERSION = 2090;
DEVELOPMENT_TEAM = "";
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = 53CWBG3QUC;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64;
@@ -1176,7 +1176,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 2.6.15;
MARKETING_VERSION = 2.6.18;
ONLY_ACTIVE_ARCH = NO;
OTHER_LDFLAGS = (
"$(inherited)",
@@ -1335,7 +1335,7 @@
CODE_SIGN_IDENTITY = "Apple Development";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 2066;
CURRENT_PROJECT_VERSION = 2090;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 53CWBG3QUC;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64;
@@ -1347,7 +1347,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 2.6.15;
MARKETING_VERSION = 2.6.18;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = org.streetwriters.notesnook.notewidget;
@@ -1378,7 +1378,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
CODE_SIGN_STYLE = Manual;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 2066;
CURRENT_PROJECT_VERSION = 2090;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = "";
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = 53CWBG3QUC;
@@ -1391,7 +1391,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 2.6.15;
MARKETING_VERSION = 2.6.18;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = org.streetwriters.notesnook.notewidget;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -1421,7 +1421,7 @@
CODE_SIGN_ENTITLEMENTS = "Make Note/Make Note.entitlements";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 2066;
CURRENT_PROJECT_VERSION = 2090;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 53CWBG3QUC;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64;
@@ -1495,7 +1495,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 2.6.15;
MARKETING_VERSION = 2.6.18;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = org.streetwriters.notesnook.share;
@@ -1526,7 +1526,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
CODE_SIGN_STYLE = Manual;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 2066;
CURRENT_PROJECT_VERSION = 2090;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = "";
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = 53CWBG3QUC;
@@ -1601,7 +1601,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 2.6.15;
MARKETING_VERSION = 2.6.18;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = org.streetwriters.notesnook.share;
PRODUCT_NAME = "$(TARGET_NAME)";

View File

@@ -1,12 +1,12 @@
{
"name": "@notesnook/mobile",
"version": "2.6.14",
"version": "2.6.17",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@notesnook/mobile",
"version": "2.6.14",
"version": "2.6.17",
"hasInstallScript": true,
"license": "GPL-3.0-or-later",
"workspaces": [
@@ -57,12 +57,13 @@
"../../packages/core": {
"name": "@notesnook/core",
"version": "7.4.1",
"hasInstallScript": true,
"license": "GPL-3.0-or-later",
"dependencies": {
"@microsoft/signalr": "^7.0.10",
"@microsoft/signalr-protocol-msgpack": "^7.0.10",
"@microsoft/signalr": "^8.0.0",
"@notesnook/logger": "file:../logger",
"@streetwriters/showdown": "^3.0.2-alpha",
"@readme/data-urls": "^3.0.0",
"@streetwriters/showdown": "^3.0.5-alpha",
"async-mutex": "^0.3.2",
"dayjs": "1.11.9",
"entities": "^4.3.1",
@@ -81,7 +82,7 @@
"@types/html-to-text": "^9.0.0",
"@types/katex": "^0.16.1",
"@types/prismjs": "^1.26.0",
"@types/showdown": "^2.0.0",
"@types/streetwriters__showdown": "npm:@types/showdown@^2.0.6",
"@vitest/coverage-v8": "^0.34.1",
"abortcontroller-polyfill": "^1.7.3",
"cross-env": "^7.0.3",
@@ -117,7 +118,7 @@
"@tiptap/extension-font-family": "2.1.12",
"@tiptap/extension-history": "2.1.12",
"@tiptap/extension-horizontal-rule": "2.1.12",
"@tiptap/extension-link": "2.1.12",
"@tiptap/extension-link": "^2.1.16",
"@tiptap/extension-list-keymap": "2.1.12",
"@tiptap/extension-placeholder": "2.1.12",
"@tiptap/extension-subscript": "2.1.12",
@@ -248,6 +249,7 @@
"dependencies": {
"@flyerhq/react-native-link-preview": "^1.6.0",
"@mdi/js": "^6.7.96",
"@readme/data-urls": "3.0.0",
"@streetwriters/showdown": "^3.0.1-alpha.2",
"absolutify": "^0.1.0",
"buffer": "^6.0.3",
@@ -7095,6 +7097,14 @@
"nanoid": "^3.1.23"
}
},
"node_modules/@readme/data-urls": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@readme/data-urls/-/data-urls-3.0.0.tgz",
"integrity": "sha512-b0L7VWqbLZqOSSAFUrxS5ZwUfec35WDsAwwCH481vYnhk0dWO3nvmNVNCbP8CY4cXqwL1W4uCAnhDz+CUmXM3g==",
"engines": {
"node": ">=18"
}
},
"node_modules/@sayem314/react-native-keep-awake": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@sayem314/react-native-keep-awake/-/react-native-keep-awake-1.2.0.tgz",
@@ -26827,15 +26837,15 @@
"@notesnook/core": {
"version": "file:../../packages/core",
"requires": {
"@microsoft/signalr": "^7.0.10",
"@microsoft/signalr-protocol-msgpack": "^7.0.10",
"@microsoft/signalr": "^8.0.0",
"@notesnook/crypto": "file:../crypto",
"@notesnook/logger": "file:../logger",
"@streetwriters/showdown": "^3.0.2-alpha",
"@readme/data-urls": "^3.0.0",
"@streetwriters/showdown": "^3.0.5-alpha",
"@types/html-to-text": "^9.0.0",
"@types/katex": "^0.16.1",
"@types/prismjs": "^1.26.0",
"@types/showdown": "^2.0.0",
"@types/streetwriters__showdown": "npm:@types/showdown@^2.0.6",
"@vitest/coverage-v8": "^0.34.1",
"abortcontroller-polyfill": "^1.7.3",
"async-mutex": "^0.3.2",
@@ -26882,7 +26892,7 @@
"@tiptap/extension-font-family": "2.1.12",
"@tiptap/extension-history": "2.1.12",
"@tiptap/extension-horizontal-rule": "2.1.12",
"@tiptap/extension-link": "2.1.12",
"@tiptap/extension-link": "^2.1.16",
"@tiptap/extension-list-keymap": "2.1.12",
"@tiptap/extension-placeholder": "2.1.12",
"@tiptap/extension-subscript": "2.1.12",
@@ -26971,6 +26981,7 @@
"requires": {
"@flyerhq/react-native-link-preview": "^1.6.0",
"@mdi/js": "^6.7.96",
"@readme/data-urls": "3.0.0",
"@streetwriters/showdown": "^3.0.1-alpha.2",
"absolutify": "^0.1.0",
"buffer": "^6.0.3",
@@ -27640,6 +27651,11 @@
"nanoid": "^3.1.23"
}
},
"@readme/data-urls": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@readme/data-urls/-/data-urls-3.0.0.tgz",
"integrity": "sha512-b0L7VWqbLZqOSSAFUrxS5ZwUfec35WDsAwwCH481vYnhk0dWO3nvmNVNCbP8CY4cXqwL1W4uCAnhDz+CUmXM3g=="
},
"@sayem314/react-native-keep-awake": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@sayem314/react-native-keep-awake/-/react-native-keep-awake-1.2.0.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "@notesnook/mobile",
"version": "2.6.15",
"version": "2.6.18",
"private": true,
"license": "GPL-3.0-or-later",
"workspaces": [
@@ -10,6 +10,7 @@
"scripts": {
"postinstall": "patch-package && node ./scripts/optimize-fonts.mjs",
"run-android": "cd native && react-native run-android --active-arch-only",
"build": "echo 'No build script defined'",
"run-ios": "cd native && react-native run-ios",
"start": "cd native && react-native start",
"repack": "cd native && react-native webpack-start",

View File

@@ -295,7 +295,7 @@ const ShareView = ({ quicknote = false }) => {
try {
if (!globalThis["IS_MAIN_APP_RUNNING"]) {
await db.sync(false, false);
await db.sync({ type: "send", force: false });
} else {
console.log("main app running, skipping sync");
}

View File

@@ -1377,7 +1377,7 @@
},
"../web": {
"name": "@notesnook/web",
"version": "2.6.14",
"version": "2.6.17",
"license": "GPL-3.0-or-later",
"dependencies": {
"@aws-sdk/util-base64-browser": "^3.208.0",

View File

@@ -241,8 +241,8 @@ export class NoteContextMenuModel extends BaseProperties {
);
if (format === "html") {
return content
.replace(/(name="created-on" content=")(.+?)"/, '$1xxx"')
.replace(/(name="last-edited-on" content=")(.+?)"/, '$1xxx"');
.replace(/(name="created-at" content=")(.+?)"/, '$1xxx"')
.replace(/(name="updated-at" content=")(.+?)"/, '$1xxx"');
}
return content;
}

View File

@@ -8,8 +8,8 @@
content="This is Test 1Test 1Test 1Test 1Test 1Test 1Test 1Test 1Test 1Test 1"
/>
<title>Test 1 - Notesnook</title>
<meta name="created-at" content="22-12-2023 11:33 AM" />
<meta name="updated-at" content="22-12-2023 11:33 AM" />
<meta name="created-at" content="xxx" />
<meta name="updated-at" content="xxx" />

View File

@@ -26,20 +26,25 @@ import { consumeReadableStream } from "../src/utils/stream";
import { xxhash64 } from "hash-wasm";
import path from "path";
const CHUNK_SIZE = 512 * 1024;
const CHUNK_SIZE = 512 * 1024 + 17;
test("chunked stream should create equal sized chunks", async (t) => {
const chunks = await consumeReadableStream(
(
Readable.toWeb(
createReadStream(
path.join(__dirname, "..", "__e2e__", "data", "importer-data.zip")
)
createReadStream(path.join(__dirname, "data", "35a4b0a78dbb9260"))
) as ReadableStream<Uint8Array>
).pipeThrough(new ChunkedStream(CHUNK_SIZE))
).pipeThrough(new ChunkedStream(CHUNK_SIZE, "copy"))
);
t.expect(await Promise.all(chunks.map((a) => xxhash64(a)))).toMatchObject([
"6234b76401d9eb97",
"338834da3f6500b2"
"9a3fa91d341b245d",
"c6b5d3ec17f14a5e",
"5163243faf462ce4",
"63aca6b8a7f68476",
"cd9d082fa3015bd3"
]);
t.expect(
await Promise.all(chunks.map((a) => a.byteOffset === 0))
).toMatchObject([true, true, true, true, true]);
});

Binary file not shown.

View File

@@ -1,12 +1,12 @@
{
"name": "@notesnook/web",
"version": "2.6.14",
"version": "2.6.17",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@notesnook/web",
"version": "2.6.14",
"version": "2.6.17",
"license": "GPL-3.0-or-later",
"dependencies": {
"@aws-sdk/util-base64-browser": "^3.208.0",
@@ -210,12 +210,13 @@
"../../packages/core": {
"name": "@notesnook/core",
"version": "7.4.1",
"hasInstallScript": true,
"license": "GPL-3.0-or-later",
"dependencies": {
"@microsoft/signalr": "^7.0.10",
"@microsoft/signalr-protocol-msgpack": "^7.0.10",
"@microsoft/signalr": "^8.0.0",
"@notesnook/logger": "file:../logger",
"@streetwriters/showdown": "^3.0.2-alpha",
"@readme/data-urls": "^3.0.0",
"@streetwriters/showdown": "^3.0.5-alpha",
"async-mutex": "^0.3.2",
"dayjs": "1.11.9",
"entities": "^4.3.1",
@@ -234,7 +235,7 @@
"@types/html-to-text": "^9.0.0",
"@types/katex": "^0.16.1",
"@types/prismjs": "^1.26.0",
"@types/showdown": "^2.0.0",
"@types/streetwriters__showdown": "npm:@types/showdown@^2.0.6",
"@vitest/coverage-v8": "^0.34.1",
"abortcontroller-polyfill": "^1.7.3",
"cross-env": "^7.0.3",
@@ -279,7 +280,7 @@
"@tiptap/extension-font-family": "2.1.12",
"@tiptap/extension-history": "2.1.12",
"@tiptap/extension-horizontal-rule": "2.1.12",
"@tiptap/extension-link": "2.1.12",
"@tiptap/extension-link": "^2.1.16",
"@tiptap/extension-list-keymap": "2.1.12",
"@tiptap/extension-placeholder": "2.1.12",
"@tiptap/extension-subscript": "2.1.12",
@@ -438,7 +439,7 @@
},
"../desktop": {
"name": "@notesnook/desktop",
"version": "2.6.14",
"version": "2.6.17",
"hasInstallScript": true,
"license": "GPL-3.0-or-later",
"dependencies": {

View File

@@ -1,7 +1,7 @@
{
"name": "@notesnook/web",
"description": "Your private note taking space",
"version": "2.6.14",
"version": "2.6.17",
"private": true,
"main": "./src/app.js",
"homepage": "https://notesnook.com/",

View File

@@ -20,11 +20,11 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { lazify } from "../utils/lazify";
import { db } from "./db";
async function download(hash: string) {
async function download(hash: string, groupId?: string) {
const attachment = db.attachments?.attachment(hash);
if (!attachment) return;
const downloadResult = await db.fs?.downloadFile(
attachment.metadata.hash,
groupId || attachment.metadata.hash,
attachment.metadata.hash,
attachment.chunkSize,
attachment.metadata
@@ -61,8 +61,12 @@ type OutputTypeToReturnType = {
export async function downloadAttachment<
TType extends "blob" | "base64" | "text",
TOutputType = OutputTypeToReturnType[TType]
>(hash: string, type: TType): Promise<TOutputType | undefined> {
const response = await download(hash);
>(
hash: string,
type: TType,
groupId?: string
): Promise<TOutputType | undefined> {
const response = await download(hash, groupId);
if (!response) return;
const { attachment, key } = response;

View File

@@ -381,13 +381,6 @@ function getDialogData(type: string) {
subtitle: "Please enter your vault password to continue.",
positiveButtonText: "Unlock"
};
case "ask_backup_password":
return {
title: "Encrypted backup",
subtitle:
"Please enter the password to decrypt and restore this backup.",
positiveButtonText: "Restore"
};
case "change_account_password":
return {
title: "Change account password",
@@ -463,6 +456,17 @@ export function showPasswordDialog(
));
}
export function showBackupPasswordDialog(
validate: (outputs: {
password?: string;
key?: string;
}) => boolean | Promise<boolean>
) {
return showDialog("BackupPasswordDialog", (Dialog, perform) => (
<Dialog onClose={() => perform(false)} validate={validate} />
));
}
export function showRecoveryKeyDialog() {
return showDialog("RecoveryKeyDialog", (Dialog, perform) => (
<Dialog onDone={() => perform(true)} />

View File

@@ -21,6 +21,11 @@ import { TaskManager } from "./task-manager";
import { ExportStream } from "../utils/streams/export-stream";
import { createZipStream } from "../utils/streams/zip-stream";
import { createWriteStream } from "../utils/stream-saver";
import { showToast } from "../utils/toast";
import Vault from "./vault";
import { db } from "./db";
import Note from "@notesnook/core/dist/models/note";
import { sanitizeFilename } from "@notesnook/common";
export async function exportToPDF(
title: string,
@@ -74,12 +79,91 @@ export async function exportNotes(
title: "Exporting notes",
subtitle: "Please wait while your notes are exported.",
action: async (report) => {
await new ExportStream(noteIds, format, undefined, (c, text) =>
report({ total: noteIds.length, current: c, text })
)
.pipeThrough(createZipStream())
.pipeTo(await createWriteStream("notes.zip"));
return true;
try {
let progress = 0;
await createNoteStream(noteIds)
.pipeThrough(
new TransformStream<Note, Note>({
transform(note, controller) {
controller.enqueue(note);
report({
total: noteIds.length,
current: progress++,
text: `Exporting "${note?.title || "Unknown note"}"`
});
}
})
)
.pipeThrough(new ExportStream(format))
.pipeThrough(createZipStream())
.pipeTo(await createWriteStream("notes.zip"));
return true;
} catch (e) {
if (e instanceof Error) showToast("error", e.message);
}
return false;
}
});
}
function createNoteStream(noteIds: string[]) {
let i = 0;
return new ReadableStream<Note>({
start() {},
async pull(controller) {
const noteId = noteIds[i++];
if (!noteId) controller.close();
else controller.enqueue(db.notes?.note(noteId));
},
async cancel(reason) {
throw new Error(reason);
}
});
}
const FORMAT_TO_EXT = {
pdf: "pdf",
md: "md",
txt: "txt",
html: "html",
"md-frontmatter": "md"
} as const;
export async function exportNote(
note: Note,
format: keyof typeof FORMAT_TO_EXT,
disableTemplate = false
) {
if (!db.vault?.unlocked && note.data.locked && !(await Vault.unlockVault())) {
showToast("error", `Skipping note "${note.title}" as it is locked.`);
return false;
}
const rawContent = note.data.contentId
? await db.content?.raw(note.data.contentId)
: undefined;
const content =
rawContent &&
!rawContent.deleted &&
(typeof rawContent.data === "object"
? await db.vault?.decryptContent(rawContent)
: rawContent);
const exported = await note
.export(format === "pdf" ? "html" : format, content, !disableTemplate)
.catch((e: Error) => {
console.error(note.data, e);
showToast("error", `Failed to export note "${note.title}": ${e.message}`);
return false as const;
});
if (typeof exported === "boolean" && !exported) return false;
const filename = sanitizeFilename(note.title, { replacement: "-" });
const ext = FORMAT_TO_EXT[format];
return {
filename: [filename, ext].join("."),
content: exported
};
}

View File

@@ -18,6 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {
showBackupPasswordDialog,
showFeatureDialog,
showPasswordDialog,
showReminderDialog
@@ -26,7 +27,8 @@ import Config from "../utils/config";
import { hashNavigate, getCurrentHash } from "../navigation";
import { db } from "./db";
import { sanitizeFilename } from "@notesnook/common";
import { store as userstore } from "../stores/user-store";
import { useStore as useUserStore } from "../stores/user-store";
import { useStore as useSettingStore } from "../stores/setting-store";
import { showToast } from "../utils/toast";
import { SUBSCRIPTION_STATUS } from "./constants";
import { readFile, showFilePicker } from "../utils/file-picker";
@@ -78,8 +80,17 @@ export async function introduceFeatures() {
export const DEFAULT_CONTEXT = { colors: [], tags: [], notebook: {} };
export async function createBackup() {
const encryptBackups =
userstore.get().isLoggedIn && Config.get("encryptBackups", false);
const { isLoggedIn } = useUserStore.getState();
const { encryptBackups, toggleEncryptBackups } = useSettingStore.getState();
if (!isLoggedIn && encryptBackups) toggleEncryptBackups();
const verified = encryptBackups || (await verifyAccount());
if (!verified) {
showToast("error", "Could not create a backup: user verification failed.");
return;
}
const encryptedBackups = isLoggedIn && encryptBackups;
const filename = sanitizeFilename(
`notesnook-backup-${getFormattedDate(Date.now())}`
@@ -101,7 +112,7 @@ export async function createBackup() {
await new ReadableStream({
start() {},
async pull(controller) {
for await (const file of db.backup!.export("web", encryptBackups)) {
for await (const file of db.backup!.export("web", encryptedBackups)) {
report({
text: `Saving chunk ${file.path}`
});
@@ -150,9 +161,9 @@ export async function restoreBackupFile(backupFile: File) {
const backup = JSON.parse(await readFile(backupFile));
if (backup.data.iv && backup.data.salt) {
await showPasswordDialog("ask_backup_password", async ({ password }) => {
if (!password) return false;
const error = await restoreWithProgress(backup, password);
await showBackupPasswordDialog(async ({ password, key }) => {
if (!password && !key) return false;
const error = await restoreWithProgress(backup, password, key);
return !error;
});
} else {
@@ -166,6 +177,7 @@ export async function restoreBackupFile(backupFile: File) {
type: "modal",
action: async (report) => {
let cachedPassword: string | undefined = undefined;
let cachedKey: string | undefined = undefined;
// const { read, totalFiles } = await Reader(backupFile);
const entries: ZipEntry[] = [];
let filesProcessed = 0;
@@ -183,20 +195,20 @@ export async function restoreBackupFile(backupFile: File) {
for (const entry of entries) {
const backup = JSON.parse(await entry.text());
if (backup.encrypted) {
if (!cachedPassword) {
const result = await showPasswordDialog(
"ask_backup_password",
async ({ password }) => {
if (!password) return false;
await db.backup?.import(backup, password);
if (!cachedPassword && !cachedKey) {
const result = await showBackupPasswordDialog(
async ({ password, key }) => {
if (!password && !key) return false;
await db.backup?.import(backup, password, key);
cachedPassword = password;
cachedKey = key;
return true;
}
);
if (!result) break;
} else await db.backup?.import(backup, cachedPassword);
} else await db.backup?.import(backup, cachedPassword, cachedKey);
} else {
await db.backup?.import(backup, null);
await db.backup?.import(backup);
}
report({
@@ -216,7 +228,8 @@ export async function restoreBackupFile(backupFile: File) {
async function restoreWithProgress(
backup: Record<string, unknown>,
password?: string
password?: string,
key?: string
) {
return await TaskManager.startTask<Error | void>({
title: "Restoring backup",
@@ -243,7 +256,7 @@ async function restoreWithProgress(
);
report({ text: `Restoring...` });
return restore(backup, password);
return restore(backup, password, key);
}
});
}
@@ -270,7 +283,7 @@ export function totalSubscriptionConsumed(user: User) {
export async function showUpgradeReminderDialogs() {
if (IS_TESTING) return;
const user = userstore.get().user;
const user = useUserStore.getState().user;
if (!user || !user.subscription || user.subscription?.expiry === 0) return;
const consumed = totalSubscriptionConsumed(user);
@@ -283,9 +296,13 @@ export async function showUpgradeReminderDialogs() {
}
}
async function restore(backup: Record<string, unknown>, password?: string) {
async function restore(
backup: Record<string, unknown>,
password?: string,
key?: string
) {
try {
await db.backup?.import(backup, password);
await db.backup?.import(backup, password, key);
showToast("success", "Backup restored!");
} catch (e) {
logger.error(e as Error, "Could not restore the backup");

View File

@@ -94,24 +94,21 @@ class Vault {
}
static lockNote(id) {
return new Promise(function lock(resolve) {
db.vault
.add(id)
.then(resolve)
.catch(({ message }) => {
switch (message) {
case db.vault.ERRORS.noVault:
return Vault.createVault();
case db.vault.ERRORS.vaultLocked:
return Vault.unlockVault();
default:
showToast("error", message);
console.error(message);
return false;
}
})
.then((result) => result && lock(resolve));
});
return db.vault
.add(id)
.then(() => true)
.catch(({ message }) => {
switch (message) {
case db.vault.ERRORS.noVault:
return Vault.createVault().then(() => Vault.lockNote(id));
case db.vault.ERRORS.vaultLocked:
return Vault.unlockVault().then(() => Vault.lockNote(id));
default:
showToast("error", message);
console.error(message);
return false;
}
});
}
static askPassword(action) {

View File

@@ -54,7 +54,7 @@ import { ScopedThemeProvider } from "../theme-provider";
import { Lightbox } from "../lightbox";
import { Allotment } from "allotment";
import { showToast } from "../../utils/toast";
import { getFormattedDate } from "@notesnook/common";
import { debounce, getFormattedDate } from "@notesnook/common";
const PDFPreview = React.lazy(() => import("../pdf-preview"));
@@ -72,11 +72,12 @@ type DocumentPreview = {
function onEditorChange(
noteId: string | undefined,
sessionId: number,
content: string
content: string,
ignoreEdit: boolean
) {
if (!content) return;
editorstore.get().saveSessionContent(noteId, sessionId, {
editorstore.get().saveSessionContent(noteId, sessionId, ignoreEdit, {
type: "tiptap",
data: content
});
@@ -135,26 +136,7 @@ export default function EditorManager({
if (result) item.data = result.data;
else EV.publish(EVENTS.vaultLocked);
}
const oldHashes = editorInstance.current.getMediaHashes();
editorInstance.current.updateContent(item.data as string);
const newHashes = editorInstance.current.getMediaHashes();
const hashesToLoad = newHashes.filter(
(hash, index) => hash !== oldHashes[index]
);
if (appstore.get().isSyncing()) {
db.eventManager.subscribe(
EVENTS.syncCompleted,
async () => {
await db.attachments?.downloadMedia(id, hashesToLoad);
},
true
);
} else {
await db.attachments?.downloadMedia(id, hashesToLoad);
}
} else if (isNote) {
if (!locked && item.locked) return EV.publish(EVENTS.vaultLocked);
@@ -180,18 +162,6 @@ export default function EditorManager({
setTimestamp(Date.now());
}, []);
const loadMedia = useCallback(async () => {
if (previewSession.current) {
await db.content?.downloadMedia(
noteId,
previewSession.current.content,
true
);
} else if (noteId && editorstore.get().session.content) {
await db.attachments?.downloadMedia(noteId);
}
}, [noteId]);
useEffect(() => {
if (!isNewSession) return;
@@ -237,6 +207,7 @@ export default function EditorManager({
/>
)}
<Editor
id={noteId}
nonce={timestamp}
content={() =>
previewSession.current?.content?.data ||
@@ -247,7 +218,6 @@ export default function EditorManager({
options={{
readonly: isReadonly || isPreviewSession,
onRequestFocus: () => toggleProperties(false),
onLoadMedia: loadMedia,
focusMode: isFocusMode,
isMobile: isMobile || isTablet
}}
@@ -351,9 +321,9 @@ type EditorOptions = {
readonly?: boolean;
focusMode?: boolean;
onRequestFocus?: () => void;
onLoadMedia?: () => void;
};
type EditorProps = {
id: string | number;
content: () => string | undefined;
nonce?: number;
options?: EditorOptions;
@@ -361,8 +331,9 @@ type EditorProps = {
onPreviewDocument?: (preview: DocumentPreview) => void;
};
export function Editor(props: EditorProps) {
const { content, nonce, options, onContentChange, onPreviewDocument } = props;
const { readonly, headless, onLoadMedia, isMobile } = options || {
const { id, content, nonce, options, onContentChange, onPreviewDocument } =
props;
const { readonly, headless, isMobile } = options || {
headless: false,
readonly: false,
focusMode: false,
@@ -375,40 +346,16 @@ export function Editor(props: EditorProps) {
useEffect(() => {
const event = AppEventManager.subscribe(
AppEvents.UPDATE_ATTACHMENT_PROGRESS,
({ hash, loaded, total, type }: AttachmentProgress) => {
({ hash, loaded, total }: AttachmentProgress) => {
editor.current?.sendAttachmentProgress(
hash,
type,
Math.round((loaded / total) * 100)
);
}
);
const mediaAttachmentDownloadedEvent = EV.subscribe(
EVENTS.mediaAttachmentDownloaded,
({
groupId,
hash,
attachmentType,
src
}: {
groupId?: string;
attachmentType: "image" | "webclip" | "generic";
hash: string;
src: string;
}) => {
if (groupId?.startsWith("monograph")) return;
if (attachmentType === "image") {
editor.current?.loadImage(hash, src);
} else if (attachmentType === "webclip") {
editor.current?.loadWebClip(hash, src);
}
}
);
return () => {
event.unsubscribe();
mediaAttachmentDownloadedEvent.unsubscribe();
};
}, [editor]);
@@ -424,7 +371,6 @@ export function Editor(props: EditorProps) {
corsHost: Config.get("corsProxy", "https://cors.notesnook.com")
}}
onLoad={() => {
if (onLoadMedia) onLoadMedia();
if (nonce && nonce > 0) setIsLoading(false);
}}
onContentChange={onContentChange}
@@ -437,8 +383,11 @@ export function Editor(props: EditorProps) {
const container = document.getElementById("dialogContainer");
if (!(container instanceof HTMLElement)) return;
const dataurl =
data.bloburl || (await downloadAttachment(hash, "base64"));
const dataurl = await downloadAttachment(
hash,
"base64",
id.toString()
);
if (!dataurl)
return showToast("error", "This image cannot be previewed.");
@@ -455,7 +404,7 @@ export function Editor(props: EditorProps) {
);
} else if (attachment && onPreviewDocument) {
onPreviewDocument({ hash });
const blob = await downloadAttachment(hash, "blob");
const blob = await downloadAttachment(hash, "blob", id.toString());
if (!blob) return;
onPreviewDocument({ url: URL.createObjectURL(blob), hash });
}
@@ -467,6 +416,13 @@ export function Editor(props: EditorProps) {
editor.current?.attachFile(file);
});
}}
onGetAttachmentData={(attachment) => {
return downloadAttachment(
attachment.hash,
attachment.type === "web-clip" ? "text" : "base64",
id.toString()
);
}}
onAttachFile={async (file) => {
const result = await attachFile(file);
if (!result) return;
@@ -489,6 +445,38 @@ function EditorChrome(
isMobile: false
};
const editorMargins = useStore((store) => store.editorMargins);
const editorContainerRef = useRef<HTMLElement>(null);
const editorScrollRef = useRef<HTMLElement>(null);
useEffect(() => {
if (!editorScrollRef.current) return;
function onResize(
entries: ResizeObserverEntry[],
_observer: ResizeObserver
) {
const editor = editorContainerRef.current?.querySelector(
".ProseMirror"
) as HTMLElement | undefined;
const parent = editorScrollRef.current?.getBoundingClientRect();
const child = editorContainerRef.current?.getBoundingClientRect();
if (!parent || !child || !editor || entries.length <= 0) return;
const CONTAINER_MARGIN = 30;
const negativeSpace = Math.abs(
parent.left - child.left - CONTAINER_MARGIN
);
editor.style.marginLeft = `-${negativeSpace}px`;
editor.style.marginRight = `-${negativeSpace}px`;
editor.style.paddingLeft = `${negativeSpace}px`;
editor.style.paddingRight = `${negativeSpace}px`;
}
const observer = new ResizeObserver(debounce(onResize, 500));
observer.observe(editorScrollRef.current);
return () => {
observer.disconnect();
};
}, []);
if (headless) return <>{children}</>;
@@ -513,10 +501,12 @@ function EditorChrome(
<Toolbar />
<FlexScrollContainer
scrollRef={editorScrollRef}
className="editorScroll"
style={{ display: "flex", flexDirection: "column", flex: 1 }}
>
<Flex
ref={editorContainerRef}
variant="columnFill"
className="editor"
sx={{
@@ -525,7 +515,7 @@ function EditorChrome(
width: "100%"
}}
pl={6}
pr={2}
pr={6}
onClick={onRequestFocus}
>
{!isMobile && (
@@ -580,7 +570,7 @@ function PreviewModeNotice(props: PreviewModeNoticeProps) {
async (cancelled: boolean) => {
const { id, sessionId } = editorstore.get().session;
if (!cancelled) {
await editorstore.saveSessionContent(id, sessionId, content);
await editorstore.saveSessionContent(id, sessionId, false, content);
}
onDiscard();
},

View File

@@ -25,6 +25,7 @@ import { TaskManager } from "../../common/task-manager";
import { isUserPremium } from "../../hooks/use-is-user-premium";
import { showToast } from "../../utils/toast";
import { showFilePicker } from "../../utils/file-picker";
import { Attachment } from "@notesnook/editor";
const FILE_SIZE_LIMIT = 500 * 1024 * 1024;
const IMAGE_SIZE_LIMIT = 50 * 1024 * 1024;
@@ -80,33 +81,54 @@ export async function reuploadAttachment(
}
/**
* @param {File} selectedFile
* @param {File} file
* @returns
*/
async function pickFile(selectedFile: File, options?: AddAttachmentOptions) {
async function pickFile(
file: File,
options?: AddAttachmentOptions
): Promise<Attachment | undefined> {
try {
if (selectedFile.size > FILE_SIZE_LIMIT)
if (file.size > FILE_SIZE_LIMIT)
throw new Error("File too big. You cannot add files over 500 MB.");
if (!selectedFile) return;
if (!file) return;
return await addAttachment(selectedFile, undefined, options);
const hash = await addAttachment(file, options);
return {
type: "file",
filename: file.name,
hash,
mime: file.type,
size: file.size
};
} catch (e) {
showToast("error", `${(e as Error).message}`);
}
}
/**
* @param {File} selectedImage
* @param {File} file
* @returns
*/
async function pickImage(selectedImage: File, options?: AddAttachmentOptions) {
async function pickImage(
file: File,
options?: AddAttachmentOptions
): Promise<Attachment | undefined> {
try {
if (selectedImage.size > IMAGE_SIZE_LIMIT)
if (file.size > IMAGE_SIZE_LIMIT)
throw new Error("Image too big. You cannot add images over 50 MB.");
if (!selectedImage) return;
if (!file) return;
const dataurl = await toDataURL(selectedImage);
return await addAttachment(selectedImage, dataurl, options);
const hash = await addAttachment(file, options);
const dimensions = await getImageDimensions(file);
return {
type: "image",
filename: file.name,
hash,
mime: file.type,
size: file.size,
...dimensions
};
} catch (e) {
showToast("error", (e as Error).message);
}
@@ -118,12 +140,6 @@ async function getEncryptionKey(): Promise<SerializedKey> {
return key;
}
async function toDataURL(file: File): Promise<string> {
const buffer = await file.arrayBuffer();
const base64 = Buffer.from(buffer).toString("base64");
return `data:${file.type};base64,${base64}`;
}
export type AttachmentProgress = {
hash: string;
type: "encrypt" | "download" | "upload";
@@ -131,15 +147,6 @@ export type AttachmentProgress = {
loaded: number;
};
export type Attachment = {
hash: string;
filename: string;
mime: string;
size: number;
dataurl?: string;
bloburl?: string;
};
type AddAttachmentOptions = {
expectedFileHash?: string;
showProgress?: boolean;
@@ -148,9 +155,8 @@ type AddAttachmentOptions = {
async function addAttachment(
file: File,
dataurl: string | undefined,
options: AddAttachmentOptions = {}
): Promise<Attachment> {
): Promise<string> {
const { default: FS } = await import("../../interfaces/fs");
const { expectedFileHash, showProgress = true } = options;
let forceWrite = options.forceWrite;
@@ -165,7 +171,7 @@ async function addAttachment(
`Please select the same file for reuploading. Expected hash ${expectedFileHash} but got ${hash}.`
);
const exists = db.attachments?.exists(hash);
const exists = db.attachments?.attachment(hash);
if (!forceWrite && exists) {
forceWrite = (await FS.getUploadedFileSize(hash)) <= 0;
}
@@ -181,19 +187,13 @@ async function addAttachment(
...output,
hash,
hashType,
filename: file.name,
type: file.type,
filename: exists?.metadata.filename || file.name,
type: exists?.metadata.type || file.type,
key
});
}
return {
hash: hash,
filename: file.name,
mime: file.type,
size: file.size,
dataurl
};
return hash;
};
const result = showProgress
@@ -204,7 +204,10 @@ async function addAttachment(
return result;
}
function withProgress<T>(file: File, action: () => Promise<T>): Promise<T> {
function withProgress<T>(
file: File,
action: () => Promise<T>
): Promise<T | Error> {
return TaskManager.startTask({
type: "modal",
title: "Encrypting attachment",
@@ -226,3 +229,19 @@ function withProgress<T>(file: File, action: () => Promise<T>): Promise<T> {
}
});
}
function getImageDimensions(file: File) {
return new Promise<{ width: number; height: number } | undefined>(
(resolve) => {
const img = new Image();
img.onload = () => {
const { naturalWidth: width, naturalHeight: height } = img;
resolve({ width, height });
};
img.onerror = () => {
resolve(undefined);
};
img.src = URL.createObjectURL(file);
}
);
}

View File

@@ -34,11 +34,11 @@ import {
getTotalWords,
countWords,
getFontById,
TiptapOptions
TiptapOptions,
Attachment
} from "@notesnook/editor";
import { Box, Flex } from "@theme-ui/components";
import { PropsWithChildren, useEffect, useMemo, useRef, useState } from "react";
import { Attachment } from "./picker";
import { IEditor } from "./types";
import {
useConfigureEditor,
@@ -57,12 +57,12 @@ import { store as editorstore } from "../../stores/editor-store";
import { ScopedThemeProvider } from "../theme-provider";
import { writeText } from "clipboard-polyfill";
import { useStore as useThemeStore } from "../../stores/theme-store";
import { toBlobURL } from "@notesnook/editor/dist/utils/downloader";
type OnChangeHandler = (
id: string | undefined,
sessionId: number,
content: string
content: string,
ignoreEdit: boolean
) => void;
type TipTapProps = {
editorContainer: HTMLElement;
@@ -72,6 +72,7 @@ type TipTapProps = {
onInsertAttachment?: (type: AttachmentType) => void;
onDownloadAttachment?: (attachment: Attachment) => void;
onPreviewAttachment?: (attachment: Attachment) => void;
onGetAttachmentData?: (attachment: Attachment) => Promise<string | undefined>;
onAttachFile?: (file: File) => void;
onFocus?: () => void;
content?: () => string | undefined;
@@ -92,6 +93,7 @@ function save(
editor: Editor,
content: Fragment,
preventSave: boolean,
ignoreEdit: boolean,
onChange?: OnChangeHandler
) {
configureEditor({
@@ -105,7 +107,7 @@ function save(
if (preventSave) return;
const html = getHTMLFromFragment(content, editor.schema);
onChange?.(noteId, sessionId, html);
onChange?.(noteId, sessionId, html, ignoreEdit);
}
const deferredSave = debounceWithId(save, SAVE_INTERVAL);
@@ -117,6 +119,7 @@ function TipTap(props: TipTapProps) {
onInsertAttachment,
onDownloadAttachment,
onPreviewAttachment,
onGetAttachmentData,
onAttachFile,
onContentChange,
onFocus = () => {},
@@ -138,6 +141,9 @@ function TipTap(props: TipTapProps) {
);
const dateFormat = useSettingsStore((store) => store.dateFormat);
const timeFormat = useSettingsStore((store) => store.timeFormat);
const markdownShortcuts = useSettingsStore(
(store) => store.markdownShortcuts
);
const { toolbarConfig } = useToolbarConfig();
const { isSearching, toggleSearch } = useSearch();
@@ -177,6 +183,7 @@ function TipTap(props: TipTapProps) {
}
}
},
enableInputRules: markdownShortcuts,
downloadOptions,
doubleSpacedLines,
dateFormat,
@@ -210,7 +217,8 @@ function TipTap(props: TipTapProps) {
onUpdate: ({ editor, transaction }) => {
onContentChange?.();
const preventSave = transaction?.getMeta("preventSave") as boolean;
const preventSave = transaction.getMeta("preventSave") as boolean;
const ignoreEdit = transaction.getMeta("ignoreEdit") as boolean;
const { id, sessionId } = editorstore.get().session;
const content = editor.state.doc.content;
deferredSave(
@@ -220,6 +228,7 @@ function TipTap(props: TipTapProps) {
editor as Editor,
content,
preventSave || !editor.isEditable,
ignoreEdit,
onChange
);
},
@@ -282,9 +291,17 @@ function TipTap(props: TipTapProps) {
onOpenLink: (url) => {
window.open(url, "_blank");
return true;
}
},
getAttachmentData: onGetAttachmentData
};
}, [readonly, nonce, doubleSpacedLines, dateFormat, timeFormat]);
}, [
readonly,
nonce,
doubleSpacedLines,
dateFormat,
timeFormat,
markdownShortcuts
]);
const editor = useTiptap(
tiptapOptions,
@@ -420,14 +437,6 @@ function toIEditor(editor: Editor): IEditor {
}),
undo: () => editor.current?.commands.undo(),
redo: () => editor.current?.commands.redo(),
getMediaHashes: () => {
if (!editor.current) return [];
const hashes: string[] = [];
editor.current.state.doc.descendants((n) => {
if (typeof n.attrs.hash === "string") hashes.push(n.attrs.hash);
});
return hashes;
},
updateContent: (content) => {
const { from, to } = editor.state.selection;
editor.current
@@ -443,27 +452,17 @@ function toIEditor(editor: Editor): IEditor {
})
.run();
},
attachFile: (file: Attachment) => {
if (file.dataurl) {
editor.current?.commands.insertImage({
...file,
bloburl: toBlobURL(file.dataurl, file.hash)
});
} else editor.current?.commands.insertAttachment(file);
},
loadWebClip: (hash, src) =>
editor.current?.commands.updateWebClip({ hash }, { src }),
loadImage: (hash, dataurl) =>
editor.current?.commands.updateImage(
{ hash },
{ hash, bloburl: toBlobURL(dataurl, hash), preventUpdate: true }
),
sendAttachmentProgress: (hash, type, progress) =>
editor.current?.commands.setAttachmentProgress({
hash,
type,
progress
})
attachFile: (file: Attachment) =>
file.type === "image"
? editor.current?.commands.insertImage(file)
: editor.current?.commands.insertAttachment(file),
sendAttachmentProgress: (hash, progress) =>
editor.current?.commands.updateAttachment(
{
progress
},
{ query: (a) => a.hash === hash, preventUpdate: true }
)
};
}

View File

@@ -17,7 +17,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Button, Flex, Text } from "@theme-ui/components";
import {
Published,
@@ -63,6 +63,7 @@ function Toolbar() {
const theme = useThemeStore((store) => store.colorScheme);
const toggleNightMode = useThemeStore((store) => store.toggleColorScheme);
const [isTitleVisible, setIsTitleVisible] = useState(false);
const onScrollTitleRef = useRef(null);
const monographs = useMonographStore((store) => store.monographs);
const { canRedo, canUndo, redo, undo } = useHistory();
@@ -92,6 +93,10 @@ function Toolbar() {
};
}, [isTitleVisible]);
useEffect(() => {
if (onScrollTitleRef.current) onScrollTitleRef.current.value = title;
}, [title]);
const tools = useMemo(
() => [
{
@@ -216,6 +221,7 @@ function Toolbar() {
}}
/>
<AnimatedInput
ref={onScrollTitleRef}
variant="clean"
ml={[2, 2, 0]}
initial={{

View File

@@ -17,7 +17,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { Attachment } from "./picker";
import { Attachment } from "@notesnook/editor";
export type NoteStatistics = {
words: {
@@ -33,14 +33,7 @@ export interface IEditor {
}) => void;
undo: () => void;
redo: () => void;
getMediaHashes: () => string[];
updateContent: (content: string) => void;
attachFile: (file: Attachment) => void;
loadWebClip: (hash: string, html: string) => void;
loadImage: (hash: string, src: string) => void;
sendAttachmentProgress: (
hash: string,
type: "download" | "upload" | "encrypt",
progress: number
) => void;
sendAttachmentProgress: (hash: string, progress: number) => void;
}

View File

@@ -56,22 +56,27 @@ type GroupingMenuOptions = {
isUngrouped: boolean;
};
const groupByMenu: (options: GroupingMenuOptions) => MenuItem = (options) => ({
type: "button",
key: "groupBy",
title: "Group by",
icon: GroupBy.path,
menu: {
items: map(options, [
{ key: "none", title: "None" },
{ key: "default", title: "Default" },
{ key: "year", title: "Year" },
{ key: "month", title: "Month" },
{ key: "week", title: "Week" },
{ key: "abc", title: "A - Z" }
])
}
});
const groupByMenu: (options: GroupingMenuOptions) => MenuItem | null = (
options
) =>
options.groupingKey === "reminders"
? null
: {
type: "button",
key: "groupBy",
title: "Group by",
icon: GroupBy.path,
menu: {
items: map(options, [
{ key: "none", title: "None" },
{ key: "default", title: "Default" },
{ key: "year", title: "Year" },
{ key: "month", title: "Month" },
{ key: "week", title: "Week" },
{ key: "abc", title: "A - Z" }
])
}
};
const orderByMenu: (options: GroupingMenuOptions) => MenuItem = (options) => ({
type: "button",
@@ -90,12 +95,20 @@ const orderByMenu: (options: GroupingMenuOptions) => MenuItem = (options) => ({
{
key: "asc",
title:
options.groupOptions.sortBy === "title" ? "A - Z" : "Oldest - newest"
options.groupOptions.sortBy === "title"
? "A - Z"
: options.groupOptions.sortBy === "dueDate"
? "Earliest first"
: "Oldest - newest"
},
{
key: "desc",
title:
options.groupOptions.sortBy === "title" ? "Z - A" : "Newest - oldest"
options.groupOptions.sortBy === "title"
? "Z - A"
: options.groupOptions.sortBy === "dueDate"
? "Latest first"
: "Newest - oldest"
}
])
}
@@ -130,6 +143,11 @@ const sortByMenu: (options: GroupingMenuOptions) => MenuItem = (options) => ({
title: "Date modified",
isHidden: options.groupingKey !== "tags"
},
{
key: "dueDate",
title: "Due date",
isHidden: options.groupingKey !== "reminders"
},
{
key: "title",
title: "Title",
@@ -331,26 +349,26 @@ function GroupHeader(props: GroupHeaderProps) {
isUngrouped: false,
refresh
};
const groupBy = groupByMenu({
...menuOptions,
parentKey: "groupBy"
});
openMenu(
[
orderByMenu({
...menuOptions,
parentKey: "sortDirection"
}),
sortByMenu({
...menuOptions,
parentKey: "sortBy"
}),
groupByMenu({
...menuOptions,
parentKey: "groupBy"
})
],
{
title: "Group & sort"
}
);
const menuItems = [
orderByMenu({
...menuOptions,
parentKey: "sortDirection"
}),
sortByMenu({
...menuOptions,
parentKey: "sortBy"
})
];
if (groupBy) menuItems.push(groupBy);
openMenu(menuItems, {
title: groupBy ? "Group & sort" : "Sort"
});
}}
/>
)}

View File

@@ -84,7 +84,7 @@ function IconTag(props: IconTagProps) {
>
<Icon
size={11}
// color={styles?.icon?.color || (highlight ? "primary" : "icon")}
color={highlight ? "accent" : "icon"}
sx={{ ...styles?.icon, flexShrink: 0 }}
/>
<Text

View File

@@ -70,7 +70,7 @@ import { hashNavigate, navigate } from "../../navigation";
import { showPublishView } from "../publish-view";
import IconTag from "../icon-tag";
import { COLORS } from "../../common/constants";
import { exportNotes } from "../../common/export";
import { exportNote, exportNotes, exportToPDF } from "../../common/export";
import { Multiselect } from "../../common/multi-select";
import { store as selectionStore } from "../../stores/selection-store";
import {
@@ -86,7 +86,7 @@ import {
ReferencesWithDateEdited
} from "../list-container/types";
import { SchemeColors } from "@notesnook/theme";
import Vault from "../../common/vault";
import FileSaver from "file-saver";
type NoteProps = {
tags: Item[];
@@ -369,10 +369,9 @@ const menuItems: (note: any, items?: any[]) => MenuItem[] = (
onClick: async () => {
const { unlock, lock } = store.get();
if (!note.locked) {
await lock(note.id);
showToast("success", "Note locked successfully!");
} else {
await unlock(note.id);
if (await lock(note.id))
showToast("success", "Note locked successfully!");
} else if (await unlock(note.id)) {
showToast("success", "Note unlocked successfully!");
}
},
@@ -422,7 +421,12 @@ const menuItems: (note: any, items?: any[]) => MenuItem[] = (
isDisabled: !isSynced,
icon: Print.path,
onClick: async () => {
await exportNotes("pdf", [note.id]);
const item = db.notes?.note(note);
if (!item) return;
const result = await exportNote(item, "pdf");
if (!result) return;
await exportToPDF(note.title, result.content);
}
},
{
@@ -456,7 +460,24 @@ const menuItems: (note: any, items?: any[]) => MenuItem[] = (
// ? "Multiple notes cannot be exported as PDF."
// : false,
isPro: format.type !== "txt",
onClick: () => exportNotes(format.type, ids)
onClick: async () => {
if (ids.length === 1) {
const item = db.notes?.note(note);
if (!item) return;
const result = await exportNote(item, format.type);
if (!result) return;
if (format.type === "pdf")
return exportToPDF(note.title, result.content);
return FileSaver.saveAs(
new Blob([new TextEncoder().encode(result.content)]),
result.filename
);
}
await exportNotes(format.type, ids);
}
}))
},
multiSelect: true,
@@ -706,17 +727,11 @@ async function copyNote(noteId: string, format: "md" | "txt") {
try {
const note = db.notes?.note(noteId);
if (!note) throw new Error("No note with this id exists.");
if (note?.data.locked && !(await Vault.unlockVault()))
throw new Error("Please unlock this note to copy it.");
const rawContent = await db.content?.raw(note.data.contentId);
const content = note?.data.locked
? await db.vault?.decryptContent(rawContent)
: rawContent;
const result = await exportNote(note, format, true);
if (!result) return;
const text = await note.export(format, content, false);
if (!text) throw new Error(`Could not convert note to ${format}.`);
await navigator.clipboard.writeText(text);
await navigator.clipboard.writeText(result.content);
showToast("success", "Copied!");
} catch (e) {
if (e instanceof Error)

View File

@@ -125,7 +125,7 @@ function PublishView(props) {
variant="body"
as="a"
target="_blank"
href={`https://monograph.notesnook.com/${publishId}`}
href={`https://monogr.ph/${publishId}`}
sx={{
textOverflow: "ellipsis",
whiteSpace: "nowrap",
@@ -134,13 +134,13 @@ function PublishView(props) {
mr: 2
}}
>
{`https://monograph.notesnook.com/${publishId}`}
{`https://monogr.ph/${publishId}`}
</Text>
<Button
variant="anchor"
className="copyPublishLink"
onClick={() => {
writeText(`https://monograph.notesnook.com/${publishId}`);
writeText(`https://monogr.ph/${publishId}`);
}}
>
<Copy size={20} color="accent" />

View File

@@ -85,6 +85,7 @@ function Reminder(props: ReminderProps) {
gap: 1
}}
>
{reminder.disabled ? null : <PriorityIcon size={14} />}
{reminder.disabled ? (
<IconTag icon={ReminderOff} text={"Disabled"} testId={"disabled"} />
) : (
@@ -95,7 +96,6 @@ function Reminder(props: ReminderProps) {
testId={"reminder-time"}
/>
)}
{reminder.disabled ? null : <PriorityIcon size={14} />}
{reminder.mode === "repeat" && reminder.recurringMode && (
<IconTag
icon={Refresh}

View File

@@ -54,6 +54,7 @@ type FlexScrollContainerProps = {
id?: string;
className?: string;
style?: React.CSSProperties;
scrollRef?: React.Ref<HTMLElement>;
} & MacScrollbarProps;
export function FlexScrollContainer({
@@ -61,11 +62,13 @@ export function FlexScrollContainer({
children,
style,
className,
scrollRef,
...restProps
}: PropsWithChildren<FlexScrollContainerProps>) {
return (
<MacScrollbar
{...restProps}
ref={scrollRef}
id={id}
className={className}
style={style}

View File

@@ -0,0 +1,115 @@
/*
This file is part of the Notesnook project (https://notesnook.com/)
Copyright (C) 2023 Streetwriters (Private) Limited
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useState } from "react";
import { Perform } from "../common/dialog-controller";
import Field from "../components/field";
import Dialog from "../components/dialog";
import { Box, Button } from "@theme-ui/components";
export type PromptDialogProps = {
onClose: Perform;
validate: (outputs: {
password?: string;
key?: string;
}) => boolean | Promise<boolean>;
};
export default function BackupPasswordDialog(props: PromptDialogProps) {
const { onClose, validate } = props;
const [error, setError] = useState<string>();
const [isLoading, setIsLoading] = useState(false);
const [isEncryptionKey, setIsEncryptionKey] = useState(false);
return (
<Dialog
isOpen={true}
title={"Encrypted backup"}
description={
"Please enter the password to decrypt and restore this backup."
}
onClose={() => onClose(false)}
positiveButton={{
form: "backupPasswordForm",
type: "submit",
loading: isLoading,
disabled: isLoading,
text: "Restore"
}}
negativeButton={{ text: "Cancel", onClick: () => onClose(false) }}
>
<Box
id="backupPasswordForm"
as="form"
onSubmit={async (e) => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
try {
setIsLoading(true);
setError(undefined);
const key = formData.get("key") as string;
const password = formData.get("password") as string;
if (!key && !password) return;
if (await validate({ key, password })) {
onClose(true);
} else {
setError("Wrong password.");
}
} catch (e) {
setError((e as Error).message);
} finally {
setIsLoading(false);
}
}}
>
{isEncryptionKey ? (
<Field
required
autoFocus
data-test-id="dialog-key"
label="Encryption key"
type="password"
id="key"
name="key"
/>
) : (
<Field
required
autoFocus
data-test-id="dialog-password"
label="Password"
type="password"
autoComplete="current-password"
id="password"
name="password"
/>
)}
</Box>
<Button variant="anchor" onClick={() => setIsEncryptionKey((s) => !s)}>
{isEncryptionKey
? "Don't have encryption key? Use password."
: "Forgot password? Use encryption key."}
</Button>
</Dialog>
);
}

View File

@@ -89,7 +89,37 @@ const features: Record<FeatureKeys, Feature> = {
)
}
]
: [],
: [
{
title: "Sort reminders by due date",
subtitle:
"You can now sort your reminders by due date to quickly see which reminders are upcoming."
},
{
title: "Restore backups using encryption key",
subtitle:
"If you forget your password but still have your recovery key, you can now use that to restore your backups."
},
{
title: "Disable markdown in editor",
subtitle:
"If you find automatic markdown shortcuts annoying, you can now turn those off from Settings > Editor > Disable markdown shortcuts."
},
{
title: "Improved password reset",
subtitle:
"Resetting password should now be much more reliable and safer."
},
...(IS_DESKTOP_APP
? [
{
title: "Proxy settings",
subtitle:
"Desktop app now support setting a custom proxy url to route all network through it. Useful if you are behind a firewall and would like to bypass it."
}
]
: [])
],
cta: {
title: "Got it",
icon: Checkmark,

View File

@@ -52,6 +52,9 @@ const MigrationDialog = React.lazy(() => import("./migration-dialog"));
const EmailChangeDialog = React.lazy(() => import("./email-change-dialog"));
const AddTagsDialog = React.lazy(() => import("./add-tags-dialog"));
const ThemeDetailsDialog = React.lazy(() => import("./theme-details-dialog"));
const BackupPasswordDialog = React.lazy(
() => import("./backup-password-dialog")
);
export const Dialogs = {
AddNotebookDialog,
@@ -79,5 +82,6 @@ export const Dialogs = {
EmailChangeDialog,
AddTagsDialog,
SettingsDialog,
ThemeDetailsDialog
ThemeDetailsDialog,
BackupPasswordDialog
};

View File

@@ -63,7 +63,11 @@ function PasswordDialog(props) {
loading: isLoading,
disabled: isLoading
}}
negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
negativeButton={{
text: "Cancel",
onClick: () => props.onClose(false),
disabled: isLoading
}}
>
<Box
id="passwordForm"

View File

@@ -19,11 +19,12 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { SettingsGroup } from "./types";
import { useStore as useUserStore } from "../../stores/user-store";
import { verifyAccount } from "../../common";
import { createBackup, verifyAccount } from "../../common";
import {
show2FARecoveryCodesDialog,
showMultifactorDialog,
showPasswordDialog
showPasswordDialog,
showRecoveryKeyDialog
} from "../../common/dialog-controller";
import { db } from "../../common/db";
import { showToast } from "../../utils/toast";
@@ -45,19 +46,22 @@ export const AuthenticationSettings: SettingsGroup[] = [
title: "Change password",
variant: "secondary",
action: async () => {
await createBackup();
const result = await showPasswordDialog(
"change_account_password",
async (data) => {
await db.user?.clearSessions();
return (
db.user?.changePassword(
(await db.user?.changePassword(
data.oldPassword,
data.newPassword
) || false
)) || false
);
}
);
if (result) showToast("success", "Account password changed!");
if (result) {
showToast("success", "Account password changed!");
await showRecoveryKeyDialog();
}
}
}
]

View File

@@ -43,17 +43,7 @@ export const BackupExportSettings: SettingsGroup[] = [
{
type: "button",
title: "Create backup",
action: async () => {
if (
!useUserStore.getState().isLoggedIn &&
useSettingStore.getState().encryptBackups
)
useSettingStore.getState().toggleEncryptBackups();
const verified =
useSettingStore.getState().encryptBackups ||
(await verifyAccount());
if (verified) await createBackup();
},
action: createBackup,
variant: "secondary"
}
]

View File

@@ -125,6 +125,7 @@ export const BehaviourSettings: SettingsGroup[] = [
selectedOption: () =>
useSettingStore.getState().trashCleanupInterval.toString(),
options: [
{ value: "1", title: "Daily" },
{ value: "7", title: "Weekly" },
{ value: "30", title: "Monthly" },
{ value: "365", title: "Yearly" },

View File

@@ -0,0 +1,53 @@
/*
This file is part of the Notesnook project (https://notesnook.com/)
Copyright (C) 2023 Streetwriters (Private) Limited
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { Button, Text } from "@theme-ui/components";
import { FlexScrollContainer } from "../../../components/scroll-container";
import { useSpellChecker } from "../../../hooks/use-spell-checker";
export function DictionaryWords() {
const words = useSpellChecker((store) => store.words);
const deleteWord = useSpellChecker((store) => store.deleteWord);
return (
<>
<FlexScrollContainer
suppressAutoHide
style={{
maxHeight: 400,
display: "flex",
flexDirection: "column"
}}
>
<Text variant="body" sx={{ my: 1 }}>
You have {words.length} custom dictionary words.
</Text>
{words.map((word) => (
<Button
variant="menuitem"
sx={{ textAlign: "left", p: 1 }}
onClick={() => deleteWord(word)}
>
{word}
</Button>
))}
</FlexScrollContainer>
</>
);
}

View File

@@ -29,6 +29,7 @@ import { useSpellChecker } from "../../hooks/use-spell-checker";
import { SpellCheckerLanguages } from "./components/spell-checker-languages";
import { CustomizeToolbar } from "./components/customize-toolbar";
import { DictionaryWords } from "./components/dictionary-words";
export const EditorSettings: SettingsGroup[] = [
{
@@ -100,7 +101,7 @@ symbols (e.g. 202305261253)`,
key: "double-spacing",
title: "Double spaced paragraphs",
description:
"Use double spacing between paragraphs and when you press Enter in the editor.",
"Use double spacing between paragraphs when you press Enter in the editor.",
onStateChange: (listener) =>
useSettingStore.subscribe((c) => c.doubleSpacedParagraphs, listener),
components: [
@@ -111,6 +112,27 @@ symbols (e.g. 202305261253)`,
useSettingStore.getState().toggleDoubleSpacedParagraphs()
}
]
},
{
key: "markdown-shortcuts",
title: "Markdown shortcuts",
description: `Markdown shortcuts are triggered whenever you input a specific character combination.
For example:
1. Typing '/date' adds the current Date
2. Wrapping something in '**' turns it into bold text
3. Typing '1.' automatically creates a numbered list.
4. etc.`,
onStateChange: (listener) =>
useSettingStore.subscribe((c) => c.markdownShortcuts, listener),
components: [
{
type: "toggle",
isToggled: () => useSettingStore.getState().markdownShortcuts,
toggle: () => useSettingStore.getState().toggleMarkdownShortcuts()
}
]
}
]
},
@@ -149,6 +171,16 @@ symbols (e.g. 202305261253)`,
component: SpellCheckerLanguages
}
]
},
{
key: "custom-dictionay-words",
title: "Custom dictionary words",
components: [
{
type: "custom",
component: DictionaryWords
}
]
}
]
},

View File

@@ -36,7 +36,8 @@ import {
Privacy,
Pro,
ShieldLock,
Sync
Sync,
Proxy
} from "../../components/icons";
import { Perform } from "../../common/dialog-controller";
import NavigationItem from "../../components/navigation-menu/navigation-item";
@@ -65,7 +66,6 @@ import {
import { AppearanceSettings } from "./appearance-settings";
import { debounce } from "@notesnook/common";
import { SubscriptionSettings } from "./subscription-settings";
import { alpha } from "@theme-ui/color";
import { ScopedThemeProvider } from "../../components/theme-provider";
type SettingsDialogProps = { onClose: Perform };

View File

@@ -115,7 +115,7 @@ What data is collected & when?`,
key: "custom-cors",
title: "Custom CORS proxy",
description:
"CORS proxy is required to directly download images from within the Notesnook app. It allows Notesnook to bypass browser restrictions by using a proxy. You can set a custom self-hosted proxy URL to increase your privacy",
"CORS proxy is required to directly download images from within the Notesnook app. It allows Notesnook to bypass browser restrictions by using a proxy. You can set a custom self-hosted proxy URL to increase your privacy.",
onStateChange: (listener) =>
useSettingStore.subscribe((s) => s.telemetry, listener),
components: [
@@ -144,6 +144,30 @@ What data is collected & when?`,
variant: "secondary"
}
]
},
{
key: "proxy-config",
title: "Proxy",
description: `Setup an HTTP/HTTPS/SOCKS proxy.
For example:
http://foobar:80
socks4://proxy.example.com
http://username:password@foobar:80
To remove the proxy, simply erase everything in the input.`,
onStateChange: (listener) =>
useSettingStore.subscribe((c) => c.proxyRules, listener),
components: [
{
type: "input",
inputType: "text",
defaultValue: () => useSettingStore.getState().proxyRules || "",
onChange: (value) => {
useSettingStore.getState().setProxyRules(value);
}
}
]
}
]
}

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