Compare commits

...

444 Commits

Author SHA1 Message Date
Ammar Ahmed
a1658b6de2 mobile: fix showing toast at bottom always 2024-09-23 13:47:25 +05:00
Ammar Ahmed
fab0f6f834 mobile: make sure toast moves with keyboard 2024-09-23 12:23:26 +05:00
Ammar Ahmed
8d10dd040f mobile: fix size of text in toast 2024-09-18 16:18:47 +05:00
Ammar Ahmed
56078a8ef3 mobile: fix toast ui in diff cond 2024-09-18 14:18:14 +05:00
Ammar Ahmed
df4fac7005 mobile: new toast 2024-09-18 13:00:20 +05:00
Abdullah Atta
7e88ec88ee core: search query should be AND by default instead of OR 2024-09-12 12:54:16 +05:00
Abdullah Atta
9ef07f22af core: ignore diacritics when searching (requires rebuilding search index) 2024-09-12 12:54:16 +05:00
Ammar Ahmed
268343be3e mobile: fix android crash when app removed from recents 2024-09-12 11:40:16 +05:00
Abdullah Atta
956e5373d1 web: ignore Error in input stream global error 2024-09-11 20:45:57 +05:00
Abdullah Atta
919fa9bdf1 web: fix invalid filename when saving recovery key (fixes #6436) 2024-09-11 15:04:31 +05:00
Abdullah Atta
e06192c5b4 core: update @streetwriters/showdown (fixes #4470) 2024-09-11 14:59:07 +05:00
Ammar Ahmed
b5be5e0b59 mobile: fix itemExists error 2024-09-11 14:12:56 +05:00
Abdullah Atta
05695cfcc8 web: add menu items to open, view & unpublish a monograph (fixes #4812) 2024-09-11 13:56:18 +05:00
Abdullah Atta
423e1c6816 web: update features list (fixes #6514) 2024-09-11 13:33:35 +05:00
Ammar Ahmed
6db1cf5cc1 clipper: add images only for pro users (#6528) 2024-09-11 13:26:57 +05:00
Ammar Ahmed
2e4a87abd9 core: fix export title has appended Notesnook to end (#6529) 2024-09-11 13:26:20 +05:00
Ammar Ahmed
c26988134f editor: fix heading and p gap (#6530)
* editor: fix heading and p gap

* Update packages/editor/styles/styles.css

Signed-off-by: Abdullah Atta <thecodrr@protonmail.com>

---------

Signed-off-by: Abdullah Atta <thecodrr@protonmail.com>
Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-09-11 13:24:58 +05:00
Abdullah Atta
bcffdd0f91 editor: improve toolbar popup controls 2024-09-11 13:22:53 +05:00
Abdullah Atta
de1051d52d editor: remove unnecessary useMemo dependency 2024-09-11 13:22:53 +05:00
Abdullah Atta
b1a360e445 editor: add more neutral default colors for highlight 2024-09-11 13:22:53 +05:00
Abdullah Atta
49e85dfa87 editor: position color picker according to mouse position 2024-09-11 13:22:53 +05:00
Abdullah Atta
452ff12071 editor: use ref instead of document.getElementById 2024-09-11 13:22:53 +05:00
Muhammad Ali
1b6fc40633 editor: fix input is not editable in color picker 2024-09-11 13:22:53 +05:00
Ammar Ahmed
82b28f8263 mobile: fix pricingPhases undefined error 2024-09-10 14:02:41 +05:00
Abdullah Atta
6e47eae30a web: fix error when registering task with invalid time (fixes #4890) 2024-09-10 09:41:16 +05:00
Abdullah Atta
4040f2ecc4 common: fix notes with empty title exporting with empty filename (fixes #6088) 2024-09-10 09:36:55 +05:00
Abdullah Atta
2293866c61 core: fix note title can be set to empty 2024-09-10 09:27:38 +05:00
Ammar Ahmed
2cb4a10076 clipper: add safe querySelector method 2024-09-09 14:57:49 +05:00
Abdullah Atta
2f7b8d3377 web: add clear instructions on how to import from other apps 2024-09-09 13:14:17 +05:00
Abdullah Atta
983220b2f2 web: add support for importing nested notebooks 2024-09-09 13:13:46 +05:00
Ammar Ahmed
ca2848e491 mobile: release v3.0.17 2024-09-06 12:58:36 +05:00
Ammar Ahmed
48e5c4d908 mobile: fix crash in background on boot 2024-09-06 12:33:34 +05:00
Ammar Ahmed
5774dd8c60 mobile: fix crash on opening app from tile 2024-09-06 12:33:00 +05:00
Steve Divskinsy
9d65184f42 docs(help): Fix typo in is-there-an-eta.md
docs(help): Fix typo in is-there-an-eta.md - unnecessary was incorrectly spelled

Signed-off-by: Stephen Argent <stevesbrain@users.noreply.github.com>

Signed-off-by: Steve Divskinsy <stevesbrain@users.noreply.github.com>
2024-09-05 20:10:54 +05:00
Abdullah Atta
395b2750e8 web: increase table viewport by 300px 2024-09-05 09:45:58 +05:00
Abdullah Atta
3bfb1d57a5 web: fix attachment downloading stuck on error 2024-09-05 09:45:44 +05:00
Abdullah Atta
e59b432007 web: ensure file exists & is of the right size after encryption 2024-09-05 09:41:06 +05:00
Abdullah Atta
efbc566386 web: compare uploaded file size with actual file size after upload 2024-09-05 09:40:45 +05:00
Abdullah Atta
2576f1dd00 web: handle errors in attachment manager 2024-09-05 09:39:29 +05:00
Abdullah Atta
7d9388bd27 web: check select all checkbox when all attachments are selected 2024-09-05 09:38:57 +05:00
Abdullah Atta
1979cd2ea4 web: show progress when rechecking attachments in bulk 2024-09-05 09:38:29 +05:00
Abdullah Atta
7bd5dfb772 web: add support for configuring server urls from login screen 2024-09-04 11:07:23 +05:00
Abdullah Atta
ac7c88218b core: fix custom server urls not working in production 2024-09-04 11:06:38 +05:00
Abdullah Atta
fb642233c8 docs(help): add xkcd comic just for kicks and laughs 2024-09-04 09:36:22 +05:00
Abdullah Atta
6e2a19d7e0 docs(help): add "is there an eta for X feature" FAQ 2024-09-04 09:20:02 +05:00
Abdullah Atta
4d4993c570 docs(help): improve merge conflicts documentation 2024-09-04 09:10:35 +05:00
Abdullah Atta
916e097cb3 clipper(web): bump version to v0.3.4 2024-09-03 11:52:53 +05:00
Abdullah Atta
6def76e1bb web: bump version to 3.0.17 2024-09-03 10:39:09 +05:00
Ammar Ahmed
d93ec27c9e mobile: release v3.0.16 2024-09-02 16:29:13 +05:00
Abdullah Atta
15329597a5 core: fix notes search for queries less than 3 letters (#6489) 2024-09-02 15:29:18 +05:00
Abdullah Atta
49caf23436 web: show loader when loading next page in themes 2024-09-02 14:58:13 +05:00
Abdullah Atta
e6d8401c56 desktop: fix multiple updates running simultaneously 2024-09-02 14:21:13 +05:00
Abdullah Atta
11a5e8c180 core: delete all relations with fromId/toId set to null 2024-09-02 14:20:58 +05:00
Abdullah Atta
5bd7a081c1 core: do not allow invalid reference to be added in relations 2024-09-02 14:20:58 +05:00
Abdullah Atta
a740a5db81 clipper(web): fix tags not assigned to clip 2024-09-02 14:20:58 +05:00
Abdullah Atta
a61f2efacf web: fix type errors 2024-09-02 13:43:05 +05:00
Brogio
51a253f3e2 mobile: fix typo in settings (#6485)
Fix typo

Signed-off-by: Brogio <contact@brog.io>
2024-09-02 12:18:49 +05:00
Abdullah Atta
19ed753079 clipper(web): only clip images if user is premium 2024-08-29 12:56:10 +05:00
Abdullah Atta
4a85c49f5d desktop: remove sodium-native package for now 2024-08-28 15:08:52 +05:00
Abdullah Atta
16dd4b3359 web: bump version to 3.0.16 2024-08-28 14:45:31 +05:00
Abdullah Atta
9279c671ac desktop: fix ft.dirname is not a function for "good" 2024-08-28 14:44:40 +05:00
Abdullah Atta
225b21977e crypto: remove libsodium-sumo patch 2024-08-28 13:46:29 +05:00
Abdullah Atta
026b9212c4 web: bump version to v3.0.15 2024-08-28 13:33:56 +05:00
Abdullah Atta
5ce59c6125 desktop: fix ft.dirname is not a function error 2024-08-28 13:32:38 +05:00
Ammar Ahmed
b7c81a956c mobile: release v3.0.15 2024-08-28 12:50:12 +05:00
Abdullah Atta
873f976fd3 crypto: fix ft.dirname is not a function 2024-08-28 12:49:14 +05:00
Ammar Ahmed
7d8a16c463 mobile: make sure settings get reset properly on logout 2024-08-28 10:29:05 +05:00
Ammar Ahmed
f5841985fa mobile: hide select folder button on ios 2024-08-28 10:29:05 +05:00
Ammar Ahmed
da86cbbe32 mobile: fix password input not focused automatically on login 2024-08-28 10:29:05 +05:00
Ammar Ahmed
ed115d3f9e mobile: set encrypted backups on signup 2024-08-28 10:29:05 +05:00
Ammar Ahmed
e52e74523a mobile: fix boot task 2024-08-28 10:29:05 +05:00
Ammar Ahmed
7e43c3b373 mobile: fix background sync 2024-08-28 10:29:05 +05:00
Ammar Ahmed
e6db186b62 mobile: fix automatic backups 2024-08-28 10:29:05 +05:00
Ammar Ahmed
998e62ade7 mobile: fix file picker does not attach file when tabId=0 2024-08-28 10:29:05 +05:00
Abdullah Atta
ac16bc74fc web: fix cache file store 2024-08-27 18:07:42 +05:00
Abdullah Atta
2aee26b082 web: restore attachment files even if they are already uploaded 2024-08-27 18:07:27 +05:00
Abdullah Atta
a188920d96 web: show but disable automatic backup settings for basic users 2024-08-27 18:07:11 +05:00
Abdullah Atta
1f3defc28c web: bump version to 3.0.14 2024-08-27 16:20:12 +05:00
Ammar Ahmed
7aeeabfb3a mobile: run sync on startup 2024-08-27 16:06:11 +05:00
Abdullah Atta
6641d3e625 web: prevent multiple simultaneous syncs 2024-08-27 16:06:11 +05:00
Abdullah Atta
72031617eb web: run sync immediately on init 2024-08-27 16:06:11 +05:00
Abdullah Atta
78090b700b web: remove debouncer for page visibility and connection changes 2024-08-27 16:06:11 +05:00
Abdullah Atta
f2f8d81b98 core: do not run sync before connecting sse 2024-08-27 16:06:11 +05:00
Abdullah Atta
84d68ca67b core: add more tests 2024-08-27 16:04:51 +05:00
Abdullah Atta
6368e47712 clipper(web): bump version to 0.3.3 2024-08-27 13:23:37 +05:00
Abdullah Atta
0f17b01a74 desktop: disable native crypto 2024-08-27 13:07:09 +05:00
Abdullah Atta
025e23356a editor: fix crash on drag dropping an embed node 2024-08-27 13:03:20 +05:00
Muhammad Ali
ac85002dff editor: fix crash when adding tasklist using md in heading or other nodes (#5923)
* editor: fixed adding tasklist using md in heading

* editor: reset nodes before converting them to a task list

---------

Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-08-27 12:49:19 +05:00
ChampionBuffalo
3a23e4fbaf web: Fix isNarrow overriding user-preference of navpane
Signed-off-by: ChampionBuffalo <49675578+ChampionBuffalo1@users.noreply.github.com>
2024-08-27 12:36:48 +05:00
Muhammad Ali
3547663af8 docs: add merge-conflicts file to help (#6420)
* Update merge-conflicts.md

edited merge conflict file

Signed-off-by: Muhammad Ali <alihamuh@gmail.com>

* Update merge-conflicts.md

Signed-off-by: Muhammad Ali <alihamuh@gmail.com>

* Update merge-conflicts.md

Signed-off-by: Muhammad Ali <alihamuh@gmail.com>

* Update merge-conflicts.md

Signed-off-by: Muhammad Ali <alihamuh@gmail.com>

* Update merge-conflicts.md

Signed-off-by: Muhammad Ali <alihamuh@gmail.com>

* Update merge-conflicts.md

Signed-off-by: Muhammad Ali <alihamuh@gmail.com>

* Update merge-conflicts.md

Signed-off-by: Muhammad Ali <alihamuh@gmail.com>

* Update merge-conflicts.md

Signed-off-by: Muhammad Ali <alihamuh@gmail.com>

* docs(help): update merge conflicts

* docs: added merge-conflicts file

---------

Signed-off-by: Muhammad Ali <alihamuh@gmail.com>
Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-08-23 16:43:41 +05:00
Abdullah Atta
c5dfc02085 web: minor refactors 2024-08-21 13:14:17 +05:00
Ammar Ahmed
bb9a6431bf mobile: remove telemetry 2024-08-20 15:08:41 +05:00
Abdullah Atta
624d3d7ce8 web: remove unused analytics import 2024-08-20 15:08:41 +05:00
Abdullah Atta
170b0aa49a web: get rid of all telemetry & analytics code 2024-08-20 15:08:41 +05:00
Muhammad Ali
07cfd74506 Delete docs/help/contents/merge-conflict.md
Signed-off-by: Muhammad Ali <alihamuh@gmail.com>
2024-08-20 14:56:56 +05:00
Muhammad Ali
1d40054ac0 Create merge-conflict.md
Signed-off-by: Muhammad Ali <alihamuh@gmail.com>
2024-08-20 14:56:09 +05:00
Muhammad Ali
5cd37f4b64 Create merge-conflicts.md
Signed-off-by: Muhammad Ali <alihamuh@gmail.com>
2024-08-20 14:53:51 +05:00
Tai Lam
25675f71e8 help: Capitalize all instances of "URL" (#6402)
Capitalize all instances of "URL"

Signed-off-by: Tai Lam <47955724+taivlam@users.noreply.github.com>
2024-08-20 12:55:27 +05:00
Ammar Ahmed
202534fca9 mobile: correctly handle error on backup failed 2024-08-19 10:51:14 +05:00
Ammar Ahmed
a57558d8ab mobile: fix restoring backups 2024-08-19 10:50:44 +05:00
Ammar Ahmed
f1c201dca9 core: fix reset attachment failed status 2024-08-19 10:50:44 +05:00
Ammar Ahmed
a73bff83fa mobile: bump version 2024-08-17 17:59:44 +05:00
Abdullah Atta
e4428299bc web: fix trial expired reminder dialog shown again and again 2024-08-16 18:10:35 +05:00
Abdullah Atta
487567ffbc web: upgrade paddle checkout code 2024-08-16 18:06:07 +05:00
Abdullah Atta
efd83e6de3 web: add debug logging to checkout 2024-08-16 11:22:13 +05:00
Ammar Ahmed
a07230f707 mobile: remove old patches 2024-08-16 10:52:16 +05:00
Abdullah Atta
35a2e11afd web: improve toast shown to basic users on using pro features 2024-08-16 10:28:39 +05:00
Abdullah Atta
cf4a7a3d34 core: limit notebooks to 20 on basic plan 2024-08-16 10:28:39 +05:00
Abdullah Atta
86e661ccd6 core: do not allow creating colors in basic plan 2024-08-16 10:28:39 +05:00
Abdullah Atta
e7be9b35ed core: limit tags to 5 on basic plan 2024-08-16 10:28:39 +05:00
Muhammad Ali
53a367b0b2 clipper(web): fix web clipper not capturing images (#6348)
* clipper: added config settings for images

* clipper(web): enable image clipping

* clipper(web): fix clipper not respecting cors proxy setting

---------

Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-08-16 10:28:14 +05:00
Ammar Ahmed
b6206e2ca7 mobile: take backup before logout 2024-08-14 12:53:57 +05:00
Abdullah Atta
a910c819f2 web: fix error text ui 2024-08-14 12:53:57 +05:00
Abdullah Atta
6dd7a4960f web: show warning if there are unsynced changes on logout 2024-08-14 12:53:57 +05:00
Abdullah Atta
c4e15b8f90 web: ask to create backup before logout in all cases 2024-08-14 12:53:57 +05:00
Abdullah Atta
f458a4b86a web: check unsynced changes and ask for backup before logout 2024-08-14 12:53:57 +05:00
Abdullah Atta
8a44a7b99a core: add api for checking unsynced changes 2024-08-14 12:53:57 +05:00
Ammar Ahmed
25065c01a0 mobile: Fix apk size increase in v3.0.13 2024-08-14 12:19:42 +05:00
Abdullah Atta
87ae9e86e7 editor: remove 500ms debounce from image observer 2024-08-14 09:18:26 +05:00
Abdullah Atta
782c53b622 web: impl chunkSize method for faster file size calculation 2024-08-14 09:18:26 +05:00
Abdullah Atta
cb52b390ab fs: add chunkSize method for faster file size calculation 2024-08-14 09:18:26 +05:00
Abdullah Atta
5a49941003 core: cache attachment key for faster attachment reading 2024-08-14 09:18:26 +05:00
Ammar Ahmed
6797b9b621 mobile: prompt before restoring a backup 2024-08-13 15:47:10 +05:00
Ammar Ahmed
031a1b31b4 mobile: fix backup success toast 2024-08-13 15:40:10 +05:00
Ammar Ahmed
4e5762be45 mobile: check server compatible 2024-08-13 11:19:47 +05:00
Abdullah Atta
7a6ba5d1d1 web: check server version compatibility when testing connection 2024-08-13 11:19:47 +05:00
Abdullah Atta
cc3ccd041d core: add function for checking compability with server 2024-08-13 11:19:47 +05:00
Ammar Ahmed
31453dc098 mobile: server configuration settings 2024-08-13 11:19:47 +05:00
Abdullah Atta
2e84099c80 web: fix typo 2024-08-13 11:19:47 +05:00
Abdullah Atta
5bbc0cd452 web: add support for changing server urls 2024-08-13 11:19:47 +05:00
Abdullah Atta
22aae401ba web: improve checks before download & upload of attachment 2024-08-13 11:09:03 +05:00
Ammar Ahmed
97f135cd07 mobile: fix attachment downloading 2024-08-13 11:09:03 +05:00
Abdullah Atta
976f933233 web: check for s3 errors on downloading attachment 2024-08-13 11:09:03 +05:00
Ammar Ahmed
95fe1044d6 mobile: clean temp backup folders and files 2024-08-13 11:09:03 +05:00
Ammar Ahmed
677201e979 mobile: fix wording 2024-08-13 11:09:03 +05:00
Ammar Ahmed
6ec9370afb mobile: add support for attachments cache 2024-08-13 11:09:03 +05:00
Abdullah Atta
bea0f1ab0e core: fix conflicts being shown on non-conflicted notes 2024-08-13 11:09:03 +05:00
Abdullah Atta
5357be4741 web: cancel attachments caching on disabling offline mode 2024-08-13 11:09:03 +05:00
Abdullah Atta
02fdec74ce web: fix bulk exists check for files 2024-08-13 11:09:03 +05:00
Abdullah Atta
dbc907ceeb web: write downloading files to temporary location before moving 2024-08-13 11:09:03 +05:00
Abdullah Atta
7bb53a5e0c fs: add support for moving files 2024-08-13 11:09:03 +05:00
Abdullah Atta
69cb24149d core: fix progress when bulk downloading files 2024-08-13 11:09:03 +05:00
Abdullah Atta
438d412ae9 web: fix "too much recursion" error 2024-08-13 11:09:03 +05:00
Abdullah Atta
1b71edef45 web: change offline mode api 2024-08-13 11:09:03 +05:00
Abdullah Atta
a4c0e8412b fs: add support for listing all files 2024-08-13 11:09:03 +05:00
Abdullah Atta
fbcb8675ca core: optimize attachment caching in offline mode 2024-08-13 11:09:03 +05:00
Ammar Ahmed
fbf5c82d04 mobile: update wording 2024-08-13 11:09:03 +05:00
Ammar Ahmed
fa40c539ed mobile: fix restoring backup files 2024-08-13 11:09:03 +05:00
Ammar Ahmed
f3218fdc31 mobile: fix restoring backup 2024-08-13 11:09:03 +05:00
Ammar Ahmed
d12ed967e3 mobile: add support for offline mode, backup with attachments 2024-08-13 11:09:03 +05:00
Abdullah Atta
b6021dc76b web: fix backup tests for good 2024-08-13 11:09:03 +05:00
Abdullah Atta
f95442a828 web: fix backup tests 2024-08-13 11:09:03 +05:00
Abdullah Atta
846aae312e core: fix backup tests 2024-08-13 11:09:03 +05:00
Abdullah Atta
68fdbcb7fc web: better status reports when taking backups in background 2024-08-13 11:09:03 +05:00
Abdullah Atta
b938c58b67 web: take automatic backups in background 2024-08-13 11:09:03 +05:00
Abdullah Atta
759fba06ae web: add options to create backups with attachments 2024-08-13 11:09:03 +05:00
Abdullah Atta
10e24ae632 web: add support for backup/restore of attachments 2024-08-13 11:09:03 +05:00
Abdullah Atta
341032c884 core: add support for including attachments in backups 2024-08-13 11:09:03 +05:00
Abdullah Atta
aa1fa0ca81 crypto: throw error if chunk decryption fails 2024-08-13 11:09:03 +05:00
Abdullah Atta
398432efde web: add setting to toggle full offline mode 2024-08-13 11:09:03 +05:00
Abdullah Atta
57ddaafc16 core: download all attachments when full offline mode is on 2024-08-13 11:09:03 +05:00
Abdullah Atta
e4a755c69f web: optimize attachment uploading 2024-08-13 11:09:03 +05:00
Abdullah Atta
053f70cdb4 fs: get rid of chunks property in file metadata 2024-08-13 11:09:03 +05:00
Abdullah Atta
cdcdc43cad web: fix encryption progress when attaching files 2024-08-13 11:09:03 +05:00
Abdullah Atta
f1111191b1 clipper: ignore stylesheets that throw cors error 2024-08-13 11:07:20 +05:00
Abdullah Atta
529e2a4dfd clipper(web): move to react 18 2024-08-13 11:07:20 +05:00
Abdullah Atta
d88d07a2b0 core: fix Cannot read properties of null (reading 'length') in migration 2024-08-11 11:48:19 +05:00
Abdullah Atta
197ff36c20 web: only show sync status in placeholder on first sync 2024-08-11 11:19:15 +05:00
Ammar Ahmed
d94474de79 mobile: fix android crash api 34 2024-08-10 16:29:05 +05:00
Ammar Ahmed
fcf0e0c531 mobile: update Podfile.lock 2024-08-10 12:35:34 +05:00
Ammar Ahmed
24048ebfbe mobile: remove USE_FULL_SCREEN_INTENT 2024-08-10 11:57:57 +05:00
Ammar Ahmed
5ae8cdd5b9 mobile: fix build errors 2024-08-10 11:31:37 +05:00
Ammar Ahmed
74187b335f ci: set java 17
Signed-off-by: Ammar Ahmed <40239442+ammarahm-ed@users.noreply.github.com>
2024-08-09 15:26:12 +05:00
Ammar Ahmed
16fc689299 mobile: release v3.0.13 2024-08-09 15:01:19 +05:00
Ammar Ahmed
578a9de680 mobile: fix ios build 2024-08-09 12:25:59 +05:00
Ammar Ahmed
62d475b2ef mobile: upgrade to react native 0.74.4 2024-08-09 12:25:59 +05:00
Ammar Ahmed
69c902c6c1 mobile: fix title input changes not detected 2024-08-09 12:25:14 +05:00
Abdullah Atta
c8c1028cbc core: fix least relevant results shown on top 2024-08-09 11:52:55 +05:00
Abdullah Atta
313807c384 web: remove Report an issue button from status bar 2024-08-09 11:47:56 +05:00
Abdullah Atta
5dc0e15094 web: fix last change in editor not getting saved 2024-08-09 10:35:53 +05:00
Ammar Ahmed
12c5b6d227 mobile: release v3.0.12 2024-07-29 10:06:21 +05:00
Ammar Ahmed
364ae51e36 mobile: fix backup share button not working 2024-07-29 09:53:20 +05:00
Ammar Ahmed
18947e0c93 mobile: fix missing fonts in share sheet 2024-07-29 09:43:37 +05:00
François Martin
3880db4339 global: clarify explanations for force push and force pull (#6255)
Signed-off-by: François Martin <f.martin@fastmail.com>
2024-07-29 09:38:30 +05:00
Ammar Ahmed
ae5b0b6fcc mobile: fix share sheet not loading on ios 2024-07-29 09:25:46 +05:00
Abdullah Atta
2c729f90cc global: update lockfiles 2024-07-27 13:30:25 +05:00
Ammar Ahmed
800514d769 mobile: fix position of password input 2024-07-27 12:49:57 +05:00
Ammar Ahmed
b03b9482dc mobile: app stuck after unlock 2024-07-27 12:49:57 +05:00
Abdullah Atta
9019490dbd web: bump version to v3.0.13 2024-07-27 11:16:42 +05:00
Abdullah Atta
4a3e23c288 web: fix reminder can't be set in january 2024-07-27 11:16:09 +05:00
Ammar Ahmed
1800ebea2d mobile: fix keyboard blocks continue button on applock 2024-07-27 11:12:09 +05:00
Ammar Ahmed
a708c9e9eb mobile: fix home shortcut not working 2024-07-27 10:56:09 +05:00
Abdullah Atta
2aeb875fec web: fix crash on moving temporary tab 2024-07-27 10:08:38 +05:00
Abdullah Atta
a8164e9f6c web: enter in title should focus editor 2024-07-27 09:46:37 +05:00
Abdullah Atta
0ee8e738e5 web: fix attachments ui in properties 2024-07-27 09:46:23 +05:00
Abdullah Atta
8fdef2ac7d web: fix attachments flicker in editor note properties 2024-07-27 09:46:23 +05:00
Abdullah Atta
920b1d91f3 web: bump version to 3.0.12 2024-07-22 15:42:18 +05:00
Abdullah Atta
0ad382aced web: fix incorrect attachment upload progress 2024-07-22 15:30:38 +05:00
Abdullah Atta
c8aa8e37cf web: add support for clearing attachments cache 2024-07-22 15:30:21 +05:00
Abdullah Atta
9a37f7c506 web: fix image picker dialog shown for non-image attachments 2024-07-22 13:08:49 +05:00
Abdullah Atta
717750d5d4 web: subscribe to user related events before fetching user 2024-07-22 13:08:36 +05:00
Abdullah Atta
1274ecc3b5 core: refresh token on user subscription change 2024-07-22 13:08:12 +05:00
Abdullah Atta
4c2ad4567c setup: use listr2 2024-07-20 10:34:40 +05:00
Abdullah Atta
ebc01af34a global: publish packages 2024-07-20 10:34:28 +05:00
Abdullah Atta
e66d8eee13 ui: add support for ss 2024-07-20 01:16:46 +05:00
Abdullah Atta
55e6a4b65a editor: do not throw during ssr 2024-07-20 00:42:54 +05:00
Abdullah Atta
0aa1db584d editor: do not keep last line in view for readonly editor 2024-07-19 23:50:20 +05:00
Abdullah Atta
a0e6266d28 ui: fix Cannot access 'mouseMoveListenerAttached' before initialization 2024-07-19 23:26:35 +05:00
Abdullah Atta
bd0aaed863 ui: add support for ssr 2024-07-19 23:22:47 +05:00
Abdullah Atta
9410c42f29 web: fix search icon overlapping route header text 2024-07-19 12:42:18 +05:00
Abdullah Atta
80186c1812 web: fix type errors 2024-07-19 11:11:51 +05:00
Abdullah Atta
37dfda5c54 desktop: set updaterCacheDirName in app-update.yml 2024-07-19 10:52:59 +05:00
Abdullah Atta
ec83517dc5 desktop: fix update check gives no feedback in ui 2024-07-19 10:51:10 +05:00
Abdullah Atta
2eb4911592 web: bump version to 3.0.11 2024-07-18 17:41:26 +05:00
Abdullah Atta
cd0a6a8fcb editor: fix editing link adds a new link right beside it 2024-07-18 17:38:18 +05:00
Abdullah Atta
b15f192244 desktop: update esbuild 2024-07-18 16:47:08 +05:00
Abdullah Atta
406cb663c9 editor: pasting list item with single spaced paragraphs shouldn't break formatting 2024-07-18 12:02:39 +05:00
Abdullah Atta
301a30a50a editor: copying a link from a list item shouldn't add spaces at the end 2024-07-18 12:02:39 +05:00
Abdullah Atta
81e3432143 editor: fix copying multiple lists only copied the first one 2024-07-18 12:02:39 +05:00
Abdullah Atta
c43c2936ac web: use resizeobserver to wait for scroll container to resize 2024-07-18 11:56:48 +05:00
Abdullah Atta
fdea1807d2 web: fix editor scroll bar hiding sometimes on startup 2024-07-18 11:56:48 +05:00
Abdullah Atta
5439578fcf server(theme): add health endpoint 2024-07-17 15:25:52 +05:00
Abdullah Atta
e05e52f870 web: fix crash on sync 2024-07-16 17:18:25 +05:00
Abdullah Atta
1c6243d12e web: fix error on resetting database on crash 2024-07-16 17:18:25 +05:00
Abdullah Atta
a51dfb5b6e web: remove all traces of immer 2024-07-16 17:18:25 +05:00
Abdullah Atta
c98bddd35b web: use sqlite for storing editor session data 2024-07-16 17:18:25 +05:00
Abdullah Atta
1eb80ccc88 web: get rid of dialog controller
dialog controller was redundant and created unnecessary overhead.
It also coupled all the dialogs together so you couldn't import a dialog
independently. This new change isolates each dialog to its own module
while keeping the behaviour mostly the same.
2024-07-16 17:18:25 +05:00
Abdullah Atta
5a346aa7de web: fix tags & colors not updating/loading on opening a note 2024-07-16 17:18:25 +05:00
Abdullah Atta
910095a769 web: replace immer with mutative for perf reasons 2024-07-16 17:18:25 +05:00
Abdullah Atta
119059befa core: update tag on rename instead of upserting 2024-07-16 17:18:25 +05:00
Abdullah Atta
a8f5dea315 core: fix type definition 2024-07-16 17:18:25 +05:00
Abdullah Atta
ca0a4cb02c core: add localStorage like ConfigStorage based on SQLite 2024-07-16 17:18:25 +05:00
Abdullah Atta
a04cd6b8dc core: send event when directly unlinking a relation 2024-07-16 17:18:25 +05:00
Abdullah Atta
3e4ab0f6df setup: update typescript to 5.5 2024-07-16 17:18:25 +05:00
Abdullah Atta
a7fe1aca44 global: update lockfiles 2024-07-16 17:18:25 +05:00
Abdullah Atta
ff0188f602 web: fix app lock verification always succeeds 2024-07-12 14:30:37 +05:00
Ammar Ahmed
c846f8abc8 mobile: release v3.0.11 2024-07-11 12:08:15 +05:00
Abdullah Atta
8d8acfb99d web: fix crash on browsers that doesn't have asyncIterator 2024-07-11 11:55:17 +05:00
Abdullah Atta
3a5b5772ad web: bump version to 3.0.10 2024-07-10 10:44:44 +05:00
Abdullah Atta
8046932e4e web: fix tags & other items lists glitching 2024-07-10 10:43:06 +05:00
Abdullah Atta
c45aa84739 editor: fix pro popup shown on every paste 2024-07-10 09:04:40 +05:00
Abdullah Atta
d98be849e3 web: refresh editor on changing editor options 2024-07-10 09:04:40 +05:00
Abdullah Atta
727ac6d907 web: allow multi tab access when using idb vfs 2024-07-10 09:04:23 +05:00
Abdullah Atta
8302f8ba4c web: update wa-sqlite 2024-07-10 09:04:23 +05:00
Abdullah Atta
4db8b0db01 desktop: update electron-builder 2024-07-08 14:22:24 +05:00
Ammar Ahmed
3f1614ab9a mobile: fix stacktrace formatting 2024-07-08 13:58:04 +05:00
Ammar Ahmed
909d8c35f8 mobile: fix issue reporting 2024-07-08 13:52:57 +05:00
Ammar Ahmed
a73780f0b0 mobile: bump version to v3.0.10 2024-07-08 13:32:45 +05:00
Ammar Ahmed
286fdbeec0 mobile: show toast error if upload file url not resolved 2024-07-08 13:32:30 +05:00
Abdullah Atta
59099552f8 web: bump version to 3.0.9 2024-07-08 12:47:45 +05:00
Ammar Ahmed
0b6013be58 mobile: fix color popup on mobile 2024-07-08 12:07:39 +05:00
Abdullah Atta
2d93a17f34 web: fix all failing tests 2024-07-08 11:22:14 +05:00
Abdullah Atta
5ef7e39e17 web: optimize ui for mobile & tablet form factor 2024-07-08 10:24:50 +05:00
Abdullah Atta
f7de4c9084 editor: fix keyboard shortcut for internal link not working 2024-07-08 10:23:30 +05:00
Abdullah Atta
0672c864f7 web: fix drag/drop with multiple items 2024-07-08 10:23:02 +05:00
Abdullah Atta
cb3706c150 editor: fix editor options not applied 2024-07-08 10:22:25 +05:00
Abdullah Atta
08c6a99336 web: fix note toc not loading on app restart 2024-07-08 10:21:46 +05:00
Abdullah Atta
adf961fa08 editor: fix search options not respected 2024-07-08 10:21:10 +05:00
Abdullah Atta
0eb9ae47e9 web: restrict tab drag/drop to horizontal axis 2024-07-08 10:15:04 +05:00
Abdullah Atta
aa706300a4 web: fix tab not closing on single click 2024-07-04 11:14:20 +05:00
Ammar Ahmed
fd183a0e1e mobile: fix error in editor with incorrect tools data 2024-07-01 11:48:52 +05:00
Ammar Ahmed
b27cd4be0f mobile: set initial lastContentChangeTime to 0 2024-07-01 11:16:52 +05:00
Abdullah Atta
9575561832 web: fix real time editor sync not updating content 2024-07-01 11:16:52 +05:00
Ammar Ahmed
02f96f8d14 mobile: fix cannot read property jsx of undefined 2024-07-01 11:14:43 +05:00
Ammar Ahmed
3cf46e7ad1 mobile: bump deps 2024-07-01 10:12:08 +05:00
Abdullah Atta
93551aa0b7 web: improve focus item in list behavior 2024-07-01 09:51:58 +05:00
Abdullah Atta
d00c35bdaf web: fix tab focus requires 2 clicks 2024-07-01 09:51:44 +05:00
Abdullah Atta
6e6b793568 web: fix web app on mobile browsers 2024-07-01 09:51:29 +05:00
Ammar Ahmed
9e064d88c6 mobile: fix privacy screen 2024-07-01 09:48:14 +05:00
Abdullah Atta
1658ad8d18 core: fix SSE not connecting 2024-06-25 08:31:07 +05:00
Abdullah Atta
c94da3bdf0 core: use single listener for receiving pushed items 2024-06-25 08:30:41 +05:00
Abdullah Atta
1f0fc83a7c editor: remove images on paste if user is not pro 2024-06-07 10:31:02 +05:00
Abdullah Atta
a6af92c330 web: handle errors when resolving upload urls 2024-06-07 10:30:36 +05:00
Abdullah Atta
ef93ecc481 web: handle errors during bootstrapping 2024-06-07 10:30:16 +05:00
Abdullah Atta
039709822c desktop: add instructions for creating packages 2024-06-05 10:38:54 +05:00
Abdullah Atta
25c861ce77 global: publish packages to npm 2024-06-05 10:28:28 +05:00
Abdullah Atta
670f1570b5 setup: add script for publishing packages 2024-06-05 10:28:13 +05:00
Abdullah Atta
c93d82d2d6 web: bump version to 3.0.8 2024-06-03 17:34:53 +05:00
Abdullah Atta
bced20031b web: fix Please unlock the key store to get values 2024-06-03 17:31:44 +05:00
Abdullah Atta
f8bd089b51 web: bump version to 3.0.7 2024-06-03 13:32:01 +05:00
Abdullah Atta
2a4d04a26f mobile: use clearer wording on logout confirmation 2024-06-03 13:27:51 +05:00
Abdullah Atta
a0c32191f9 web: use clearer wording on logout confirmation 2024-06-03 13:27:51 +05:00
Abdullah Atta
662d59f60a web: use clearer wording on database corruption errors 2024-06-03 13:27:51 +05:00
Abdullah Atta
13befe1947 web: handle crashes during export 2024-06-03 13:27:21 +05:00
Abdullah Atta
21f8b6d557 web: allow resetting side bar order & hidden items 2024-06-03 13:08:20 +05:00
Abdullah Atta
aef53cace9 web: disable non pro items in context menu 2024-06-03 13:00:36 +05:00
Abdullah Atta
382b5b0240 web: improve web app loading performance by 10x (#5845)
* web: improve web app loading performance by 10x

* web: update test snapshots
2024-06-03 11:07:44 +05:00
Ammar Ahmed
a45b66d449 mobile: release v3.0.9 2024-06-01 14:14:01 +05:00
Ammar Ahmed
dd67b1a803 mobile: fix login 2fa sheet gets blocked by keyboard 2024-06-01 13:45:28 +05:00
Ammar Ahmed
00568ae839 mobile: add back undo/redo buttons 2024-06-01 13:21:27 +05:00
Abdullah Atta
2b2ea5717c web: bring back undo/redo buttons 2024-06-01 13:21:27 +05:00
Abdullah Atta
5672de8565 desktop: allow using native titlebar on desktop app (#5826) 2024-06-01 13:21:05 +05:00
Ammar Ahmed
1c70ad8cec web: fix tags & colors not included in imported notes (#5801)
* web: include tags and colors in imports

* web: refactors

---------

Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-06-01 11:40:16 +05:00
Abdullah Atta
0c344a2146 core: fix sqlite hangs on restoring notebook 2024-06-01 11:28:40 +05:00
Yoonjae Choi
38f69b514c web: fix readonly locked notes opening as editable (#5731)
Signed-off-by: Yoonjae Choi <dbswo9795@email.com>
2024-06-01 11:27:59 +05:00
Abdullah Atta
b502f6a08f web: fix CVE-2024-4367 2024-06-01 11:26:43 +05:00
Abdullah Atta
d68c3269d3 editor: fix extra padding around image 2024-06-01 11:26:28 +05:00
Abdullah Atta
6d9af85e2a web: fix background color of count in nav item 2024-05-21 13:14:56 +05:00
Abdullah Atta
1d58cfea3c web: fix navigation bar in settings dialog not themed 2024-05-21 13:14:56 +05:00
Abdullah Atta
c1fa4d3400 web: fix wrong version saved on conflict resolve 2024-05-21 13:14:42 +05:00
Abdullah Atta
df179056d6 logger: fix logger in core not working 2024-05-21 12:19:39 +05:00
Abdullah Atta
26f9e08c23 web: fix sync not running on page focus 2024-05-21 10:47:25 +05:00
Abdullah Atta
f719bebe5a core: create triggers after resetting database 2024-05-21 09:59:20 +05:00
Abdullah Atta
9693c8ea54 desktop: run sqlite on another thread 2024-05-21 09:59:20 +05:00
Abdullah Atta
040a677895 core: add support for closing logger db 2024-05-21 09:59:20 +05:00
Ammar Ahmed
df2708147e mobile: release v3.0.8 2024-05-20 15:35:59 +05:00
Ammar Ahmed
faba5f6385 mobile: always recreate editor on changing note 2024-05-20 15:08:27 +05:00
Ammar Ahmed
eab5bccb99 mobile: use sqlite based logger 2024-05-20 15:05:18 +05:00
Abdullah Atta
ed399c0d0a web: use noop logger before initializing 2024-05-20 15:05:18 +05:00
Abdullah Atta
3c7e962fe0 logger: minor refactor 2024-05-20 15:05:18 +05:00
Abdullah Atta
56614ef19d core: use chunks and set date only once 2024-05-20 15:05:18 +05:00
Abdullah Atta
169318c549 core: remove attachments initialized log 2024-05-20 15:05:18 +05:00
Abdullah Atta
bd6a1b9bff web: add support for opening multiple sqlite databases 2024-05-20 15:05:18 +05:00
Abdullah Atta
443d6625f9 core: add support for deleting logs for a specific date 2024-05-20 15:05:18 +05:00
Abdullah Atta
b6f95ff7cd core: use sqlite for storing logs 2024-05-20 15:05:18 +05:00
Ammar Ahmed
1b13da54a1 mobile: fix image extension 2024-05-20 12:55:34 +05:00
Ammar Ahmed
adf0f132fd mobile: convert heic/heif images to jpeg 2024-05-20 12:55:34 +05:00
Ammar Ahmed
73ec04b42d mobile: fix error when writing user key 2024-05-20 10:45:02 +05:00
Abdullah Atta
54a68e4406 themebuilder: bump version to 1.2.0 2024-05-18 13:09:49 +05:00
Abdullah Atta
bd73ae9df4 theme: add titleBar to theme scopes 2024-05-18 13:09:49 +05:00
Abdullah Atta
fe41f7b687 themebuilder: make theme builder compile 2024-05-18 13:09:49 +05:00
Ammar Ahmed
c9adaa2442 mobile: release v3.0.7 2024-05-17 12:41:13 +05:00
Abdullah Atta
10be5771c6 web: bump version to 3.0.6 2024-05-17 12:31:22 +05:00
Abdullah Atta
43f4669360 core: fix notes with no conflict marked as conflicted 2024-05-17 12:29:58 +05:00
Ammar Ahmed
3b04925e54 mobile: update changelog 2024-05-17 09:58:43 +05:00
Ammar Ahmed
ba3959af9e mobile: release v3.0.6 2024-05-17 09:58:08 +05:00
Ammar Ahmed
552d86d9d2 mobile: fix android compilation on java 17 2024-05-17 09:56:51 +05:00
Ammar Ahmed
096602150e mobile: fix encryption key not found error on login 2024-05-17 09:56:51 +05:00
Abdullah Atta
e5795bcbb2 web: fix app asking password on auto backups with encryption off 2024-05-16 16:25:04 +05:00
Ammar Ahmed
9be52a69ad mobile: add changelog 2024-05-16 15:45:38 +05:00
Ammar Ahmed
5809384f62 mobile: release v3.0.5 2024-05-16 15:44:48 +05:00
Ammar Ahmed
fff70dce16 mobile: fix recovery key dialog ui 2024-05-16 15:14:14 +05:00
Ammar Ahmed
258140b1e0 mobile: fix share widget title issues
1. Do not change title of note when choosing append to note
2. Fix color of title in widget
2024-05-16 12:07:29 +05:00
Ammar Ahmed
0a00844e64 mobile: fix locked note title cannot be edited 2024-05-16 12:07:05 +05:00
Abdullah Atta
03cea85efc web: bump version to 3.0.5 2024-05-16 11:57:12 +05:00
Abdullah Atta
8a16ef9b85 web: fix unlock a note for editing test 2024-05-16 11:55:50 +05:00
Abdullah Atta
c82c30b530 editor: fix search replace 2024-05-16 11:34:10 +05:00
Abdullah Atta
46599f66da web: fix search not working in readonly editor 2024-05-16 11:33:53 +05:00
Abdullah Atta
d1b532a4ae editor: show (empty) toolbar in readonly mode 2024-05-16 11:33:53 +05:00
Abdullah Atta
0baf7afc25 web: allow locked note duplication without unlocking 2024-05-16 09:31:46 +05:00
Abdullah Atta
a0595a7d23 core: copy all note relations when duplicating 2024-05-16 09:31:46 +05:00
Abdullah Atta
1e6f6ab477 core: fix Cannot read properties of undefined (reading 'startsWith') error on export 2024-05-16 09:31:18 +05:00
Abdullah Atta
62d677f9ad web: fix web app not working on safari 2024-05-16 09:30:49 +05:00
Abdullah Atta
8de98d98ab core: fix merger tests 2024-05-16 09:30:28 +05:00
Ammar Ahmed
5b57614bfe mobile: fix app lock issues 2024-05-16 09:27:27 +05:00
Ammar Ahmed
ae7c538ad7 mobile: enable privacy screen with applock 2024-05-16 09:27:27 +05:00
Ammar Ahmed
c6394c9e37 mobile: allow removing app lock with account password 2024-05-16 09:27:27 +05:00
Ammar Ahmed
acf3740a68 mobile: fix pricing plans stuck at loading 2024-05-16 09:24:19 +05:00
Ammar Ahmed
8423543904 mobile: show diff in note history 2024-05-16 09:23:45 +05:00
Abdullah Atta
b90cb28637 web: handle corrupted+migrations: error 2024-05-16 08:40:03 +05:00
Abdullah Atta
780e1e9db0 web: reopen editor session if conflict is resolved/created 2024-05-15 12:37:50 +05:00
Abdullah Atta
ca6f8e5e4b web: fix real time sync ignored when resolved content is synced 2024-05-15 12:37:08 +05:00
Abdullah Atta
4c4cda1c39 core: create conflict if local item is unsynced
previously we were only creating a conflict when the local item was
edited after the remote item. This failed in cases where even though
the local item was edited before the remote item, it still contained
important information.

Now we only check if the local item is synced or not. If it isn't synced,
we most probably want to preserve the local changes, or at least want
to be notified.
2024-05-15 12:36:38 +05:00
Abdullah Atta
6fcbde772c core: fix notes marked as conflicted wrongly 2024-05-15 12:34:23 +05:00
Abdullah Atta
eac1750b1c core: add test for merge conflicts during sync 2024-05-14 15:21:00 +05:00
Abdullah Atta
5eea179a58 core: set conflicted property on notes after fetch is done 2024-05-14 15:21:00 +05:00
Abdullah Atta
fe1ea6dc27 core: do not update dateModified when updating content internally 2024-05-14 15:21:00 +05:00
Abdullah Atta
cf1b774255 core: filter out conflicted notes & content during sync 2024-05-14 15:21:00 +05:00
Abdullah Atta
198fa33fc0 core: do not update dateModified when setting synced=true 2024-05-14 15:21:00 +05:00
Abdullah Atta
e722866d62 web: better handling of database disk image is malformed error 2024-05-14 15:21:00 +05:00
Ammar Ahmed
58845e5508 mobile: release v3.0.4 2024-05-11 15:19:12 +05:00
Abdullah Atta
543c6f17ed web: enable sourcemaps for web app 2024-05-11 13:09:59 +05:00
Abdullah Atta
533f95fcff editor: fix editor crash due to TypeError: t.startsWith is not a function 2024-05-11 12:53:30 +05:00
Ammar Ahmed
c02f1cde16 mobile: disable template when pin note to notifications 2024-05-11 12:49:11 +05:00
Ammar Ahmed
043f55ead0 mobile: fix exporting note to text for share/copy 2024-05-11 12:49:11 +05:00
Ammar Ahmed
fcece06a1c mobile: fix update notification not showing on mobile app 2024-05-11 12:49:11 +05:00
Abdullah Atta
da7d79edc6 core: token without a scope is invalid 2024-05-11 12:36:23 +05:00
Ammar Ahmed
a2e7190a4a mobile: fix colors of error popup in editor 2024-05-11 11:26:15 +05:00
Ammar Ahmed
503f2b5876 mobile: fix cannot read property 'groupBy' of undefined 2024-05-11 11:22:59 +05:00
Abdullah Atta
68d57e2b27 web: bump version to 3.0.4 2024-05-11 10:48:48 +05:00
Abdullah Atta
400aa574cd core: fix 2fa codes not being sent 2024-05-11 10:29:02 +05:00
Abdullah Atta
5028bb1275 web: update snapshots 2024-05-10 15:30:35 +05:00
Abdullah Atta
27ae5bb5a2 desktop: use npx prebuildify instead of yarn 2024-05-10 15:24:39 +05:00
Abdullah Atta
83316fe299 web: update snapshots for linux 2024-05-10 15:20:57 +05:00
Ammar Ahmed
8869224de2 mobile: fix image preview not rendered on iOS 2024-05-10 15:04:28 +05:00
Ammar Ahmed
c4152f0fc0 mobile: set editor reset time to 10 minutes 2024-05-10 14:53:10 +05:00
Ammar Ahmed
d803005637 mobile: release v3.0.3 2024-05-10 14:47:27 +05:00
Ammar Ahmed
53d896be2b mobile: fix opening exported files after export 2024-05-10 14:44:12 +05:00
Abdullah Atta
8c37c6409a ci: use actions/upload-artifact@v4 2024-05-10 12:36:56 +05:00
Abdullah Atta
9195244890 web: fix tests 2024-05-10 12:31:55 +05:00
Ammar Ahmed
152794ccd0 mobile: fix image filename in picker 2024-05-10 12:24:40 +05:00
Ammar Ahmed
2e8b234b63 mobile: fix editor content update on realtime sync 2024-05-10 12:24:40 +05:00
Abdullah Atta
055c647698 web: add Audios tab in attachments dialog 2024-05-10 12:08:38 +05:00
Abdullah Atta
2b7bcfe7c6 web: bump version to 3.0.3 2024-05-10 12:00:06 +05:00
Abdullah Atta
3c8b8a7bc9 web: fix real time sync test 2024-05-10 11:58:56 +05:00
Abdullah Atta
fde45fb6de web: saving timeout notice shown every time 2024-05-10 11:58:44 +05:00
Abdullah Atta
4a616a3e67 web: fix tab not updating when note is locked/unlocked 2024-05-10 11:27:26 +05:00
Abdullah Atta
bd0a338dd6 core: fix dateEdited not updating on saving locked content 2024-05-10 10:46:11 +05:00
Abdullah Atta
5ab721e3e2 core: fix async iterator on sql collection only returning dateCreated & id 2024-05-10 10:22:03 +05:00
Ammar Ahmed
cb70bb9429 mobile: fix errors 2024-05-10 09:22:23 +05:00
Abdullah Atta
82cadd473c web: show error if saving takes more than 30 seconds 2024-05-10 09:22:23 +05:00
Ammar Ahmed
0e8ea3ddeb mobile: fix editor loading 2024-05-10 09:22:23 +05:00
Ammar Ahmed
511acc5fca mobile: handle editor not responding 2024-05-10 09:22:23 +05:00
Ammar Ahmed
001cf8ee92 mobile: add editor lock safety 2024-05-10 09:22:23 +05:00
Muhammad Ali
a965cd694b web: fix color not updating on note (#5573) 2024-05-10 09:16:59 +05:00
Ammar Ahmed
d3c1c1959b mobile: fix wording of push/pull sync 2024-05-09 17:39:35 +05:00
Abdullah Atta
9a866a552a web: replace force sync with force push/pull 2024-05-09 17:39:35 +05:00
Ammar Ahmed
837c296821 mobile: push/pull force sync 2024-05-09 17:39:35 +05:00
Abdullah Atta
9aed6faed8 common: fix locked notes not getting exported 2024-05-09 17:39:16 +05:00
Abdullah Atta
734f491e8d editor: fix crash due to undefined is not an object (evaluating 'a.nodeSize') (#5553) 2024-05-09 17:38:18 +05:00
Ammar Ahmed
0ea13024e9 mobile: fix editor crash due to position (#5519)
Signed-off-by: Ammar Ahmed <40239442+ammarahm-ed@users.noreply.github.com>
2024-05-09 15:55:33 +05:00
Abdullah Atta
cb27039245 web: close shared service on window close 2024-05-09 10:30:46 +05:00
Abdullah Atta
714ac2deac core: do not use auth access tokens as normal access tokens 2024-05-09 10:30:25 +05:00
Abdullah Atta
d605bc29bf desktop: fix crash on toggling custom dns (#5538) 2024-05-09 10:15:14 +05:00
Abdullah Atta
080101bc45 core: fix database disk image malformed error (#5525) 2024-05-09 10:08:44 +05:00
Abdullah Atta
4819e17da3 core: rerun sync if there are unsynced changes after sync complete 2024-05-08 16:48:59 +05:00
Ammar Ahmed
69a5d5a1b6 global: update .gitignore 2024-05-08 10:43:35 +05:00
Ammar Ahmed
68a6d6c313 mobile: fix crash when taking camera picture 2024-05-08 09:48:28 +05:00
Ammar Ahmed
c51ef4d5f6 mobile: fix camera permission 2024-05-08 09:48:28 +05:00
Ammar Ahmed
d9c5c1f893 mobile: remove margin in editor 2024-05-08 09:47:56 +05:00
Ammar Ahmed
5a75ca73a9 mobile: fix editor scrolling on update 2024-05-08 09:47:56 +05:00
Abdullah Atta
626d393376 desktop: use yarn instead of npx for build scripts 2024-05-08 09:14:55 +05:00
Abdullah Atta
68d06ff3f8 core: fix legacy backup restoration 2024-05-07 15:57:22 +05:00
Abdullah Atta
79f20d100c core: fix File already exists error on duplicate downloads 2024-05-07 12:57:51 +05:00
Ammar Ahmed
9d5bec3bfb ci: upload sourcemaps 2024-05-07 11:49:58 +05:00
Abdullah Atta
ac96354b4c core: handle case when updating item while a push is ongoing 2024-05-06 22:04:04 +05:00
Abdullah Atta
63f44d6fbc core: set synced to false on removing content by note id 2024-05-06 15:45:45 +05:00
Abdullah Atta
f9bfa88c83 core: set synced to false on unlinking relations 2024-05-06 15:45:45 +05:00
Ammar Ahmed
ef192f3d22 mobile: release v3.0.2 2024-05-05 01:14:20 +05:00
Abdullah Atta
c9a8134265 core: fix notes & notebooks sorting 2024-05-05 00:00:49 +05:00
Ammar Ahmed
cd7a5d2ec0 mobile: fix error not rendered correctly 2024-05-04 23:52:47 +05:00
Abdullah Atta
b92bc03fa9 web: handle errors when saving attachment 2024-05-04 23:51:42 +05:00
Abdullah Atta
5f5e472800 web: bump version to 3.0.2 2024-05-04 23:35:49 +05:00
Ammar Ahmed
0951906cac mobile: do not check for .nnbackup file in zip 2024-05-04 23:29:59 +05:00
Abdullah Atta
6f0fe03760 core: do not throw if user not found during legacy backup 2024-05-04 23:28:37 +05:00
Muhammad Ali
159ce97e42 core: fix crash due to unsanitized sort options (#5324)
Co-authored-by: Abdullah Atta <abdullahatta@streetwriters.co>
2024-05-04 23:26:58 +05:00
Ammar Ahmed
8a9848634c mobile: fix note not opening from notifications 2024-05-04 23:26:07 +05:00
Ammar Ahmed
282705a683 mobile: add logging 2024-05-04 23:11:30 +05:00
Ammar Ahmed
c91b706ed0 mobile: correctly show mime type 2024-05-04 23:11:30 +05:00
Ammar Ahmed
16afc07b2f mobile: fix all attachments show in audios 2024-05-04 23:11:30 +05:00
Ammar Ahmed
04f8be5a62 core: add missing audios attachments filter 2024-05-04 23:11:30 +05:00
Ammar Ahmed
0e8a5ca1fa editor: fix n.startsWith is not a function 2024-05-04 23:03:54 +05:00
Ammar Ahmed
1491bf771e Fix image and file uploads on mobile (#5304)
* mobile: fix image file formats support

* mobile: fix image and file uploads

---------

Signed-off-by: Ammar Ahmed <40239442+ammarahm-ed@users.noreply.github.com>
2024-05-04 23:02:07 +05:00
Abdullah Atta
0f5ce465c3 web: add logging related to attachments 2024-05-04 22:51:01 +05:00
Abdullah Atta
647ff7ae0e web: prevent overwriting uploaded attachments 2024-05-04 22:51:01 +05:00
Abdullah Atta
45a552adef web: handle errors during uploaded file size check 2024-05-04 22:51:01 +05:00
Abdullah Atta
8e207d787d web: delete file before reuploading 2024-05-04 22:51:01 +05:00
Abdullah Atta
00754593ac web: fix attachment not getting marked as failed on error 2024-05-04 22:51:01 +05:00
Abdullah Atta
b22770f1ae core: do not reset attachment dateUploaded when marking as failed 2024-05-04 22:51:01 +05:00
Abdullah Atta
523da4e91f core: only delete attachment file (not the metadata) on sync conflict 2024-05-04 22:51:01 +05:00
Abdullah Atta
de6c8154a3 web: fix password recovery not working 2024-05-04 22:50:44 +05:00
Abdullah Atta
9ef32e8081 web: do not hide attachment manager for logged out user 2024-05-01 20:14:20 +05:00
Abdullah Atta
5f53593a26 web: do not throw if backup doesn't contain .nnbackup file 2024-05-01 20:12:23 +05:00
Abdullah Atta
1f404944d9 web: re-enable service worker 2024-05-01 16:38:09 +05:00
556 changed files with 31515 additions and 65019 deletions

View File

@@ -147,8 +147,10 @@ jobs:
apps/mobile/native/android/app/build/outputs/apk/release/notesnook-x86.apk
apps/mobile/native/android/app/build/outputs/apk/release/notesnook-x86_64.apk
- name: Upload signed aab to Github
uses: actions/upload-artifact@v2
- name: Upload sourcemaps
uses: actions/upload-artifact@v4
with:
name: Notesnook.aab
path: ${{steps.sign_app.outputs.signedReleaseFile}}
name: sourcemaps
path: |
apps/mobile/native/android/app/build/**/*.map
packages/editor-mobile/sourcemaps/*.map

View File

@@ -22,7 +22,7 @@ jobs:
- name: Use specific Java version for the builds
uses: joschi/setup-jdk@v2
with:
java-version: "11"
java-version: "17"
architecture: "x64"
- name: Install node modules
@@ -133,7 +133,6 @@ jobs:
status: completed
whatsNewDirectory: apps/mobile/native/android/releasenotes/
- name: Create release draft on Github
uses: softprops/action-gh-release@v1
with:
@@ -148,8 +147,10 @@ jobs:
apps/mobile/native/android/app/build/outputs/apk/release/notesnook-x86.apk
apps/mobile/native/android/app/build/outputs/apk/release/notesnook-x86_64.apk
- name: Upload signed aab to Github
uses: actions/upload-artifact@v2
- name: Upload sourcemaps
uses: actions/upload-artifact@v4
with:
name: Notesnook.aab
path: ${{steps.sign_app.outputs.signedReleaseFile}}
name: sourcemaps
path: |
apps/mobile/native/android/app/build/**/*.map
packages/editor-mobile/sourcemaps/*.map

View File

@@ -98,7 +98,10 @@ jobs:
api-private-key: ${{ secrets.API_KEY }}
- name: Upload Notesnook.ipa to Github
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v4
with:
name: Notesnook.ipa
path: Notesnook.ipa
name: Notesnook.zip
path: |
Notesnook.ipa
apps/mobile/native/ios/**/*.map
packages/editor-mobile/sourcemaps/*.map

View File

@@ -40,7 +40,7 @@ jobs:
run: npm run build:test:web
- name: Archive build artifact
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v4
with:
name: build
path: apps/web/build/**/*
@@ -56,7 +56,7 @@ jobs:
uses: actions/checkout@v3
- name: Download build
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: build
path: ./apps/web/build
@@ -88,7 +88,7 @@ jobs:
working-directory: apps/web
- name: Upload test results
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: test-results-${{ matrix.shard }}

View File

@@ -40,12 +40,35 @@ Once you are inside the `./notesnook` directory, run the preparation step:
npm install
```
Now you can finally start the desktop app:
Now you can finally start the desktop app for development:
```bash
npm run start:desktop
```
To run the app in release mode:
```bash
npm run staging -- --rebuild
```
This will compile and run the app in production mode but it won't generate any packages. To create the final packages, you'll have to run the following commands:
```bash
npm run release -- --rebuild
# For macOS
npx electron-builder --mac dmg --arm64 --x64 -publish never
# For Linux (AppImage)
npx electron-builder --linux AppImage:x64 AppImage:arm64 -publish never
# For Windows
npx electron-builder --win --publish never
```
Feel free to play around with the `electron-builder` command to get the packages you need. `npx electron-builder --help` is a great resource to learn different commands & platforms supported by `electron-builder`.
## Developer guide
### The tech stack

View File

@@ -1,3 +1,4 @@
owner: streetwriters
repo: notesnook
provider: github
updaterCacheDirName: Notesnook

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,7 @@
"name": "@notesnook/desktop",
"productName": "Notesnook",
"description": "Your private note taking space",
"version": "3.0.1",
"version": "3.0.17",
"appAppleId": "1544027013",
"private": true,
"main": "./dist/index.js",
@@ -11,14 +11,12 @@
"repository": "https://github.com/streetwriters/notesnook",
"license": "GPL-3.0-or-later",
"dependencies": {
"@notesnook/crypto": "file:../../packages/crypto",
"@trpc/client": "10.38.3",
"@trpc/server": "10.38.3",
"better-sqlite3-multiple-ciphers": "^9.5.0",
"electron-trpc": "0.5.2",
"electron-updater": "6.1.4",
"electron-updater": "^6.2.1",
"icojs": "^0.17.1",
"sodium-native": "^4.1.1",
"typed-emitter": "^2.1.0",
"yargs": "^17.6.2",
"zod": "^3.21.4"
@@ -29,7 +27,8 @@
"chokidar": "^3.5.3",
"electron": "^29.3.1",
"electron-builder": "^24.13.3",
"esbuild": "^0.20.0",
"esbuild": "^0.23.0",
"kysely": "^0.27.3",
"node-gyp-build": "^4.8.0",
"prebuildify": "^6.0.1",
"tree-kill": "^1.2.2",

View File

@@ -38,7 +38,7 @@ await fs.rm("./build/", { force: true, recursive: true });
if (args.rebuild || !existsSync(path.join(webAppPath, "build"))) {
await exec(
"npx nx build:desktop @notesnook/web",
"yarn nx build:desktop @notesnook/web",
path.join(__dirname, "..", "..", "..")
);
}
@@ -46,11 +46,11 @@ if (args.rebuild || !existsSync(path.join(webAppPath, "build"))) {
// temporary until there's support for prebuilt binaries for linux ARM
if (os.platform() === "linux") await patchBetterSQLite3();
if (os.platform() === "win32")
await exec(
`npx prebuildify --arch=arm64 --strip -t electron@${packageJson.devDependencies.electron}`,
path.join(__dirname, "..", "node_modules", "sodium-native")
);
// if (os.platform() === "win32")
// await exec(
// `npx prebuildify --arch=arm64 --strip -t electron@${packageJson.devDependencies.electron}`,
// path.join(__dirname, "..", "node_modules", "sodium-native")
// );
await fs.cp(path.join(webAppPath, "build"), "build", {
recursive: true,
@@ -58,15 +58,15 @@ await fs.cp(path.join(webAppPath, "build"), "build", {
});
if (args.variant === "mas") {
await exec(`npm run bundle:mas`);
await exec(`yarn run bundle:mas`);
} else {
await exec(`npm run bundle`);
await exec(`yarn run bundle`);
}
await exec(`npx tsc`);
await exec(`yarn tsc`);
if (args.run) {
await exec(`npx electron-builder --dir --x64`);
await exec(`yarn electron-builder --dir --x64`);
if (process.platform === "win32") {
await exec(`.\\output\\win-unpacked\\Notesnook.exe`);
} else if (process.platform === "darwin") {

View File

@@ -53,11 +53,11 @@ async function onChange(first) {
if (first) {
await fs.rm("./build/", { force: true, recursive: true });
await exec("npx electron-builder install-app-deps");
await exec("yarn electron-builder install-app-deps");
}
await exec(`npm run bundle`);
execAsync(`npx`, [`tsc`]);
await exec(`yarn run bundle`);
execAsync(`yarn`, [`tsc`]);
if (await isBundleSame()) {
console.log("Bundle is same. Doing nothing.");
@@ -66,7 +66,7 @@ async function onChange(first) {
if (first) {
await spawnAndWaitUntil(
["npx", "nx", "start:desktop", "@notesnook/web"],
["yarn", "nx", "start:desktop", "@notesnook/web"],
path.join(__dirname, "..", "..", ".."),
(data) => data.includes("Network: use --host to expose")
);
@@ -78,7 +78,7 @@ async function onChange(first) {
}
execAsync(
"npx",
"yarn",
["electron", path.join("build", "electron.js")],
true,
cleanup

View File

@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { initTRPC } from "@trpc/server";
import { z } from "zod";
import { dialog, nativeTheme, Notification, shell } from "electron";
import { app, dialog, nativeTheme, Notification, shell } from "electron";
import { AutoLaunch } from "../utils/autolaunch";
import { config, DesktopIntegration } from "../utils/config";
import { bringToFront } from "../utils/bring-to-front";
@@ -58,11 +58,11 @@ export const osIntegrationRouter = t.router({
customDns: t.procedure.query(() => config.customDns),
setCustomDns: t.procedure
.input(z.boolean())
.input(z.boolean().optional())
.mutation(({ input: customDns }) => {
if (customDns) enableCustomDns();
else disableCustomDns();
config.customDns = customDns;
config.customDns = !!customDns;
}),
proxyRules: t.procedure.query(() => config.proxyRules),
@@ -152,6 +152,10 @@ export const osIntegrationRouter = t.router({
await rm(input);
}),
restart: t.procedure.query(() => {
app.relaunch();
app.exit();
}),
showNotification: t.procedure
.input(NotificationOptions)
.query(({ input }) => {
@@ -191,7 +195,10 @@ export const osIntegrationRouter = t.router({
({ input: { theme, windowControlsIconColor, backgroundColor } }) => {
if (windowControlsIconColor) {
config.windowControlsIconColor = windowControlsIconColor;
if (process.platform === "win32")
if (
process.platform === "win32" &&
!config.desktopSettings.nativeTitlebar
)
globalThis.window?.setTitleBarOverlay({
symbolColor: windowControlsIconColor
});

View File

@@ -0,0 +1,143 @@
/*
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 type { Database, Statement } from "better-sqlite3-multiple-ciphers";
import type { QueryResult } from "kysely";
type SQLiteCompatibleType =
| number
| string
| Uint8Array
| Array<number>
| bigint
| null;
export class SQLite {
sqlite?: Database;
initialized = false;
preparedStatements: Map<string, Statement<unknown[]>> = new Map();
retryCounter: Record<string, number> = {};
constructor() {
console.log("new sqlite worker");
}
async open(filePath: string) {
if (this.sqlite) {
console.error("Database is already initialized");
return;
}
this.sqlite = require("better-sqlite3-multiple-ciphers")(
filePath
).unsafeMode(true);
}
/**
* Wrapper function for preparing SQL statements with caching
* to avoid unnecessary computations.
*/
async prepare(sql: string): Promise<Statement | undefined> {
if (!this.sqlite) throw new Error("Database is not initialized.");
try {
const cached = this.preparedStatements.get(sql);
if (cached !== undefined) return cached;
const prepared = this.sqlite.prepare(sql);
if (!prepared) return;
this.preparedStatements.set(sql, prepared);
// reset retry count on success
this.retryCounter[sql] = 0;
return prepared;
} catch (ex) {
console.error(ex);
// statement prepare process can be flaky so retry at least 5 times
// before giving up.
if (this.retryCounter[sql] < 5) {
this.retryCounter[sql] = (this.retryCounter[sql] || 0) + 1;
console.warn("Failed to prepare statement. Retrying:", sql);
return this.prepare(sql);
} else this.retryCounter[sql] = 0;
if (ex instanceof Error) ex.message += ` (query: ${sql})`;
throw ex;
}
}
async exec<R>(
sql: string,
parameters: SQLiteCompatibleType[] = []
): Promise<QueryResult<R>> {
const prepared = await this.prepare(sql);
if (!prepared) return { rows: [] };
try {
if (prepared.reader) {
return {
rows: prepared.all(parameters) as R[]
};
} else {
const { changes, lastInsertRowid } = prepared.run(parameters);
const numAffectedRows =
changes !== undefined && changes !== null && !isNaN(changes)
? BigInt(changes)
: undefined;
return {
numAffectedRows,
insertId:
lastInsertRowid !== undefined && lastInsertRowid !== null
? typeof lastInsertRowid === "bigint"
? lastInsertRowid
: BigInt(lastInsertRowid)
: undefined,
rows: [] as R[]
};
}
} catch (e) {
if (e instanceof Error) e.message += ` (query: ${sql})`;
throw e;
}
}
async run<R>(
sql: string,
parameters?: SQLiteCompatibleType[]
): Promise<QueryResult<R>> {
if (!this.sqlite) throw new Error("No database is not opened.");
return await this.exec(sql, parameters);
}
async close() {
if (!this.sqlite) return;
this.preparedStatements.clear();
this.sqlite.close();
this.sqlite = undefined;
}
async delete(filePath: string) {
await this.close();
await require("fs/promises").rm(filePath, {
force: true,
maxRetries: 5,
retryDelay: 500
});
}
}

View File

@@ -29,19 +29,37 @@ type Progress = { percent: number };
const t = initTRPC.create();
let cancellationToken: CancellationToken | undefined = undefined;
let downloadTimeout: NodeJS.Timeout | undefined = undefined;
export const updaterRouter = t.router({
autoUpdates: t.procedure.query(() => config.automaticUpdates),
install: t.procedure.query(() => autoUpdater.quitAndInstall()),
download: t.procedure.query(async () => {
if (cancellationToken) return;
cancellationToken = new CancellationToken();
await autoUpdater
.downloadUpdate(cancellationToken)
.finally(() => (cancellationToken = undefined));
clearTimeout(downloadTimeout);
await new Promise<string[]>((resolve, reject) => {
downloadTimeout = setTimeout(async () => {
cancellationToken = new CancellationToken();
autoUpdater.isUpdaterActive();
await autoUpdater
.downloadUpdate(cancellationToken)
.then(resolve)
.catch(reject)
.finally(() => (cancellationToken = undefined));
}, 1000);
});
}),
check: t.procedure.query(async () => {
await autoUpdater.checkForUpdates().catch(console.error);
if (cancellationToken) return;
clearTimeout(downloadTimeout);
await new Promise<void>((resolve) => {
downloadTimeout = setTimeout(async () => {
await autoUpdater
.checkForUpdates()
.catch(console.error)
.finally(resolve);
}, 1000);
});
}),
toggleAutoUpdates: t.procedure
@@ -61,7 +79,18 @@ export const updaterRouter = t.router({
"update-not-available"
),
onAvailable: createSubscription<"update-available", UpdateInfo>(
"update-available"
"update-available",
() => {
if (!config.automaticUpdates) return false;
autoUpdater.emit("download-progress", {
bytesPerSecond: 0,
delta: 0,
percent: 0,
total: 100,
transferred: 0
});
return true;
}
),
onError: createSubscription("error")
});
@@ -69,10 +98,11 @@ export const updaterRouter = t.router({
function createSubscription<
TName extends keyof AppUpdaterEvents,
TReturnType = Parameters<AppUpdaterEvents[TName]>[0]
>(eventName: TName) {
>(eventName: TName, handler?: (args: TReturnType) => boolean) {
return t.procedure.subscription(() => {
return observable<TReturnType>((emit) => {
const listener: AppUpdaterEvents[TName] = (...args: any[]) => {
if (handler?.(args[0])) return;
emit.next(args[0]);
};
autoUpdater.removeAllListeners(eventName);

View File

@@ -21,3 +21,4 @@ export * from "./constants";
export type { AppRouter } from "./api";
export { type UpdateInfo } from "builder-util-runtime";
export { type DesktopIntegration } from "./utils/config";
export { SQLite } from "./api/sqlite-kysely.js";

View File

@@ -84,22 +84,27 @@ async function createWindow() {
format: process.platform === "win32" ? "ico" : "png"
}),
titleBarStyle: "hidden",
frame: process.platform === "win32" || process.platform === "darwin",
titleBarOverlay: {
height: 37,
color: "#00000000",
symbolColor: config.windowControlsIconColor
},
trafficLightPosition: {
x: 16,
y: 12
},
...(config.desktopSettings.nativeTitlebar
? {}
: {
titleBarStyle: "hidden",
frame: process.platform === "win32" || process.platform === "darwin",
titleBarOverlay: {
height: 37,
color: "#00000000",
symbolColor: config.windowControlsIconColor
},
trafficLightPosition: {
x: 16,
y: 12
}
}),
webPreferences: {
zoomFactor: config.zoomFactor,
nodeIntegration: true,
contextIsolation: false,
nodeIntegrationInWorker: true,
spellcheck: config.isSpellCheckerEnabled,
preload: __dirname + "/preload.js"
}

View File

@@ -20,16 +20,14 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { ELECTRON_TRPC_CHANNEL } from "electron-trpc/main";
import { type RendererGlobalElectronTRPC } from "electron-trpc/src/types";
import type { NNCrypto } from "@notesnook/crypto";
// import type { NNCrypto } from "@notesnook/crypto";
import { ipcRenderer } from "electron";
import { platform } from "os";
import sqlite3, { Database } from "better-sqlite3-multiple-ciphers";
declare global {
var os: () => "mas" | ReturnType<typeof platform>;
var electronTRPC: RendererGlobalElectronTRPC;
var NativeNNCrypto: (new () => NNCrypto) | undefined;
var createSQLite3Database: (filename: string) => Database;
// var NativeNNCrypto: (new () => NNCrypto) | undefined;
}
process.once("loaded", async () => {
@@ -42,6 +40,5 @@ process.once("loaded", async () => {
globalThis.electronTRPC = electronTRPC;
});
globalThis.NativeNNCrypto = require("@notesnook/crypto").NNCrypto;
globalThis.createSQLite3Database = (filename) => sqlite3(filename);
// globalThis.NativeNNCrypto = require("@notesnook/crypto").NNCrypto;
globalThis.os = () => (MAC_APP_STORE ? "mas" : platform());

View File

@@ -35,6 +35,7 @@ async function configureAutoUpdater() {
autoUpdater.allowDowngrade = false;
autoUpdater.allowPrerelease = false;
autoUpdater.autoInstallOnAppQuit = true;
autoUpdater.disableWebInstaller = true;
}
export { configureAutoUpdater };

View File

@@ -25,7 +25,8 @@ export const DesktopIntegration = z.object({
autoStart: z.boolean().optional(),
startMinimized: z.boolean().optional(),
minimizeToSystemTray: z.boolean().optional(),
closeToSystemTray: z.boolean().optional()
closeToSystemTray: z.boolean().optional(),
nativeTitlebar: z.boolean().optional()
});
export type DesktopIntegration = z.infer<typeof DesktopIntegration>;
@@ -35,7 +36,8 @@ export const config = {
autoStart: false,
startMinimized: false,
minimizeToSystemTray: false,
closeToSystemTray: false
closeToSystemTray: false,
nativeTitlebar: false
},
privacyMode: false,
isSpellCheckerEnabled: true,

View File

@@ -38,7 +38,7 @@ DerivedData
*.ipa
*.xcuserstate
*.hprof
ios/.xcode.env.local
**/.xcode.env.local
# Android/IntelliJ
#
rn-build-deps/

View File

@@ -16,13 +16,13 @@ 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 "react-native-gesture-handler";
import {
THEME_COMPATIBILITY_VERSION,
useThemeEngineStore
} from "@notesnook/theme";
import React, { useEffect } from "react";
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";
import AppLockedOverlay from "./components/app-lock-overlay";
@@ -40,30 +40,25 @@ import { useUserStore } from "./stores/use-user-store";
I18nManager.allowRTL(false);
I18nManager.forceRTL(false);
I18nManager.swapLeftAndRightInRTL(false);
const { appLockEnabled, appLockMode } = SettingsService.get();
if (appLockEnabled || appLockMode !== "none") {
useUserStore.getState().lockApp(true);
}
const App = () => {
const init = useAppEvents();
useAppEvents();
//@ts-ignore
globalThis["IS_MAIN_APP_RUNNING"] = true;
useEffect(() => {
const { appLockEnabled, appLockMode } = SettingsService.get();
if (appLockEnabled || appLockMode !== "none") {
useUserStore.getState().lockApp(true);
}
//@ts-ignore
globalThis["IS_MAIN_APP_RUNNING"] = true;
init();
SettingsService.onFirstLaunch();
setTimeout(async () => {
SettingsService.onFirstLaunch();
await Notifications.get();
if (SettingsService.get().notifNotes) {
Notifications.pinQuickNote(true);
}
TipManager.init();
}, 100);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<View
style={{

View File

@@ -1,156 +0,0 @@
/*
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 { Platform } from "react-native";
import { MMKV } from "../database/mmkv";
import { useSettingStore } from "../../stores/use-setting-store";
const WEBSITE_ID = "3c6890ce-8410-49d5-8831-15fb2eb28a21";
const baseUrl = "https://analytics.streetwriters.co/api/collect";
const UA =
Platform.OS === "ios"
? "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1"
: `
Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36`;
/**
*
* @param {Routes} route
* @param {Routes[]} conditions
* @returns
*/
async function canUpdateAnalytics(route, conditions = []) {
if (!useSettingStore?.getState()?.settings?.telemetry) return false;
let eventsList = MMKV.getString("notesnookUserEvents");
if (eventsList) {
eventsList = JSON.parse(eventsList);
}
if (eventsList && eventsList[route]) {
console.log("analytics: event already sent", route);
return false;
}
if (route !== "/welcome") {
for (let cond of conditions) {
if (!eventsList || !eventsList[cond]) {
console.log("analytics: conditions not met for event", route, cond);
return false;
}
}
}
console.log("analytics: will send event", route);
return true;
}
async function saveAnalytics(route, value = true) {
let eventsList = MMKV.getString("notesnookUserEvents");
if (eventsList) {
eventsList = JSON.parse(eventsList);
} else {
eventsList = {};
}
eventsList[route] = value;
MMKV.setString("notesnookUserEvents", JSON.stringify(eventsList));
}
/**
*@typedef {"/welcome" | "/home" | "/signup" | "/first-note" | "/account-created" | "/pro-sheet" | "/pro-plans" | "/iap-native" | "/pro-screen" | "/editor" | "/editor-toolbar" | "/properties" | "/sidemenu"} Routes
* @param {Routes} prevRoute
* @param {Routes} route
* @param {Routes[]} conditions
* @param {boolean} once
* @returns
*/
async function pageView(
route,
prevRoute = "",
conditions = ["/welcome"],
once = true
) {
if (__DEV__) return;
if (!(await canUpdateAnalytics(route, conditions)) && once) return;
let body = {
payload: {
website: WEBSITE_ID,
url: `notesnook-${Platform.OS}${prevRoute}${route}`,
referrer: `https://notesnook.com/notesnook-${Platform.OS}${prevRoute}`,
hostname: `notesnook-${Platform.OS}`,
language: "en-US",
screen: "1920x1080"
},
type: "pageview"
};
try {
let response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": UA
},
body: JSON.stringify(body)
});
console.log("analytics: event sent", route);
await saveAnalytics(route);
return await response.text();
} catch (e) {
console.log(e);
}
}
async function sendEvent(type, value, once = true) {
if (__DEV__) return;
if (!(await canUpdateAnalytics(type)) && once) return;
let body = {
payload: {
website: WEBSITE_ID,
url: "/",
event_type: type,
event_value: value,
hostname: "notesnook-android-app",
language: "en-US",
screen: "1920x1080"
},
type: "event"
};
try {
let response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": UA
},
body: JSON.stringify(body)
});
console.log(response.status);
return await response.text();
} catch (e) {
console.log(e);
}
}
export default {
sendEvent,
pageView,
saveAnalytics
};

View File

@@ -25,6 +25,7 @@ import { MMKVLoader, ProcessingModes } from "react-native-mmkv-storage";
import { generateSecureRandom } from "react-native-securerandom";
import { DatabaseLogger } from ".";
import { MMKV } from "./mmkv";
import { ToastManager } from "../../services/event-manager";
// Database key cipher is persisted across different user sessions hence it has
// it's independent storage which we will never clear. This is only used when application has
@@ -43,9 +44,8 @@ const IOS_KEYCHAIN_ACCESS_GROUP = "group.org.streetwriters.notesnook";
const IOS_KEYCHAIN_SERVICE_NAME = "org.streetwriters.notesnook";
const KEYCHAIN_SERVER_DBKEY = "notesnook:db";
const NOTESNOOK_APPLOCK_KEY_SALT = "3dqclWbOYllfk9kk";
const NOTESNOOK_DB_KEY_SALT = "2rcgSprDmRvZ1AAa";
const NOTESNOOK_USER_KEY_SALT = "7qO4qeoM6PbsAJ0Q";
const NOTESNOOK_APPLOCK_KEY_SALT = "kBwr1Kre86ebOZ8ThLu2OA";
const NOTESNOOK_DB_KEY_SALT = "SNuzOcEK3amoqL0WvPeKqw";
const DB_KEY_CIPHER = "databaseKeyCipher";
const USER_KEY_CIPHER = "userKeyCipher";
@@ -117,9 +117,7 @@ export async function setAppLockVerificationCipher(appLockPassword) {
NOTESNOOK_APPLOCK_KEY_SALT
);
const encrypted = await encrypt(appLockCredentials, generatePassword());
CipherStorage.setMap(APPLOCK_CIPHER, encrypted);
DatabaseLogger.info("setAppLockVerificationCipher");
} catch (e) {
DatabaseLogger.error(e);
@@ -135,10 +133,8 @@ export async function validateAppLockPassword(appLockPassword) {
try {
const appLockCipher = CipherStorage.getMap(APPLOCK_CIPHER);
if (!appLockCipher) return true;
const decrypted = await decrypt(
await Sodium.deriveKey(appLockPassword, NOTESNOOK_APPLOCK_KEY_SALT),
appLockCipher
);
const key = await Sodium.deriveKey(appLockPassword, appLockCipher.salt);
const decrypted = await decrypt(key, appLockCipher);
DatabaseLogger.info(
`validateAppLockPassword: ${typeof decrypted === "string"}`
@@ -214,7 +210,7 @@ export async function getDatabaseKey(appLockPassword) {
const userKeyCipher = await encrypt(
{
key: DB_KEY,
salt: NOTESNOOK_USER_KEY_SALT
salt: NOTESNOOK_DB_KEY_SALT
},
userKeyCredentials.password
);
@@ -227,6 +223,7 @@ export async function getDatabaseKey(appLockPassword) {
return DB_KEY;
} catch (e) {
ToastManager.error(e, "Error getting database key");
console.log(e, "error");
DatabaseLogger.error(e);
return null;
@@ -239,7 +236,7 @@ export async function deriveCryptoKey(data) {
const userKeyCipher = await encrypt(
{
key: await getDatabaseKey(),
salt: NOTESNOOK_USER_KEY_SALT
salt: NOTESNOOK_DB_KEY_SALT
},
credentials.key
);
@@ -264,13 +261,12 @@ export async function getCryptoKey(_name) {
const key = await decrypt(
{
key: await getDatabaseKey()
key: await getDatabaseKey(),
salt: keyCipher.salt
},
keyCipher
);
DatabaseLogger.info("User key decrypted: ", !!key);
return key;
} catch (e) {
console.log("getCryptoKey", e);

View File

@@ -28,29 +28,7 @@ import filesystem from "../filesystem";
import Storage from "./storage";
import { RNSqliteDriver } from "./sqlite.kysely";
import { getDatabaseKey } from "./encryption";
database.host(
__DEV__
? {
API_HOST: "https://api.notesnook.com",
AUTH_HOST: "https://auth.streetwriters.co",
SSE_HOST: "https://events.streetwriters.co",
SUBSCRIPTIONS_HOST: "https://subscriptions.streetwriters.co",
ISSUES_HOST: "https://issues.streetwriters.co"
// API_HOST: "http://192.168.43.5:5264",
// AUTH_HOST: "http://192.168.43.5:8264",
// SSE_HOST: "http://192.168.43.5:7264",
// SUBSCRIPTIONS_HOST: "http://192.168.43.5:9264",
// ISSUES_HOST: "http://192.168.43.5:2624"
}
: {
API_HOST: "https://api.notesnook.com",
AUTH_HOST: "https://auth.streetwriters.co",
SSE_HOST: "https://events.streetwriters.co",
SUBSCRIPTIONS_HOST: "https://subscriptions.streetwriters.co",
ISSUES_HOST: "https://issues.streetwriters.co"
}
);
import SettingsService from "../../services/settings";
export async function setupDatabase(password) {
const key = await getDatabaseKey(password);
@@ -59,6 +37,15 @@ export async function setupDatabase(password) {
console.log("Opening database with key:", !!key);
database.host({
API_HOST: "https://api.notesnook.com",
AUTH_HOST: "https://auth.streetwriters.co",
SSE_HOST: "https://events.streetwriters.co",
SUBSCRIPTIONS_HOST: "https://subscriptions.streetwriters.co",
ISSUES_HOST: "https://issues.streetwriters.co",
...(SettingsService.getProperty("serverUrls") || {})
});
database.setup({
storage: Storage,
eventsource: Platform.OS === "ios" ? EventSource : AndroidEventSource,
@@ -85,4 +72,10 @@ export async function setupDatabase(password) {
}
export const db = database;
export const DatabaseLogger = dbLogger;
let DatabaseLogger = dbLogger.scope(Platform.OS);
const setLogger = () => {
DatabaseLogger = dbLogger.scope(Platform.OS);
};
export { DatabaseLogger, setLogger };

View File

@@ -16,14 +16,30 @@ 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 { MMKVLoader } from "react-native-mmkv-storage";
import { initialize } from "@notesnook/core/dist/logger";
import { KV } from "./storage";
import { SqliteAdapter, SqliteIntrospector, SqliteQueryCompiler } from "kysely";
import { Platform } from "react-native";
import { setLogger } from ".";
import { RNSqliteDriver } from "./sqlite.kysely";
const LoggerStorage = new MMKVLoader()
.withInstanceID("notesnook_logs")
.initialize();
let loggerLoaded = false;
const initializeLogger = async () => {
if (loggerLoaded) return;
await initialize({
dialect: (name) => ({
createDriver: () => {
return new RNSqliteDriver({ async: true, dbName: name });
},
createAdapter: () => new SqliteAdapter(),
createIntrospector: (db) => new SqliteIntrospector(db),
createQueryCompiler: () => new SqliteQueryCompiler()
}),
tempStore: "memory",
journalMode: Platform.OS === "ios" ? "DELETE" : "WAL"
});
setLogger();
loggerLoaded = true;
};
initialize(new KV(LoggerStorage));
export { LoggerStorage };
export { initializeLogger };

View File

@@ -21,15 +21,15 @@ import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import {
decrypt,
decryptMulti,
deriveCryptoKey,
encrypt,
encryptMulti,
generateCryptoKey,
getCryptoKey,
getRandomBytes,
hash,
removeCryptoKey,
decryptMulti,
encryptMulti
removeCryptoKey
} from "./encryption";
import { MMKV } from "./mmkv";

View File

@@ -20,7 +20,6 @@ import { Dimensions, Image, Platform } from "react-native";
import ImageResizer from "@bam.tech/react-native-image-resizer";
import RNFetchBlob from "react-native-blob-util";
console.log("hello world");
/**
* Scale down & compress images to screen width
* for loading in editor.

View File

@@ -18,24 +18,20 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Sodium from "@ammarahmed/react-native-sodium";
import {
getFileNameWithExtension,
isImage,
isDocument
} from "@notesnook/core/dist/utils/filename";
import { getFileNameWithExtension } from "@notesnook/core/dist/utils/filename";
import React from "react";
import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import * as ScopedStorage from "react-native-scoped-storage";
import { subscribe, zip } from "react-native-zip-archive";
import RNFetchBlob from "react-native-blob-util";
import { ShareComponent } from "../../components/sheets/export-notes/share";
import { ToastManager, presentSheet } from "../../services/event-manager";
import { useAttachmentStore } from "../../stores/use-attachment-store";
import { IOS_APPGROUPID } from "../../utils/constants";
import { DatabaseLogger, db } from "../database";
import Storage from "../database/storage";
import { cacheDir, copyFileAsync, releasePermissions } from "./utils";
import { createCacheDir, exists } from "./io";
import { IOS_APPGROUPID } from "../../utils/constants";
import { cacheDir, copyFileAsync, releasePermissions } from "./utils";
export const FileDownloadStatus = {
Success: 1,
@@ -211,7 +207,11 @@ export default async function downloadAttachment(
try {
await db
.fs()
.downloadFile(options.groupId || attachment.hash, attachment.hash);
.downloadFile(
options.groupId || attachment.hash,
attachment.hash,
attachment.chunkSize
);
if (!(await exists(attachment.hash))) {
DatabaseLogger.log("Attachment does not exist after download.");
return;
@@ -259,15 +259,6 @@ export default async function downloadAttachment(
});
}
if (
attachment.dateUploaded &&
!isImage(attachment.mimeType) &&
!isDocument(attachment.mimeType)
) {
RNFetchBlob.fs
.unlink(RNFetchBlob.fs.dirs.CacheDir + `/${attachment.hash}`)
.catch(console.log);
}
if (Platform.OS === "ios" && !options.cache) {
fileUri = folder.uri + `/${filename}`;
}
@@ -287,7 +278,6 @@ export default async function downloadAttachment(
return fileUri;
} catch (e) {
DatabaseLogger.error(e);
if (attachment.dateUploaded) {
RNFetchBlob.fs
.unlink(RNFetchBlob.fs.dirs.CacheDir + `/${attachment.hash}`)
@@ -296,6 +286,7 @@ export default async function downloadAttachment(
.unlink(RNFetchBlob.fs.dirs.CacheDir + `/${attachment.hash}_dcache`)
.catch(console.log);
}
DatabaseLogger.error(e);
useAttachmentStore.getState().remove(attachment.hash);
if (options.throwError) {
throw e;

View File

@@ -17,64 +17,120 @@ 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 hosts from "@notesnook/core/dist/utils/constants";
import NetInfo from "@react-native-community/netinfo";
import RNFetchBlob from "react-native-blob-util";
import { ToastManager } from "../../services/event-manager";
import { useAttachmentStore } from "../../stores/use-attachment-store";
import { db } from "../database";
import { cacheDir, fileCheck } from "./utils";
import { DatabaseLogger, db } from "../database";
import { createCacheDir, exists } from "./io";
import { ABYTES, cacheDir, getUploadedFileSize, parseS3Error } from "./utils";
export async function downloadFile(filename, data, cancelToken) {
if (!data) return false;
export async function downloadFile(filename, requestOptions, cancelToken) {
if (!requestOptions) {
DatabaseLogger.log(
`Error downloading file: ${filename}, reason: No requestOptions`
);
return false;
}
console.log("Downloading", filename);
DatabaseLogger.log(`Downloading ${filename}`);
await createCacheDir();
let { url, headers } = data;
let path = `${cacheDir}/${filename}`;
let { url, headers, chunkSize } = requestOptions;
let tempFilePath = `${cacheDir}/${filename}_temp`;
let originalFilePath = `${cacheDir}/${filename}`;
try {
if (await exists(filename)) {
console.log("Exists already", filename);
DatabaseLogger.log(`File Exists already: ${filename}`);
return true;
}
const attachment = await db.attachments.attachment(filename);
const size = await getUploadedFileSize(filename);
if (size === -1) {
const error = `Uploaded file verification failed. (File hash: ${filename})`;
throw new Error(error);
}
if (size === 0) {
const error = `File length is 0. Please upload this file again from the attachment manager. (File hash: ${filename})`;
await db.attachments.markAsFailed(attachment.id, error);
throw new Error(error);
}
const totalChunks = Math.ceil(size / chunkSize);
const decryptedLength = size - totalChunks * ABYTES;
if (attachment && attachment.size !== decryptedLength) {
const error = `File length mismatch. Expected ${attachment.size} but got ${decryptedLength} bytes. Please upload this file again from the attachment manager. (File hash: ${filename})`;
await db.attachments.markAsFailed(attachment.id, error);
throw new Error(error);
}
let res = await fetch(url, {
method: "GET",
headers
});
if (!res.ok)
if (!res.ok) {
DatabaseLogger.log(
`Error downloading file: ${filename}, ${res.status}, ${res.statusText}, reason: Unable to resolve download url`
);
throw new Error(`${res.status}: Unable to resolve download url`);
}
const downloadUrl = await res.text();
if (!downloadUrl) throw new Error("Unable to resolve download url");
let totalSize = 0;
console.log("Download starting");
if (!downloadUrl) {
DatabaseLogger.log(
`Error downloading file: ${filename}, reason: Unable to resolve download url`
);
throw new Error("Unable to resolve download url");
}
DatabaseLogger.log(`Download starting: ${filename}`);
let request = RNFetchBlob.config({
path: path,
path: tempFilePath,
IOSBackgroundTask: true
})
.fetch("GET", downloadUrl, null)
.progress((recieved, total) => {
.progress(async (recieved, total) => {
useAttachmentStore
.getState()
.setProgress(0, total, filename, recieved, "download");
totalSize = total;
console.log("downloading: ", recieved, total);
DatabaseLogger.log(`Downloading: ${filename}, ${recieved}/${total}`);
});
cancelToken.cancel = () => {
useAttachmentStore.getState().remove(filename);
request.cancel();
RNFetchBlob.fs.unlink(tempFilePath).catch(console.log);
DatabaseLogger.log(`Download cancelled: ${filename}`);
};
let response = await request;
await fileCheck(response, totalSize);
console.log(response.info().headers);
const contentType =
response.info().headers?.["content-type"] ||
response.info().headers?.["Content-Type"];
if (contentType === "application/xml") {
const error = parseS3Error(await response.text());
throw new Error(`[${error.Code}] ${error.Message}`);
}
let status = response.info().status;
useAttachmentStore.getState().remove(filename);
await RNFetchBlob.fs.mv(tempFilePath, originalFilePath);
if (!(await exists(filename))) {
throw new Error("File size mismatch");
}
return status >= 200 && status < 300;
} catch (e) {
if (e.message !== "canceled") {
if (e.message !== "canceled" && !e.message.includes("NoSuchKey")) {
ToastManager.show({
heading: "Error downloading file",
message: e.message,
@@ -90,28 +146,13 @@ export async function downloadFile(filename, data, cancelToken) {
}
useAttachmentStore.getState().remove(filename);
RNFetchBlob.fs.unlink(path).catch(console.log);
console.log("Download file error:", e, url, headers);
return false;
}
}
export async function getUploadedFileSize(hash) {
try {
const url = `${hosts.API_HOST}/s3?name=${hash}`;
const token = await db.tokenManager.getAccessToken();
const attachmentInfo = await fetch(url, {
method: "HEAD",
headers: { Authorization: `Bearer ${token}` }
RNFetchBlob.fs.unlink(tempFilePath).catch(console.log);
RNFetchBlob.fs.unlink(originalFilePath).catch(console.log);
DatabaseLogger.error(e, {
url,
headers
});
const contentLength = parseInt(
attachmentInfo.headers?.get("content-length")
);
return isNaN(contentLength) ? 0 : contentLength;
} catch (e) {
return 0;
return false;
}
}
@@ -119,13 +160,19 @@ export async function checkAttachment(hash) {
const internetState = await NetInfo.fetch();
const isInternetReachable =
internetState.isConnected && internetState.isInternetReachable;
if (!isInternetReachable) return { success: true };
if (!isInternetReachable) return;
const attachment = await db.attachments.attachment(hash);
if (!attachment) return { failed: "Attachment not found." };
try {
const size = await getUploadedFileSize(hash);
if (size <= 0) return { failed: "File length is 0." };
console.log("File Size", size);
if (size === -1) return { success: true };
if (size === 0)
return {
failed: `File length is 0. Please upload this file again from the attachment manager. (File hash: ${hash})`
};
} catch (e) {
return { failed: e?.message };
}

View File

@@ -17,17 +17,22 @@ 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 { checkAttachment, downloadFile, getUploadedFileSize } from "./download";
import { checkAttachment, downloadFile } from "./download";
import {
clearFileStorage,
deleteFile,
exists,
readEncrypted,
writeEncryptedBase64,
hashBase64
hashBase64,
clearCache,
deleteCacheFileByName,
deleteCacheFileByPath,
bulkExists,
getCacheSize
} from "./io";
import { uploadFile } from "./upload";
import { cancelable } from "./utils";
import { cancelable, getUploadedFileSize } from "./utils";
export default {
readEncrypted,
@@ -39,5 +44,10 @@ export default {
exists,
clearFileStorage,
getUploadedFileSize,
checkAttachment
checkAttachment,
clearCache,
deleteCacheFileByName,
deleteCacheFileByPath,
bulkExists,
getCacheSize
};

View File

@@ -20,13 +20,14 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import Sodium from "@ammarahmed/react-native-sodium";
import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import { eSendEvent } from "../../services/event-manager";
import { IOS_APPGROUPID } from "../../utils/constants";
import { db } from "../database";
import { cacheDir, cacheDirOld, getRandomId } from "./utils";
import { DatabaseLogger, db } from "../database";
import { ABYTES, cacheDir, cacheDirOld, getRandomId } from "./utils";
export async function readEncrypted(filename, key, cipherData) {
await migrateFilesFromCache();
console.log("Read encrypted file...");
DatabaseLogger.log("Read encrypted file...");
let path = `${cacheDir}/${filename}`;
try {
@@ -34,8 +35,6 @@ export async function readEncrypted(filename, key, cipherData) {
return false;
}
const attachment = await db.attachments.attachment(filename);
console.log("decrypting....");
let output = await Sodium.decryptFile(
key,
{
@@ -45,12 +44,13 @@ export async function readEncrypted(filename, key, cipherData) {
},
cipherData.outputType === "base64" ? "base64" : "text"
);
console.log("file decrypted...", attachment?.mimeType);
DatabaseLogger.log("File decrypted...");
return output;
} catch (e) {
RNFetchBlob.fs.unlink(path).catch(console.log);
console.log("readEncrypted", e);
DatabaseLogger.error(e);
return false;
}
}
@@ -128,7 +128,7 @@ export async function clearFileStorage() {
export async function createCacheDir() {
if (!(await RNFetchBlob.fs.exists(cacheDir))) {
await RNFetchBlob.fs.mkdir(cacheDir);
console.log("Cache directory created");
DatabaseLogger.log("Cache directory created");
}
}
@@ -159,7 +159,35 @@ export async function migrateFilesFromCache() {
}
}
const ABYTES = 17;
export async function clearCache() {
await RNFetchBlob.fs.unlink(cacheDir).catch(console.log);
await createCacheDir();
eSendEvent("cache-cleared");
}
export async function deleteCacheFileByPath(path) {
await RNFetchBlob.fs.unlink(path).catch(console.log);
}
export async function deleteCacheFileByName(name) {
const iosAppGroup =
Platform.OS === "ios"
? await RNFetchBlob.fs.pathForAppGroup(IOS_APPGROUPID)
: null;
const appGroupPath = `${iosAppGroup}/${name}`;
await RNFetchBlob.fs.unlink(appGroupPath).catch(console.log);
await RNFetchBlob.fs.unlink(`${cacheDir}/${name}`).catch(console.log);
}
export async function deleteDCacheFiles() {
const files = await RNFetchBlob.fs.ls(cacheDir);
for (const file of files) {
if (file.includes("_dcache")) {
await RNFetchBlob.fs.unlink(file).catch(console.log);
}
}
}
export async function exists(filename) {
let path = `${cacheDir}/${filename}`;
@@ -188,6 +216,9 @@ export async function exists(filename) {
);
if (stat.size !== expectedFileSize) {
DatabaseLogger.log(
`File size mismatch: ${filename}, expected: ${expectedFileSize}, actual: ${stat.size}`
);
RNFetchBlob.fs
.unlink(existsInAppGroup ? appGroupPath : path)
.catch(console.log);
@@ -198,3 +229,29 @@ export async function exists(filename) {
}
return exists;
}
export async function bulkExists(files) {
const cacheFiles = await RNFetchBlob.fs.ls(cacheDir);
let missingFiles = files.filter((file) => !cacheFiles.includes(file));
if (Platform.OS === "ios") {
const iosAppGroup =
Platform.OS === "ios"
? await RNFetchBlob.fs.pathForAppGroup(IOS_APPGROUPID)
: null;
const appGroupFiles = await RNFetchBlob.fs.ls(iosAppGroup);
missingFiles = missingFiles.filter((file) => !appGroupFiles.includes(file));
}
return missingFiles;
}
export async function getCacheSize() {
const stat = await RNFetchBlob.fs.lstat(`file://` + cacheDir);
let total = 0;
console.log("Total files", stat.length);
stat.forEach((s) => {
total += parseInt(s.size);
});
return total;
}

View File

@@ -17,29 +17,47 @@ 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 RNFetchBlob from "react-native-blob-util";
import { useAttachmentStore } from "../../stores/use-attachment-store";
import { DatabaseLogger, db } from "../database";
import { cacheDir } from "./utils";
import { isImage, isDocument } from "@notesnook/core/dist/utils/filename";
import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import { ToastManager } from "../../services/event-manager";
import { useAttachmentStore } from "../../stores/use-attachment-store";
import { IOS_APPGROUPID } from "../../utils/constants";
import { DatabaseLogger, db } from "../database";
import { createCacheDir } from "./io";
import { cacheDir, getUploadedFileSize } from "./utils";
export async function uploadFile(filename, data, cancelToken) {
if (!data) return false;
let { url, headers } = data;
export async function uploadFile(filename, requestOptions, cancelToken) {
if (!requestOptions) return false;
let { url, headers } = requestOptions;
await createCacheDir();
DatabaseLogger.info(`Preparing to upload file: ${filename}`);
try {
const uploadedFileSize = await getUploadedFileSize(filename);
if (uploadedFileSize === -1) {
const error = `Uploaded file verification failed. (File hash: ${filename})`;
throw new Error(error);
}
if (uploadedFileSize !== 0) {
DatabaseLogger.log(`File ${filename} is already uploaded.`);
return true;
}
let res = await fetch(url, {
method: "PUT",
headers
});
if (!res.ok) throw new Error(`${res.status}: Unable to resolve upload url`);
const uploadUrl = await res.text();
if (!uploadUrl) throw new Error("Unable to resolve attachment upload url");
const uploadUrl = res.ok ? await res.text() : await res.json();
if (typeof uploadUrl !== "string") {
throw new Error(
uploadUrl.error || "Unable to resolve attachment upload url."
);
}
let uploadFilePath = `${cacheDir}/${filename}`;
const iosAppGroup =
@@ -50,7 +68,15 @@ export async function uploadFile(filename, data, cancelToken) {
let exists = await RNFetchBlob.fs.exists(uploadFilePath);
if (!exists && Platform.OS === "ios") {
uploadFilePath = appGroupPath;
exists = await RNFetchBlob.fs.exists(uploadFilePath);
}
if (!exists) {
throw new Error(
`Trying to upload file at path ${uploadFilePath} that doest not exist.`
);
}
DatabaseLogger.info(`Starting upload: ${filename}`);
let request = RNFetchBlob.config({
@@ -89,9 +115,6 @@ export async function uploadFile(filename, data, cancelToken) {
);
let attachment = await db.attachments.attachment(filename);
if (!attachment) return result;
if (!isImage(attachment.mimeType) && !isDocument(attachment.mimeType)) {
RNFetchBlob.fs.unlink(`${cacheDir}/${filename}`).catch(console.log);
}
} else {
const fileInfo = await RNFetchBlob.fs.stat(uploadFilePath);
throw new Error(
@@ -104,8 +127,10 @@ export async function uploadFile(filename, data, cancelToken) {
return result;
} catch (e) {
useAttachmentStore.getState().remove(filename);
DatabaseLogger.info(`File upload error: ${filename}, ${e}`);
DatabaseLogger.error(e);
ToastManager.error(e, "File upload failed");
DatabaseLogger.error(e, "File upload failed", {
filename
});
return false;
}
}

View File

@@ -17,10 +17,13 @@ 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 * as ScopedStorage from "react-native-scoped-storage";
import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import * as ScopedStorage from "react-native-scoped-storage";
import { DatabaseLogger, db } from "../database";
import hosts from "@notesnook/core/dist/utils/constants";
export const ABYTES = 17;
export const cacheDirOld = RNFetchBlob.fs.dirs.CacheDir;
export const cacheDir =
@@ -34,24 +37,36 @@ export function getRandomId(prefix) {
.replace("0.", prefix || "");
}
export function extractValueFromXmlTag(code, xml) {
if (!xml.includes(code)) return `Unknown ${code}`;
return xml.slice(
xml.indexOf(`<${code}>`) + code.length + 2,
xml.indexOf(`</${code}>`)
);
}
/**
*
* @param {string | undefined} data
* @returns
*/
export function parseS3Error(data) {
const xml = typeof data === "string" ? data : null;
export async function fileCheck(response, totalSize) {
if (totalSize < 1000) {
let text = await response.text();
if (text.startsWith("<?xml")) {
let errorJson = {
Code: extractValueFromXmlTag("Code", text),
Message: extractValueFromXmlTag("Message", text)
};
throw new Error(`${errorJson.Code}: ${errorJson.Message}`);
const error = {
Code: "UNKNOWN",
Message: xml
};
try {
if (!xml) return error;
const doc = new DOMParser().parseFromString(xml, "text/xml");
const ErrorElement = doc.getElementsByTagName("Error")[0];
if (!ErrorElement) return error;
for (const child of ErrorElement.children) {
if (
child.textContent &&
(child.tagName === "Code" || child.tagName === "Message")
)
error[child.tagName] = child.textContent;
}
return error;
} catch (e) {
return error;
}
}
@@ -59,12 +74,11 @@ export function cancelable(operation) {
const cancelToken = {
cancel: () => {}
};
return (filename, { url, headers }) => {
return (filename, requestOptions) => {
return {
execute: () => operation(filename, { url, headers }, cancelToken),
execute: () => operation(filename, requestOptions, cancelToken),
cancel: async () => {
await cancelToken.cancel();
RNFetchBlob.fs.unlink(`${cacheDir}/${filename}`).catch(console.log);
}
};
};
@@ -91,3 +105,21 @@ export async function releasePermissions(path) {
}
}
}
export async function getUploadedFileSize(hash) {
try {
const url = `${hosts.API_HOST}/s3?name=${hash}`;
const token = await db.tokenManager.getAccessToken();
const attachmentInfo = await fetch(url, {
method: "HEAD",
headers: { Authorization: `Bearer ${token}` }
});
const contentLength = parseInt(
attachmentInfo.headers?.get("content-length")
);
return isNaN(contentLength) ? 0 : contentLength;
} catch (e) {
DatabaseLogger.error(e);
return -1;
}
}

View File

@@ -20,15 +20,13 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import React from "react";
import { Linking, View } from "react-native";
//import SettingsBackupAndRestore from '../../screens/settings/backup-restore';
import { eSendEvent, presentSheet } from "../../services/event-manager";
import Sync from "../../services/sync";
import { useThemeColors } from "@notesnook/theme";
import { eCloseAnnouncementDialog, eCloseSheet } from "../../utils/events";
import { eSendEvent, presentSheet } from "../../services/event-manager";
import { eCloseAnnouncementDialog } from "../../utils/events";
import { SIZE } from "../../utils/size";
import { sleep } from "../../utils/time";
import { PricingPlans } from "../premium/pricing-plans";
import SheetProvider from "../sheet-provider";
import { Progress } from "../sheets/progress";
import { Button } from "../ui/button";
import { allowedOnPlatform, getStyle } from "./functions";
@@ -56,13 +54,6 @@ export const Cta = ({ actions, style = {}, color, inline }) => {
/>
)
});
} else if (item.type === "force-sync") {
eSendEvent(eCloseSheet);
await sleep(300);
Progress.present();
Sync.run("global", true, true, () => {
eSendEvent(eCloseSheet);
});
}
};
return (

View File

@@ -18,10 +18,15 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React, { useCallback, useEffect, useRef } from "react";
import { AppStateStatus, Platform, TextInput, View } from "react-native";
import {
AppStateStatus,
Platform,
TextInput,
useWindowDimensions,
View
} from "react-native";
//@ts-ignore
import { useThemeColors } from "@notesnook/theme";
import { enabled } from "react-native-privacy-snapshot";
import { DatabaseLogger } from "../../common/database";
import {
decrypt,
@@ -34,17 +39,20 @@ import {
import { MMKV } from "../../common/database/mmkv";
import { useAppState } from "../../hooks/use-app-state";
import BiometricService from "../../services/biometrics";
import { ToastManager } from "../../services/event-manager";
import SettingsService from "../../services/settings";
import { useSettingStore } from "../../stores/use-setting-store";
import { useUserStore } from "../../stores/use-user-store";
import { NotesnookModule } from "../../utils/notesnook-module";
import { SIZE } from "../../utils/size";
import { Toast } from "../toast";
import { Button } from "../ui/button";
import { IconButton } from "../ui/icon-button";
import Input from "../ui/input";
import Seperator from "../ui/seperator";
import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
const getUser = () => {
const user = MMKV.getString("user");
@@ -85,6 +93,7 @@ const AppLockedOverlay = () => {
const appState = useAppState();
const lastAppState = useRef<AppStateStatus>(appState);
const biometricUnlockAwaitingUserInput = useRef(false);
const { height } = useWindowDimensions();
const keyboardType = useSettingStore(
(state) => state.settings.applockKeyboardType
);
@@ -119,7 +128,6 @@ const AppLockedOverlay = () => {
);
if (unlocked) {
lockApp(false);
enabled(false);
password.current = undefined;
}
biometricUnlockAwaitingUserInput.current = false;
@@ -146,8 +154,13 @@ const AppLockedOverlay = () => {
}
lockApp(false);
enabled(false);
password.current = undefined;
} else {
ToastManager.show({
heading: `Invalid ${keyboardType === "numeric" ? "pin" : "password"}`,
type: "error",
context: "local"
});
}
} catch (e) {
console.error(e);
@@ -155,10 +168,6 @@ const AppLockedOverlay = () => {
};
useEffect(() => {
if (appState === "active") {
enabled(false);
}
const prevState = lastAppState.current;
lastAppState.current = appState;
@@ -184,31 +193,28 @@ const AppLockedOverlay = () => {
DatabaseLogger.info("Biometric unlock request");
onUnlockAppRequested();
}
enabled(false);
} else {
SettingsService.appEnteredBackground();
if (
SettingsService.get().privacyScreen ||
SettingsService.getProperty("appLockEnabled")
) {
enabled(true);
}
}
}, [appState, onUnlockAppRequested, appLocked]);
return appLocked ? (
<View
<KeyboardAwareScrollView
style={{
backgroundColor: colors.primary.background,
width: "100%",
height: "100%",
position: "absolute",
zIndex: 999,
justifyContent: "center"
zIndex: 999
}}
contentContainerStyle={{
justifyContent: "center",
minHeight: height
}}
keyboardDismissMode="interactive"
keyboardShouldPersistTaps="handled"
>
<Toast context="local" />
<View
style={{
flex: 1,
@@ -321,7 +327,7 @@ const AppLockedOverlay = () => {
</View>
</View>
</View>
</View>
</KeyboardAwareScrollView>
) : null;
};

View File

@@ -56,6 +56,7 @@ import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
import { useTabStore } from "../../screens/editor/tiptap/use-tab-store";
import { editorController } from "../../screens/editor/tiptap/utils";
import SheetProvider from "../sheet-provider";
const Actions = ({
attachment,
@@ -117,12 +118,14 @@ const Actions = ({
setLoading({
name: "Run file check"
});
const res = await filesystem.checkAttachment(attachment.hash);
if (res.failed) {
db.attachments.markAsFailed(attachment.id, res.failed);
setFailed(res.failed);
const result = await filesystem.checkAttachment(attachment.hash);
if (!result) return;
if (result.failed) {
db.attachments.markAsFailed(attachment.id, result.failed);
setFailed(result.failed);
ToastManager.show({
heading: "File check failed with error: " + res.failed,
heading: "File check failed with error: " + result.failed,
type: "error",
context: "local"
});
@@ -218,6 +221,7 @@ const Actions = ({
}}
>
<Dialog context={contextId} />
<SheetProvider context={contextId} />
<View
style={{
borderBottomWidth: 1,
@@ -238,36 +242,20 @@ const Actions = ({
style={{
flexDirection: "row",
marginBottom: 10,
paddingHorizontal: 12
paddingHorizontal: 12,
marginTop: 6,
gap: 10
}}
>
<Paragraph
size={SIZE.xs}
style={{
marginRight: 10
}}
color={colors.secondary.paragraph}
>
{attachment.type}
<Paragraph size={SIZE.xs} color={colors.secondary.paragraph}>
{attachment.mimeType}
</Paragraph>
<Paragraph
style={{
marginRight: 10
}}
size={SIZE.xs}
color={colors.secondary.paragraph}
>
<Paragraph size={SIZE.xs} color={colors.secondary.paragraph}>
{formatBytes(attachment.size)}
</Paragraph>
{notes.length ? (
<Paragraph
style={{
marginRight: 10
}}
size={SIZE.xs}
color={colors.secondary.paragraph}
>
<Paragraph size={SIZE.xs} color={colors.secondary.paragraph}>
{notes.length} note
{notes.length > 1 ? "s" : ""}
</Paragraph>
@@ -366,7 +354,7 @@ const Actions = ({
{failed ? (
<Notice
type="alert"
text={`File check failed with error: ${attachment.failed} Try reuploading the file to fix the issue.`}
text={`File check failed: ${failed} Try reuploading the file to fix the issue.`}
size="small"
/>
) : null}

View File

@@ -122,10 +122,11 @@ export const AttachmentDialog = ({ note }: { note?: Note }) => {
const attachment = (await attachments.item(i))?.item;
if (!attachment) continue;
const result = await filesystem.checkAttachment(attachment.hash);
if (!result) return;
if (result.failed) {
await db.attachments.markAsFailed(attachment.hash, result.failed);
} else {
await db.attachments.markAsFailed(attachment.id, undefined);
await db.attachments.markAsFailed(attachment.id);
}
}
refresh();
@@ -177,7 +178,7 @@ export const AttachmentDialog = ({ note }: { note?: Note }) => {
case "audio":
items = note
? db.attachments.ofNote(note.id, "audio")
: db.attachments.all;
: db.attachments.audios;
break;
case "documents":
items = note
@@ -355,6 +356,7 @@ export const AttachmentDialog = ({ note }: { note?: Note }) => {
AttachmentDialog.present = (note?: Note) => {
presentSheet({
component: () => <AttachmentDialog note={note} />
component: () => <AttachmentDialog note={note} />,
keyboardHandlerDisabled: true
});
};

View File

@@ -68,7 +68,8 @@ export const ChangePassword = () => {
setLoading(true);
try {
const result = await BackupService.run(false, "change-password-dialog");
if (!result) throw new Error("Failed to create backup");
if (result.error)
throw new Error(`Failed to create backup: ${result.error}`);
await db.user.clearSessions();
await db.user.changePassword(oldPassword.current, password.current);

View File

@@ -17,12 +17,16 @@ 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 { useThemeColors } from "@notesnook/theme";
import React, { useEffect, useState } from "react";
import { TouchableOpacity, View, useWindowDimensions } from "react-native";
import { SheetManager } from "react-native-actions-sheet";
import { DDS } from "../../services/device-detection";
import { eSendEvent } from "../../services/event-manager";
import { useThemeColors } from "@notesnook/theme";
import Sync from "../../services/sync";
import { useSettingStore } from "../../stores/use-setting-store";
import { useUserStore } from "../../stores/use-user-store";
import { eUserLoggedIn } from "../../utils/events";
import { SIZE } from "../../utils/size";
import { sleep } from "../../utils/time";
import SheetProvider from "../sheet-provider";
@@ -34,11 +38,6 @@ import Paragraph from "../ui/typography/paragraph";
import { hideAuth } from "./common";
import { ForgotPassword } from "./forgot-password";
import { useLogin } from "./use-login";
import { useSettingStore } from "../../stores/use-setting-store";
import { eUserLoggedIn } from "../../utils/events";
import { useUserStore } from "../../stores/use-user-store";
import Sync from "../../services/sync";
import { Notice } from "../ui/notice";
const LoginSteps = {
emailAuth: 1,
@@ -67,7 +66,7 @@ export const Login = ({ changeMode }) => {
Progress.present();
setTimeout(() => {
if (!useUserStore.getState().syncing) {
Sync.run("global", false, true);
Sync.run("global", false, "full");
}
}, 5000);
});
@@ -184,7 +183,11 @@ export const Login = ({ changeMode }) => {
defaultValue={email.current}
editable={step === LoginSteps.emailAuth && !loading}
onSubmit={() => {
passwordInputRef.current?.focus();
if (step === LoginSteps.emailAuth) {
login();
} else {
passwordInputRef.current?.focus();
}
}}
/>
@@ -243,6 +246,7 @@ export const Login = ({ changeMode }) => {
width: 250,
borderRadius: 100
}}
height={50}
fontSize={SIZE.md}
type="accent"
title={!loading ? "Continue" : null}

View File

@@ -112,7 +112,11 @@ export const SessionExpired = () => {
if (!res) throw new Error("no token found");
if (db.tokenManager._isTokenExpired(res))
throw new Error("token expired");
Sync.run("global", false, true, async (complete) => {
const key = await db.user.getEncryptionKey();
if (!key) throw new Error("No encryption key found.");
Sync.run("global", false, "full", async (complete) => {
if (!complete) {
let user = await db.user.getUser();
if (!user) return;
@@ -127,7 +131,6 @@ export const SessionExpired = () => {
setVisible(false);
});
} catch (e) {
console.log(e);
let user = await db.user.getUser();
if (!user) return;
email.current = user.email;

View File

@@ -35,6 +35,7 @@ import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
import { hideAuth } from "./common";
import { useSettingStore } from "../../stores/use-setting-store";
import SettingsService from "../../services/settings";
export const Signup = ({ changeMode, trial }) => {
const { colors } = useThemeColors();
@@ -77,6 +78,7 @@ export const Signup = ({ changeMode, trial }) => {
clearMessage();
setEmailVerifyMessage();
hideAuth();
SettingsService.setProperty("encryptedBackup", true);
await sleep(300);
if (trial) {
PremiumService.sheet(null, null, true);

View File

@@ -37,6 +37,7 @@ import Seperator from "../ui/seperator";
import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
import { useCallback } from "react";
import { ScrollView } from "react-native-actions-sheet";
const TwoFactorVerification = ({ onMfaLogin, mfaInfo }) => {
const { colors } = useThemeColors();
@@ -143,7 +144,10 @@ const TwoFactorVerification = ({ onMfaLogin, mfaInfo }) => {
}, [currentMethod.method, mfaInfo.token, seconds, sending, start]);
return (
<View>
<ScrollView
keyboardShouldPersistTaps="handled"
keyboardDismissMode="interactive"
>
<View
style={{
alignItems: "center",
@@ -214,6 +218,7 @@ const TwoFactorVerification = ({ onMfaLogin, mfaInfo }) => {
code.current = value;
//onNext();
}}
onSubmitEditing={onNext}
caretHidden
inputStyle={{
fontSize: SIZE.lg,
@@ -225,6 +230,7 @@ const TwoFactorVerification = ({ onMfaLogin, mfaInfo }) => {
keyboardType={
currentMethod.method === "recoveryCode" ? "default" : "numeric"
}
enablesReturnKeyAutomatically
containerStyle={{
height: 60,
borderWidth: 0,
@@ -297,7 +303,7 @@ const TwoFactorVerification = ({ onMfaLogin, mfaInfo }) => {
</>
)}
</View>
</View>
</ScrollView>
);
};

View File

@@ -83,7 +83,7 @@ export const useLogin = (onFinishLogin, sessionExpired = false) => {
setLoading(false);
setTimeout(() => {
passwordInputRef.current?.focus();
}, 1);
}, 500);
callback && callback(true);
}
callback && callback(false);

View File

@@ -23,6 +23,7 @@ import { AnnouncementDialog } from "../announcements";
import AuthModal from "../auth/auth-modal";
import { SessionExpired } from "../auth/session-expired";
import { Dialog } from "../dialog";
import { AppLockPassword } from "../dialogs/applock-password";
import JumpToSectionDialog from "../dialogs/jump-to-section";
import { LoadingDialog } from "../dialogs/loading";
import PDFPreview from "../dialogs/pdf-preview";
@@ -35,8 +36,7 @@ import { Expiring } from "../premium/expiring";
import SheetProvider from "../sheet-provider";
import RateAppSheet from "../sheets/rate-app";
import RecoveryKeySheet from "../sheets/recovery-key";
import RestoreDataSheet from "../sheets/restore-data";
import { AppLockPassword } from "../dialogs/applock-password";
import Progress from "../dialogs/progress";
const DialogProvider = () => {
const { colors } = useThemeColors();
@@ -52,7 +52,6 @@ const DialogProvider = () => {
<RecoveryKeySheet colors={colors} />
<SheetProvider />
<SheetProvider context="sync_progress" />
<RestoreDataSheet />
<ResultDialog />
<VaultDialog colors={colors} />
<RateAppSheet />
@@ -62,6 +61,7 @@ const DialogProvider = () => {
<SessionExpired />
<PDFPreview />
<JumpToSectionDialog />
<Progress />
</>
);
};

View File

@@ -32,21 +32,29 @@ const DialogContainer = ({
}: ViewProps & {
width?: any;
height?: any;
noBorder?: boolean;
}) => {
const { colors } = useThemeColors();
return (
<View
{...restProps}
style={{
...getElevationStyle(5),
width: width || DDS.isTab ? 500 : "85%",
maxHeight: height || 450,
borderRadius: 10,
backgroundColor: colors.primary.background,
paddingTop: 12,
...getContainerBorder(colors.secondary.background, 0.8, 0.05)
}}
style={[
style,
{
width: width || DDS.isTab ? 500 : "85%",
maxHeight: height || 450,
borderRadius: 10,
backgroundColor: colors.primary.background,
paddingTop: 12
},
restProps?.noBorder
? {}
: {
...getElevationStyle(5),
...getContainerBorder(colors.secondary.background, 0.8, 0.05)
}
]}
/>
);
};

View File

@@ -25,7 +25,7 @@ type DialogInfo = {
paragraph?: string;
positiveText?: string;
negativeText?: string;
positivePress?: (value: any) => void;
positivePress?: (...args: any[]) => void;
onClose?: () => void;
positiveType?:
| "transparent"
@@ -44,6 +44,16 @@ type DialogInfo = {
// eslint-disable-next-line @typescript-eslint/ban-types
context: "global" | "local" | (string & {});
secureTextEntry?: boolean;
keyboardType?: string;
check?: {
info: string;
type?: string;
defaultValue?: boolean;
};
notice: {
text: string;
type: "alert" | "information";
};
};
export function presentDialog(data: Partial<DialogInfo>): void {

View File

@@ -37,6 +37,7 @@ import DialogHeader from "./dialog-header";
import { useCallback } from "react";
import { Button } from "../ui/button";
import { getContainerBorder } from "../../utils/colors";
import { Notice } from "../ui/notice";
export const Dialog = ({ context = "global" }) => {
const { colors } = useThemeColors();
@@ -62,7 +63,8 @@ export const Dialog = ({ context = "global" }) => {
disableBackdropClosing: false,
check: {
info: "Check",
type: "transparent"
type: "transparent",
defaultValue: false
}
});
@@ -86,7 +88,7 @@ export const Dialog = ({ context = "global" }) => {
if (!data.context) data.context = "global";
if (data.context !== context) return;
setDialogInfo(data);
setChecked(false);
setChecked(data.check?.defaultValue);
values.current.inputValue = data.defaultValue;
setVisible(true);
},
@@ -174,11 +176,25 @@ export const Dialog = ({ context = "global" }) => {
onSubmit={onPressPositive}
returnKeyLabel="Done"
returnKeyType="done"
keyboardType={dialogInfo.keyboardType || "default"}
placeholder={dialogInfo.inputPlaceholder}
/>
</View>
) : null}
{dialogInfo?.notice ? (
<View
style={{
paddingHorizontal: 12
}}
>
<Notice
type={dialogInfo.notice.type || "information"}
text={dialogInfo.notice.text}
/>
</View>
) : null}
{dialogInfo.check ? (
<>
<Button
@@ -197,7 +213,7 @@ export const Dialog = ({ context = "global" }) => {
iconSize={20}
width="100%"
title={dialogInfo.check.info}
type={checked ? dialogInfo.check.type || "selected" : "plain"}
type={checked ? dialogInfo.check.type || "plain" : "plain"}
/>
</>
) : null}

View File

@@ -19,6 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { useThemeColors } from "@notesnook/theme";
import React, { useEffect, useRef, useState } from "react";
import { TextInput, View } from "react-native";
import { db } from "../../../common/database";
import {
clearAppLockVerificationCipher,
setAppLockVerificationCipher,
@@ -44,6 +45,7 @@ import BaseDialog from "../../dialog/base-dialog";
import DialogButtons from "../../dialog/dialog-buttons";
import DialogHeader from "../../dialog/dialog-header";
import { Toast } from "../../toast";
import { Button } from "../../ui/button";
import { IconButton } from "../../ui/icon-button";
import Input from "../../ui/input";
import Seperator from "../../ui/seperator";
@@ -66,6 +68,7 @@ export const AppLockPassword = () => {
confirmPassword?: string;
}>({});
const [secureTextEntry, setSecureTextEntry] = useState(true);
const [accountPass, setAccountPass] = useState(false);
useEffect(() => {
const subs = [
@@ -73,6 +76,7 @@ export const AppLockPassword = () => {
eOpenAppLockPasswordDialog,
(mode: "create" | "change" | "remove") => {
setMode(mode);
setAccountPass(false);
setVisible(true);
}
),
@@ -126,7 +130,9 @@ export const AppLockPassword = () => {
mode === "change"
? `Change app lock ${keyboardType}`
: mode === "remove"
? `Remove app lock ${keyboardType}`
? `Enter ${
accountPass ? "account password" : `app lock ${keyboardType}`
} to remove ${keyboardType}`
: `Set up a custom app lock ${keyboardType} to unlock the app`
}
icon="shield"
@@ -169,33 +175,39 @@ export const AppLockPassword = () => {
confirmPasswordInputRef.current?.focus();
}}
defaultValue={values.current.password}
keyboardType={keyboardType === "pin" ? "number-pad" : "default"}
keyboardType={
keyboardType === "pin" && !accountPass ? "number-pad" : "default"
}
autoComplete="password"
returnKeyLabel={mode !== "remove" ? "Next" : "Remove"}
returnKeyType={mode !== "remove" ? "next" : "done"}
secureTextEntry={secureTextEntry}
buttonLeft={
<IconButton
name={keyboardType === "password" ? "numeric" : "keyboard"}
onPress={() => {
setKeyboardType(
keyboardType === "password" ? "pin" : "password"
);
setSecureTextEntry(false);
setImmediate(() => {
setSecureTextEntry(true);
});
}}
style={{
width: 25,
height: 25,
marginRight: 5
}}
size={SIZE.lg}
/>
accountPass ? null : (
<IconButton
name={keyboardType === "password" ? "numeric" : "keyboard"}
onPress={() => {
setKeyboardType(
keyboardType === "password" ? "pin" : "password"
);
setSecureTextEntry(false);
setImmediate(() => {
setSecureTextEntry(true);
});
}}
style={{
width: 25,
height: 25,
marginRight: 5
}}
size={SIZE.lg}
/>
)
}
placeholder={
mode === "change"
accountPass
? "Account password"
: mode === "change"
? `New ${keyboardType}`
: `${keyboardType === "pin" ? "Pin" : "Password"}`
}
@@ -222,6 +234,36 @@ export const AppLockPassword = () => {
placeholder={`Confirm ${keyboardType}`}
/>
) : null}
{mode === "remove" ? (
<>
<Button
icon={
accountPass ? "checkbox-marked" : "checkbox-blank-outline"
}
onPress={() => {
setSecureTextEntry(false);
setAccountPass(!accountPass);
setTimeout(() => {
setSecureTextEntry(true);
});
}}
iconSize={SIZE.lg}
type="plain"
iconColor={
accountPass ? colors.primary.accent : colors.primary.icon
}
title="Use account password instead"
style={{
width: "100%",
alignSelf: "flex-start",
justifyContent: "flex-start",
paddingHorizontal: 0,
height: 30
}}
/>
</>
) : null}
</View>
<DialogButtons
@@ -249,7 +291,8 @@ export const AppLockPassword = () => {
);
return;
}
await setAppLockVerificationCipher(values.current.password);
const password = values.current.password;
setAppLockVerificationCipher(password);
SettingsService.setProperty("appLockHasPasswordSecurity", true);
} else if (mode === "change") {
if (
@@ -277,7 +320,6 @@ export const AppLockPassword = () => {
);
return;
}
const isCurrentPasswordCorrect = await validateAppLockPassword(
values.current.currentPassword
);
@@ -293,8 +335,10 @@ export const AppLockPassword = () => {
return;
}
const password = values.current.password;
await clearAppLockVerificationCipher();
SettingsService.setProperty("appLockHasPasswordSecurity", true);
await setAppLockVerificationCipher(values.current.password);
await setAppLockVerificationCipher(password);
} else if (mode === "remove") {
if (!values.current.password) {
ToastManager.error(
@@ -305,14 +349,18 @@ export const AppLockPassword = () => {
return;
}
const isCurrentPasswordCorrect = await validateAppLockPassword(
values.current.password
);
const isCurrentPasswordCorrect = accountPass
? await db.user.verifyPassword(values.current.password)
: await validateAppLockPassword(values.current.password);
if (!isCurrentPasswordCorrect) {
ToastManager.error(
new Error(
`${keyboardType === "pin" ? "Pin" : "Password"} incorrect`
accountPass
? "Account password incorrect"
: `${
keyboardType === "pin" ? "Pin" : "Password"
} incorrect`
),
undefined,
"local"
@@ -342,7 +390,9 @@ export const AppLockPassword = () => {
close();
}}
positiveTitle="Save"
positiveTitle={
mode === "remove" ? "Remove" : mode === "change" ? "Change" : "Save"
}
negativeTitle="Cancel"
positiveType="transparent"
loading={false}

View File

@@ -17,8 +17,14 @@ 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 React, { useState } from "react";
import { Image, ScrollView, TouchableOpacity, View } from "react-native";
import { ImagePickerResponse } from "react-native-image-picker";
import {
Image,
Platform,
ScrollView,
TouchableOpacity,
View
} from "react-native";
import { Image as ImageType } from "react-native-image-crop-picker";
import { useThemeColors } from "../../../../../../packages/theme/dist";
import { presentSheet } from "../../../services/event-manager";
import { SIZE } from "../../../utils/size";
@@ -32,7 +38,7 @@ export default function AttachImage({
onAttach,
close
}: {
response: ImagePickerResponse;
response: ImageType[];
onAttach: ({ compress }: { compress: boolean }) => void;
close: ((ctx?: string | undefined) => void) | undefined;
}) {
@@ -58,14 +64,17 @@ export default function AttachImage({
}}
>
<Paragraph style={{ color: colors.primary.paragraph, marginBottom: 6 }}>
Attaching {response.assets?.length} image(s):
Attaching {response?.length} image(s):
</Paragraph>
<ScrollView horizontal>
{response.assets?.map((item) => (
<TouchableOpacity key={item.fileName} activeOpacity={0.9}>
{response?.map?.((item) => (
<TouchableOpacity key={item.filename} activeOpacity={0.9}>
<Image
source={{
uri: item.uri
uri:
Platform.OS === "ios"
? item.sourceURL || item.path
: item.path
}}
style={{
width: 100,
@@ -142,7 +151,7 @@ export default function AttachImage({
<Button
title={`${
(response.assets?.length || 0) > 1 ? "Attach Images" : "Attach Image"
(response?.length || 0) > 1 ? "Attach Images" : "Attach Image"
}`}
type="accent"
width="100%"
@@ -156,10 +165,16 @@ export default function AttachImage({
);
}
AttachImage.present = (response: ImagePickerResponse) => {
return new Promise((resolve) => {
AttachImage.present = (response: ImageType[], context?: string) => {
return new Promise<
| {
compress: boolean;
}
| undefined
>((resolve) => {
let resolved = false;
presentSheet({
context: context,
component: (ref, close, update) => (
<AttachImage
response={response}

View File

@@ -44,6 +44,7 @@ import { ProgressBarComponent } from "../../ui/svg/lazy";
import Paragraph from "../../ui/typography/paragraph";
import { sleep } from "../../../utils/time";
import { MMKV } from "../../../common/database/mmkv";
import { deleteCacheFileByPath } from "../../../common/filesystem/io";
const WIN_WIDTH = Dimensions.get("window").width;
const WIN_HEIGHT = Dimensions.get("window").height;
@@ -124,6 +125,7 @@ const PDFPreview = () => {
);
const close = () => {
deleteCacheFileByPath(pdfSource);
setPDFSource(null);
setVisible(false);
setPassword("");

View File

@@ -0,0 +1,198 @@
/*
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 { useThemeColors } from "@notesnook/theme";
import React, { useEffect } from "react";
import { View } from "react-native";
import { eSendEvent, eSubscribeEvent } from "../../../services/event-manager";
import { SIZE } from "../../../utils/size";
import { Dialog } from "../../dialog";
import BaseDialog from "../../dialog/base-dialog";
import DialogContainer from "../../dialog/dialog-container";
import { Button } from "../../ui/button";
import { ProgressBarComponent } from "../../ui/svg/lazy";
import Heading from "../../ui/typography/heading";
import Paragraph from "../../ui/typography/paragraph";
export type ProgressOptions = {
progress?: string;
cancelCallback?: () => void;
title?: string;
paragraph?: string;
fillBackground?: boolean;
canHideProgress?: boolean;
};
export const PROGRESS_EVENTS = {
start: "startProgress",
end: "endProgress",
update: "updateProgress"
};
export default function Progress() {
const { colors } = useThemeColors();
const [progress, setProgress] = React.useState<string | undefined>();
const [visible, setVisible] = React.useState(false);
const cancelCallback = React.useRef<() => void>();
const [data, setData] = React.useState<{
title?: string;
paragraph?: string;
fillBackground?: boolean;
canHideProgress?: boolean;
}>();
useEffect(() => {
const events = [
eSubscribeEvent(PROGRESS_EVENTS.start, (options: ProgressOptions) => {
setProgress(options.progress);
cancelCallback.current = options.cancelCallback;
console.log("options", options.fillBackground);
setData({
title: options.title,
paragraph: options.paragraph,
fillBackground: options.fillBackground,
canHideProgress: options.canHideProgress
});
setVisible(true);
}),
eSubscribeEvent(PROGRESS_EVENTS.end, () => {
setProgress(undefined);
setVisible(false);
setData(undefined);
cancelCallback.current?.();
cancelCallback.current = undefined;
}),
eSubscribeEvent(PROGRESS_EVENTS.update, (options: ProgressOptions) => {
setProgress(options.progress);
if (options.cancelCallback) {
cancelCallback.current = options.cancelCallback;
}
const data: ProgressOptions = {};
if (options.title) data.title = options.title;
if (options.paragraph) data.paragraph = options.paragraph;
if (options.fillBackground)
data.fillBackground = options.fillBackground;
setData((current) => {
return {
...current,
...data
};
});
})
];
return () => {
events.forEach((event) => event?.unsubscribe());
cancelCallback.current = undefined;
};
}, []);
return !visible ? null : (
<BaseDialog
background={data?.fillBackground ? colors.primary.background : undefined}
visible
>
<DialogContainer
style={{
paddingHorizontal: 12,
paddingBottom: 10
}}
noBorder={data?.fillBackground ? true : false}
>
<Dialog context="local" />
<View
style={{
justifyContent: "center",
alignItems: "center",
paddingHorizontal: 12,
gap: 10,
paddingBottom: 20
}}
>
<Heading
style={{
textAlign: "center"
}}
color={colors.primary.paragraph}
size={SIZE.lg}
>
{data?.title}
</Heading>
<Paragraph
style={{
textAlign: "center"
}}
color={colors.secondary.paragraph}
>
{progress ? progress : data?.paragraph}
</Paragraph>
<View
style={{
flexDirection: "row",
width: 100,
paddingVertical: 12
}}
>
<ProgressBarComponent
height={5}
width={100}
animated={true}
useNativeDriver
indeterminate
indeterminateAnimationDuration={2000}
unfilledColor={colors.secondary.background}
color={colors.primary.accent}
borderWidth={0}
/>
</View>
{data?.canHideProgress ? null : (
<Button
title={cancelCallback.current ? "Cancel" : "Hide"}
type="secondaryAccented"
onPress={() => {
if (cancelCallback.current) {
cancelCallback.current?.();
}
setVisible(false);
setProgress(undefined);
setData(undefined);
}}
width="100%"
/>
)}
</View>
</DialogContainer>
</BaseDialog>
);
}
export function startProgress(options: ProgressOptions) {
eSendEvent(PROGRESS_EVENTS.start, options);
}
export function endProgress() {
eSendEvent(PROGRESS_EVENTS.end);
}
export function updateProgress(options: ProgressOptions) {
eSendEvent(PROGRESS_EVENTS.update, options);
}

View File

@@ -586,7 +586,7 @@ export class VaultDialog extends Component {
}
async _copyNote(note) {
Clipboard.setString(await convertNoteToText(note));
Clipboard.setString((await convertNoteToText(note, true)) || "");
ToastManager.show({
heading: "Note copied",
type: "success",
@@ -602,7 +602,7 @@ export class VaultDialog extends Component {
await Share.open({
heading: "Share note",
failOnCancel: false,
message: await convertNoteToText(note)
message: (await convertNoteToText(note)) || ""
});
} catch (e) {
console.error(e);

View File

@@ -23,10 +23,7 @@ import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
import { Dialog } from "../dialog";
import { Issue } from "../sheets/github/issue";
const error = (
stack: string,
component: string
) => `Please let us know what happened. What steps we can take to reproduce the issue here.
const error = (stack: string, component: string) => `
_______________________________
Stacktrace: In ${component}::${stack}`;
@@ -39,9 +36,9 @@ class ExceptionHandler extends React.Component<{
error: Error | null;
hasError: boolean;
} = {
hasError: false,
error: null
};
hasError: false,
error: null
};
static getDerivedStateFromError(error: Error) {
return { hasError: true, error: error };
}

View File

@@ -19,10 +19,12 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import Sodium from "@ammarahmed/react-native-sodium";
import dataurl from "@notesnook/core/dist/utils/dataurl";
import type { ImageAttributes } from "@notesnook/editor/dist/extensions/image/index";
import { useThemeColors } from "@notesnook/theme";
import React, { useEffect, useState } from "react";
import React, { useEffect, useRef, useState } from "react";
import { Platform, View } from "react-native";
import ImageViewer from "react-native-image-zoom-viewer";
import { db } from "../../common/database";
import downloadAttachment from "../../common/filesystem/download-attachment";
import { cacheDir } from "../../common/filesystem/utils";
import {
@@ -32,13 +34,13 @@ import {
import BaseDialog from "../dialog/base-dialog";
import { IconButton } from "../ui/icon-button";
import { ProgressBarComponent } from "../ui/svg/lazy";
import type { ImageAttributes } from "@notesnook/editor/dist/extensions/image/index";
const ImagePreview = () => {
const { colors } = useThemeColors("dialog");
const [visible, setVisible] = useState(false);
const [image, setImage] = useState<string>();
const [loading, setLoading] = useState(false);
const imageRef = useRef<ImageAttributes>();
useEffect(() => {
eSubscribeEvent("ImagePreview", open);
@@ -48,6 +50,7 @@ const ImagePreview = () => {
}, []);
const open = async (image: ImageAttributes) => {
imageRef.current = image;
setVisible(true);
setLoading(true);
setTimeout(async () => {
@@ -60,6 +63,9 @@ const ImagePreview = () => {
type: "base64",
uri: ""
});
if (imageRef.current) {
imageRef.current.hash = hash;
}
}
if (!hash) return;
//@ts-ignore // FIX ME
@@ -80,7 +86,13 @@ const ImagePreview = () => {
return (
visible && (
<BaseDialog animation="slide" visible={true} onRequestClose={close}>
<BaseDialog
background="black"
animation="slide"
visible={true}
onRequestClose={close}
transparent
>
<View
style={{
width: "100%",
@@ -101,6 +113,21 @@ const ImagePreview = () => {
color={colors.primary.accent}
borderColor="transparent"
/>
<IconButton
onPress={() => {
if (imageRef.current?.hash) {
db.fs().cancel(imageRef.current?.hash);
}
close();
}}
style={{
position: "absolute",
top: Platform.OS === "android" ? 35 : 0,
right: 12
}}
color={colors.static.white}
name="close"
/>
</View>
) : (
<ImageViewer
@@ -117,13 +144,12 @@ const ImagePreview = () => {
width: "100%",
justifyContent: "flex-end",
alignItems: "center",
height: 80,
marginTop: 0,
paddingHorizontal: 12,
height: 50,
paddingHorizontal: 24,
position: "absolute",
zIndex: 999,
backgroundColor: "rgba(0,0,0,0.3)",
paddingTop: Platform.OS === "android" ? 30 : 0
marginTop: Platform.OS === "android" ? 30 : 0
}}
>
<IconButton
@@ -137,7 +163,7 @@ const ImagePreview = () => {
)}
imageUrls={[
{
url: image
url: image as string
}
]}
/>

View File

@@ -43,9 +43,6 @@ import { eSendEvent } from "../../services/event-manager";
const Intro = ({ navigation }) => {
const { colors } = useThemeColors();
const isTelemetryEnabled = useSettingStore(
(state) => state.settings.telemetry
);
const { width, height } = useWindowDimensions();
const deviceMode = useSettingStore((state) => state.deviceMode);
const insets = useGlobalSafeAreaInsets();
@@ -217,44 +214,6 @@ const Intro = ({ navigation }) => {
type="accent"
title="Get started"
/>
<TouchableOpacity
activeOpacity={1}
style={{
flexDirection: "row",
alignSelf: "center",
width: "90%",
marginBottom: 12,
paddingHorizontal: 12,
justifyContent: "center",
padding: 12,
maxWidth: 500
}}
onPress={() => {
SettingsService.set({ telemetry: !isTelemetryEnabled });
}}
>
<Icon
size={SIZE.md}
name={
isTelemetryEnabled ? "checkbox-marked" : "checkbox-blank-outline"
}
color={
isTelemetryEnabled ? colors.primary.accent : colors.primary.icon
}
/>
<Paragraph
style={{
flexShrink: 1,
marginLeft: 6
}}
size={SIZE.xs}
>
Help improve Notesnook by sending completely anonymized{" "}
<Heading size={SIZE.xs}>private analytics and bug reports.</Heading>
</Paragraph>
</TouchableOpacity>
</View>
</ScrollView>
);

View File

@@ -49,7 +49,8 @@ export const Card = ({ color }: { color?: string }) => {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: 0
paddingHorizontal: 0,
width: "100%"
}}
>
<View
@@ -91,7 +92,6 @@ export const Card = ({ color }: { color?: string }) => {
<View
style={{
marginLeft: 10,
flexShrink: 1,
marginRight: 10
}}
>

View File

@@ -80,7 +80,7 @@ export default function List(props: ListProps) {
const groupOptions = useGroupOptions(groupType);
const _onRefresh = async () => {
Sync.run("global", false, true, () => {
Sync.run("global", false, "full", () => {
props.onRefresh?.();
});
};

View File

@@ -21,10 +21,10 @@ import { useThemeColors } from "@notesnook/theme";
import React, { useEffect, useState } from "react";
import { View } from "react-native";
import { db } from "../../common/database";
import Editor from "../../screens/editor";
import { ReadonlyEditor } from "../../screens/editor/readonly-editor";
import { useTabStore } from "../../screens/editor/tiptap/use-tab-store";
import { editorController } from "../../screens/editor/tiptap/utils";
import { eSendEvent, ToastManager } from "../../services/event-manager";
import { ToastManager, eSendEvent } from "../../services/event-manager";
import Navigation from "../../services/navigation";
import { useSelectionStore } from "../../stores/use-selection-store";
import { useTrashStore } from "../../stores/use-trash-store";
@@ -34,7 +34,7 @@ import DialogHeader from "../dialog/dialog-header";
import { presentDialog } from "../dialog/functions";
import { Button } from "../ui/button";
import Paragraph from "../ui/typography/paragraph";
import { ReadonlyEditor } from "../../screens/editor/readonly-editor";
import { diff } from "diffblazer";
/**
*
@@ -121,12 +121,21 @@ export default function NotePreview({ session, content, note }) {
<ReadonlyEditor
editorId="historyPreview"
onLoad={async (loadContent) => {
if (content.data) {
const _note = note || (await db.notes.note(session?.noteId));
loadContent({
data: content.data,
id: _note.id
});
try {
if (content.data) {
const _note = note || (await db.notes.note(session?.noteId));
const currentContent = await db.content.get(_note.contentId);
loadContent({
data: diff(currentContent.data, content.data),
id: _note.id
});
}
} catch (e) {
ToastManager.error(
e,
"Failed to load history preview",
"local"
);
}
}}
/>

View File

@@ -167,7 +167,7 @@ export const Component = ({ close, promo }) => {
>
(
{Platform.OS === "android"
? pricing.product?.subscriptionOfferDetails[0].pricingPhases
? pricing.product?.subscriptionOfferDetails[0]?.pricingPhases
.pricingPhaseList?.[0].formattedPrice
: pricing.product?.localizedPrice}{" "}
/ mo)

View File

@@ -85,7 +85,7 @@ export const PricingItem = ({
>
{Platform.OS === "android"
? (product.data as RNIap.SubscriptionAndroid | undefined)
?.subscriptionOfferDetails[0].pricingPhases
?.subscriptionOfferDetails?.[0]?.pricingPhases
.pricingPhaseList?.[0]?.formattedPrice
: (product.data as RNIap.SubscriptionIOS | undefined)
?.localizedPrice}

View File

@@ -393,7 +393,7 @@ export const PricingPlans = ({
>
{Platform.OS === "android"
? (product.data as RNIap.SubscriptionAndroid)
?.subscriptionOfferDetails[0].pricingPhases
?.subscriptionOfferDetails[0]?.pricingPhases
.pricingPhaseList?.[0]?.formattedPrice
: (product.data as RNIap.SubscriptionIOS)
?.introductoryPrice ||

View File

@@ -19,7 +19,13 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { useThemeColors } from "@notesnook/theme";
import React, { Fragment, useState } from "react";
import { ActivityIndicator, Platform, StyleSheet, View } from "react-native";
import {
ActivityIndicator,
Linking,
Platform,
StyleSheet,
View
} from "react-native";
import FileViewer from "react-native-file-viewer";
import Share from "react-native-share";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
@@ -29,14 +35,12 @@ import { requestInAppReview } from "../../../services/app-review";
import {
PresentSheetOptions,
ToastManager,
eSendEvent,
presentSheet
} from "../../../services/event-manager";
import Exporter from "../../../services/exporter";
import PremiumService from "../../../services/premium";
import { useUserStore } from "../../../stores/use-user-store";
import { getElevationStyle } from "../../../utils/elevation";
import { eCloseSheet } from "../../../utils/events";
import { SIZE, ph, pv } from "../../../utils/size";
import { sleep } from "../../../utils/time";
import { Dialog } from "../../dialog";
@@ -65,6 +69,7 @@ const ExportNotesSheet = ({
filePath: string;
name: string;
type: string;
fileDir: string;
}
| undefined
>();
@@ -295,7 +300,9 @@ const ExportNotesSheet = ({
successfully as {result?.fileName}
</Paragraph>
<Button
title="Open"
title={
Platform.OS === "android" ? "Open file location" : "Open"
}
type="accent"
width={250}
fontSize={SIZE.md}
@@ -305,20 +312,23 @@ const ExportNotesSheet = ({
}}
onPress={async () => {
if (!result?.filePath) return;
eSendEvent(eCloseSheet);
await sleep(500);
FileViewer.open(result?.filePath, {
showOpenWithDialog: true,
showAppsSuggestions: true
}).catch((e) => {
console.log(e);
ToastManager.show({
heading: "Cannot open",
message: `No application found to open ${result.name} file.`,
type: "success",
context: "local"
if (Platform.OS === "android") {
Linking.openURL(result.fileDir).catch((e) => {
ToastManager.error(e as Error);
});
});
} else {
FileViewer.open(result?.filePath, {
showOpenWithDialog: true,
showAppsSuggestions: true
}).catch((e) => {
ToastManager.show({
heading: "Cannot open",
message: `No application found to open ${result.name} file.`,
type: "success",
context: "local"
});
});
}
}}
/>
<Button
@@ -331,10 +341,10 @@ const ExportNotesSheet = ({
borderRadius: 100
}}
onPress={async () => {
if (!result?.filePath) return;
if (!result) return;
if (Platform.OS === "ios") {
Share.open({
url: result.filePath
url: result?.fileDir + result.fileName
}).catch(console.log);
} else {
FileViewer.open(result.filePath, {
@@ -347,7 +357,7 @@ const ExportNotesSheet = ({
/>
<Button
title="Export in another format"
type="secondaryAccented"
type="inverted"
width={250}
fontSize={SIZE.md}
style={{

View File

@@ -18,35 +18,33 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { Debug } from "@notesnook/core/dist/api/debug";
import { getModel, getBrand, getSystemVersion } from "react-native-device-info";
import { useThemeColors } from "@notesnook/theme";
import Clipboard from "@react-native-clipboard/clipboard";
import React, { useRef, useState } from "react";
import { Linking, Platform, Text, TextInput, View } from "react-native";
import { getVersion } from "react-native-device-info";
import { useStoredRef } from "../../../hooks/use-stored-ref";
import { ToastManager, eSendEvent } from "../../../services/event-manager";
import { ToastManager } from "../../../services/event-manager";
import PremiumService from "../../../services/premium";
import { useUserStore } from "../../../stores/use-user-store";
import { eCloseSheet } from "../../../utils/events";
import { openLinkInBrowser } from "../../../utils/functions";
import { SIZE } from "../../../utils/size";
import { sleep } from "../../../utils/time";
import DialogHeader from "../../dialog/dialog-header";
import { presentDialog } from "../../dialog/functions";
import { Button } from "../../ui/button";
import Seperator from "../../ui/seperator";
import Heading from "../../ui/typography/heading";
import Paragraph from "../../ui/typography/paragraph";
export const Issue = ({ defaultTitle, defaultBody, issueTitle }) => {
const { colors } = useThemeColors();
const body = useStoredRef("issueBody", defaultBody);
const body = useStoredRef("issueBody");
const title = useStoredRef("issueTitle", defaultTitle);
const [done, setDone] = useState(false);
const user = useUserStore((state) => state.user);
const [loading, setLoading] = useState(false);
const bodyRef = useRef();
const initialLayout = useRef(false);
const issueUrl = useRef();
const onPress = async () => {
if (loading) return;
@@ -56,57 +54,24 @@ export const Issue = ({ defaultTitle, defaultBody, issueTitle }) => {
try {
setLoading(true);
let issue_url = await Debug.report({
issueUrl.current = await Debug.report({
title: title.current,
body:
body.current +
`\n${defaultBody || ""}` +
`\n_______________
**Device information:**
App version: ${getVersion()}
Platform: ${Platform.OS}
Model: ${Platform.constants.Brand || ""}-${Platform.constants.Model || ""}-${
Platform.constants.Version || ""
}
Device: ${getBrand() || ""}-${getModel() || ""}-${getSystemVersion() || ""}
Pro: ${PremiumService.get()}
Logged in: ${user ? "yes" : "no"}`,
userId: user?.id
});
setLoading(false);
eSendEvent(eCloseSheet);
body.reset();
title.reset();
await sleep(300);
presentDialog({
title: "Issue reported",
paragraph: (
<Text>
You can track your issue at{" "}
<Text
style={{
textDecorationLine: "underline",
color: colors.primary.accent
}}
onPress={() => {
Linking.openURL(issue_url);
}}
>
{issue_url}.
</Text>{" "}
Please note that we will respond to your issue on the given link. We
recommend that you save it.
</Text>
),
positiveText: "Copy link",
positivePress: () => {
Clipboard.setString(issue_url);
ToastManager.show({
heading: "Issue url copied!",
type: "success",
context: "global"
});
},
negativeText: "Close"
});
setDone(true);
} catch (e) {
setLoading(false);
ToastManager.show({
@@ -124,125 +89,177 @@ Logged in: ${user ? "yes" : "no"}`,
width: "100%"
}}
>
<DialogHeader
title={issueTitle || "Report issue"}
paragraph={
issueTitle
? "We are sorry, it seems that the app crashed due to an error. You can submit a bug report below so we can fix this asap."
: "Let us know if you have faced any issue/bug while using Notesnook."
}
/>
{done ? (
<>
<View
style={{
height: 250,
justifyContent: "center",
alignItems: "center",
gap: 10
}}
>
<Heading>Issue submitted</Heading>
<Paragraph
style={{
textAlign: "center"
}}
selectable={true}
>
You can track your issue at{" "}
<Paragraph
style={{
textDecorationLine: "underline",
color: colors.primary.accent
}}
onPress={() => {
Linking.openURL(issueUrl.current);
}}
>
{issueUrl.current}
</Paragraph>
. Please note that we will respond to your issue on the given
link. We recommend that you save it.
</Paragraph>
<Seperator half />
<TextInput
placeholder="Title"
onChangeText={(v) => (title.current = v)}
defaultValue={title.current}
style={{
borderWidth: 1,
borderColor: colors.primary.border,
borderRadius: 5,
padding: 12,
fontFamily: "OpenSans-Regular",
marginBottom: 10,
fontSize: SIZE.md,
color: colors.primary.heading
}}
placeholderTextColor={colors.primary.placeholder}
/>
<TextInput
ref={bodyRef}
placeholder={`Tell us more about the issue you are facing.
For example:
- Steps to reproduce the issue
- Things you have tried etc.`}
multiline
numberOfLines={5}
textAlignVertical="top"
onChangeText={(v) => (body.current = v)}
onLayout={() => {
if (initialLayout.current) return;
initialLayout.current = true;
if (body.current) {
bodyRef.current?.setNativeProps({
text: body.current,
selection: {
start: 0,
end: 0
}
});
}
}}
style={{
borderWidth: 1,
borderColor: colors.primary.border,
borderRadius: 5,
padding: 12,
fontFamily: "OpenSans-Regular",
maxHeight: 200,
fontSize: SIZE.sm,
marginBottom: 2.5,
color: colors.primary.paragraph
}}
placeholderTextColor={colors.primary.placeholder}
/>
<Paragraph
size={SIZE.xs}
color={colors.secondary.paragraph}
>{`App version: ${getVersion()} Platform: ${Platform.OS} Model: ${
Platform.constants.Brand
}-${Platform.constants.Model}-${Platform.constants.Version}`}</Paragraph>
<Seperator />
<Button
onPress={onPress}
title={loading ? null : "Submit"}
loading={loading}
width="100%"
type="accent"
/>
<Paragraph
color={colors.secondary.paragraph}
size={SIZE.xs}
style={{
marginTop: 10,
textAlign: "center"
}}
>
The information above will be publically available at{" "}
<Text
onPress={() => {
Linking.openURL("https://github.com/streetwriters/notesnook");
}}
style={{
textDecorationLine: "underline",
color: colors.primary.accent
}}
>
github.com/streetwriters/notesnook.
</Text>{" "}
If you want to ask something in general or need some assistance, we
would suggest that you{" "}
<Text
style={{
textDecorationLine: "underline",
color: colors.primary.accent
}}
onPress={async () => {
try {
await openLinkInBrowser("https://discord.gg/zQBK97EE22", colors);
} catch (e) {
console.error(e);
<Button
title="Open issue"
onPress={() => {
Linking.openURL(issueUrl.current);
}}
type="accent"
width="100%"
/>
</View>
</>
) : (
<>
<DialogHeader
title={issueTitle || "Report issue"}
paragraph={
issueTitle
? "We are sorry, it seems that the app crashed due to an error. You can submit a bug report below so we can fix this asap."
: "Let us know if you have faced any issue/bug while using Notesnook."
}
}}
>
join our community on Discord.
</Text>
</Paragraph>
/>
<Seperator half />
<TextInput
placeholder="Title"
onChangeText={(v) => (title.current = v)}
defaultValue={title.current}
style={{
borderWidth: 1,
borderColor: colors.primary.border,
borderRadius: 5,
padding: 12,
fontFamily: "OpenSans-Regular",
marginBottom: 10,
fontSize: SIZE.md,
color: colors.primary.heading
}}
placeholderTextColor={colors.primary.placeholder}
/>
<TextInput
ref={bodyRef}
multiline
placeholder={`Tell us more about the issue you are facing.
For example:
- What were you trying to do in the app?
- What did you expect to happen?
- Steps to reproduce the issue
- Things you have tried etc.`}
numberOfLines={5}
textAlignVertical="top"
onChangeText={(v) => (body.current = v)}
onLayout={() => {
if (initialLayout.current) return;
initialLayout.current = true;
if (body.current) {
bodyRef.current?.setNativeProps({
text: body.current,
selection: {
start: 0,
end: 0
}
});
}
}}
style={{
borderWidth: 1,
borderColor: colors.primary.border,
borderRadius: 5,
padding: 12,
fontFamily: "OpenSans-Regular",
maxHeight: 200,
fontSize: SIZE.sm,
marginBottom: 2.5,
color: colors.primary.paragraph
}}
placeholderTextColor={colors.primary.placeholder}
/>
<Paragraph
size={SIZE.xs}
color={colors.secondary.paragraph}
>{`App version: ${getVersion()} Platform: ${
Platform.OS
} Model: ${getBrand()}-${getModel()}-${getSystemVersion()}`}</Paragraph>
<Seperator />
<Button
onPress={onPress}
title={loading ? null : "Submit"}
loading={loading}
width="100%"
type="accent"
/>
<Paragraph
color={colors.secondary.paragraph}
size={SIZE.xs}
style={{
marginTop: 10,
textAlign: "center"
}}
>
The information above will be publically available at{" "}
<Text
onPress={() => {
Linking.openURL("https://github.com/streetwriters/notesnook");
}}
style={{
textDecorationLine: "underline",
color: colors.primary.accent
}}
>
github.com/streetwriters/notesnook.
</Text>{" "}
If you want to ask something in general or need some assistance, we
would suggest that you{" "}
<Text
style={{
textDecorationLine: "underline",
color: colors.primary.accent
}}
onPress={async () => {
try {
await openLinkInBrowser(
"https://discord.gg/zQBK97EE22",
colors
);
} catch (e) {
console.error(e);
}
}}
>
join our community on Discord.
</Text>
</Paragraph>
</>
)}
</View>
);
};

View File

@@ -35,7 +35,10 @@ import Input from "../../ui/input";
import { Pressable } from "../../ui/pressable";
import Paragraph from "../../ui/typography/paragraph";
import type { LinkAttributes } from "@notesnook/editor/dist/extensions/link";
import { editorController } from "../../../screens/editor/tiptap/utils";
import {
EditorEvents,
editorController
} from "../../../screens/editor/tiptap/utils";
const ListNoteItem = ({
id,
@@ -190,13 +193,13 @@ export default function LinkNote(props: {
}
: undefined
);
editorController.current.commands.createInternalLink(
{
editorController.current?.postMessage(EditorEvents.resolve, {
data: {
href: link,
title: selectedNote.title
},
props.resolverId
);
resolverId: props.resolverId
});
};
const onSelectNote = async (note: Note) => {

View File

@@ -42,10 +42,7 @@ import { ProgressBarComponent } from "../../ui/svg/lazy";
import Paragraph from "../../ui/typography/paragraph";
import { Issue } from "../github/issue";
export const makeError = (
stack: string,
component: string
) => `Please let us know what happened. What steps we can take to reproduce the issue here.
export const makeError = (stack: string, component: string) => `
_______________________________
Stacktrace: In ${component}::${stack}`;
@@ -96,10 +93,12 @@ export default function Migrate() {
});
setLoading(true);
await sleep(1);
const { error } = await BackupService.run(false, "local");
const { error, report } = await BackupService.run(false, "local");
if (error) {
ToastManager.error(error, "Backup failed");
reportError(error);
ToastManager.error(error as Error, "Backup failed");
if (report) {
reportError(error as Error);
}
setLoading(false);
return;
}

View File

@@ -1,600 +0,0 @@
/*
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 { 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 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 {
ToastManager,
eSubscribeEvent,
eUnSubscribeEvent
} from "../../../services/event-manager";
import Navigation from "../../../services/navigation";
import SettingsService from "../../../services/settings";
import { refreshAllStores } from "../../../stores/create-db-collection-store";
import { eCloseRestoreDialog, eOpenRestoreDialog } from "../../../utils/events";
import { SIZE } from "../../../utils/size";
import { Dialog } from "../../dialog";
import DialogHeader from "../../dialog/dialog-header";
import { presentDialog } from "../../dialog/functions";
import { Toast } from "../../toast";
import { Button } from "../../ui/button";
import Seperator from "../../ui/seperator";
import SheetWrapper from "../../ui/sheet";
import Paragraph from "../../ui/typography/paragraph";
import { useUserStore } from "../../../stores/use-user-store";
const RestoreDataSheet = () => {
const [visible, setVisible] = useState(false);
const [restoring, setRestoring] = useState(false);
const sheet = useRef();
useEffect(() => {
const open = async () => {
setVisible(true);
setTimeout(() => {
sheet.current?.show();
}, 1);
};
eSubscribeEvent(eOpenRestoreDialog, open);
eSubscribeEvent(eCloseRestoreDialog, close);
return () => {
eUnSubscribeEvent(eOpenRestoreDialog, open);
eUnSubscribeEvent(eCloseRestoreDialog, close);
};
}, [close]);
const close = useCallback(() => {
if (restoring) {
showIsWorking();
return;
}
sheet.current?.hide();
setTimeout(() => {
setVisible(false);
}, 150);
}, [restoring]);
const showIsWorking = () => {
ToastManager.show({
heading: "Restoring Backup",
message: "Your backup data is being restored. please wait.",
type: "error",
context: "local"
});
};
return !visible ? null : (
<SheetWrapper
fwdRef={sheet}
gestureEnabled={!restoring}
closeOnTouchBackdrop={!restoring}
onClose={() => {
setVisible(false);
close();
}}
>
<RestoreDataComponent
close={close}
restoring={restoring}
setRestoring={setRestoring}
actionSheetRef={sheet}
/>
<Toast context="local" />
</SheetWrapper>
);
};
export default RestoreDataSheet;
const RestoreDataComponent = ({ close, setRestoring, restoring }) => {
const { colors } = useThemeColors();
const [files, setFiles] = useState([]);
const [loading, setLoading] = useState(true);
const [backupDirectoryAndroid, setBackupDirectoryAndroid] = useState(false);
const [progress, setProgress] = useState();
useEffect(() => {
const subscription = db.eventManager.subscribe(
EVENTS.migrationProgress,
(progress) => {
setProgress(progress);
}
);
return () => {
subscription?.unsubscribe();
};
}, []);
useEffect(() => {
setTimeout(() => {
checkBackups();
}, 1000);
}, []);
const restore = async (item) => {
if (restoring) {
return;
}
try {
const file = Platform.OS === "ios" ? item.path : item.uri;
console.log(file);
if (file.endsWith(".nnbackupz")) {
setRestoring(true);
if (Platform.OS === "android") {
const cacheFile = `file://${RNFetchBlob.fs.dirs.CacheDir}/backup.zip`;
if (await RNFetchBlob.fs.exists(cacheFile)) {
await RNFetchBlob.fs.unlink(cacheFile);
}
await RNFetchBlob.fs.createFile(cacheFile, "", "utf8");
console.log("copying");
await copyFileAsync(file, cacheFile);
console.log("copied");
await restoreFromZip(cacheFile);
} else {
await restoreFromZip(file, false);
}
} else if (file.endsWith(".nnbackup")) {
let backup;
if (Platform.OS === "android") {
backup = await ScopedStorage.readFile(file, "utf8");
} else {
backup = await RNFetchBlob.fs.readFile(file, "utf8");
}
await restoreFromNNBackup(JSON.parse(backup));
}
} catch (e) {
console.log("error", e);
setRestoring(false);
backupError(e);
}
};
const withPassword = () => {
return new Promise((resolve) => {
let resolved = false;
presentDialog({
context: "local",
title: "Encrypted backup",
input: true,
inputPlaceholder: "Password",
paragraph: "Please enter password of this backup file",
positiveText: "Restore",
secureTextEntry: true,
onClose: () => {
if (resolved) return;
resolve(undefined);
},
negativeText: "Cancel",
positivePress: async (password, isEncryptionKey) => {
resolve({
value: password,
isEncryptionKey
});
resolved = true;
return true;
},
check: {
info: "Use encryption key",
type: "transparent"
}
});
});
};
const checkBackups = async () => {
try {
let files = [];
if (Platform.OS === "android") {
let backupDirectory = SettingsService.get().backupDirectoryAndroid;
if (backupDirectory) {
setBackupDirectoryAndroid(backupDirectory);
files = await ScopedStorage.listFiles(backupDirectory.uri);
} else {
setLoading(false);
return;
}
} else {
let path = await storage.checkAndCreateDir("/backups/");
files = await RNFetchBlob.fs.lstat(path);
}
files = files
.filter((file) => {
const name = Platform.OS === "android" ? file.name : file.filename;
return name.endsWith(".nnbackup") || name.endsWith(".nnbackupz");
})
.sort(function (a, b) {
let timeA = a.lastModified;
let timeB = b.lastModified;
return timeB - timeA;
});
setFiles(files);
setLoading(false);
} catch (e) {
console.log(e);
setLoading(false);
}
};
const restoreBackup = async (backup, password, key) => {
await db.transaction(async () => {
await db.backup.import(backup, password, key);
});
await db.initCollections();
refreshAllStores();
ToastManager.show({
heading: "Backup restored successfully.",
type: "success",
context: "global"
});
Navigation.queueRoutesForUpdate();
return true;
};
const backupError = (e) => {
console.log(e.stack);
ToastManager.show({
heading: "Restore failed",
message:
e.message ||
"The selected backup data file is invalid. You must select a *.nnbackup file to restore.",
type: "error",
context: "local"
});
};
/**
*
* @param {string} file
*/
async function restoreFromZip(file, remove) {
try {
const zipOutputFolder = `${cacheDir}/backup_extracted`;
if (await RNFetchBlob.fs.exists(zipOutputFolder)) {
await RNFetchBlob.fs.unlink(zipOutputFolder);
await RNFetchBlob.fs.mkdir(zipOutputFolder);
}
await unzip(file, zipOutputFolder);
console.log("Unzipped files successfully to", zipOutputFolder);
const backupFiles = await RNFetchBlob.fs.ls(zipOutputFolder);
if (backupFiles.findIndex((file) => file === ".nnbackup") === -1) {
throw new Error("Backup file is invalid");
}
await db.transaction(async () => {
let password;
let key;
console.log(
`Found ${backupFiles?.length} files to restore from backup`
);
for (const path of backupFiles) {
if (path === ".nnbackup") continue;
const filePath = `${zipOutputFolder}/${path}`;
const data = await RNFetchBlob.fs.readFile(filePath, "utf8");
const parsed = JSON.parse(data);
if (parsed.encrypted && !password) {
console.log("Backup is encrypted...", "requesting password");
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, key);
console.log("Imported", path);
}
});
// Remove files from cache
RNFetchBlob.fs.unlink(zipOutputFolder).catch(console.log);
if (remove) {
RNFetchBlob.fs.unlink(file).catch(console.log);
}
refreshAllStores();
Navigation.queueRoutesForUpdate();
setRestoring(false);
close();
ToastManager.show({
heading: "Backup restored successfully.",
type: "success",
context: "global"
});
} catch (e) {
backupError(e);
setRestoring(false);
}
}
/**
*
* @param {string} file
*/
async function restoreFromNNBackup(backup) {
try {
if (backup.data.iv && backup.data.salt) {
const { value, isEncryptionKey } = await withPassword();
let key;
let password;
if (isEncryptionKey) {
key = value;
} else {
password = value;
}
if (key || password) {
try {
await restoreBackup(backup, password, key);
close();
setRestoring(false);
} catch (e) {
setRestoring(false);
backupError(e);
}
} else {
setRestoring(false);
}
} else {
await restoreBackup(backup);
setRestoring(false);
close();
}
} catch (e) {
setRestoring(false);
backupError(e);
}
}
const button = {
title: "Restore from files",
onPress: async () => {
if (restoring) {
return;
}
try {
useUserStore.setState({
disableAppLockRequests: true
});
console.log("disabled...");
const file = await DocumentPicker.pickSingle({
copyTo: "cachesDirectory"
});
setTimeout(() => {
useUserStore.setState({
disableAppLockRequests: false
});
}, 1000);
if (file.name.endsWith(".nnbackupz")) {
setRestoring(true);
await restoreFromZip(file.fileCopyUri, true);
} else if (file.name.endsWith(".nnbackup")) {
RNFetchBlob.fs.unlink(file.fileCopyUri).catch(console.log);
setRestoring(true);
const data = await fetch(file.uri);
await restoreFromNNBackup(await data.json());
}
} catch (e) {
console.log("error", e.stack);
setTimeout(() => {
useUserStore.setState({
disableAppLockRequests: false
});
}, 1000);
setRestoring(false);
backupError(e);
}
}
};
const renderItem = ({ item, index }) => (
<View
style={{
minHeight: 50,
justifyContent: "space-between",
alignItems: "center",
width: "100%",
borderRadius: 0,
flexDirection: "row",
borderBottomWidth: 0.5,
borderBottomColor: colors.primary.border
}}
>
<View
style={{
maxWidth: "75%"
}}
>
<Paragraph size={SIZE.sm} style={{ width: "100%", maxWidth: "100%" }}>
{getFormattedDate(item?.lastModified * 1)}
</Paragraph>
<Paragraph size={SIZE.xs}>
{(item.filename || item.name).replace(".nnbackup", "")}
</Paragraph>
</View>
<Button
title="Restore"
height={30}
type="accent"
style={{
borderRadius: 100,
paddingHorizontal: 12
}}
fontSize={SIZE.sm - 1}
onPress={() => restore(item, index)}
/>
</View>
);
return (
<>
<View>
<Dialog context="local" />
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
paddingHorizontal: 8,
paddingRight: 8,
alignItems: "center",
paddingTop: restoring ? 8 : 0
}}
>
<DialogHeader
title="Backups"
paragraph={`All the backups are stored in ${
Platform.OS === "ios"
? "File Manager/Notesnook/Backups"
: "selected backups folder."
}`}
button={button}
/>
</View>
<Seperator half />
<FlatList
ListEmptyComponent={
!restoring ? (
loading ? (
<View
style={{
justifyContent: "center",
alignItems: "center",
height: 100
}}
>
<ActivityIndicator
color={colors.primary.accent}
size={SIZE.lg}
/>
</View>
) : (
<View
style={{
justifyContent: "center",
alignItems: "center",
height: 100
}}
>
{Platform.OS === "android" && !backupDirectoryAndroid ? (
<>
<Button
title="Select backups folder"
icon="folder"
onPress={async () => {
let folder = await ScopedStorage.openDocumentTree(
true
);
let subfolder;
if (folder.name !== "Notesnook backups") {
subfolder = await ScopedStorage.createDirectory(
folder.uri,
"Notesnook backups"
);
} else {
subfolder = folder;
}
SettingsService.set({
backupDirectoryAndroid: subfolder
});
setBackupDirectoryAndroid(subfolder);
setLoading(true);
checkBackups();
}}
style={{
marginTop: 10,
paddingHorizontal: 12
}}
height={30}
width={null}
/>
<Paragraph
style={{
textAlign: "center",
marginTop: 5
}}
size={SIZE.xs}
textBreakStrategy="balanced"
color={colors.secondary.paragraph}
>
Select the folder that includes your backup files to
list them here.
</Paragraph>
</>
) : (
<Paragraph color={colors.secondary.paragraph}>
No backups found
</Paragraph>
)}
</View>
)
) : (
<View
style={{
justifyContent: "center",
alignItems: "center",
height: 200
}}
>
<ActivityIndicator color={colors.primary.accent} />
<Paragraph color={colors.secondary.paragraph}>
Restoring {progress ? progress?.collection : null}
{progress ? `(${progress.current}/${progress.total}) ` : null}
...Please wait.
</Paragraph>
</View>
)
}
keyExtractor={(item) => item.name || item.filename}
style={{
paddingHorizontal: 12
}}
data={restoring || loading ? [] : files}
renderItem={renderItem}
ListFooterComponent={
restoring || loading || files.length === 0 ? null : (
<View
style={{
height: 200
}}
/>
)
}
/>
</View>
</>
);
};

View File

@@ -86,16 +86,16 @@ const Sort = ({ type, screen }) => {
<Button
title={
groupOptions?.sortDirection === "asc"
? groupOptions.groupBy === "abc" ||
groupOptions.sortBy === "title"
? groupOptions?.groupBy === "abc" ||
groupOptions?.sortBy === "title"
? "A - Z"
: groupOptions.sortBy === "dueDate"
: groupOptions?.sortBy === "dueDate"
? "Earliest first"
: "Old - New"
: groupOptions.groupBy === "abc" ||
groupOptions.sortBy === "title"
: groupOptions?.groupBy === "abc" ||
groupOptions?.sortBy === "title"
? "Z - A"
: groupOptions.sortBy === "dueDate"
: groupOptions?.sortBy === "dueDate"
? "Latest first"
: "New - Old"
}
@@ -134,7 +134,7 @@ const Sort = ({ type, screen }) => {
alignItems: "center"
}}
>
{groupOptions.groupBy === "abc" ? (
{groupOptions?.groupBy === "abc" ? (
<Button
type="secondary"
title="Title"
@@ -154,18 +154,18 @@ const Sort = ({ type, screen }) => {
item === "dateEdited") ? null : (
<Button
key={item}
type={groupOptions.sortBy === item ? "selected" : "plain"}
type={groupOptions?.sortBy === item ? "selected" : "plain"}
title={SORT[item]}
height={40}
iconPosition="left"
icon={groupOptions.sortBy === item ? "check" : null}
icon={groupOptions?.sortBy === item ? "check" : null}
style={{
marginRight: 10,
paddingHorizontal: 8
}}
buttonType={{
text:
groupOptions.sortBy === item
groupOptions?.sortBy === item
? colors.primary.accent
: colors.secondary.paragraph
}}
@@ -213,11 +213,11 @@ const Sort = ({ type, screen }) => {
key={item}
testID={"btn-" + item}
type={
groupOptions.groupBy === GROUP[item] ? "selected" : "plain"
groupOptions?.groupBy === GROUP[item] ? "selected" : "plain"
}
buttonType={{
text:
groupOptions.groupBy === GROUP[item]
groupOptions?.groupBy === GROUP[item]
? colors.primary.accent
: colors.secondary.paragraph
}}
@@ -235,7 +235,7 @@ const Sort = ({ type, screen }) => {
updateGroupOptions(_groupOptions);
}}
height={40}
icon={groupOptions.groupBy === GROUP[item] ? "check" : null}
icon={groupOptions?.groupBy === GROUP[item] ? "check" : null}
title={
item.slice(0, 1).toUpperCase() + item.slice(1, item.length)
}

View File

@@ -1,235 +0,0 @@
/*
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 React, { useCallback, useEffect, useRef, useState } from "react";
import { TouchableOpacity, View } from "react-native";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { notesnook } from "../../../e2e/test.ids";
import useGlobalSafeAreaInsets from "../../hooks/use-global-safe-area-insets";
import { DDS } from "../../services/device-detection";
import {
eSubscribeEvent,
eUnSubscribeEvent
} from "../../services/event-manager";
import { useThemeColors } from "@notesnook/theme";
import { getElevationStyle } from "../../utils/elevation";
import { eHideToast, eShowToast } from "../../utils/events";
import { SIZE } from "../../utils/size";
import { Button } from "../ui/button";
import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
export const Toast = ({ context = "global" }) => {
const { colors } = useThemeColors();
const [data, setData] = useState({});
const insets = useGlobalSafeAreaInsets();
const hideTimeout = useRef();
const [visible, setVisible] = useState(false);
const toastMessages = useRef([]);
const show = useCallback(
async (data) => {
if (!data) return;
if (data.context !== context) return;
if (
toastMessages.current.findIndex((m) => m.message === data.message) >= 0
) {
return;
}
toastMessages.current.push(data);
if (toastMessages.current?.length > 1) return;
setData(data);
setVisible(true);
if (hideTimeout.current) {
clearTimeout(hideTimeout.current);
}
hideTimeout.current = setTimeout(() => {
hide();
}, data.duration);
},
[context, hide]
);
const next = useCallback(
(data) => {
if (!data) {
hide();
return;
}
setData(data);
if (hideTimeout.current) {
clearTimeout(hideTimeout.current);
}
hideTimeout.current = setTimeout(() => {
hide();
}, data?.duration);
},
[hide]
);
const hide = useCallback(() => {
if (hideTimeout.current) {
clearTimeout(hideTimeout.current);
}
let msg =
toastMessages.current.length > 1 ? toastMessages.current.shift() : null;
if (msg) {
setVisible(false);
next(msg);
setTimeout(() => {
setVisible(true);
}, 300);
} else {
setVisible(false);
toastMessages.current.shift();
setTimeout(() => {
setData({});
if (hideTimeout.current) {
clearTimeout(hideTimeout.current);
}
}, 100);
}
}, [next]);
useEffect(() => {
eSubscribeEvent(eShowToast, show);
eSubscribeEvent(eHideToast, hide);
return () => {
toastMessages.current = [];
eUnSubscribeEvent(eShowToast, show);
eUnSubscribeEvent(eHideToast, hide);
};
}, [hide, show]);
return (
visible && (
<TouchableOpacity
onPress={hide}
activeOpacity={1}
style={{
width: DDS.isTab ? 400 : "100%",
alignItems: "center",
alignSelf: "center",
minHeight: 30,
top: insets.top + 10,
position: "absolute",
zIndex: 999,
elevation: 15
}}
>
<View
style={{
...getElevationStyle(5),
maxWidth: "95%",
backgroundColor: colors.secondary.background,
minWidth: data?.func ? "95%" : "50%",
alignSelf: "center",
borderRadius: 5,
minHeight: 30,
paddingVertical: 10,
paddingLeft: 12,
paddingRight: 5,
justifyContent: "space-between",
flexDirection: "row",
alignItems: "center",
width: "95%"
}}
>
<View
style={{
flexDirection: "row",
alignItems: "center",
flexGrow: 1,
flex: 1
}}
>
<View
style={{
height: 30,
borderRadius: 100,
justifyContent: "center",
alignItems: "center",
marginRight: 10
}}
>
<Icon
name={data?.type === "success" ? "check" : "close"}
size={SIZE.lg}
color={
data?.type === "error"
? colors.error.icon
: colors.primary.accent
}
/>
</View>
<View
style={{
flexGrow: 1,
paddingRight: 25
}}
>
{data?.heading ? (
<Heading
color={colors.primary.paragraph}
size={SIZE.md}
onPress={() => {
hide();
}}
>
{data.heading}
</Heading>
) : null}
{data?.message ? (
<Paragraph
color={colors.primary.paragraph}
style={{
maxWidth: "100%",
paddingRight: 10
}}
onPress={() => {
hide();
}}
>
{data.message}
</Paragraph>
) : null}
</View>
</View>
{data.func ? (
<Button
testID={notesnook.toast.button}
fontSize={SIZE.md}
type={data.type === "error" ? "errorShade" : "transparent"}
onPress={data.func}
title={data.actionText}
height={30}
style={{
zIndex: 10
}}
/>
) : null}
</View>
</TouchableOpacity>
)
);
};

View File

@@ -0,0 +1,219 @@
/*
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 { useThemeColors } from "@notesnook/theme";
import React, { useCallback, useEffect, useRef, useState } from "react";
import {
Platform,
TouchableOpacity,
useWindowDimensions,
View
} from "react-native";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { notesnook } from "../../../e2e/test.ids";
import useGlobalSafeAreaInsets from "../../hooks/use-global-safe-area-insets";
import useKeyboard from "../../hooks/use-keyboard";
import { DDS } from "../../services/device-detection";
import {
eSubscribeEvent,
eUnSubscribeEvent,
ToastOptions
} from "../../services/event-manager";
import { getElevationStyle } from "../../utils/elevation";
import { eHideToast, eShowToast } from "../../utils/events";
import { SIZE } from "../../utils/size";
import { Button } from "../ui/button";
import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
export const Toast = ({ context = "global" }) => {
const { colors, isDark } = useThemeColors();
const [toastOptions, setToastOptions] = useState<ToastOptions | undefined>();
const hideTimeout = useRef<NodeJS.Timeout | undefined>();
const insets = useGlobalSafeAreaInsets();
const [visible, setVisible] = useState(false);
const toastMessages = useRef<ToastOptions[]>([]);
const dimensions = useWindowDimensions();
const keyboard = useKeyboard();
const hideToast = useCallback(() => {
const nextToastMessage = toastMessages.current.shift();
if (nextToastMessage) {
if (hideTimeout.current) {
clearTimeout(hideTimeout.current);
}
setVisible(true);
setToastOptions(nextToastMessage);
hideTimeout.current = setTimeout(() => {
hideToast();
}, nextToastMessage?.duration);
} else {
setVisible(false);
setToastOptions(undefined);
if (hideTimeout.current) {
clearTimeout(hideTimeout.current);
}
}
}, []);
const showToast = useCallback(
(data?: ToastOptions) => {
if (
!data ||
data.context !== context ||
toastMessages.current.findIndex((m) => m.message === data.message) != -1
)
return;
toastMessages.current.push(data);
if (toastMessages.current?.length > 1) return;
if (hideTimeout.current) {
clearTimeout(hideTimeout.current);
}
setVisible(true);
const nextToastMessage = toastMessages.current.shift();
setToastOptions(nextToastMessage);
hideTimeout.current = setTimeout(() => {
hideToast();
}, nextToastMessage?.duration);
},
[context, hideToast]
);
useEffect(() => {
eSubscribeEvent(eShowToast, showToast);
eSubscribeEvent(eHideToast, hideToast);
return () => {
eUnSubscribeEvent(eShowToast, showToast);
eUnSubscribeEvent(eHideToast, hideToast);
};
}, [hideToast, showToast]);
const isFullToastMessage = toastOptions?.heading && toastOptions?.message;
return visible && toastOptions ? (
<TouchableOpacity
onPress={() => {
hideToast();
}}
activeOpacity={1}
style={{
width: DDS.isTab ? dimensions.width / 2 : "100%",
alignItems: "center",
alignSelf: "center",
bottom:
Platform.OS === "android"
? Math.max(insets.bottom, 40)
: Math.max(insets.bottom, 40) +
(keyboard.keyboardShown ? keyboard.keyboardHeight : 0),
position: "absolute",
zIndex: 999,
elevation: 15
}}
>
<View
style={{
...getElevationStyle(5),
backgroundColor: isDark ? colors.static.black : colors.static.white,
alignSelf: "center",
borderRadius: 100,
paddingVertical: 12,
paddingHorizontal: 12,
justifyContent: "space-between",
flexDirection: "row",
alignItems: "center",
maxWidth: "95%",
gap: 10,
flexShrink: 1
}}
>
<View
style={{
flexDirection: "row",
alignItems: "center",
gap: 10,
flexShrink: 1
}}
>
<Icon
name={
toastOptions.type === "success"
? "check"
: toastOptions.type === "info"
? "information"
: "close"
}
size={isFullToastMessage ? SIZE.xxxl : SIZE.xl}
color={
toastOptions?.icon
? toastOptions?.icon
: toastOptions.type === "error"
? colors.error.icon
: toastOptions.type === "info"
? isDark
? colors.static.white
: colors.static.black
: colors.success.icon
}
/>
<View
style={{
paddingRight: toastOptions?.func ? 0 : 12,
flexShrink: 1
}}
>
{isFullToastMessage ? (
<Heading
color={!isDark ? colors.static.black : colors.static.white}
size={SIZE.sm}
>
{toastOptions.heading}
</Heading>
) : null}
{toastOptions.message || toastOptions.heading ? (
<Paragraph
color={!isDark ? colors.static.black : colors.static.white}
size={SIZE.xs}
>
{toastOptions.message || toastOptions.heading}
</Paragraph>
) : null}
</View>
</View>
{toastOptions.func ? (
<Button
testID={notesnook.toast.button}
fontSize={SIZE.md}
type={toastOptions.type === "error" ? "errorShade" : "transparent"}
onPress={toastOptions.func}
title={toastOptions.actionText}
height={35}
style={{
zIndex: 10
}}
/>
) : null}
</View>
</TouchableOpacity>
) : null;
};

View File

@@ -25,7 +25,8 @@ import {
DimensionValue,
TextStyle,
View,
ViewStyle
ViewStyle,
useWindowDimensions
} from "react-native";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { useUserStore } from "../../../stores/use-user-store";
@@ -92,6 +93,9 @@ export const Button = ({
});
const textColor = buttonType?.text ? buttonType.text : text;
const { fontScale } = useWindowDimensions();
const growFactor = 1 + (fontScale - 1) / 10;
const Component = bold ? Heading : Paragraph;
return (
@@ -108,7 +112,7 @@ export const Button = ({
NativeTooltip.show(event, tooltipText, NativeTooltip.POSITIONS.TOP);
}
}}
disabled={loading}
disabled={loading || restProps.disabled}
type={type}
accentColor={accentColor}
accentText={accentText}
@@ -117,14 +121,18 @@ export const Button = ({
customOpacity={buttonType?.opacity}
customAlpha={buttonType?.alpha}
style={{
height: height,
width: (width as DimensionValue) || undefined,
height: typeof height === "number" ? height * growFactor : height,
width:
typeof width === "number"
? width * growFactor
: (width as DimensionValue) || undefined,
paddingHorizontal: 12,
borderRadius: 5,
alignSelf: "center",
justifyContent: "center",
alignItems: "center",
flexDirection: "row",
opacity: restProps?.disabled ? 0.5 : 1,
...(style as ViewStyle)
}}
>

View File

@@ -41,6 +41,7 @@ import { SIZE } from "../../../utils/size";
import { IconButton } from "../icon-button";
import Paragraph from "../typography/paragraph";
import phone from "phone";
import isURL from "validator/lib/isURL";
interface InputProps extends TextInputProps {
fwdRef?: RefObject<TextInput>;
@@ -49,7 +50,8 @@ interface InputProps extends TextInputProps {
| "email"
| "confirmPassword"
| "username"
| "phonenumber";
| "phonenumber"
| "url";
loading?: boolean;
onSubmit?: (
event: NativeSyntheticEvent<TextInputSubmitEditingEventData>
@@ -151,6 +153,9 @@ const Input = ({
case "confirmPassword":
isError = customValidator && value === customValidator();
break;
case "url":
isError = isURL(value);
break;
case "phonenumber": {
const result = phone(value, {
strictDetection: true,

View File

@@ -21,11 +21,12 @@ import { VariantsWithStaticColors, useThemeColors } from "@notesnook/theme";
import React, { RefObject, useCallback } from "react";
import {
ColorValue,
PressableStateCallbackType,
Pressable as RNPressable,
PressableProps as RNPressableProps,
PressableStateCallbackType,
View,
ViewStyle
ViewStyle,
useWindowDimensions
} from "react-native";
import {
RGB_Linear_Shade,
@@ -256,6 +257,8 @@ export const Pressable = ({
? 1
: colorOpacity;
const alpha = customAlpha ? customAlpha : isDark ? 0.03 : -0.03;
const { fontScale } = useWindowDimensions();
const growFactor = 1 + (fontScale - 1) / 8;
const getStyle = useCallback(
({ pressed }: PressableStateCallbackType): ViewStyle | ViewStyle[] => [
@@ -276,7 +279,13 @@ export const Pressable = ({
: borderColor || "transparent",
borderWidth: borderWidth
},
style
style,
{
height:
typeof style.height === "number"
? style.height * growFactor
: style.height
}
],
[
alpha,
@@ -288,7 +297,8 @@ export const Pressable = ({
borderSelectedColor,
borderColor,
borderWidth,
style
style,
growFactor
]
);

View File

@@ -600,20 +600,11 @@ export const useActions = ({
});
return;
}
const text = await convertNoteToText(item as Note, false);
if (!text) {
ToastManager.error(
new Error(Errors.export("text")),
undefined,
"local"
);
return;
}
const html = text.replace(/\n/g, "<br />");
const text = await convertNoteToText(item as Note, true);
const html = (text || "").replace(/\n/g, "<br />");
await Notifications.displayNotification({
title: item.title,
message: (item as Note).headline || text,
message: (item as Note).headline || text || "",
subtitle: "",
bigText: html,
ongoing: true,
@@ -684,15 +675,11 @@ export const useActions = ({
} else {
processingId.current = "shareNote";
const convertedText = await convertNoteToText(item);
if (!convertedText) {
ToastManager.error(new Error(Errors.export("text")));
return;
}
processingId.current = undefined;
Share.open({
title: "Share note to",
failOnCancel: false,
message: convertedText
message: convertedText || ""
});
}
}
@@ -772,11 +759,7 @@ export const useActions = ({
} else {
processingId.current = "copyContent";
const text = await convertNoteToText(item as Note, true);
if (!text) {
ToastManager.error(new Error(Errors.export("text")));
return;
}
Clipboard.setString(text);
Clipboard.setString(text || "");
processingId.current = undefined;
ToastManager.show({
heading: "Note copied to clipboard",

View File

@@ -26,10 +26,7 @@ import {
} from "@notesnook/core/dist/common";
import { EventManagerSubscription } from "@notesnook/core/dist/utils/event-manager";
import notifee from "@notifee/react-native";
import NetInfo, {
NetInfoState,
NetInfoSubscription
} from "@react-native-community/netinfo";
import NetInfo, { NetInfoSubscription } from "@react-native-community/netinfo";
import React, { useCallback, useEffect, useRef } from "react";
import {
AppState,
@@ -47,6 +44,7 @@ import { checkVersion } from "react-native-check-version";
import Config from "react-native-config";
import * as RNIap from "react-native-iap";
import { DatabaseLogger, db, setupDatabase } from "../common/database";
import { initializeLogger } from "../common/database/logger";
import { MMKV } from "../common/database/mmkv";
import Migrate from "../components/sheets/migrate";
import NewFeature from "../components/sheets/new-feature";
@@ -86,6 +84,7 @@ import { updateStatusBarColor } from "../utils/colors";
import { BETA } from "../utils/constants";
import {
eCloseSheet,
eEditorReset,
eLoginSessionExpired,
eOnLoadNote,
eOpenAnnouncementDialog,
@@ -96,6 +95,7 @@ import {
import { getGithubVersion } from "../utils/github-version";
import { tabBarRef } from "../utils/global-refs";
import { sleep } from "../utils/time";
import { NotesnookModule } from "../utils/notesnook-module";
const onCheckSyncStatus = async (type: SyncStatusEvent) => {
const { disableSync, disableAutoSync } = SettingsService.get();
@@ -200,11 +200,13 @@ const onRequestPartialSync = async (
`onRequestPartialSync full:${full}, force:${force}, lastSyncTime:${lastSyncTime}`
);
if (full || force) {
await Sync.run("global", force, full, undefined, lastSyncTime);
} else {
await Sync.run("global", false, false, undefined, lastSyncTime);
}
await Sync.run(
"global",
force,
full ? "full" : "send",
undefined,
lastSyncTime
);
};
const onLogout = async (reason: string) => {
@@ -233,7 +235,7 @@ async function checkForShareExtensionLaunchedInBackground() {
if (notesAddedFromIntent || shareExtensionOpened) {
const id = useTabStore.getState().getCurrentNoteId();
const note = id && (await db.notes.note(id));
eSendEvent("webview_reset");
eSendEvent(eEditorReset);
if (note) setTimeout(() => eSendEvent("loadingNote", note), 1);
MMKV.removeItem("shareExtensionOpened");
}
@@ -253,9 +255,9 @@ async function saveEditorState() {
movedAway: editorState().movedAway,
timestamp: Date.now()
});
MMKV.setString("appState", state);
NotesnookModule.setAppState(state);
} else {
MMKV.removeItem("appState");
NotesnookModule.setAppState("");
}
}
@@ -277,8 +279,109 @@ const onSubscriptionError = async (error: RNIap.PurchaseError) => {
const SodiumEventEmitter = new NativeEventEmitter(NativeModules.Sodium);
const doAppLoadActions = async () => {
if (SettingsService.get().sessionExpired) {
eSendEvent(eLoginSessionExpired);
return;
}
notifee.setBadgeCount(0);
if (!(await db.user.getUser())) {
setLoginMessage();
return;
}
await useMessageStore.getState().setAnnouncement();
if (NewFeature.present()) return;
if (await checkAppUpdateAvailable()) return;
if (await checkForRateAppRequest()) return;
if (await PremiumService.getRemainingTrialDaysStatus()) return;
if (SettingsService.get().introCompleted) {
useMessageStore.subscribe((state) => {
const dialogs = state.dialogs;
if (dialogs.length > 0) {
eSendEvent(eOpenAnnouncementDialog, dialogs[0]);
}
});
}
};
const checkAppUpdateAvailable = async () => {
if (__DEV__ || Config.isTesting === "true" || Config.FDROID_BUILD || BETA)
return;
try {
const version =
Config.GITHUB_RELEASE === "true"
? await getGithubVersion()
: await checkVersion();
if (!version || !version?.needsUpdate) return false;
setUpdateAvailableMessage(version);
return true;
} catch (e) {
return false;
}
};
const checkForRateAppRequest = async () => {
const rateApp = SettingsService.get().rateApp as number;
if (
rateApp &&
rateApp < Date.now() &&
!useMessageStore.getState().message?.visible
) {
setRateAppMessage();
return false;
}
return false;
};
const IsDatabaseMigrationRequired = () => {
if (!db.migrations.required() || useUserStore.getState().appLocked)
return false;
presentSheet({
component: <Migrate />,
onClose: () => {
if (!db.migrations.required()) {
initializeDatabase();
}
},
disableClosing: true
});
return true;
};
const initializeDatabase = async (password?: string) => {
if (useUserStore.getState().appLocked) return;
if (!db.isInitialized) {
RNBootSplash.hide({ fade: true });
DatabaseLogger.info("Initializing database");
try {
await setupDatabase(password);
await db.init();
Sync.run();
} catch (e) {
DatabaseLogger.error(e as Error);
ToastManager.error(e as Error, "Error initializing database", "global");
}
}
if (IsDatabaseMigrationRequired()) return;
if (db.isInitialized) {
Notifications.setupReminders(true);
if (SettingsService.get().notifNotes) {
Notifications.pinQuickNote(false);
}
useSettingStore.getState().setAppLoading(false);
DatabaseLogger.info("Database initialized");
}
Walkthrough.init();
};
export const useAppEvents = () => {
const loading = useSettingStore((state) => state.isAppLoading);
const isAppLoading = useSettingStore((state) => state.isAppLoading);
const [setLastSynced, setUser, appLocked, syncing] = useUserStore((state) => [
state.setLastSynced,
state.setUser,
@@ -287,18 +390,15 @@ export const useAppEvents = () => {
]);
const syncedOnLaunch = useRef(false);
const refValues = useRef<
Partial<{
subsriptionSuccessListener: EmitterSubscription;
subsriptionErrorListener: EmitterSubscription;
isUserReady: boolean;
prevState: AppStateStatus;
showingDialog: boolean;
removeInternetStateListener: NetInfoSubscription;
isReconnecting: boolean;
initialUrl: string;
backupDidWait: boolean;
isConnectingSSE: boolean;
}>
>({});
@@ -309,7 +409,7 @@ export const useAppEvents = () => {
}, [setLastSynced]);
useEffect(() => {
if (loading) return;
if (isAppLoading) return;
let subscriptions: EventManagerSubscription[] = [];
const eventManager = db.eventManager;
@@ -324,7 +424,7 @@ export const useAppEvents = () => {
return () => {
subscriptions.forEach((sub) => sub?.unsubscribe?.());
};
}, [loading, onSyncComplete]);
}, [isAppLoading, onSyncComplete]);
const subscribeToPurchaseListeners = useCallback(async () => {
if (Platform.OS === "android") {
@@ -361,14 +461,31 @@ export const useAppEvents = () => {
const user = await db.user.getUser();
if (PremiumService.get() && user) {
if (
await BackupService.checkBackupRequired(SettingsService.get().reminder)
SettingsService.get().backupDirectoryAndroid ||
Platform.OS !== "android"
) {
if (
!SettingsService.get().backupDirectoryAndroid &&
Platform.OS === "android"
)
return;
sleep(2000).then(() => BackupService.run());
const partialBackup = await BackupService.checkBackupRequired(
SettingsService.get().reminder,
"lastBackupDate"
);
const fullBackup = await BackupService.checkBackupRequired(
SettingsService.get().fullBackupReminder,
"lastFullBackupDate"
);
await sleep(2000);
if (partialBackup) {
await BackupService.run();
}
if (fullBackup) {
await BackupService.run(true, undefined, "full");
}
}
if (SettingsService.getProperty("offlineMode")) {
db.attachments.cacheAttachments().catch(console.log);
}
}
}, []);
@@ -429,7 +546,6 @@ export const useAppEvents = () => {
setRecoveryKeyMessage();
}
if (!user?.isEmailConfirmed) setEmailVerifyMessage();
refValues.current.isUserReady = true;
syncedOnLaunch.current = true;
if (!isLogin) {
@@ -503,20 +619,21 @@ export const useAppEvents = () => {
}, [onSyncComplete, onUserUpdated]);
useEffect(() => {
const onInternetStateChanged = async (state: NetInfoState) => {
const onInternetStateChanged = async () => {
if (!syncedOnLaunch.current) return;
reconnectSSE(state);
Sync.run("global", false, "full");
reconnectSSE();
};
const onAppStateChanged = async (state: AppStateStatus) => {
if (state === "active") {
notifee.setBadgeCount(0);
updateStatusBarColor();
checkAutoBackup();
await reconnectSSE();
Sync.run("global", false, "full");
reconnectSSE();
await checkForShareExtensionLaunchedInBackground();
MMKV.removeItem("appState");
NotesnookModule.setAppState("");
let user = await db.user.getUser();
if (user && !user?.isEmailConfirmed) {
try {
@@ -530,6 +647,14 @@ export const useAppEvents = () => {
}
//@ts-ignore
globalThis["IS_SHARE_EXTENSION"] = false;
if (
SettingsService.getBackgroundEnterTime() + 60 * 1000 * 10 <
Date.now()
) {
// Reset the editor if the app has been in background for more than 10 minutes.
eSendEvent(eEditorReset);
}
} else {
await saveEditorState();
if (
@@ -561,7 +686,7 @@ export const useAppEvents = () => {
});
}
let sub: NativeEventSubscription;
if (!loading && !appLocked) {
if (!isAppLoading && !appLocked) {
setTimeout(() => {
sub = AppState.addEventListener("change", onAppStateChanged);
if (
@@ -583,7 +708,7 @@ export const useAppEvents = () => {
sub?.remove();
unsubscribePurchaseListeners();
};
}, [loading, appLocked, checkAutoBackup]);
}, [isAppLoading, appLocked, checkAutoBackup]);
useEffect(() => {
if (!appLocked && !syncing && refValues.current.backupDidWait) {
@@ -592,167 +717,35 @@ export const useAppEvents = () => {
}
}, [appLocked, syncing, checkAutoBackup]);
async function reconnectSSE(connection?: NetInfoState) {
if (refValues.current?.isReconnecting || !refValues.current?.isUserReady)
return;
if (useSettingStore.getState().appDidEnterBackgroundForAction) {
useSettingStore.getState().setAppDidEnterBackgroundForAction(false);
console.log("AppDidEnterForegroundAfterAction");
return;
}
if (SettingsService.get().sessionExpired) {
refValues.current.isReconnecting = false;
return;
}
refValues.current.isReconnecting = true;
let connectionState = connection;
async function reconnectSSE() {
try {
if (!connectionState) {
connectionState = await NetInfo.fetch();
}
const user = await db.user.getUser();
if (
user &&
connectionState.isConnected &&
connectionState.isInternetReachable
) {
await db.connectSSE();
} else {
useUserStore.getState().setSyncing(false);
await db.syncer.stop();
}
refValues.current.isReconnecting = false;
if (refValues.current?.isConnectingSSE) return;
refValues.current.isConnectingSSE = true;
await db.connectSSE();
refValues.current.isConnectingSSE = false;
} catch (e) {
refValues.current.isReconnecting = false;
refValues.current.isConnectingSSE = false;
DatabaseLogger.error(e as Error);
}
}
useEffect(() => {
if (!loading) {
if (!isAppLoading) {
onUserUpdated();
doAppLoadActions();
}
}, [loading, onUserUpdated]);
const initializeDatabase = useCallback(async (password?: string) => {
const IsDatabaseMigrationRequired = () => {
if (!db.migrations.required() || useUserStore.getState().appLocked)
return false;
presentSheet({
component: <Migrate />,
onClose: () => {
if (!db.migrations.required()) {
initializeDatabase();
}
},
disableClosing: true
});
return true;
};
if (useUserStore.getState().appLocked) return;
if (!db.isInitialized) {
RNBootSplash.hide({ fade: true });
DatabaseLogger.info("Initializing database");
try {
await setupDatabase(password);
await db.init();
} catch (e) {
DatabaseLogger.error(e as Error);
ToastManager.error(e as Error, "Error initializing database", "global");
}
}
if (IsDatabaseMigrationRequired()) return;
if (db.isInitialized) {
Notifications.setupReminders(true);
if (SettingsService.get().notifNotes) {
Notifications.pinQuickNote(false);
}
useSettingStore.getState().setAppLoading(false);
DatabaseLogger.info("Database initialized");
}
Walkthrough.init();
}, []);
}, [isAppLoading, onUserUpdated]);
useEffect(() => {
let sub: () => void;
if (appLocked) {
const sub = useUserStore.subscribe((state) => {
if (!state.appLocked && useSettingStore.getState().isAppLoading) {
console.log("DB initialized");
if (!appLocked && isAppLoading) {
initializeLogger()
.catch((e) => {
console.log(e);
})
.finally(() => {
//@ts-ignore
initializeDatabase();
sub();
}
});
});
}
return () => {
sub?.();
};
}, [appLocked, initializeDatabase]);
return initializeDatabase;
};
const doAppLoadActions = async () => {
if (SettingsService.get().sessionExpired) {
eSendEvent(eLoginSessionExpired);
return;
}
notifee.setBadgeCount(0);
if (!(await db.user.getUser())) {
setLoginMessage();
return;
}
await useMessageStore.getState().setAnnouncement();
if (NewFeature.present()) return;
if (await checkAppUpdateAvailable()) return;
if (await checkForRateAppRequest()) return;
if (await PremiumService.getRemainingTrialDaysStatus()) return;
if (SettingsService.get().introCompleted) {
useMessageStore.subscribe((state) => {
const dialogs = state.dialogs;
if (dialogs.length > 0) {
eSendEvent(eOpenAnnouncementDialog, dialogs[0]);
}
});
}
};
const checkAppUpdateAvailable = async () => {
if (__DEV__ || Config.isTesting === "true" || Config.FDROID_BUILD || BETA)
return;
try {
const version =
Config.GITHUB_RELEASE === "true"
? await getGithubVersion()
: await checkVersion();
if (!version || !version?.needsUpdate) return false;
setUpdateAvailableMessage(version);
return true;
} catch (e) {
return false;
}
};
const checkForRateAppRequest = async () => {
const rateApp = SettingsService.get().rateApp as number;
if (
rateApp &&
rateApp < Date.now() &&
!useMessageStore.getState().message?.visible
) {
setRateAppMessage();
return false;
}
return false;
}, [appLocked, isAppLoading]);
};

View File

@@ -22,20 +22,14 @@ import { Platform } from "react-native";
import { Subscription } from "react-native-iap";
import PremiumService from "../services/premium";
import { db } from "../common/database";
import { Product } from "@notesnook/core/dist/api/pricing";
type PurchaseInfo = {
country: string;
countryCode: string;
sku: string;
discount: number;
};
const skuInfos: { [name: string]: PurchaseInfo | undefined } = {};
const skuInfos: { [name: string]: Product | undefined } = {};
export const usePricing = (period: "monthly" | "yearly") => {
const [current, setCurrent] = useState<{
period: string;
info?: PurchaseInfo;
info?: Product;
product?: Subscription;
}>();
@@ -54,6 +48,7 @@ export const usePricing = (period: "monthly" | "yearly") => {
period
));
skuInfos[period] = skuInfo;
const products = (await PremiumService.getProducts()) as Subscription[];
let product = products.find((p) => p.productId === skuInfo?.sku);
if (!product)

View File

@@ -62,7 +62,6 @@ import {
} from "../services/event-manager";
import { useSettingStore } from "../stores/use-setting-store";
import {
eClearEditor,
eCloseFullscreenEditor,
eOnEnterEditor,
eOnExitEditor,
@@ -286,9 +285,10 @@ const _TabsHolder = () => {
break;
case "mobile":
if (
state &&
!state?.movedAway &&
useTabStore.getState().getCurrentNoteId()
(state &&
!state?.movedAway &&
useTabStore.getState().getCurrentNoteId()) ||
editorState().movedAway === false
) {
tabBarRef.current?.goToIndex(2, false);
} else {

View File

@@ -16,7 +16,7 @@
"html-to-text": "9.0.5",
"phone": "^3.1.14",
"qclone": "^1.2.0",
"react-native-actions-sheet": "0.9.3",
"react-native-actions-sheet": "0.9.7",
"react-native-check-version": "https://github.com/flexible-agency/react-native-check-version",
"react-native-drax": "^0.10.2",
"react-native-image-zoom-viewer": "^3.0.1",

View File

@@ -39,6 +39,7 @@ import {
eSubscribeEvent
} from "../../services/event-manager";
import {
eEditorReset,
eOnLoadNote,
eUnlockNote,
eUnlockWithBiometrics,
@@ -54,8 +55,10 @@ import { syncTabs, useTabStore } from "./tiptap/use-tab-store";
import {
editorController,
editorState,
openInternalLink
openInternalLink,
randId
} from "./tiptap/utils";
import { tabBarRef } from "../../utils/global-refs";
const style: ViewStyle = {
height: "100%",
@@ -102,24 +105,20 @@ const Editor = React.memo(
noToolbar,
noHeader
});
const renderKey = useRef(`editor-0` + editorId);
const renderKey = useRef(randId("editor-id") + editorId);
useImperativeHandle(ref, () => ({
get: () => editor
}));
useLockedNoteHandler();
const onError = useCallback(() => {
renderKey.current =
renderKey.current === `editor-0`
? `editor-1` + editorId
: `editor-0` + editorId;
renderKey.current = randId("editor-id") + editorId;
editor.state.current.ready = false;
editor.setLoading(true);
}, [editor, editorId]);
useEffect(() => {
const sub = [eSubscribeEvent("webview_reset", onError)];
const sub = [eSubscribeEvent(eEditorReset, onError)];
return () => {
sub.forEach((s) => s?.unsubscribe());
};
@@ -146,6 +145,7 @@ const Editor = React.memo(
nestedScrollEnabled
onError={onError}
injectedJavaScriptBeforeContentLoaded={`
globalThis.__DEV__ = ${__DEV__}
globalThis.readonly=${readonly};
globalThis.noToolbar=${noToolbar};
globalThis.noHeader=${noHeader};
@@ -339,7 +339,7 @@ const useLockedNoteHandler = () => {
}),
eSubscribeEvent(eUnlockWithPassword, onSubmit)
];
if (tabRef.current?.locked) {
if (tabRef.current?.locked && tabBarRef.current?.page() === 2) {
unlock();
}
return () => {

View File

@@ -75,14 +75,16 @@ export function ReadonlyEditor(props: {
if (editorMessage.type === EventTypes.readonlyEditorLoaded) {
console.log("Readonly editor loaded.");
props.onLoad?.((content: { data: string; id: string }) => {
noteId.current = content.id;
editorRef.current?.postMessage(
JSON.stringify({
type: "native:html",
value: content.data
})
);
setLoading(false);
setTimeout(() => {
noteId.current = content.id;
editorRef.current?.postMessage(
JSON.stringify({
type: "native:html",
value: content.data
})
);
setLoading(false);
}, 300);
});
} else if (editorMessage.type === EventTypes.getAttachmentData) {
const attachment = (editorMessage.value as any).attachment as Attachment;

View File

@@ -48,5 +48,6 @@ export const EventTypes = {
unlockWithBiometrics: "editor-events:unlock-biometrics",
disableReadonlyMode: "editor-events:disable-readonly-mode",
readonlyEditorLoaded: "readonlyEditorLoaded",
error: "editorError"
error: "editorError",
dbLogger: "editor-events:dbLogger"
};

View File

@@ -19,14 +19,14 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import Sodium from "@ammarahmed/react-native-sodium";
import { isImage } from "@notesnook/core/dist/utils/filename";
import { basename } from "pathe";
import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import DocumentPicker from "react-native-document-picker";
import {
ImagePickerResponse,
launchCamera,
launchImageLibrary
} from "react-native-image-picker";
import DocumentPicker, {
DocumentPickerOptions,
DocumentPickerResponse
} from "react-native-document-picker";
import { Image, openCamera, openPicker } from "react-native-image-crop-picker";
import { DatabaseLogger, db } from "../../../common/database";
import filesystem from "../../../common/filesystem";
import { compressToFile } from "../../../common/filesystem/compress";
@@ -43,7 +43,7 @@ import { eCloseSheet } from "../../../utils/events";
import { useTabStore } from "./use-tab-store";
import { editorController, editorState } from "./utils";
const showEncryptionSheet = (file) => {
const showEncryptionSheet = (file: DocumentPickerResponse) => {
presentSheet({
title: "Encrypting attachment",
paragraph: `Please wait while we encrypt ${file.name} file for upload`,
@@ -51,24 +51,25 @@ const showEncryptionSheet = (file) => {
});
};
const santizeUri = (uri) => {
const santizeUri = (uri: string) => {
uri = decodeURI(uri);
uri = Platform.OS === "ios" ? uri.replace("file:///", "/") : uri;
return uri;
};
/**
* @param {{
* noteId: string,
* tabId: string,
* type: "image" | "camera" | "file"
* reupload: boolean
* hash?: string
* }} fileOptions
*/
const file = async (fileOptions) => {
type PickerOptions = {
noteId?: string;
tabId?: number;
type: "image" | "camera" | "file";
reupload: boolean;
hash?: string;
context?: string;
outputType?: "base64" | "url" | "cache";
};
const file = async (fileOptions: PickerOptions) => {
try {
const options = {
const options: DocumentPickerOptions<"ios"> = {
mode: "import",
allowMultiSelection: false
};
@@ -87,11 +88,11 @@ const file = async (fileOptions) => {
file = file[0];
let uri = Platform.OS === "ios" ? file.fileCopyUri : file.uri;
let uri = Platform.OS === "ios" ? file.fileCopyUri || file.uri : file.uri;
if (file.size > FILE_SIZE_LIMIT) {
if ((file.size || 0) > FILE_SIZE_LIMIT) {
ToastManager.show({
title: "File too large",
heading: "File too large",
message: "The maximum allowed size per file is 500 MB",
type: "error"
});
@@ -108,29 +109,40 @@ const file = async (fileOptions) => {
return;
}
console.log("file uri: ", uri);
uri = Platform.OS === "ios" ? santizeUri(uri) : uri;
showEncryptionSheet(file);
const hash = await Sodium.hashFile({
uri: uri,
type: "url"
});
if (!(await attachFile(uri, hash, file.type, file.name, fileOptions)))
return;
if (
!(await attachFile(
uri,
hash,
file.type || "application/octet-stream",
file.name,
fileOptions
))
) {
throw new Error("Failed to attach file");
}
if (Platform.OS === "ios") await RNFetchBlob.fs.unlink(uri);
if (
useTabStore.getState().getNoteIdForTab(options.tabId) === options.noteId
fileOptions.tabId !== undefined &&
fileOptions.noteId &&
useTabStore.getState().getNoteIdForTab(fileOptions.tabId) ===
fileOptions.noteId
) {
if (isImage(file.type)) {
if (isImage(file.type || "application/octet-stream")) {
editorController.current?.commands.insertImage(
{
hash: hash,
filename: file.name,
mime: file.type,
size: file.size,
dataurl: await db.attachments.read(hash, "base64"),
title: file.name
mime: file.type || "application/octet-stream",
size: file.size || 0,
dataurl: (await db.attachments.read(hash, "base64")) as string,
type: "image"
},
fileOptions.tabId
);
@@ -139,51 +151,86 @@ const file = async (fileOptions) => {
{
hash: hash,
filename: file.name,
mime: file.type,
size: file.size
mime: file.type || "application/octet-stream",
size: file.size || 0,
type: "file"
},
fileOptions.tabId
);
}
} else {
throw new Error("Failed to attach file, no tabId is set");
}
setTimeout(() => {
eSendEvent(eCloseSheet);
}, 1000);
eSendEvent(eCloseSheet);
} catch (e) {
eSendEvent(eCloseSheet);
ToastManager.show({
heading: e.message,
message: "You need internet access to attach a file",
heading: "Failed to attach file",
message: (e as Error).message,
type: "error",
context: "global"
});
console.log("attachment error: ", e);
DatabaseLogger.error(e);
}
};
/**
* @param {{
* noteId: string,
* tabId: string,
* type: "image" | "camera" | "file"
* reupload: boolean
* hash?: string
* }} options
*/
const camera = async (options) => {
const camera = async (options: PickerOptions) => {
try {
await db.attachments.generateKey();
useSettingStore.getState().setAppDidEnterBackgroundForAction(true);
launchCamera(
{
includeBase64: true,
mediaType: "photo"
},
(response) => handleImageResponse(response, options)
);
openCamera({
mediaType: "photo",
includeBase64: true,
cropping: false,
multiple: true,
maxFiles: 10,
writeTempFile: true,
compressImageQuality: 1
})
.then((response) => {
handleImageResponse(
Array.isArray(response) ? response : [response],
options
);
})
.catch((e) => {
console.log("camera error: ", e);
});
} catch (e) {
ToastManager.show({
heading: e.message,
heading: (e as Error).message,
type: "error",
context: "global"
});
}
};
const gallery = async (options: PickerOptions) => {
try {
await db.attachments.generateKey();
useSettingStore.getState().setAppDidEnterBackgroundForAction(true);
openPicker({
includeBase64: true,
mediaType: "photo",
maxFiles: 10,
cropping: false,
multiple: true,
compressImageQuality: 1
})
.then((response) =>
handleImageResponse(
Array.isArray(response) ? response : [response],
options
)
)
.catch((e) => {
console.log("gallery error: ", e);
});
} catch (e) {
useSettingStore.getState().setAppDidEnterBackgroundForAction(false);
ToastManager.show({
heading: (e as Error).message,
message: "You need internet access to attach a file",
type: "error",
context: "global"
@@ -192,53 +239,9 @@ const camera = async (options) => {
}
};
const gallery = async (options) => {
try {
await db.attachments.generateKey();
useSettingStore.getState().setAppDidEnterBackgroundForAction(true);
launchImageLibrary(
{
includeBase64: true,
mediaType: "photo",
selectionLimit: 10
},
(response) => handleImageResponse(response, options)
);
} catch (e) {
ToastManager.show({
heading: e.message,
message: "You need internet access to attach a file",
type: "error",
context: "global"
});
console.log("attachment error:", e);
}
};
/**
*
* @typedef {{
* noteId?: string,
* tabId?: string,
* type: "image" | "camera" | "file"
* reupload: boolean
* hash?: string
* context?: string
* }} ImagePickerOptions
*
* @param {{
* noteId?: string,
* tabId?: string,
* type: "image" | "camera" | "file"
* reupload: boolean
* hash?: string
* context?: string
* }} options
* @returns
*/
const pick = async (options) => {
const pick = async (options: PickerOptions) => {
if (!PremiumService.get()) {
let user = await db.user.getUser();
const user = await db.user.getUser();
if (editorState().isFocused) {
editorState().isFocused = true;
}
@@ -259,58 +262,59 @@ const pick = async (options) => {
file(options);
}
};
/**
*
* @param {ImagePickerResponse} response
* @param {ImagePickerOptions} options
* @returns
*/
const handleImageResponse = async (response, options) => {
if (
response.didCancel ||
response.errorMessage ||
!response.assets ||
response.assets?.length === 0
) {
return;
}
const result = await AttachImage.present(response);
const handleImageResponse = async (
response: Image[],
options: PickerOptions
) => {
const result = await AttachImage.present(response, options.context);
if (!result) return;
const compress = result.compress;
for (let image of response.assets) {
const isPng = /(png)/g.test(image.type);
const isJpeg = /(jpeg|jpg)/g.test(image.type);
for (const image of response) {
const isPng = /(png)/g.test(image.mime);
const isJpeg = /(jpeg|jpg)/g.test(image.mime);
if (compress && (isPng || isJpeg)) {
image.uri = await compressToFile(
Platform.OS === "ios" ? "file://" + image.uri : image.uri,
image.path = await compressToFile(
Platform.OS === "ios" ? "file://" + image.path : image.path,
isPng ? "PNG" : "JPEG"
);
const stat = await RNFetchBlob.fs.stat(image.uri.replace("file://", ""));
image.fileSize = stat.size;
const stat = await RNFetchBlob.fs.stat(image.path.replace("file://", ""));
image.size = stat.size;
image.path =
Platform.OS === "ios" ? image.path.replace("file://", "") : image.path;
}
if (image.fileSize > IMAGE_SIZE_LIMIT) {
if (image.size > IMAGE_SIZE_LIMIT) {
ToastManager.show({
title: "File too large",
heading: "File too large",
message: "The maximum allowed size per image is 50 MB",
type: "error"
});
return;
}
let b64 = `data:${image.type};base64, ` + image.base64;
const uri = decodeURI(image.uri);
const b64 = `data:${image.mime};base64, ` + image.data;
const uri = decodeURI(image.path);
const hash = await Sodium.hashFile({
uri: uri,
type: "url"
});
let fileName = image.originalFileName || image.fileName;
let fileName = image.sourceURL
? basename(image.sourceURL)
: image.filename || "image";
fileName =
image.mime === "image/jpeg"
? fileName.replace(/HEIC|HEIF/, "jpeg")
: fileName;
console.log("attaching image...", fileName);
console.log("attaching file...");
if (!(await attachFile(uri, hash, image.type, fileName, options))) return;
if (!(await attachFile(uri, hash, image.mime, fileName, options))) return;
if (Platform.OS === "ios") await RNFetchBlob.fs.unlink(uri);
console.log("attaching image to note...");
@@ -322,11 +326,13 @@ const handleImageResponse = async (response, options) => {
editorController.current?.commands.insertImage(
{
hash: hash,
mime: image.type,
title: fileName,
mime: image.mime,
type: "image",
dataurl: b64,
size: image.fileSize,
filename: fileName
size: image.size,
filename: fileName as string,
width: image.width,
height: image.height
},
options.tabId
);
@@ -343,10 +349,16 @@ const handleImageResponse = async (response, options) => {
* @param {ImagePickerOptions} options
* @returns
*/
export async function attachFile(uri, hash, type, filename, options) {
export async function attachFile(
uri: string,
hash: string,
type: string,
filename: string,
options: PickerOptions
) {
try {
let exists = await db.attachments.exists(hash);
let encryptionInfo;
const exists = await db.attachments.exists(hash);
let encryptionInfo: any;
if (options?.hash && options.hash !== hash) {
ToastManager.show({
heading: "Please select the same file for reuploading",
@@ -358,26 +370,36 @@ export async function attachFile(uri, hash, type, filename, options) {
}
if (!options.reupload && exists) {
options.reupload = (await filesystem.getUploadedFileSize(hash)) <= 0;
options.reupload = (await filesystem.getUploadedFileSize(hash)) === 0;
}
if (options.reupload) {
DatabaseLogger.log(`Deleting file before reupload. ${hash}`);
const deleted = await db.fs().deleteFile(hash, false);
if (!deleted)
throw new Error(`Failed to delete file before reupload. ${hash}`);
}
if (!exists || options?.reupload) {
let key = await db.attachments.generateKey();
const key = await db.attachments.generateKey();
encryptionInfo = await Sodium.encryptFile(key, {
uri: uri,
type: options.type || "url",
type: options.outputType || "url",
hash: hash
});
} as any);
encryptionInfo.mimeType = type;
encryptionInfo.filename = filename;
encryptionInfo.alg = "xcha-stream";
encryptionInfo.size = encryptionInfo.length;
encryptionInfo.key = key;
if (options?.reupload && exists) await db.attachments.reset(hash);
if (options?.reupload && exists) {
const attachment = await db.attachments.attachment(hash);
if (attachment) await db.attachments.reset(attachment?.id);
}
} else {
encryptionInfo = { hash: hash };
}
await db.attachments.add(encryptionInfo, options.noteId);
await db.attachments.add(encryptionInfo);
return true;
} catch (e) {
DatabaseLogger.error(e);

View File

@@ -37,6 +37,7 @@ export type EditorState = {
isAwaitingResult: boolean;
scrollPosition: number;
overlay?: boolean;
initialLoadCalled?: boolean;
};
export type Settings = {
@@ -74,6 +75,8 @@ export type EditorMessage<T> = {
type: string;
noteId: string;
tabId: number;
resolverId?: string;
hasTimeout?: boolean;
};
export type SavePayload = {
@@ -84,6 +87,7 @@ export type SavePayload = {
sessionHistoryId?: number;
ignoreEdit: boolean;
tabId: number;
pendingChanges?: boolean;
};
export type AppState = {

View File

@@ -353,8 +353,15 @@ export const useEditorEvents = (
const data = event.nativeEvent.data;
const editorMessage = JSON.parse(data) as EditorMessage<any>;
if (editorMessage.hasTimeout && editorMessage.resolverId) {
editor.postMessage(EditorEvents.resolve, {
data: true,
resolverId: editorMessage.resolverId
});
}
if (editorMessage.type === EventTypes.load) {
console.log("Editor loaded");
DatabaseLogger.log("Editor is ready");
editor.onLoad();
return;
}
@@ -382,21 +389,36 @@ export const useEditorEvents = (
content: editorMessage.value.html as string,
noteId: noteId,
tabId: editorMessage.tabId,
ignoreEdit: (editorMessage.value as ContentMessage).ignoreEdit
ignoreEdit: (editorMessage.value as ContentMessage).ignoreEdit,
pendingChanges: editorMessage.value?.pendingChanges
});
break;
case EventTypes.title:
DatabaseLogger.log("EventTypes.title");
editor.saveContent({
type: editorMessage.type,
title: editorMessage.value as string,
title: editorMessage.value?.title as string,
noteId: noteId,
tabId: editorMessage.tabId,
ignoreEdit: false
ignoreEdit: false,
pendingChanges: editorMessage.value?.pendingChanges
});
break;
case EventTypes.logger:
logger.info("[WEBVIEW LOG]", editorMessage.value);
logger.info("[EDITOR LOG]", editorMessage.value);
break;
case EventTypes.dbLogger:
if (editorMessage.value.error) {
DatabaseLogger.error(
editorMessage.value.error,
editorMessage.value.error,
{
message: "[EDITOR_ERROR]" + editorMessage.value.message
}
);
} else {
DatabaseLogger.info("[EDITOR_LOG]" + editorMessage.value.message);
}
break;
case EventTypes.contentchange:
editor.onContentChanged(editorMessage.noteId);
@@ -449,7 +471,7 @@ export const useEditorEvents = (
break;
case EventTypes.filepicker:
editorState().isAwaitingResult = true;
const { pick } = require("./picker.js").default;
const { pick } = require("./picker").default;
pick({
type: editorMessage.value,
noteId: noteId,
@@ -484,17 +506,17 @@ export const useEditorEvents = (
console.log(
"Got attachment data:",
!!data,
(editorMessage.value as any).resolverId
editorMessage.resolverId
);
editor.postMessage(EditorEvents.attachmentData, {
resolverId: (editorMessage.value as any).resolverId,
editor.postMessage(EditorEvents.resolve, {
resolverId: editorMessage.resolverId,
data
});
})
.catch((e) => {
DatabaseLogger.error(e);
editor.postMessage(EditorEvents.attachmentData, {
resolverId: (editorMessage.value as any).resolverId,
editor.postMessage(EditorEvents.resolve, {
resolverId: editorMessage.resolverId,
data: undefined
});
});
@@ -621,7 +643,7 @@ export const useEditorEvents = (
case EventTypes.createInternalLink: {
LinkNote.present(
editorMessage.value.attributes,
editorMessage.value.resolverId
editorMessage.resolverId as string
);
break;
}

View File

@@ -39,6 +39,7 @@ import { DatabaseLogger, db } from "../../../common/database";
import useGlobalSafeAreaInsets from "../../../hooks/use-global-safe-area-insets";
import { DDS } from "../../../services/device-detection";
import {
ToastManager,
eSendEvent,
eSubscribeEvent,
eUnSubscribeEvent
@@ -46,16 +47,20 @@ import {
import Navigation from "../../../services/navigation";
import Notifications from "../../../services/notifications";
import SettingsService from "../../../services/settings";
import { useSettingStore } from "../../../stores/use-setting-store";
import { useTagStore } from "../../../stores/use-tag-store";
import {
eEditorReset,
eEditorTabFocused,
eOnLoadNote,
eShowMergeDialog,
eUpdateNoteInEditor
} from "../../../utils/events";
import { tabBarRef } from "../../../utils/global-refs";
import { unlockVault } from "../../../utils/unlock-vault";
import { onNoteCreated } from "../../notes/common";
import Commands from "./commands";
import { EventTypes } from "./editor-events";
import { SessionHistory } from "./session-history";
import { EditorState, SavePayload } from "./types";
import { syncTabs, useTabStore } from "./use-tab-store";
@@ -68,6 +73,7 @@ import {
isEditorLoaded,
post
} from "./utils";
import { sleep } from "../../../utils/time";
type NoteWithContent = Note & {
content?: NoteContent<false>;
@@ -145,8 +151,9 @@ export const useEditor = (
useEffect(() => {
const event = eSubscribeEvent(eEditorTabFocused, (tabId) => {
console.log("Editot tab focus changed", lastTabFocused.current, tabId);
if (lastTabFocused.current !== tabId) lock.current = false;
lastTabFocused.current = tabId as number;
console.log(tabId);
});
return () => {
event?.unsubscribe();
@@ -165,10 +172,11 @@ export const useEditor = (
useEffect(() => {
if (loading) {
overlay(true);
state.current.ready = false;
setLoading(false);
}
}, [loading]);
}, [loading, overlay]);
const withTimer = useCallback(
(id: string, fn: () => void, duration: number) => {
@@ -216,7 +224,8 @@ export const useEditor = (
type,
ignoreEdit,
sessionHistoryId: currentSessionHistoryId,
tabId
tabId,
pendingChanges
}: SavePayload) => {
if (currentNotes.current[id as string]?.readonly || readonly) return;
try {
@@ -277,12 +286,26 @@ export const useEditor = (
);
}, 50);
const saveTimer = setTimeout(() => {
DatabaseLogger.log(`Note save timeout: ${id}...`);
ToastManager.error(
new Error(
"Copy your changes and restart the app to avoid data loss. If the issue persists, please report to us at support@streetwriters.co."
),
"Saving note is taking too long",
"global",
15000
);
}, 30 * 1000);
if (!locked) {
DatabaseLogger.log(`Saving note: ${id}...`);
id = await db.notes?.add({ ...noteData });
saved = true;
DatabaseLogger.log(`Note saved: ${id}...`);
clearTimeout(saveTimer);
if (!note && id) {
editorSessionHistory.newSession(id);
if (id) {
@@ -316,9 +339,31 @@ export const useEditor = (
Notifications.pinNote(id as string);
}
} else {
noteData.contentId = note?.contentId;
if (!db.vault.unlocked) {
if (pendingChanges) await sleep(3000);
const unlocked = await unlockVault({
title: "Unlock vault to save note",
paragraph: `This note is locked, unlock to save ${
pendingChanges ? "some pending" : ""
} changes`,
context: "global"
});
if (!unlocked)
throw new Error("Could not save note, vault is locked");
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await db.vault?.save(noteData as any);
if (typeof noteData.title === "string") {
await db.notes.add({
title: noteData.title,
id: noteData.id
});
}
noteData.contentId = note?.contentId;
if (data) {
await db.vault?.save(noteData as any);
}
clearTimeout(saveTimer);
}
if (id && useTabStore.getState().getTabForNote(id) === tabId) {
@@ -341,6 +386,16 @@ export const useEditor = (
}
}
if (
id &&
id === useTabStore.getState().getCurrentNoteId() &&
pendingChanges
) {
postMessage(EditorEvents.title, title || note?.title, tabId);
postMessage(EditorEvents.html, data, tabId);
currentNotes.current[id] = note;
}
saveCount.current++;
return id;
} catch (e) {
@@ -415,7 +470,11 @@ export const useEditor = (
commands.focus(tabId);
});
} else {
if (!event.item) return;
if (!event.item) {
overlay(false);
return;
}
console.log("LOADING NOTE", event.item.id);
const item = event.item;
const currentTab = useTabStore
@@ -443,7 +502,6 @@ export const useEditor = (
useTabStore.getState().focusTab(tabId);
setTimeout(() => {
if (blockIdRef.current) {
console.log("scrolling to block", blockIdRef.current);
commands.scrollIntoViewById(blockIdRef.current);
blockIdRef.current = undefined;
}
@@ -502,6 +560,7 @@ export const useEditor = (
loadingState.current === currentContents.current[item.id]?.data
) {
// If note is already loading, return.
console.log("Note is already loading...");
return;
}
@@ -510,7 +569,7 @@ export const useEditor = (
return;
}
lastContentChangeTime.current[item.id] = item.dateEdited;
lastContentChangeTime.current[item.id] = 0;
currentLoadingNoteId.current = item.id;
currentNotes.current[item.id] = item;
@@ -535,11 +594,8 @@ export const useEditor = (
10000
);
console.log("blockId", blockIdRef.current);
setTimeout(() => {
if (blockIdRef.current) {
console.log("scrolling to block", blockIdRef.current);
commands.scrollIntoViewById(blockIdRef.current);
blockIdRef.current = undefined;
}
@@ -573,124 +629,130 @@ export const useEditor = (
data: Note | ContentItem | TrashItem | DeletedItem,
isLocal?: boolean
) => {
if (SettingsService.get().disableRealtimeSync && !isLocal) return;
if (!data) return;
try {
await (async () => {
if (SettingsService.get().disableRealtimeSync && !isLocal) return;
if (!data) return;
if (isDeleted(data) || isTrashItem(data)) {
const tabId = useTabStore.getState().getTabForNote(data.id);
if (tabId !== undefined) {
console.log("Removing tab");
await commands.clearContent(tabId);
useTabStore.getState().removeTab(tabId);
}
return;
}
const noteId =
(data as ContentItem).type === "tiptap"
? (data as ContentItem).noteId
: data.id;
if (!useTabStore.getState().hasTabForNote(noteId)) return;
const tabId = useTabStore.getState().getTabForNote(noteId) as number;
const tab = useTabStore.getState().getTab(tabId);
const note = data.type === "note" ? data : await db.notes?.note(noteId);
lock.current = true;
// Handle this case where note was locked on another device and synced.
const locked = await db.vaults.itemExists(
currentNotes.current[noteId] as ItemReference
);
if (note) {
if (!locked && tab?.noteLocked) {
// Note lock removed.
if (tab.locked) {
if (useTabStore.getState().currentTab === tabId) {
eSendEvent(eOnLoadNote, {
item: note,
forced: true
});
} else {
useTabStore.getState().updateTab(tabId, {
locked: false,
noteLocked: false
});
commands.setLoading(true, tabId);
if (isDeleted(data) || isTrashItem(data)) {
const tabId = useTabStore.getState().getTabForNote(data.id);
if (tabId !== undefined) {
console.log("Removing tab");
await commands.clearContent(tabId);
useTabStore.getState().removeTab(tabId);
}
}
} else if (!tab?.noteLocked && locked) {
// Note lock added.
useTabStore.getState().updateTab(tabId, {
locked: true,
noteLocked: true
});
if (useTabStore.getState().currentTab !== tabId) {
commands.clearContent(tabId);
commands.setLoading(true, tabId);
}
}
if (currentNotes.current[noteId]?.title !== note.title) {
postMessage(EditorEvents.title, note.title, tabId);
}
commands.setTags(note);
if (currentNotes.current[noteId]?.dateEdited !== note.dateEdited) {
commands.setStatus(
getFormattedDate(note.dateEdited, "date-time"),
"Saved",
tabId as number
);
}
console.log("readonly state changed...", note.readonly);
useTabStore.getState().updateTab(tabId, {
readonly: note.readonly
});
}
if (data.type === "tiptap" && note && !isLocal) {
if (lastContentChangeTime.current[noteId] >= data.dateEdited) {
lock.current = false;
return;
}
if (locked && isEncryptedContent(data)) {
const decryptedContent = await db.vault?.decryptContent(data, noteId);
if (!decryptedContent) {
useTabStore.getState().updateTab(tabId, {
locked: true,
noteLocked: true
});
if (useTabStore.getState().currentTab !== tabId) {
commands.clearContent(tabId);
commands.setLoading(true, tabId);
}
} else {
await postMessage(
EditorEvents.updatehtml,
decryptedContent.data,
tabId
);
currentContents.current[note.id] = decryptedContent;
}
} else {
const _nextContent = data.data;
if (_nextContent === currentContents.current?.data) {
lock.current = false;
return;
}
lastContentChangeTime.current[note.id] = note.dateEdited;
await postMessage(EditorEvents.updatehtml, _nextContent, tabId);
if (!isEncryptedContent(data)) {
currentContents.current[note.id] = data as UnencryptedContentItem;
const noteId =
(data as ContentItem).type === "tiptap"
? (data as ContentItem).noteId
: data.id;
if (!useTabStore.getState().hasTabForNote(noteId)) return;
const tabId = useTabStore.getState().getTabForNote(noteId) as number;
const tab = useTabStore.getState().getTab(tabId);
const note =
data.type === "note" ? data : await db.notes?.note(noteId);
lock.current = true;
// Handle this case where note was locked on another device and synced.
const locked = note
? await db.vaults.itemExists(note as ItemReference)
: false;
if (note) {
if (!locked && tab?.noteLocked) {
// Note lock removed.
if (tab.locked) {
if (useTabStore.getState().currentTab === tabId) {
eSendEvent(eOnLoadNote, {
item: note,
forced: true
});
} else {
useTabStore.getState().updateTab(tabId, {
locked: false,
noteLocked: false
});
commands.setLoading(true, tabId);
}
}
} else if (!tab?.noteLocked && locked) {
// Note lock added.
useTabStore.getState().updateTab(tabId, {
locked: true,
noteLocked: true
});
if (useTabStore.getState().currentTab !== tabId) {
commands.clearContent(tabId);
commands.setLoading(true, tabId);
}
}
if (currentNotes.current[noteId]?.title !== note.title) {
postMessage(EditorEvents.title, note.title, tabId);
}
commands.setTags(note);
if (currentNotes.current[noteId]?.dateEdited !== note.dateEdited) {
commands.setStatus(
getFormattedDate(note.dateEdited, "date-time"),
"Saved",
tabId as number
);
}
useTabStore.getState().updateTab(tabId, {
readonly: note.readonly
});
}
}
if (data.type === "tiptap" && note && !isLocal) {
if (lastContentChangeTime.current[noteId] >= data.dateModified) {
return;
}
if (locked && isEncryptedContent(data)) {
const decryptedContent = await db.vault?.decryptContent(data);
if (!decryptedContent) {
useTabStore.getState().updateTab(tabId, {
locked: true,
noteLocked: true
});
if (useTabStore.getState().currentTab !== tabId) {
commands.clearContent(tabId);
commands.setLoading(true, tabId);
}
} else {
await postMessage(
EditorEvents.updatehtml,
decryptedContent.data,
tabId
);
currentContents.current[note.id] = decryptedContent;
}
} else {
const _nextContent = data.data;
if (_nextContent === currentContents.current[note.id]?.data) {
return;
}
lastContentChangeTime.current[note.id] = note.dateEdited;
await postMessage(EditorEvents.updatehtml, _nextContent, tabId);
if (!isEncryptedContent(data)) {
currentContents.current[note.id] =
data as UnencryptedContentItem;
}
}
}
})();
} catch (e) {
DatabaseLogger.error(e as Error, "Error when applying sync changes");
} finally {
lock.current = false;
}
lock.current = false;
},
[postMessage, commands]
);
@@ -713,7 +775,8 @@ export const useEditor = (
type,
ignoreEdit,
noteId,
tabId
tabId,
pendingChanges
}: {
noteId?: string;
title?: string;
@@ -721,18 +784,29 @@ export const useEditor = (
type: string;
ignoreEdit: boolean;
tabId: number;
pendingChanges?: boolean;
}) => {
DatabaseLogger.log(`Saving content...`);
DatabaseLogger.log(
`saveContent... title: ${!!title}, content: ${!!content}, noteId: ${noteId}`
);
if (
lock.current ||
(currentLoadingNoteId.current &&
currentLoadingNoteId.current === noteId)
) {
DatabaseLogger.log(`Skipped saving conent:
DatabaseLogger.log(`Skipped saving content:
lock.current: ${lock.current}
currentLoadingNoteId.current: ${currentLoadingNoteId.current}
`);
if (lock.current) {
setTimeout(() => {
if (lock.current) {
DatabaseLogger.warn("Editor force removed lock after 5 seconds");
lock.current = false;
}
}, 5000);
}
return;
}
@@ -740,7 +814,7 @@ export const useEditor = (
lastContentChangeTime.current[noteId] = Date.now();
}
if (type === EditorEvents.content && noteId) {
if (type === EventTypes.content && noteId) {
currentContents.current[noteId as string] = {
data: content,
type: "tiptap",
@@ -755,7 +829,8 @@ export const useEditor = (
id: noteId,
ignoreEdit,
sessionHistoryId: noteId ? editorSessionHistory.get(noteId) : undefined,
tabId: tabId
tabId: tabId,
pendingChanges
};
withTimer(
noteId || "newnote",
@@ -767,7 +842,16 @@ export const useEditor = (
onChange(params.data);
return;
}
saveNote(params);
if (useSettingStore.getState().isAppLoading) {
const sub = useSettingStore.subscribe((state) => {
if (!state.isAppLoading) {
saveNote(params);
sub();
}
});
} else {
saveNote(params);
}
},
ignoreEdit ? 0 : 150
);
@@ -810,7 +894,7 @@ export const useEditor = (
useTabStore.getState().currentTab
))
) {
eSendEvent("webview_reset", "onReady");
eSendEvent(eEditorReset, "onReady");
return false;
} else {
syncTabs();
@@ -820,7 +904,6 @@ export const useEditor = (
}, [isDefaultEditor, restoreEditorState]);
const onLoad = useCallback(async () => {
if (currentNotes.current) overlay(true);
setTimeout(() => {
postMessage(EditorEvents.theme, theme);
});
@@ -835,12 +918,22 @@ export const useEditor = (
const noteId = useTabStore.getState().getCurrentNoteId();
if (!noteId) {
overlay(false);
loadNote({ newNote: true });
if (tabBarRef.current?.page() === 1) {
state.current.currentlyEditing = false;
}
} else if (state.current?.initialLoadCalled) {
const note = currentNotes.current[noteId];
if (note) {
loadNote({
item: note
});
}
}
if (!state.current?.initialLoadCalled) {
state.current.initialLoadCalled = true;
}
overlay(false);
}, [
postMessage,
theme,

View File

@@ -31,6 +31,7 @@ import { useTabStore } from "./use-tab-store";
import { parseInternalLink } from "@notesnook/core";
import { eOnLoadNote } from "../../../utils/events";
import { db } from "../../../common/database";
import { NotesnookModule } from "../../../utils/notesnook-module";
export const textInput = createRef<TextInput>();
export const editorController =
createRef<useEditorType>() as MutableRefObject<useEditorType>;
@@ -46,7 +47,7 @@ export function editorState() {
return editorController.current?.state.current || defaultState;
}
export const EditorEvents: { [name: string]: string } = {
export const EditorEvents = {
html: "native:html",
updatehtml: "native:updatehtml",
title: "native:title",
@@ -55,7 +56,8 @@ export const EditorEvents: { [name: string]: string } = {
logger: "native:logger",
status: "native:status",
keyboardShown: "native:keyboardShown",
attachmentData: "native:attachment-data"
attachmentData: "native:attachment-data",
resolve: "native:resolve"
};
export function randId(prefix: string) {
@@ -164,7 +166,7 @@ const canRestoreAppState = (appState: AppState) => {
let appState: AppState | undefined;
export function getAppState() {
if (appState && canRestoreAppState(appState)) return appState as AppState;
const json = MMKV.getString("appState");
const json = NotesnookModule.getAppState();
if (json) {
appState = JSON.parse(json) as AppState;
if (canRestoreAppState(appState)) {
@@ -179,7 +181,7 @@ export function getAppState() {
export function clearAppState() {
appState = undefined;
MMKV.removeItem("appState");
NotesnookModule.setAppState("");
}
export async function openInternalLink(url: string) {

View File

@@ -32,9 +32,12 @@ import {
TimeFormatPicker,
TrashIntervalPicker,
BackupReminderPicker,
ApplockTimerPicker
ApplockTimerPicker,
BackupWithAttachmentsReminderPicker
} from "./picker/pickers";
import ThemeSelector from "./theme-selector";
import { RestoreBackup } from "./restore-backup";
import { ServersConfiguration } from "./server-config";
export const components: { [name: string]: ReactElement } = {
colorpicker: <AccentColorPicker />,
@@ -51,5 +54,8 @@ export const components: { [name: string]: ReactElement } = {
"date-format-selector": <DateFormatPicker />,
"time-format-selector": <TimeFormatPicker />,
"theme-selector": <ThemeSelector />,
"applock-timer": <ApplockTimerPicker />
"applock-timer": <ApplockTimerPicker />,
autobackupsattachments: <BackupWithAttachmentsReminderPicker />,
backuprestore: <RestoreBackup />,
"server-config": <ServersConfiguration />
};

View File

@@ -122,7 +122,8 @@ export default function DebugLogs() {
colors.primary.paragraph,
colors.error.paragraph,
colors.static.black,
colors.static.orange
colors.static.orange,
colors.primary.border
]
);

View File

@@ -90,13 +90,26 @@ export async function verifyUserWithApplock() {
positiveText: "Verify",
secureTextEntry: true,
negativeText: "Cancel",
keyboardType: keyboardType,
positivePress: async (value) => {
try {
const verified = await validateAppLockPassword(value);
if (!verified) {
ToastManager.show({
heading: `Invalid ${
keyboardType === "numeric" ? "pin" : "password"
}`,
type: "error",
context: "local"
});
return false;
}
resolve(verified);
} catch (e) {
resolve(false);
return false;
}
return true;
}
});
} else {

View File

@@ -18,35 +18,22 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import React, { useEffect, useState } from "react";
import React from "react";
import { View } from "react-native";
import Animated, { FadeInDown } from "react-native-reanimated";
import DelayLayout from "../../components/delay-layout";
import BaseDialog from "../../components/dialog/base-dialog";
import { ProgressBarComponent } from "../../components/ui/svg/lazy";
import Heading from "../../components/ui/typography/heading";
import Paragraph from "../../components/ui/typography/paragraph";
import { Header } from "../../components/header";
import { useNavigationFocus } from "../../hooks/use-navigation-focus";
import {
eSubscribeEvent,
eUnSubscribeEvent
} from "../../services/event-manager";
import useNavigationStore from "../../stores/use-navigation-store";
import { useThemeColors } from "@notesnook/theme";
import { SIZE } from "../../utils/size";
import { SectionGroup } from "./section-group";
import { settingsGroups } from "./settings-data";
import { RouteParams, SettingSection } from "./types";
import SettingsUserSection from "./user-section";
import { Header } from "../../components/header";
const keyExtractor = (item: SettingSection) => item.id;
const Home = ({
navigation
}: NativeStackScreenProps<RouteParams, "SettingsHome">) => {
const { colors } = useThemeColors();
const [loading, setLoading] = useState(false);
useNavigationFocus(navigation, {
onFocus: () => {
useNavigationStore.getState().setFocusedRouteId("Settings");
@@ -62,16 +49,6 @@ const Home = ({
<SectionGroup item={item} />
);
useEffect(() => {
function settingsLoading(state: boolean) {
setLoading(state || true);
}
eSubscribeEvent("settings-loading", settingsLoading);
return () => {
eUnSubscribeEvent("settings-loading", settingsLoading);
};
}, []);
return (
<>
<Header
@@ -81,57 +58,6 @@ const Home = ({
id="Settings"
/>
<DelayLayout delay={300} type="settings">
{loading && (
//@ts-ignore // Migrate to typescript required.
<BaseDialog animated={false} bounce={false} visible={true}>
<View
style={{
width: "100%",
height: "100%",
backgroundColor: colors.primary.background,
justifyContent: "center",
alignItems: "center"
}}
>
<View
style={{
width: "100%",
height: "100%",
backgroundColor: colors.primary.background,
justifyContent: "center",
alignItems: "center"
}}
>
<Heading color={colors.primary.paragraph} size={SIZE.lg}>
Logging out
</Heading>
<Paragraph color={colors.secondary.paragraph}>
Please wait while we log out and clear app data.
</Paragraph>
<View
style={{
flexDirection: "row",
width: 100,
marginTop: 15
}}
>
<ProgressBarComponent
height={5}
width={100}
animated={true}
useNativeDriver
indeterminate
indeterminateAnimationDuration={2000}
unfilledColor={colors.secondary.background}
color={colors.primary.accent}
borderWidth={0}
/>
</View>
</View>
</View>
</BaseDialog>
)}
<Animated.FlatList
entering={FadeInDown}
data={settingsGroups}

View File

@@ -164,12 +164,6 @@ export const LICENSES = [
author: "dooboolab",
link: "https://github.com/dooboolab/react-native-iap"
},
{
name: "react-native-image-picker",
licenseType: "MIT",
author: "Johan du Toit (Johan-dutoit)",
link: "https://github.com/react-native-image-picker/react-native-image-picker"
},
{
name: "react-native-keychain",
licenseType: "MIT",

View File

@@ -121,8 +121,8 @@ export const BackupReminderPicker = createSettingsPicker({
SettingsService.set({ reminder: item });
},
formatValue: (item) => {
return item === "useroff"
? "Never"
return item === "useroff" || item === "off" || item === "never"
? "Off"
: item.slice(0, 1).toUpperCase() + item.slice(1);
},
getItemKey: (item) => item,
@@ -140,6 +140,31 @@ export const BackupReminderPicker = createSettingsPicker({
}
});
export const BackupWithAttachmentsReminderPicker = createSettingsPicker({
getValue: () => useSettingStore.getState().settings.fullBackupReminder,
updateValue: (item) => {
SettingsService.set({ fullBackupReminder: item });
},
formatValue: (item) => {
return item === "useroff" || item === "off" || item === "never"
? "Off"
: item.slice(0, 1).toUpperCase() + item.slice(1);
},
getItemKey: (item) => item,
options: ["never", "weekly", "monthly"],
compareValue: (current, item) => current === item,
premium: true,
requiresVerification: () => {
return (
!useSettingStore.getState().settings.encryptedBackup &&
useUserStore.getState().user
);
},
onCheckOptionIsPremium: (item) => {
return item !== "never";
}
});
export const ApplockTimerPicker = createSettingsPicker({
getValue: () => useSettingStore.getState().settings.appLockTimer,
updateValue: (item) => {

View File

@@ -0,0 +1,558 @@
/*
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 { formatBytes, getFormattedDate } from "@notesnook/common";
import { LegacyBackupFile } from "@notesnook/core";
import { useThemeColors } from "@notesnook/theme";
import React, { useEffect, useState } from "react";
import { ActivityIndicator, FlatList, Platform, View } from "react-native";
import RNFetchBlob, { ReactNativeBlobUtilStat } from "react-native-blob-util";
import DocumentPicker from "react-native-document-picker";
import * as ScopedStorage from "react-native-scoped-storage";
import { unzip } from "react-native-zip-archive";
import { DatabaseLogger, db } from "../../../common/database";
import storage from "../../../common/database/storage";
import { deleteCacheFileByName } from "../../../common/filesystem/io";
import { cacheDir, copyFileAsync } from "../../../common/filesystem/utils";
import { presentDialog } from "../../../components/dialog/functions";
import {
endProgress,
startProgress,
updateProgress
} from "../../../components/dialogs/progress";
import { Button } from "../../../components/ui/button";
import Heading from "../../../components/ui/typography/heading";
import Paragraph from "../../../components/ui/typography/paragraph";
import { SectionItem } from "../../../screens/settings/section-item";
import { ToastManager } from "../../../services/event-manager";
import Navigation from "../../../services/navigation";
import SettingsService from "../../../services/settings";
import { refreshAllStores } from "../../../stores/create-db-collection-store";
import { useUserStore } from "../../../stores/use-user-store";
import { SIZE } from "../../../utils/size";
type PasswordOrKey = { password?: string; encryptionKey?: string };
const withPassword = () => {
return new Promise<PasswordOrKey>((resolve) => {
let resolved = false;
presentDialog({
context: "local",
title: "Encrypted backup",
input: true,
inputPlaceholder: "Password",
paragraph: "Please enter password of this backup file",
positiveText: "Restore",
secureTextEntry: true,
onClose: () => {
if (resolved) return;
resolve({});
},
negativeText: "Cancel",
positivePress: async (password, isEncryptionKey) => {
resolve({
encryptionKey: isEncryptionKey ? password : undefined,
password: isEncryptionKey ? undefined : password
});
resolved = true;
return true;
},
check: {
info: "Use encryption key",
type: "transparent"
}
});
});
};
const restoreBackup = async (options: {
uri: string;
deleteFile?: boolean;
}) => {
try {
const isLegacyBackup = options.uri.endsWith(".nnbackup");
startProgress({
title: "Restoring backup",
paragraph: "Preparing to restore backup file...",
canHideProgress: false
});
let filePath = options.uri;
let deleteBackupFile = options.deleteFile;
if (!isLegacyBackup) {
if (Platform.OS === "android") {
updateProgress({
progress: `Copying backup file to cache...`
});
const cacheFile = `file://${RNFetchBlob.fs.dirs.CacheDir}/backup.zip`;
if (await RNFetchBlob.fs.exists(cacheFile)) {
await RNFetchBlob.fs.unlink(cacheFile);
}
await RNFetchBlob.fs.createFile(cacheFile, "", "utf8");
if (filePath.startsWith("content://")) {
await copyFileAsync(filePath, cacheFile);
} else {
await RNFetchBlob.fs.cp(filePath, cacheFile);
}
filePath = cacheFile;
deleteBackupFile = true;
}
const zipOutputFolder = `${cacheDir}/backup_extracted`;
if (await RNFetchBlob.fs.exists(zipOutputFolder)) {
await RNFetchBlob.fs.unlink(zipOutputFolder);
await RNFetchBlob.fs.mkdir(zipOutputFolder);
}
updateProgress({
progress: `Extracting files from backup...`
});
await unzip(filePath, zipOutputFolder);
const extractedBackupFiles = await RNFetchBlob.fs.ls(zipOutputFolder);
const extractedAttachments = extractedBackupFiles.includes("attachments")
? await RNFetchBlob.fs.ls(`${zipOutputFolder}/attachments`)
: [];
const attachmentsKeyPath: any = extractedAttachments?.find(
(path) => path === ".attachments_key"
);
const attachmentsKey = attachmentsKeyPath
? await JSON.parse(
await RNFetchBlob.fs.readFile(
`${zipOutputFolder}/attachments/${attachmentsKeyPath}`,
"utf8"
)
)
: undefined;
let count = 0;
await db.transaction(async () => {
let passwordOrKey: PasswordOrKey;
for (const path of extractedBackupFiles) {
if (path === ".nnbackup" || path === "attachments") continue;
updateProgress({
progress: `Restoring data (${count++}/${
extractedBackupFiles.length
})`
});
const filePath = `${zipOutputFolder}/${path}`;
const data = await RNFetchBlob.fs.readFile(filePath, "utf8");
const backup = JSON.parse(data);
const isEncryptedBackup = backup.encrypted;
passwordOrKey = !isEncryptedBackup
? ({} as PasswordOrKey)
: await withPassword();
if (
isEncryptedBackup &&
!passwordOrKey?.encryptionKey &&
!passwordOrKey?.password
) {
endProgress();
throw new Error("Failed to decrypt backup");
}
await db.backup.import(backup, {
...passwordOrKey,
attachmentsKey: attachmentsKey
});
}
});
await db.initCollections();
count = 0;
for (const path of extractedAttachments) {
if (path === ".attachments_key") continue;
updateProgress({
progress: `Restoring attachments (${count++}/${
extractedAttachments.length
})`
});
const hash = path;
const attachment = await db.attachments.attachment(hash as string);
if (!attachment) continue;
console.log("Saving attachment file", hash);
await deleteCacheFileByName(hash);
await RNFetchBlob.fs.cp(
`${zipOutputFolder}/attachments/${hash}`,
`${cacheDir}/${hash}`
);
}
updateProgress({
progress: `Cleaning up...`
});
// Remove files from cache
RNFetchBlob.fs.unlink(zipOutputFolder).catch(console.log);
if (Platform.OS === "android" || deleteBackupFile) {
RNFetchBlob.fs.unlink(filePath).catch(console.log);
}
} else {
updateProgress({
progress: `Reading backup file...`
});
const rawData =
Platform.OS === "android"
? await ScopedStorage.readFile(filePath, "utf8")
: await RNFetchBlob.fs.readFile(filePath, "utf8");
const backup: LegacyBackupFile = JSON.parse(rawData) as LegacyBackupFile;
const isEncryptedBackup =
typeof backup.data !== "string" && backup.data.cipher;
updateProgress({
progress: isEncryptedBackup
? `Backup is encrypted, decrypting...`
: "Preparing to restore backup file..."
});
const { encryptionKey, password } = isEncryptedBackup
? ({} as PasswordOrKey)
: await withPassword();
if (isEncryptedBackup && !encryptionKey && !password) {
endProgress();
throw new Error("Failed to decrypt backup");
}
await db.transaction(async () => {
updateProgress({
progress: "Restoring backup..."
});
await db.backup.import(backup, {
encryptionKey,
password
});
});
endProgress();
}
ToastManager.show({
heading: "Backup restored successfully",
type: "success"
});
await db.initCollections();
refreshAllStores();
Navigation.queueRoutesForUpdate();
endProgress();
} catch (e) {
endProgress();
DatabaseLogger.error(e as Error);
ToastManager.error(e as Error, `Failed to restore backup`);
}
};
const BACKUP_FILES_CACHE: (ReactNativeBlobUtilStat | ScopedStorage.FileType)[] =
[];
export const RestoreBackup = () => {
const { colors } = useThemeColors();
const [files, setFiles] =
useState<(ReactNativeBlobUtilStat | ScopedStorage.FileType)[]>(
BACKUP_FILES_CACHE
);
const [loading, setLoading] = useState(true);
const [backupDirectoryAndroid, setBackupDirectoryAndroid] =
useState<ScopedStorage.FileType>();
useEffect(() => {
setTimeout(() => {
checkBackups();
}, 1000);
}, []);
const checkBackups = async () => {
try {
let files: (ReactNativeBlobUtilStat | ScopedStorage.FileType)[] = [];
if (Platform.OS === "android") {
const backupDirectory = SettingsService.get().backupDirectoryAndroid;
if (backupDirectory) {
setBackupDirectoryAndroid(backupDirectory);
files = await ScopedStorage.listFiles(backupDirectory.uri);
} else {
setLoading(false);
return;
}
} else {
const path = await storage.checkAndCreateDir("/backups/");
files = await RNFetchBlob.fs.lstat(path);
}
files = files
.filter((file) => {
const name =
Platform.OS === "android"
? (file as ScopedStorage.FileType).name
: (file as ReactNativeBlobUtilStat).filename;
return name.endsWith(".nnbackup") || name.endsWith(".nnbackupz");
})
.sort(function (a, b) {
const timeA = a.lastModified;
const timeB = b.lastModified;
return timeB - timeA;
});
setFiles(files);
BACKUP_FILES_CACHE.splice(0, BACKUP_FILES_CACHE.length, ...files);
} catch (e) {
e;
} finally {
setLoading(false);
}
};
const renderItem = React.useCallback(
({
item,
index
}: {
item: ReactNativeBlobUtilStat | ScopedStorage.FileType;
index: number;
}) => <BackupItem item={item} index={index} />,
[]
);
return (
<>
<FlatList
data={[0]}
renderItem={() => {
return (
<View>
<SectionItem
item={{
id: "restore-from-files",
name: "Restore from files",
icon: "folder",
modifer: async () => {
useUserStore.setState({
disableAppLockRequests: true
});
const file = await DocumentPicker.pickSingle({
copyTo: "cachesDirectory"
});
setTimeout(() => {
useUserStore.setState({
disableAppLockRequests: false
});
}, 1000);
restoreBackup({
uri:
Platform.OS === "android"
? (("file://" + file.fileCopyUri) as string)
: (file.fileCopyUri as string),
deleteFile: true
});
},
description:
"Select a backup file from your device to restore backup"
}}
/>
{Platform.OS === "android" ? (
<SectionItem
item={{
id: "select-backup-folder",
name: "Select folder with backup files",
icon: "folder",
modifer: async () => {
const folder = await ScopedStorage.openDocumentTree(true);
let subfolder;
if (folder.name !== "Notesnook backups") {
subfolder = await ScopedStorage.createDirectory(
folder.uri,
"Notesnook backups"
);
} else {
subfolder = folder;
}
SettingsService.set({
backupDirectoryAndroid: subfolder
});
setBackupDirectoryAndroid(subfolder);
setLoading(true);
checkBackups();
},
description:
"Select folder where Notesnook backup files are stored to view and restore them from the app"
}}
/>
) : null}
<FlatList
ListHeaderComponent={
<View
style={{
backgroundColor: colors.primary.background,
marginBottom: 10
}}
>
<Heading color={colors.primary.accent} size={SIZE.xs}>
RECENT BACKUPS
</Heading>
</View>
}
stickyHeaderIndices={[0]}
ListEmptyComponent={
loading ? (
<View
style={{
justifyContent: "center",
alignItems: "center",
height: 300,
paddingHorizontal: 50
}}
>
<ActivityIndicator
color={colors.primary.accent}
size={SIZE.lg}
/>
</View>
) : (
<View
style={{
justifyContent: "center",
alignItems: "center",
gap: 12,
height: 300,
paddingHorizontal: 50
}}
>
<Paragraph
style={{
textAlign: "center"
}}
color={colors.secondary.paragraph}
>
No backups were found.{" "}
{!backupDirectoryAndroid
? `Please select a folder with backup files to view them here.`
: null}
</Paragraph>
</View>
)
}
windowSize={2}
keyExtractor={(item) =>
(item as ScopedStorage.FileType).name ||
(item as ReactNativeBlobUtilStat).filename
}
style={{
paddingHorizontal: 12
}}
ListFooterComponent={
<View
style={{
height: 200
}}
/>
}
data={files}
renderItem={renderItem}
/>
</View>
);
}}
/>
</>
);
};
const BackupItem = ({
item,
index
}: {
item: ReactNativeBlobUtilStat | ScopedStorage.FileType;
index: number;
}) => {
const { colors } = useThemeColors();
const isLegacyBackup =
item.path?.endsWith(".nnbackup") ||
(item as ScopedStorage.FileType).uri?.endsWith(".nnbackup");
const itemName = (
(item as ReactNativeBlobUtilStat).filename ||
(item as ScopedStorage.FileType).name
)
.replace(".nnbackupz", "")
.replace(".nnbackup", "");
return (
<View
style={{
justifyContent: "space-between",
alignItems: "center",
width: "100%",
borderRadius: 0,
flexDirection: "row",
borderBottomWidth: 0.5,
borderBottomColor: colors.primary.border,
paddingVertical: 12
}}
>
<View>
<Paragraph size={SIZE.sm}>{itemName}</Paragraph>
<Paragraph
size={SIZE.xs}
color={colors.secondary.paragraph}
style={{ width: "100%", maxWidth: "100%" }}
>
Created on {getFormattedDate(item?.lastModified, "date-time")}
{isLegacyBackup ? "(Legacy backup)" : ""} (
{formatBytes((item as ReactNativeBlobUtilStat).size)})
</Paragraph>
</View>
<Button
title="Restore"
type="secondaryAccented"
style={{
paddingHorizontal: 12,
height: 35
}}
onPress={() => {
presentDialog({
title: `Restore ${itemName}`,
paragraph: `Are you sure you want to restore this backup?`,
positiveText: "Restore",
negativeText: "Cancel",
positivePress: async () => {
console.log("file path", (item as ScopedStorage.FileType).uri);
restoreBackup({
uri:
Platform.OS === "android"
? (item as ScopedStorage.FileType).uri
: (item as ReactNativeBlobUtilStat).path
});
}
});
}}
/>
</View>
);
};

View File

@@ -0,0 +1,213 @@
/*
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 { isServerCompatible } from "@notesnook/core";
import { useThemeColors } from "@notesnook/theme";
import React, { useState } from "react";
import { View } from "react-native";
import { presentDialog } from "../../components/dialog/functions";
import { Button } from "../../components/ui/button";
import Input from "../../components/ui/input";
import { Notice } from "../../components/ui/notice";
import Paragraph from "../../components/ui/typography/paragraph";
import SettingsService from "../../services/settings";
import { HostId, HostIds } from "../../stores/use-setting-store";
import { useUserStore } from "../../stores/use-user-store";
import { ToastManager } from "../../services/event-manager";
export const ServerIds = ["notesnook-sync", "auth", "sse"] as const;
export type ServerId = (typeof ServerIds)[number];
type Server = {
id: ServerId;
host: HostId;
title: string;
example: string;
description: string;
};
type VersionResponse = {
version: number;
id: string;
instance: string;
};
const SERVERS: Server[] = [
{
id: "notesnook-sync",
host: "API_HOST",
title: "Sync server",
example: "http://localhost:4326",
description: "Server used to sync your notes & other data between devices."
},
{
id: "auth",
host: "AUTH_HOST",
title: "Auth server",
example: "http://localhost:5326",
description: "Server used for login/sign up and authentication."
},
{
id: "sse",
host: "SSE_HOST",
title: "Events server",
example: "http://localhost:7326",
description: "Server used to receive important notifications & events."
}
];
export function ServersConfiguration() {
const { colors } = useThemeColors();
const [error, setError] = useState<string>();
const [success, setSuccess] = useState<boolean>();
const [urls, setUrls] = useState<Partial<Record<HostId, string>>>(
SettingsService.getProperty("serverUrls") || {}
);
const isLoggedIn = useUserStore((state) => !!state.user);
return (
<View
style={{
paddingHorizontal: 12,
gap: 12,
marginTop: 12
}}
>
{isLoggedIn ? (
<Notice
text="You must log out in order to change/reset server URLs."
type="alert"
/>
) : null}
<View style={{ flexDirection: "column" }}>
{SERVERS.map((server) => (
<Input
key={server.id}
editable={!isLoggedIn}
placeholder={`${server.id} e.g. ${server.example}`}
validationType="url"
defaultValue={urls[server.host]}
errorMessage="Please enter a valid URL."
onChangeText={(value) =>
setUrls((s) => {
s[server.host] = value;
return s;
})
}
/>
))}
{error ? (
<Paragraph
style={{
paddingVertical: 12
}}
color={colors.error.paragraph}
>
{error}
</Paragraph>
) : null}
{success === true ? (
<Paragraph
style={{
paddingVertical: 12
}}
color={colors.success.paragraph}
>
Connected to all servers sucessfully.
</Paragraph>
) : null}
<View style={{ marginTop: 1, justifyContent: "flex-end", gap: 12 }}>
<Button
disabled={isLoggedIn}
type="secondary"
width="100%"
onPress={async () => {
try {
for (const host of HostIds) {
const url = urls[host];
const server = SERVERS.find((s) => s.host === host)!;
if (!url) throw new Error("All server urls are required.");
const version = await fetch(`${url}/version`)
.then((r) => r.json() as Promise<VersionResponse>)
.catch(() => undefined);
if (!version)
throw new Error(`Could not connect to ${server.title}.`);
if (version.id !== server.id)
throw new Error(
`The URL you have given (${url}) does not point to the ${server.title}.`
);
if (!isServerCompatible(version.version)) {
throw new Error(
`The server version is not compatible with the app.`
);
}
}
setSuccess(true);
setError(undefined);
} catch (e) {
setError((e as Error).message);
}
}}
title="Test connection"
/>
<Button
type="accent"
disabled={isLoggedIn}
width="100%"
onPress={async () => {
if (!success) {
ToastManager.show({
heading: "Test connection before changing server urls"
});
return;
}
SettingsService.setProperty(
"serverUrls",
urls as Record<HostId, string>
);
presentDialog({
title: "Server url changed",
paragraph: "Restart the app for changes to take effect.",
negativeText: "Done"
});
}}
title="Save"
/>
<Button
disabled={isLoggedIn}
type="error"
width="100%"
title="Reset server urls"
onPress={async () => {
if (isLoggedIn) return;
SettingsService.setProperty("serverUrls", undefined);
presentDialog({
title: "Server urls reset",
paragraph: "Restart the app for changes to take effect.",
negativeText: "Done"
});
}}
/>
</View>
</View>
</View>
);
}

View File

@@ -17,6 +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 { formatBytes } from "@notesnook/common";
import notifee from "@notifee/react-native";
import dayjs from "dayjs";
import React from "react";
@@ -24,12 +25,19 @@ import { Appearance, Linking, Platform } from "react-native";
import { getVersion } from "react-native-device-info";
import * as RNIap from "react-native-iap";
import { enabled } from "react-native-privacy-snapshot";
import { db } from "../../common/database";
import ScreenGuardModule from "react-native-screenguard";
import { DatabaseLogger, db } from "../../common/database";
import { MMKV } from "../../common/database/mmkv";
import filesystem from "../../common/filesystem";
import { AttachmentDialog } from "../../components/attachments";
import { ChangePassword } from "../../components/auth/change-password";
import { presentDialog } from "../../components/dialog/functions";
import { AppLockPassword } from "../../components/dialogs/applock-password";
import {
endProgress,
startProgress,
updateProgress
} from "../../components/dialogs/progress";
import { ChangeEmail } from "../../components/sheets/change-email";
import ExportNotesSheet from "../../components/sheets/export-notes";
import { Issue } from "../../components/sheets/github/issue";
@@ -42,6 +50,7 @@ import BiometricService from "../../services/biometrics";
import {
ToastManager,
eSendEvent,
eSubscribeEvent,
openVault,
presentSheet
} from "../../services/event-manager";
@@ -60,8 +69,7 @@ import {
eCloseSheet,
eCloseSimpleDialog,
eOpenLoginDialog,
eOpenRecoveryKeyDialog,
eOpenRestoreDialog
eOpenRecoveryKeyDialog
} from "../../utils/events";
import { NotesnookModule } from "../../utils/notesnook-module";
import { sleep } from "../../utils/time";
@@ -330,43 +338,144 @@ export const settingsGroups: SettingSection[] = [
},
description: "Verify your subscription to Notesnook Pro"
},
{
id: "clear-cache",
name: "Clear cache",
icon: "delete",
modifer: async () => {
presentDialog({
title: "Clear cache",
paragraph: "Are you sure you want to clear the cache?",
positiveText: "Clear",
positivePress: async () => {
filesystem.clearCache();
ToastManager.show({
heading: "Cache cleared",
message: "All cached attachments have been removed",
type: "success"
});
}
});
},
description(current) {
return `Clear all cached attachments. Current cache size: ${
current as number
}`;
},
useHook: () => {
const [cacheSize, setCacheSize] = React.useState(0);
React.useEffect(() => {
filesystem.getCacheSize().then(setCacheSize).catch(console.log);
const sub = eSubscribeEvent("cache-cleared", () => {
setCacheSize(0);
});
return () => {
sub?.unsubscribe();
};
}, []);
return formatBytes(cacheSize);
}
},
{
id: "logout",
name: "Log out",
description: "Clear all your data and reset the app.",
name: "Logout",
description:
"Logging out will clear all data stored on this device.",
icon: "logout",
modifer: () => {
modifer: async () => {
const hasUnsyncedChanges = await db.hasUnsyncedChanges();
presentDialog({
title: "Logout",
paragraph: "Clear all your data and reset the app.",
paragraph:
"Are you sure you want to logout and clear all data stored on this device?",
positiveText: "Logout",
positivePress: async () => {
try {
eSendEvent(eCloseSimpleDialog);
setTimeout(async () => {
eSendEvent("settings-loading", true);
Navigation.popToTop();
check: {
info: "Take a backup before logging out",
defaultValue: true
},
notice: hasUnsyncedChanges
? {
text: "You have unsynced notes. Take a backup or sync your notes to avoid losing your critical data.",
type: "alert"
}
: undefined,
positivePress: async (_, takeBackup) => {
eSendEvent(eCloseSimpleDialog);
setTimeout(async () => {
try {
startProgress({
fillBackground: true,
title: "Logging out",
canHideProgress: true,
paragraph:
"Please wait while we log out and clear app data."
});
Navigation.navigate("Notes");
if (takeBackup) {
updateProgress({
progress: "Taking a backup of your notes"
});
try {
const result = await BackupService.run(
false,
"local",
"partial"
);
if (result.error) throw result.error as Error;
} catch (e) {
DatabaseLogger.error(e);
const error = e;
const canLogout = await new Promise((resolve) => {
presentDialog({
context: "local",
title: "Backup failed",
paragraph: `${
(error as Error).message
}. Do you want to continue logging out?`,
positiveText: "Continue",
positivePress: () => {
resolve(true);
},
onClose: () => {
resolve(false);
}
});
});
if (!canLogout) {
endProgress();
return;
}
}
}
updateProgress({
progress: "Logging out... please wait"
});
await db.user?.logout();
setLoginMessage();
await PremiumService.setPremiumStatus();
await BiometricService.resetCredentials();
MMKV.clearStore();
clearAllStores();
refreshAllStores();
setImmediate(() => {
refreshAllStores();
});
Navigation.queueRoutesForUpdate();
SettingsService.resetSettings();
useUserStore.getState().setUser(null);
useUserStore.getState().setSyncing(false);
Navigation.goBack();
Navigation.popToTop();
setTimeout(() => {
eSendEvent("settings-loading", false);
}, 3000);
}, 300);
} catch (e) {
ToastManager.error(e as Error, "Error logging out");
eSendEvent("settings-loading", false);
}
endProgress();
} catch (e) {
DatabaseLogger.error(e);
ToastManager.error(e as Error, "Error logging out");
endProgress();
}
}, 300);
}
});
}
@@ -392,12 +501,18 @@ export const settingsGroups: SettingSection[] = [
try {
const verified = await db.user?.verifyPassword(value);
if (verified) {
eSendEvent("settings-loading", true);
await db.user?.deleteUser(value);
await BiometricService.resetCredentials();
SettingsService.set({
introCompleted: true
});
setTimeout(async () => {
startProgress({
title: "Deleting account",
paragraph: "Please wait while we delete your account"
});
Navigation.navigate("Notes");
await db.user?.deleteUser(value);
await BiometricService.resetCredentials();
SettingsService.set({
introCompleted: true
});
}, 300);
} else {
ToastManager.show({
heading: "Incorrect password",
@@ -408,9 +523,9 @@ export const settingsGroups: SettingSection[] = [
});
}
eSendEvent("settings-loading", false);
endProgress();
} catch (e) {
eSendEvent("settings-loading", false);
endProgress();
console.log(e);
ToastManager.error(
e as Error,
@@ -431,6 +546,25 @@ export const settingsGroups: SettingSection[] = [
type: "screen",
icon: "autorenew",
sections: [
{
id: "offline-mode",
name: "Full offline mode",
description: "Download everything including attachments on sync",
type: "switch",
property: "offlineMode",
modifer: () => {
const current = SettingsService.get().offlineMode;
if (current) {
SettingsService.setProperty("offlineMode", false);
db.fs().cancel("offline-mode");
return;
}
PremiumService.verify(() => {
SettingsService.setProperty("offlineMode", true);
db.attachments.cacheAttachments().catch(console.log);
});
}
},
{
id: "auto-sync",
name: "Disable auto sync",
@@ -458,7 +592,7 @@ export const settingsGroups: SettingSection[] = [
id: "background-sync",
name: "Background sync (experimental)",
description:
"Periodically wake up the app in background to sync your notes from other devices.",
"Periodically wake up the app in background to run sync.",
type: "switch",
property: "backgroundSync",
onChange: (value) => {
@@ -470,22 +604,43 @@ export const settingsGroups: SettingSection[] = [
}
},
{
id: "sync-issues-fix",
name: "Having problems with sync",
description: "Try force sync to resolve issues with syncing",
icon: "sync-alert",
modifer: async () => {
id: "pull-sync",
name: "Force pull changes",
description: `Use this if changes from other devices are not appearing on this device. This will overwrite the data on this device with the latest data from the server.\n\nThis must only be used for troubleshooting. Using it regularly for sync is not recommended and will lead to unexpected data loss and other issues. If you are having persistent issues with sync, please report them to us at support@streetwriters.co.`,
modifer: () => {
presentDialog({
title: "Force sync",
title: "Force Pull changes",
paragraph:
"If your data on two devices is out of sync even after trying to sync normally. You can run force sync to solve such problems. Usually you should never need to run this otherwise. Force sync means that all your data on this device is reuploaded to the server.",
"This must only be used for troubleshooting. Using this regularly for sync is not recommended and will lead to unexpected data loss and other issues. If you are having persistent issues with sync, please report them to us at support@streetwriters.co.",
negativeText: "Cancel",
positiveText: "Start",
positivePress: async () => {
eSendEvent(eCloseSheet);
await sleep(300);
Progress.present();
Sync.run("global", true, true, () => {
Sync.run("global", true, "fetch", () => {
eSendEvent(eCloseSheet);
});
}
});
}
},
{
id: "push-sync",
name: "Force push changes",
description: `Use this if changes made on this device are not appearing on other devices. This will overwrite the data on the server with the data from this device.\n\nThis must only be used for troubleshooting. Using it regularly for sync is not recommended and will lead to unexpected data loss and other issues. If you are having persistent issues with sync, please report them to us at support@streetwriters.co.`,
modifer: () => {
presentDialog({
title: "Force Push changes",
paragraph:
"This must only be used for troubleshooting. Using this regularly for sync is not recommended and will lead to unexpected data loss and other issues. If you are having persistent issues with sync, please report them to us at support@streetwriters.co.",
negativeText: "Cancel",
positiveText: "Start",
positivePress: async () => {
eSendEvent(eCloseSheet);
await sleep(300);
Progress.present();
Sync.run("global", true, "send", () => {
eSendEvent(eCloseSheet);
});
}
@@ -665,6 +820,14 @@ export const settingsGroups: SettingSection[] = [
type: "switch"
}
]
},
{
id: "servers",
type: "screen",
name: "Servers",
description: "Configure server URLs for Notesnook",
icon: "server",
component: "server-config"
}
]
},
@@ -672,15 +835,6 @@ export const settingsGroups: SettingSection[] = [
id: "privacy-security",
name: "Privacy and security",
sections: [
{
id: "temeltery",
type: "switch",
name: "Telemetry",
icon: "radar",
description:
"Contribute towards a better Notesnook. All tracking information is anonymous.",
property: "telemetry"
},
{
id: "marketing-emails",
type: "switch",
@@ -827,9 +981,18 @@ export const settingsGroups: SettingSection[] = [
"Hide app contents when you switch to other apps. This will also disable screenshot taking in the app.",
modifer: () => {
const settings = SettingsService.get();
Platform.OS === "android"
? NotesnookModule.setSecureMode(!settings.privacyScreen)
: enabled(true);
if (Platform.OS === "ios") {
enabled(!settings.privacyScreen);
if (settings.privacyScreen) {
ScreenGuardModule.unregister();
} else {
ScreenGuardModule.register({
backgroundColor: "#000000"
});
}
} else {
NotesnookModule.setSecureMode(!settings.privacyScreen);
}
SettingsService.set({ privacyScreen: !settings.privacyScreen });
},
@@ -850,6 +1013,9 @@ export const settingsGroups: SettingSection[] = [
type: "switch",
property: "appLockEnabled",
onChange: () => {
SettingsService.set({
privacyScreen: true
});
SettingsService.setPrivacyScreen(SettingsService.get());
},
onVerify: async () => {
@@ -952,7 +1118,7 @@ export const settingsGroups: SettingSection[] = [
SettingsService.getProperty("applockKeyboardType") === "numeric"
? "pin"
: "password"
}, app lock will fallback to using account password to unlock the app`,
}, app lock will be disabled if no other security method is enabled.`,
hidden: () => {
return !SettingsService.getProperty("appLockHasPasswordSecurity");
},
@@ -1005,7 +1171,8 @@ export const settingsGroups: SettingSection[] = [
{
id: "backup-now",
name: "Backup now",
description: "Create a backup of your data",
description:
"Take a partial backup of your data that does not include attachments",
modifer: async () => {
const user = useUserStore.getState().user;
if (!user || SettingsService.getProperty("encryptedBackup")) {
@@ -1016,14 +1183,41 @@ export const settingsGroups: SettingSection[] = [
verifyUser(null, () => BackupService.run(true));
}
},
{
id: "backup-now",
name: "Backup now with attachments",
hidden: () => !useUserStore.getState().user,
description: "Take a full backup of your data with all attachments",
modifer: async () => {
const user = useUserStore.getState().user;
if (!user || SettingsService.getProperty("encryptedBackup")) {
await BackupService.run(true, undefined, "full");
return;
}
verifyUser(null, () =>
BackupService.run(true, undefined, "full")
);
}
},
{
id: "auto-backups",
type: "component",
name: "Automatic backups",
description:
"Backup your data once every week or daily automatically.",
"Set the interval to create a partial backup (without attachments) automatically.",
component: "autobackups"
},
{
id: "auto-backups-with-attachments",
type: "component",
hidden: () => !useUserStore.getState().user,
name: "Automatic backups with attachments",
description: `Set the interval to create a backup (with attachments) automatically.
NOTE: Creating a backup with attachments can take a while, and also fail completely. The app will try to resume/restart the backup in case of interruptions.`,
component: "autobackupsattachments"
},
{
id: "select-backup-dir",
name: "Select backup directory",
@@ -1115,9 +1309,8 @@ export const settingsGroups: SettingSection[] = [
id: "restore-backup",
name: "Restore backup",
description: "Restore backup from phone storage.",
modifer: () => {
eSendEvent(eOpenRestoreDialog);
}
type: "screen",
component: "backuprestore"
},
{
id: "export-notes",
@@ -1297,9 +1490,9 @@ export const settingsGroups: SettingSection[] = [
}
},
{
id: "join-mastodom",
id: "join-mastodon",
name: "Follow us on Mastodon",
description: "We are on mastodom",
description: "We are on mastodon",
icon: "mastodon",
modifer: () => {
Linking.openURL("https://fosstodon.org/@notesnook").catch(

View File

@@ -90,7 +90,7 @@ export const Subscription = () => {
function getPrice() {
return Platform.OS === "android"
? monthlyPlan?.product?.subscriptionOfferDetails[0].pricingPhases
? monthlyPlan?.product?.subscriptionOfferDetails[0]?.pricingPhases
.pricingPhaseList?.[0]?.formattedPrice
: monthlyPlan?.product?.localizedPrice;
}

View File

@@ -16,14 +16,15 @@ 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 { Platform } from "react-native";
import BackgroundFetch from "@ammarahmed/react-native-background-fetch";
import { AppRegistry, AppState, Platform } from "react-native";
import {
beginBackgroundTask,
endBackgroundTask
} from "react-native-begin-background-task";
import BackgroundFetch from "@ammarahmed/react-native-background-fetch";
import { DatabaseLogger, db, setupDatabase } from "../common/database";
import { AppState, AppRegistry } from "react-native";
import { deleteDCacheFiles } from "../common/filesystem/io";
import { useUserStore } from "../stores/use-user-store";
import Notifications from "./notifications";
import SettingsService from "./settings";
@@ -114,15 +115,19 @@ async function onBackgroundSyncStarted() {
await db.init();
}
const user = await db.user?.getUser();
if (user) {
if (user && !useUserStore.getState().syncing) {
useUserStore.getState().setSyncing(true);
await db.sync({
type: "full",
force: false
});
useUserStore.getState().setSyncing(false);
}
await Notifications.setupReminders();
deleteDCacheFiles();
DatabaseLogger.info("BACKGROUND SYNC COMPLETE");
} catch (e) {
useUserStore.getState().setSyncing(false);
DatabaseLogger.error(e as Error);
console.log("BACKGROUND SYNC ERROR", (e as Error).message);
}
@@ -132,16 +137,17 @@ const onBoot = async () => {
try {
if (!SettingsService.getProperty("backgroundSync")) {
DatabaseLogger.info("BACKGROUND SYNC ON BOOT DISABLED");
return;
}
DatabaseLogger.info("BOOT TASK STARTED");
if (!db.isInitialized) {
await setupDatabase();
await db.init();
}
await Notifications.setupReminders();
SettingsService.init();
if (SettingsService.get().notifNotes) {
Notifications.pinQuickNote(false);
}

View File

@@ -17,6 +17,8 @@ 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 { sanitizeFilename } from "@notesnook/common";
import { formatDate } from "@notesnook/core/dist/utils/date";
import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import FileViewer from "react-native-file-viewer";
@@ -25,27 +27,32 @@ import Share from "react-native-share";
import { zip } from "react-native-zip-archive";
import { DatabaseLogger, db } from "../common/database";
import storage from "../common/database/storage";
import filesystem from "../common/filesystem";
import { cacheDir, copyFileAsync } from "../common/filesystem/utils";
import { presentDialog } from "../components/dialog/functions";
import {
endProgress,
startProgress,
updateProgress
} from "../components/dialogs/progress";
import { eCloseSheet } from "../utils/events";
import { sleep } from "../utils/time";
import { ToastManager, eSendEvent, presentSheet } from "./event-manager";
import SettingsService from "./settings";
import { useUserStore } from "../stores/use-user-store";
const MS_DAY = 86400000;
const MS_WEEK = MS_DAY * 7;
const MONTH = MS_DAY * 30;
async function getDirectoryAndroid() {
let folder = await ScopedStorage.openDocumentTree(true);
const folder = await ScopedStorage.openDocumentTree(true);
if (!folder) return null;
let subfolder;
if (!folder.name.includes("Notesnook backups")) {
let folderFiles = await ScopedStorage.listFiles(folder.uri);
for (let f of folderFiles) {
if (f.type === "directory" && f.name === "Notesnook backups") {
subfolder = f;
const files = await ScopedStorage.listFiles(folder.uri);
for (const file of files) {
if (file.type === "directory" && file.name === "Notesnook backups") {
subfolder = file;
}
}
if (!subfolder) {
@@ -68,10 +75,10 @@ async function checkBackupDirExists(reset = false, context = "global") {
let dir = SettingsService.get().backupDirectoryAndroid;
if (reset) dir = null;
if (dir) {
let allDirs = await ScopedStorage.getPersistedUriPermissions();
const allDirs = await ScopedStorage.getPersistedUriPermissions();
let exists = allDirs.findIndex((d) => {
return d === dir.uri || dir.uri.includes(d);
});
return d === dir?.uri || dir?.uri.includes(d);
}) as number | boolean;
exists = exists !== -1;
dir = exists ? dir : null;
}
@@ -101,7 +108,7 @@ async function checkBackupDirExists(reset = false, context = "global") {
return dir;
}
async function presentBackupCompleteSheet(backupFilePath) {
async function presentBackupCompleteSheet(backupFilePath: string) {
presentSheet({
title: "Backup complete",
icon: "cloud-upload",
@@ -124,7 +131,7 @@ async function presentBackupCompleteSheet(backupFilePath) {
showOpenWithDialog: true,
showAppsSuggestions: true,
shareFile: true
}).catch(console.log);
} as any).catch(console.log);
}
},
actionText: "Share"
@@ -143,88 +150,135 @@ async function presentBackupCompleteSheet(backupFilePath) {
});
}
async function updateNextBackupTime() {
async function updateNextBackupTime(type: "full" | "partial") {
SettingsService.set({
nextBackupRequestTime: Date.now() + 86400000 * 3,
lastBackupDate: Date.now()
[type === "full" ? "lastFullBackupDate" : "lastBackupDate"]: Date.now()
});
}
/**
* @param {boolean=} progress
* @param {string=} context
* @returns {Promise<{path?: string, error?: Error}}>
* @returns {Promise<{path?: string, error?: Error, report?: boolean}}>
*/
async function run(progress = false, context) {
let androidBackupDirectory = await checkBackupDirExists(false, context);
async function run(
progress = false,
context?: string,
backupType: "full" | "partial" = "partial"
) {
console.log("Creating backup:", backupType, progress, context);
const androidBackupDirectory = (await checkBackupDirExists(
false,
context
)) as ScopedStorage.FileType;
if (!androidBackupDirectory)
return {
error: new Error("Backup directory not selected")
error: new Error("Backup directory not selected"),
report: false
};
let path;
if (Platform.OS === "ios") {
path = await storage.checkAndCreateDir("/backups");
}
const backupFileName = sanitizeFilename(
`${formatDate(Date.now(), {
type: "date-time",
dateFormat: "YYYY-MM-DD",
timeFormat: "24-hour"
})}-${new Date().getSeconds()}${backupType === "full" ? "-full" : ""}`,
{ replacement: "-" }
);
if (progress) {
presentSheet({
title: "Backing up your data",
paragraph:
"All your backups are stored in 'Phone Storage/Notesnook/backups/' folder",
progress: true
startProgress({
title: `Creating ${backupType === "full" ? "a full " : ""}backup`,
paragraph: `Please wait while we create a backup of your data. This may take a few minutes.`,
progress: undefined
});
}
let path;
let backupFilePath;
let backupFileName = "notesnook_backup_" + Date.now();
if (Platform.OS === "ios") {
path = await storage.checkAndCreateDir("/backups/");
}
const zipSourceFolder = `${cacheDir}/${backupFileName}`;
const zipSourceFolder = `${cacheDir}/backup_temp`;
const zipOutputFile =
Platform.OS === "ios"
? `${path}/${backupFileName}.nnbackupz`
: `${cacheDir}/${backupFileName}.nnbackupz`;
try {
if (await RNFetchBlob.fs.exists(zipSourceFolder))
await RNFetchBlob.fs.unlink(zipSourceFolder);
} catch (e) {}
await RNFetchBlob.fs.unlink(zipSourceFolder).catch(console.log);
await RNFetchBlob.fs.mkdir(zipSourceFolder);
const attachmentsDir = zipSourceFolder + "/attachments";
if (backupType === "full") {
await RNFetchBlob.fs.mkdir(attachmentsDir);
}
try {
const user = await db.user.getUser();
for await (const file of db.backup.export(
"mobile",
SettingsService.get().encryptedBackup && user
)) {
console.log("Writing backup chunk of size...", file?.data?.length);
await RNFetchBlob.fs.writeFile(
`${zipSourceFolder}/${file.path}`,
file.data,
"utf8"
);
for await (const file of db.backup.export({
type: "mobile",
encrypt: SettingsService.get().encryptedBackup && !!user,
mode: backupType
})) {
if (file.type === "file") {
updateProgress({
progress: `Writing backup chunk of size... ${file?.data?.length}`
});
await RNFetchBlob.fs.writeFile(
`${zipSourceFolder}/${file.path}`,
file.data,
"utf8"
);
} else if (file.type === "attachment") {
updateProgress({
progress: `Saving attachments in backup... ${file.hash}`
});
if (await filesystem.exists(file.hash)) {
await RNFetchBlob.fs.cp(
`${cacheDir}/${file.hash}`,
`${attachmentsDir}/${file.hash}`
);
}
}
}
updateProgress({
progress: "Creating backup zip file..."
});
await zip(zipSourceFolder, zipOutputFile);
if (Platform.OS === "android") {
// Move the zip to user selected directory.
const file = await ScopedStorage.createFile(
androidBackupDirectory.uri,
androidBackupDirectory?.uri,
`${backupFileName}.nnbackupz`,
"application/nnbackupz"
);
console.log("Copying zip file...");
await copyFileAsync(`file://${zipOutputFile}`, file.uri);
console.log("Copyied zip file...");
console.log("Copied zip file...");
path = file.uri;
} else {
path = zipOutputFile;
}
RNFetchBlob.fs.unlink(zipSourceFolder).catch(console.log);
updateNextBackupTime();
let showBackupCompleteSheet =
RNFetchBlob.fs.unlink(zipSourceFolder).catch(console.log);
if (Platform.OS === "android") {
RNFetchBlob.fs.unlink(zipOutputFile).catch(console.log);
}
updateNextBackupTime(backupType || "partial");
if (progress) {
endProgress();
}
const canShowCompletionStatus =
progress && SettingsService.get().showBackupCompleteSheet;
if (context) {
@@ -235,15 +289,12 @@ async function run(progress = false, context) {
await sleep(300);
if (showBackupCompleteSheet) {
presentBackupCompleteSheet(backupFilePath);
} else {
progress && eSendEvent(eCloseSheet);
if (canShowCompletionStatus) {
presentBackupCompleteSheet(path);
}
ToastManager.show({
heading: "Backup successful",
message: "Your backup is stored in Notesnook folder on your phone.",
type: "success",
context: "global"
});
@@ -252,50 +303,68 @@ async function run(progress = false, context) {
path: path
};
} catch (e) {
ToastManager.error(e, "Backup failed", context || "global");
ToastManager.error(e as Error, "Backup failed", context || "global");
if (e?.message?.includes("android.net.Uri") && androidBackupDirectory) {
if (
(e as Error)?.message?.includes("android.net.Uri") &&
androidBackupDirectory
) {
SettingsService.setProperty("backupDirectoryAndroid", null);
return run(progress, context);
return run(progress, context, backupType);
}
DatabaseLogger.error(e, "Backup failed");
RNFetchBlob.fs.unlink(zipSourceFolder).catch(console.log);
if (Platform.OS === "android") {
RNFetchBlob.fs.unlink(zipOutputFile).catch(console.log);
}
DatabaseLogger.error(e);
await sleep(300);
progress && eSendEvent(eCloseSheet);
if (progress) {
endProgress();
}
return {
error: e
error: e,
report: true
};
}
}
async function getLastBackupDate() {
return SettingsService.get().lastBackupDate;
}
async function checkBackupRequired(
type: "daily" | "off" | "useroff" | "weekly" | "monthly" | "never",
lastBackupDateType: "lastBackupDate" | "lastFullBackupDate" = "lastBackupDate"
) {
console.log(lastBackupDateType, type);
if (type === "off" || type === "useroff" || type === "never" || !type) return;
const now = Date.now();
const lastBackupDate = SettingsService.getProperty(lastBackupDateType) as
| number
| "never";
async function checkBackupRequired(type) {
if (type === "off" || type === "useroff") return;
let now = Date.now();
let lastBackupDate = await getLastBackupDate();
if (!lastBackupDate || lastBackupDate === "never") {
if (
lastBackupDate === undefined ||
lastBackupDate === "never" ||
lastBackupDate === 0
) {
return true;
}
lastBackupDate = parseInt(lastBackupDate);
if (type === "daily" && lastBackupDate + MS_DAY < now) {
DatabaseLogger.info("Daily backup started");
DatabaseLogger.info(`Daily backup started: ${type}`);
return true;
} else if (type === "weekly" && lastBackupDate + MS_WEEK < now) {
DatabaseLogger.info("Weekly backup started");
DatabaseLogger.info(`Weekly backup started: ${type}`);
return true;
} else if (type === "monthly" && lastBackupDate + MONTH < now) {
DatabaseLogger.info("Monthly backup started");
DatabaseLogger.info(`Monthly backup started: ${type}`);
return true;
}
return false;
}
const checkAndRun = async () => {
let settings = SettingsService.get();
if (await checkBackupRequired(settings.reminder)) {
const settings = SettingsService.get();
if (await checkBackupRequired(settings?.reminder)) {
try {
await run();
} catch (e) {

View File

@@ -139,6 +139,7 @@ export type ToastOptions = {
duration?: number;
func?: () => void;
actionText?: string;
icon?: string;
};
export const ToastManager = {
@@ -162,7 +163,7 @@ export const ToastManager = {
});
},
hide: () => eSendEvent(eHideToast),
error: (e: Error, title?: string, context?: any) => {
error: (e: Error, title?: string, context?: any, duration = 5000) => {
ToastManager.show({
heading: title,
message: e?.message || "",
@@ -176,7 +177,7 @@ export const ToastManager = {
heading: "Logs copied!",
type: "success",
context: "global",
duration: 5000
duration: duration
});
}
});

View File

@@ -17,40 +17,26 @@ 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 { decode, EntityLevel } from "entities";
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 { zip } from "react-native-zip-archive";
import { DatabaseLogger, db } from "../common/database/index";
import { DatabaseLogger } from "../common/database/index";
import Storage from "../common/database/storage";
import {
exportNote as _exportNote,
ExportableAttachment,
ExportableNote,
exportNotes,
sanitizeFilename
exportNotes
} from "@notesnook/common";
import { Note } from "@notesnook/core";
import { NoteContent } from "@notesnook/core/dist/collections/session-content";
import { FilteredSelector } from "@notesnook/core/dist/database/sql-collection";
import { basename, dirname, join } from "pathe";
import downloadAttachment from "../common/filesystem/download-attachment";
import { presentDialog } from "../components/dialog/functions";
import { useSettingStore } from "../stores/use-setting-store";
import BiometricService from "./biometrics";
import { ToastManager } from "./event-manager";
import { cacheDir } from "../common/filesystem/utils";
const MIMETypes = {
txt: "text/plain",
pdf: "application/pdf",
md: "text/markdown",
"md-frontmatter": "text/markdown",
html: "text/html"
};
import { unlockVault } from "../utils/unlock-vault";
const FolderNames: { [name: string]: string } = {
txt: "Text",
@@ -59,16 +45,6 @@ const FolderNames: { [name: string]: string } = {
html: "Html"
};
async function releasePermissions(path: string) {
if (Platform.OS === "ios") return;
const uris = await ScopedStorage.getPersistedUriPermissions();
for (const uri of uris) {
if (path.startsWith(uri)) {
await ScopedStorage.releasePersistableUriPermission(uri);
}
}
}
async function getPath(type: string) {
let path =
Platform.OS === "ios" &&
@@ -82,153 +58,11 @@ async function getPath(type: string) {
return path;
}
async function save(
path: string,
data: string,
fileName: string,
extension: "txt" | "pdf" | "md" | "html" | "md-frontmatter"
) {
let uri;
if (Platform.OS === "android") {
uri = await ScopedStorage.writeFile(
path,
data,
`${fileName}.${extension}`,
MIMETypes[extension],
extension === "pdf" ? "base64" : "utf8",
false
);
await releasePermissions(path);
} else {
path = path + fileName + `.${extension}`;
await RNFetchBlob.fs.writeFile(path, data, "utf8");
}
return uri || path;
}
async function makeHtml(note: Note, content?: NoteContent<false>) {
let html = await db.notes.export(note.id, {
format: "html",
contentItem: content
});
if (!html) return "";
html = decode(html, {
level: EntityLevel.HTML
});
return html;
}
async function exportAs(
type: string,
note: Note,
bulk?: boolean,
content?: NoteContent<false>
) {
let data;
switch (type) {
case "html":
{
data = await makeHtml(note, content);
}
break;
case "md":
data = await db.notes.export(note.id, {
format: "md",
contentItem: content
});
break;
case "md-frontmatter":
data = await db.notes.export(note.id, {
format: "md-frontmatter",
contentItem: content
});
break;
case "pdf":
{
const html = await makeHtml(note, content);
const fileName = sanitizeFilename(note.title + Date.now(), {
replacement: "_"
});
const options = {
html: html,
fileName:
Platform.OS === "ios" ? "/exported/PDF/" + fileName : fileName,
width: 595,
height: 852,
bgColor: "#FFFFFF",
padding: 30,
base64: bulk || Platform.OS === "android"
} as { [name: string]: any };
if (Platform.OS === "ios") {
options.directory = "Documents";
}
const res = await RNHTMLtoPDF.convert(options);
data = !bulk && Platform.OS === "ios" ? res.filePath : res.base64;
if (bulk && res.filePath) {
RNFetchBlob.fs.unlink(res.filePath);
}
}
break;
case "txt":
{
data = await db.notes.export(note.id, {
format: "txt",
contentItem: content
});
}
break;
}
return data;
}
async function unlockVault() {
const biometry = await BiometricService.isBiometryAvailable();
const fingerprint = await BiometricService.hasInternetCredentials();
if (biometry && fingerprint) {
const credentials = await BiometricService.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) {
ToastManager.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);
}
});
});
async function unlockVaultForNoteExport() {
return await unlockVault({
title: "Unlock vault",
paragraph: "Some exported notes are locked, Unlock to export them",
context: "export-notes"
});
}
@@ -285,6 +119,7 @@ async function createZip(
callback: (progress?: string) => void
) {
const fileName = `nn-export-${totalNotes}-${type}-${Date.now()}.zip`;
const dir = path;
try {
callback("Creating zip");
const zipOutputPath =
@@ -292,6 +127,7 @@ async function createZip(
? join(path, fileName)
: join(RNFetchBlob.fs.dirs.CacheDir, fileName);
await zip(cacheFolder, zipOutputPath);
callback("Saving zip file");
if (Platform.OS === "android") {
const file = await ScopedStorage.createFile(
@@ -303,6 +139,8 @@ async function createZip(
await copyFileAsync("file://" + zipOutputPath, path);
await RNFetchBlob.fs.unlink(zipOutputPath);
callback();
} else {
path = zipOutputPath;
}
RNFetchBlob.fs.unlink(cacheFolder);
} catch (e) {
@@ -311,6 +149,7 @@ async function createZip(
return {
filePath: path,
fileDir: dir,
type: "application/zip",
name: "zip",
fileName: fileName,
@@ -388,7 +227,7 @@ async function bulkExport(
let currentAttachmentProgress = 0;
for await (const item of exportNotes(notes, {
format: type,
unlockVault: unlockVault as () => Promise<boolean>
unlockVault: unlockVaultForNoteExport as () => Promise<boolean>
})) {
if (item instanceof Error) {
DatabaseLogger.error(item);
@@ -432,7 +271,7 @@ async function exportNote(
let currentAttachmentProgress = 0;
for await (const item of _exportNote(note, {
format: type,
unlockVault: unlockVault as () => Promise<boolean>
unlockVault: unlockVaultForNoteExport as () => Promise<boolean>
})) {
if (item instanceof Error) {
DatabaseLogger.error(item);

View File

@@ -59,14 +59,14 @@ const recoveryKeyMessage = {
() => {
eSendEvent(eOpenRecoveryKeyDialog);
},
true,
false,
async () => {
SettingsService.set({
recoveryKeySaved: true
});
clearMessage();
},
"I have saved my key already"
"Cancel"
);
},
data: {},

View File

@@ -35,21 +35,21 @@ import dayjs, { Dayjs } from "dayjs";
import { encodeNonAsciiHTML } from "entities";
import { Platform } from "react-native";
import { db, setupDatabase } from "../common/database";
import { MMKV } from "../common/database/mmkv";
import { presentDialog } from "../components/dialog/functions";
import { useTabStore } from "../screens/editor/tiptap/use-tab-store";
import { editorState } from "../screens/editor/tiptap/utils";
import { useRelationStore } from "../stores/use-relation-store";
import { useReminderStore } from "../stores/use-reminder-store";
import { useSettingStore } from "../stores/use-setting-store";
import { eOnLoadNote } from "../utils/events";
import { useUserStore } from "../stores/use-user-store";
import { tabBarRef } from "../utils/global-refs";
import { convertNoteToText } from "../utils/note-to-text";
import { NotesnookModule } from "../utils/notesnook-module";
import { sleep } from "../utils/time";
import { DDS } from "./device-detection";
import { eSendEvent } from "./event-manager";
import Navigation from "./navigation";
import SettingsService from "./settings";
import { useUserStore } from "../stores/use-user-store";
let pinned: DisplayedNotification[] = [];
@@ -125,7 +125,7 @@ const onEvent = async ({ type, detail }: Event) => {
if (type === EventType.PRESS) {
notifee.decrementBadgeCount();
if (notification?.data?.type === "quickNote") return;
MMKV.removeItem("appState");
NotesnookModule.setAppState("");
if (notification?.data?.type === "reminder" && notification?.id) {
const reminder = await db.reminders?.reminder(
notification.id?.split("_")[0]
@@ -140,6 +140,7 @@ const onEvent = async ({ type, detail }: Event) => {
}
editorState().movedAway = false;
const noteId = notification?.id;
console.log("NOTE ID", noteId);
loadNote(noteId as string, true);
}
@@ -408,18 +409,29 @@ async function loadNote(id: string, jump: boolean) {
if (!DDS.isTab && jump) {
tabBarRef.current?.goToPage(1);
}
eSendEvent("loadingNote", note);
setTimeout(
() => {
eSendEvent(eOnLoadNote, {
item: note
});
if (!jump && !DDS.isTab) {
tabBarRef.current?.goToPage(1);
}
},
tabBarRef?.current ? 0 : 2000
NotesnookModule.setAppState(
JSON.stringify({
editing: true,
movedAway: false,
timestamp: Date.now()
})
);
const isLocked = await db.vaults.itemExists({
type: "note",
id: id
});
const tab = useTabStore.getState().getTabForNote(id);
if (tab !== undefined) {
useTabStore.getState().focusTab(tab);
} else {
useTabStore.getState().focusPreviewTab(id, {
noteId: id,
readonly: note.readonly,
noteLocked: isLocked
});
}
}
async function getChannelId(id: "silent" | "vibrate" | "urgent" | "default") {
@@ -937,13 +949,13 @@ async function pinNote(id: string) {
const note = await db.notes.note(id as string);
if (!note) return;
let text = await convertNoteToText(note, false);
let text = await convertNoteToText(note, true);
if (!text) text = "";
const html = text.replace(/\n/g, "<br />");
Notifications.displayNotification({
title: note.title,
message: note.headline || text,
subtitle: note.headline || text,
subtitle: "",
bigText: html,
ongoing: true,
actions: ["UNPIN"],

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