Compare commits

..

81 Commits

Author SHA1 Message Date
adrian-fuertes
34db181af0
fix typos in sync messages and comments (startting -> starting) (#876)
Some checks failed
BuildCI / build (20.x) (push) Failing after 5m56s
2024-11-10 18:16:22 +08:00
Liam Swayne
6631a9c5eb
typo fixes (#870) 2024-11-10 18:14:16 +08:00
fyears
e39edcea70 bump to 0.5.25
Some checks failed
Release A New Version / build (20.x) (push) Failing after 46s
2024-10-20 17:12:42 +08:00
fyears
9ac7ecf828 fix undefined 2024-10-20 16:58:22 +08:00
fyears
50c08400ff add more prefix 2024-10-20 16:42:47 +08:00
fyears
7bc2fad88b bump to 0.5.24
Some checks failed
Release A New Version / build (20.x) (push) Failing after 41s
2024-09-30 21:15:53 +08:00
fyears
6dc1c28361 add caddy 2024-09-30 21:15:23 +08:00
fyears
2220f511e3 fix webdav path with /.. leading 2024-09-30 20:51:55 +08:00
fyears
06de1a4ab0 bump to 0.5.23
Some checks failed
Release A New Version / build (20.x) (push) Failing after 47s
2024-09-30 18:11:43 +08:00
fyears
df184ff9d8 correct way to deal with .obsidian and bookmarks 2024-09-30 18:11:08 +08:00
fyears
f50ba953f1 fix ci
Some checks failed
Release A New Version / build (20.x) (push) Failing after 50s
2024-09-29 10:19:48 +08:00
fyears
55cb26bd22 bump to 0.5.22 2024-09-29 10:11:01 +08:00
fyears
36d3018efb fix ignore logic 2024-09-29 10:09:49 +08:00
fyears
421b43d937 update complex logic for config 2024-09-29 09:32:04 +08:00
xvqinghong
17708359a1
fix bug of unwished synchronizing Config Directory and Bookmarks File (#816)
In the original code, if we set syncConfigDir to false, which means we don't want to sync this directory, but it will also cause `if( syncConfigDir && isInsideObsFolder(key, configDir) )` statement NEVER be entered.  Thus, in the original code, our setting is actually be ignored.
2024-09-29 09:20:27 +08:00
fyears
9acae1b077 fix google drive expire 2024-09-29 08:59:14 +08:00
fyears
4ade975585 warn in console about expire 2024-09-29 08:58:57 +08:00
fyears
e988fc7ae9 update ci 2024-09-09 00:39:19 +08:00
fyears
5c56f2146f 0.5.21
Some checks failed
Release A New Version / build (20.x) (push) Failing after 41s
2024-09-09 00:13:09 +08:00
fyears
74125f8dff fix config dir special empty condiction 2024-09-09 00:12:38 +08:00
fyears
ace16de20c add complex logic to allow list and ignore list 2024-09-09 00:00:12 +08:00
fyears
716e5aa6c5 not detect chars in name for now 2024-09-07 15:26:19 +08:00
fyears
fcdbb71493 add star and download history 2024-09-01 18:53:19 +08:00
fyears
0040e18b49 fix link 2024-09-01 18:30:31 +08:00
fyears
b5d56843fd bump to 0.5.20
Some checks failed
Release A New Version / build (20.x) (push) Failing after 52s
2024-09-01 18:28:46 +08:00
fyears
b63b6791aa re-enable profiler 2024-09-01 18:28:08 +08:00
Matvey Romanov
2a3d1265b3
Update en.json (#794) 2024-09-01 17:34:46 +08:00
fyears
245d529821 bump to 0.5.19
Some checks failed
Release A New Version / build (20.x) (push) Failing after 43s
2024-09-01 17:29:48 +08:00
fyears
74e5231861 not transfer data to worker for safety 2024-09-01 17:26:32 +08:00
fyears
ac9c2a9248 mini support to ctimeCli 2024-09-01 17:17:08 +08:00
fyears
b2dea5a351 add allow list mode 2024-09-01 16:48:35 +08:00
fyears
e9b9cd97ac check if folder/file name is valid 2024-09-01 16:15:42 +08:00
fyears
fccebb0594 fix error notice 2024-09-01 16:15:17 +08:00
fyears
dda304c857 add cn for readme 2024-08-04 00:25:21 +08:00
fyears
c0aec40bcc bump to 0.5.18
Some checks failed
Release A New Version / build (20.x) (push) Failing after 51s
2024-07-29 22:19:02 +08:00
fyears
fb2f4ef46f fix checking 2024-07-29 22:18:33 +08:00
fyears
52f3e6a265 bump to 0.5.17
Some checks failed
Release A New Version / build (20.x) (push) Failing after 41s
2024-07-28 16:14:41 +08:00
fyears
b5099854af webdis add prefix in scan 2024-07-28 15:50:01 +08:00
fyears
d42b31cea2 update node ci
Some checks failed
Release A New Version / build (20.x) (push) Failing after 51s
2024-07-27 23:08:49 +08:00
fyears
69e0c77444 bump to 0.5.16 2024-07-27 22:58:36 +08:00
fyears
ee4394873b upgrade check connections 2024-07-27 22:58:05 +08:00
fyears
f2845cdcbf finally we can switch from ts-node to tsx 2024-07-27 22:55:04 +08:00
fyears
bbee873b64 remove debug log 2024-07-27 22:08:22 +08:00
fyears
f5fee16130 bump to 0.5.15 2024-07-27 19:38:25 +08:00
fyears
f4b82204c1 update packages 2024-07-27 19:37:55 +08:00
fyears
f1a06a3f52 add append mode for sabre 2024-07-27 19:22:57 +08:00
fyears
ae4e67f3b4 fix smart conflict 2024-07-27 19:09:42 +08:00
fyears
254231e4bd add onedrive mtime error 2024-07-27 15:02:21 +08:00
fyears
871e8dc3cf encode username 2024-07-27 14:41:37 +08:00
fyears
85aed7cfb9 dufs 2024-07-27 14:41:26 +08:00
fyears
3f7a6dbf6a Merge branch 'master' of https://github.com/fyears/remotely-save 2024-07-27 12:37:31 +08:00
fyears
13cca9025e hard code famous website 2024-07-27 12:30:17 +08:00
Vincent Whizin
a81af9ccec
Update docs on "large" files sync issues (#753) 2024-07-18 13:14:06 +08:00
fyears
db86a75534
Add vConsole tutorial 2024-07-14 22:31:08 +08:00
fyears
72e059d5cc
description of config folder and bookmarks 2024-07-14 21:09:09 +08:00
fyears
b083f006b1 bump to 0.5.14
Some checks failed
Release A New Version / build (16.x) (push) Failing after 46s
2024-07-14 17:16:31 +08:00
fyears
12ed023cd1 add bookmarks sync 2024-07-14 17:04:05 +08:00
fyears
5c86bc039d bump to 0.5.13
Some checks failed
Release A New Version / build (16.x) (push) Failing after 49s
2024-07-14 00:44:38 +08:00
fyears
91e358fcea custom header for webdav 2024-07-14 00:44:11 +08:00
fyears
733fa1d306 export 5 changes 2024-07-13 23:24:41 +08:00
fyears
f256936bae slightly optimize two way merge 2024-07-13 23:19:39 +08:00
fyears
7228398d0a more debug 2024-07-13 23:14:05 +08:00
fyears
6ed04a651b simplify merge file 2024-07-13 23:11:54 +08:00
fyears
be5518e320 add more rclone desc 2024-07-13 23:08:37 +08:00
fyears
c7bb3646a4 no longer transfer array buffer 2024-07-13 23:04:28 +08:00
fyears
428e23941a fix feature detect 2024-07-13 23:03:55 +08:00
fyears
1012bf3d09 remove dup files 2024-07-13 16:31:09 +08:00
fyears
57bdc4d0c6 remove msft temp files 2024-07-13 16:31:02 +08:00
fyears
3c85fff17c fix bug in smart conflict and encryption 2024-07-13 13:57:12 +08:00
fyears
9aa1bd821e bump to 0.5.12
Some checks failed
Release A New Version / build (16.x) (push) Failing after 45s
2024-06-29 18:34:11 +08:00
fyears
a967d6ffd9 move onedrive full to below, and add separator 2024-06-29 18:33:41 +08:00
fyears
a2ce95441a download at best effort 2024-06-29 00:43:01 +08:00
fyears
e74e49538e more logic for potentially the same files in smart conflict 2024-06-29 00:14:53 +08:00
fyears
11c66d7030 fix smart conflict for .obsidian 2024-06-28 23:17:41 +08:00
fyears
56bd4c000e Merge branch 'master' of https://github.com/fyears/remotely-save 2024-06-28 23:06:33 +08:00
fyears
a7cc4e2d7e more robust for rclone 2024-06-28 23:06:14 +08:00
fyears
f306445e0d save resources 2024-06-28 23:05:22 +08:00
lyiton
9f4de49495
修改一处细节 (#720)
* Update zh_cn.json

* Update zh_cn.json

* Update zh_tw.json
2024-06-24 22:52:25 +08:00
fyears
54c25a70ed add pro tag to onedrive 2024-06-23 18:09:48 +08:00
fyears
6befa3cca3 bump to 0.5.11
Some checks failed
Release A New Version / build (16.x) (push) Failing after 45s
2024-06-23 17:45:26 +08:00
fyears
0463ae8222 onedrive full 2024-06-23 17:44:02 +08:00
66 changed files with 4101 additions and 351 deletions

View File

@ -34,18 +34,18 @@ jobs:
strategy: strategy:
matrix: matrix:
node-version: [16.x] node-version: [20.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps: steps:
- name: Checkout codes - name: Checkout codes
uses: actions/checkout@v2 uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
- name: Checkout LFS file list - name: Checkout LFS file list
run: git lfs ls-files --long | cut -d ' ' -f1 | sort > .lfs-assets-id run: git lfs ls-files --long | cut -d ' ' -f1 | sort > .lfs-assets-id
- name: LFS Cache - name: LFS Cache
uses: actions/cache@v3 uses: actions/cache@v4
with: with:
path: .git/lfs/objects path: .git/lfs/objects
key: ${{ runner.os }}-lfs-${{ hashFiles('.lfs-assets-id') }} key: ${{ runner.os }}-lfs-${{ hashFiles('.lfs-assets-id') }}
@ -54,13 +54,13 @@ jobs:
- name: Git LFS Pull - name: Git LFS Pull
run: git lfs pull run: git lfs pull
- name: Use Node.js ${{ matrix.node-version }} - name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2 uses: actions/setup-node@v4
with: with:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
- run: npm install - run: npm install
- run: npm test - run: npm test
- run: npm run build - run: npm run build
- uses: actions/upload-artifact@v2 - uses: actions/upload-artifact@v4
with: with:
name: my-dist name: my-dist
path: | path: |

View File

@ -38,17 +38,17 @@ jobs:
strategy: strategy:
matrix: matrix:
node-version: [16.x] node-version: [20.x]
steps: steps:
- name: Checkout codes - name: Checkout codes
uses: actions/checkout@v2 uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
- name: Checkout LFS file list - name: Checkout LFS file list
run: git lfs ls-files --long | cut -d ' ' -f1 | sort > .lfs-assets-id run: git lfs ls-files --long | cut -d ' ' -f1 | sort > .lfs-assets-id
- name: LFS Cache - name: LFS Cache
uses: actions/cache@v3 uses: actions/cache@v4
with: with:
path: .git/lfs/objects path: .git/lfs/objects
key: ${{ runner.os }}-lfs-${{ hashFiles('.lfs-assets-id') }} key: ${{ runner.os }}-lfs-${{ hashFiles('.lfs-assets-id') }}
@ -57,50 +57,20 @@ jobs:
- name: Git LFS Pull - name: Git LFS Pull
run: git lfs pull run: git lfs pull
- name: Use Node.js ${{ matrix.node-version }} - name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2 uses: actions/setup-node@v4
with: with:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
- run: npm install - run: npm install
- run: npm test - run: npm test
- run: npm run build - run: npm run build
- name: Create Release - name: Create Release And Upload
id: create_release uses: softprops/action-gh-release@v2
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ github.ref }}
with: with:
tag_name: ${{ github.ref }} files: |
release_name: ${{ github.ref }} main.js
manifest.json
styles.css
token: ${{ secrets.GITHUB_TOKEN }}
draft: false draft: false
prerelease: true prerelease: false
- name: Upload main.js make_latest: true
id: upload-main
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./main.js
asset_name: main.js
asset_content_type: text/javascript
- name: Upload manifest.json
id: upload-manifest
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./manifest.json
asset_name: manifest.json
asset_content_type: application/json
- name: Upload styles.css
id: upload-styles
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./styles.css
asset_name: styles.css
asset_content_type: text/css

View File

@ -1,5 +1,7 @@
# Remotely Save # Remotely Save
English | [中文](./README.zh-cn.md)
This is yet another unofficial sync plugin for Obsidian. If you like it or find it useful, please consider give it a [star ![GitHub Repo stars](https://img.shields.io/github/stars/fyears/remotely-save?style=social)](https://github.com/fyears/remotely-save) on Github. This is yet another unofficial sync plugin for Obsidian. If you like it or find it useful, please consider give it a [star ![GitHub Repo stars](https://img.shields.io/github/stars/fyears/remotely-save?style=social)](https://github.com/fyears/remotely-save) on Github.
[![BuildCI](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml/badge.svg)](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml) [![BuildCI](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml/badge.svg)](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml)
@ -19,7 +21,8 @@ This is yet another unofficial sync plugin for Obsidian. If you like it or find
- Supports: - Supports:
- Amazon S3 or S3-compatible (Cloudflare R2 / BackBlaze B2 / MinIO / ...) - Amazon S3 or S3-compatible (Cloudflare R2 / BackBlaze B2 / MinIO / ...)
- Dropbox - Dropbox
- OneDrive for personal - OneDrive for personal (App Folder)
- OneDrive for personal (Full) (PRO feature)
- Webdav (NextCloud / InfiniCloud / Synology webdav server / ...) - Webdav (NextCloud / InfiniCloud / Synology webdav server / ...)
- Webdis - Webdis
- Google Drive (GDrive) (PRO feature) - Google Drive (GDrive) (PRO feature)
@ -30,7 +33,7 @@ This is yet another unofficial sync plugin for Obsidian. If you like it or find
- Azure Blob Storage (PRO feature) - Azure Blob Storage (PRO feature)
- [Here](./docs/services_connectable_or_not.md) shows more connectable (or not-connectable) services in details. - [Here](./docs/services_connectable_or_not.md) shows more connectable (or not-connectable) services in details.
- **Obsidian Mobile supported.** Vaults can be synced across mobile and desktop devices with the cloud service as the "broker". - **Obsidian Mobile supported.** Vaults can be synced across mobile and desktop devices with the cloud service as the "broker".
- **[End-to-end encryption](./docs/encryption/README.md) supported.** Files would be encrypted using openssl format before being sent to the cloud **if** user specify a password. - **[End-to-end encryption](./docs/encryption/README.md) supported.** Files would be encrypted using openssl / rclone crypt format before being sent to the cloud **if** user specify a password.
- **Scheduled auto sync supported.** You can also manually trigger the sync using sidebar ribbon, or using the command from the command palette (or even bind the hot key combination to the command then press the hot key combination). - **Scheduled auto sync supported.** You can also manually trigger the sync using sidebar ribbon, or using the command from the command palette (or even bind the hot key combination to the command then press the hot key combination).
- **[Minimal Intrusive](./docs/minimal_intrusive_design.md).** - **[Minimal Intrusive](./docs/minimal_intrusive_design.md).**
- **Skip Large files** and **skip paths** by custom regex conditions! - **Skip Large files** and **skip paths** by custom regex conditions!
@ -45,21 +48,23 @@ This is yet another unofficial sync plugin for Obsidian. If you like it or find
- **You should protect your `data.json` file.** The file contains sensitive information. - **You should protect your `data.json` file.** The file contains sensitive information.
- It's strongly advised **NOT** to share your `data.json` file to anyone. - It's strongly advised **NOT** to share your `data.json` file to anyone.
- It's usually **NOT** a good idea to check the file into version control. By default, the plugin tries to create a `.gitignore` file inside the plugin directory if it doesn't exist, for ignoring `data.json` in the `git` version control. If you know exactly what it means and want to remove the setting, please modify the `.gitignore` file or set it to be empty. - It's usually **NOT** a good idea to check the file into version control. By default, the plugin tries to create a `.gitignore` file inside the plugin directory if it doesn't exist, for ignoring `data.json` in the `git` version control. If you know exactly what it means and want to remove the setting, please modify the `.gitignore` file or set it to be empty.
- **Obsidian API on Mobile has performance issues syncing large files (>= 50 MB).**
- Setting the "Skip Large Files" option can help resolve issues related to syncing large files.
## Questions, Suggestions, Or Bugs ## Questions, Suggestions, Or Bugs
You are greatly welcome to ask questions, post any suggestions, or report any bugs! The project is mainly maintained on GitHub: You are greatly welcome to ask questions, post any suggestions, or report any bugs! The project is mainly maintained on GitHub:
- Questions: [GitHub repo Discussions](https://github.com/fyears/remotely-save/discussions) - Questions: [GitHub repo Discussions](https://github.com/remotely-save/remotely-save/discussions)
- Suggestions: also in [GitHub repo Discussions](https://github.com/fyears/remotely-save/discussions) - Suggestions: also in [GitHub repo Discussions](https://github.com/remotely-save/remotely-save/discussions)
- Bugs: [GitHub repo Issues](https://github.com/fyears/remotely-save/issues) (NOT Discussion) - Bugs: [GitHub repo Issues](https://github.com/remotely-save/remotely-save/issues) (NOT Discussion)
Additionally, the plugin author may occasionally visit Obsidian official forum and official Discord server, and pay attention to this-plugin-related information there. Additionally, the plugin author may occasionally visit Obsidian official forum and official Discord server, and pay attention to this-plugin-related information there.
## Download and Install ## Download and Install
- Option #1: Search in the official "community plugin list", or visit this: [https://obsidian.md/plugins?id=remotely-save](https://obsidian.md/plugins?id=remotely-save) (which should redirect you into Obsidian app), then install the plugin. - Option #1: Search in the official "community plugin list", or visit this: [https://obsidian.md/plugins?id=remotely-save](https://obsidian.md/plugins?id=remotely-save) (which should redirect you into Obsidian app), then install the plugin.
- Option #2: You can also use [Obsidian42 - BRAT](https://github.com/TfTHacker/obsidian42-brat) to install this plugin. Input `fyears/remotely-save` in the configuration of BRAT. - Option #2: You can also use [Obsidian42 - BRAT](https://github.com/TfTHacker/obsidian42-brat) to install this plugin. Input `remotely-save/remotely-save` in the configuration of BRAT.
- Option #3: [![GitHub release (latest by SemVer and asset including pre-releases)](https://img.shields.io/github/downloads-pre/fyears/remotely-save/latest/main.js?sort=semver)](https://github.com/fyears/remotely-save/releases) Manually download assets (`main.js`, `manifest.json`, `styles.css`) from the latest release. - Option #3: [![GitHub release (latest by SemVer and asset including pre-releases)](https://img.shields.io/github/downloads-pre/fyears/remotely-save/latest/main.js?sort=semver)](https://github.com/fyears/remotely-save/releases) Manually download assets (`main.js`, `manifest.json`, `styles.css`) from the latest release.
- Option #4: [![BuildCI](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml/badge.svg)](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml) Every artifacts are placed in the "Summary" under every successful builds. It's automatically generated by every commit, may break something. - Option #4: [![BuildCI](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml/badge.svg)](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml) Every artifacts are placed in the "Summary" under every successful builds. It's automatically generated by every commit, may break something.
@ -93,11 +98,11 @@ Additionally, the plugin author may occasionally visit Obsidian official forum a
- Password-based end-to-end encryption is also supported. But please be aware that **the vault name itself is not encrypted**. - Password-based end-to-end encryption is also supported. But please be aware that **the vault name itself is not encrypted**.
- If you want to sync the files across multiple devices, **your vault name should be the same** while using default settings. - If you want to sync the files across multiple devices, **your vault name should be the same** while using default settings.
### OneDrive for personal ### OneDrive for personal (App Folder)
- **This plugin is NOT an official Microsoft / OneDrive product.** The plugin just uses Microsoft's [OneDrive's public API](https://docs.microsoft.com/en-us/onedrive/developer/rest-api). - **This plugin is NOT an official Microsoft / OneDrive product.** The plugin just uses Microsoft's [OneDrive's public API](https://docs.microsoft.com/en-us/onedrive/developer/rest-api).
- This plugin only works for "OneDrive for personal", and not works for "OneDrive for Business" (yet). See [#11](https://github.com/fyears/remotely-save/issues/11) to further details. - This plugin only works for "OneDrive for personal", and not works for "OneDrive for Business" (yet). See [#11](https://github.com/fyears/remotely-save/issues/11) to further details.
- After the authorization, the plugin can read your name and email, and read and write files in your OneDrive's `/Apps/remotely-save` folder. - After the authorization, the plugin can read your name and email, and read and write files in your OneDrive's `/Apps/remotely-save` folder. **The free version of Remotely Save only connects to App Folder, while the PRO version can connect to the root folder in Onedrive. See below PRO part.**
- If you decide to authorize this plugin to connect to OneDrive, please go to plugin's settings, and choose OneDrive then follow the instructions. - If you decide to authorize this plugin to connect to OneDrive, please go to plugin's settings, and choose OneDrive then follow the instructions.
- Password-based end-to-end encryption is also supported. But please be aware that **the vault name itself is not encrypted**. - Password-based end-to-end encryption is also supported. But please be aware that **the vault name itself is not encrypted**.
- If you want to sync the files across multiple devices, **your vault name should be the same** while using default settings. - If you want to sync the files across multiple devices, **your vault name should be the same** while using default settings.
@ -111,11 +116,13 @@ Additionally, the plugin author may occasionally visit Obsidian official forum a
- [ownCloud](./docs/remote_services/webdav_owncloud/README.md) - [ownCloud](./docs/remote_services/webdav_owncloud/README.md)
- [InfiniCloud](./docs/remote_services/webdav_infinicloud_teracloud/README.md) - [InfiniCloud](./docs/remote_services/webdav_infinicloud_teracloud/README.md)
- [Synology webdav server](./docs/remote_services/webdav_synology_webdav_server/README.md) | [群晖 webdav server](./docs/remote_services/webdav_synology_webdav_server/README.zh-cn.md) - [Synology webdav server](./docs/remote_services/webdav_synology_webdav_server/README.md) | [群晖 webdav server](./docs/remote_services/webdav_synology_webdav_server/README.zh-cn.md)
- [dufs](./docs/remote_services/webdav_dufs/README.md)
- [AList中文](./docs/remote_services/webdav_alist/README.zh-cn.md) | [AList (English)](./docs/remote_services/webdav_alist/README.md) - [AList中文](./docs/remote_services/webdav_alist/README.zh-cn.md) | [AList (English)](./docs/remote_services/webdav_alist/README.md)
- [坚果云](./docs/remote_services/webdav_jianguoyun/README.zh-cn.md) | [JianGuoYun/NutStore](./docs/remote_services/webdav_jianguoyun/README.md) - [坚果云](./docs/remote_services/webdav_jianguoyun/README.zh-cn.md) | [JianGuoYun/NutStore](./docs/remote_services/webdav_jianguoyun/README.md)
- [Open Media Vault](./docs/remote_services/webdav_openmediavault/README.md) - [Open Media Vault](./docs/remote_services/webdav_openmediavault/README.md)
- [Nginx (`ngx_http_dav_module`, `nginx-dav-ext-module`, with Docker)](./docs/remote_services/webdav_nginx/README.md) - [Nginx (`ngx_http_dav_module`, `nginx-dav-ext-module`, with Docker)](./docs/remote_services/webdav_nginx/README.md)
- [Apache (with Docker)](./docs/remote_services/webdav_apache/README.md) - [Apache (with Docker)](./docs/remote_services/webdav_apache/README.md)
- [Caddy with `http.handlers.webdav` module](./docs/remote_services/webdav_caddy/README.md)
- Very old version of Obsidian needs [configuring CORS](./docs/remote_services/webdav_general/webav_cors.md). - Very old version of Obsidian needs [configuring CORS](./docs/remote_services/webdav_general/webav_cors.md).
- Your data would be synced to a `${vaultName}` sub folder on your webdav server. - Your data would be synced to a `${vaultName}` sub folder on your webdav server.
- Password-based end-to-end encryption is also supported. But please be aware that **the vault name itself is not encrypted**. - Password-based end-to-end encryption is also supported. But please be aware that **the vault name itself is not encrypted**.
@ -128,6 +135,10 @@ Additionally, the plugin author may occasionally visit Obsidian official forum a
- Mostly experimental. - Mostly experimental.
- You have to setup and protect your web server by yourself. - You have to setup and protect your web server by yourself.
### Onedrive (Full access) (PRO feature)
PRO (paid) feature "sync with Onedrive (Full)" allows users to to sync with Onedrive root folder. Tutorials and limitations are documented [here](./docs/remote_services/onedrivefull/README.md).
### Google Drive (GDrive) (PRO feature) ### Google Drive (GDrive) (PRO feature)
PRO (paid) feature "sync with Google Drive" allows users to to sync with Google Drive. Tutorials and limitations are documented [here](./docs/remote_services/googledrive/README.md). PRO (paid) feature "sync with Google Drive" allows users to to sync with Google Drive. Tutorials and limitations are documented [here](./docs/remote_services/googledrive/README.md).
@ -156,7 +167,7 @@ PRO (paid) feature "sync with Azure Blob Storage" allows users to to sync with A
Basic (free) version can detect conflicts, but users have to choose to keep newer version or larger version of the files. Basic (free) version can detect conflicts, but users have to choose to keep newer version or larger version of the files.
PRO (paid) feature "Smart Conflict" gives users one more option: merge small markdown files, or duplicate large markdown files or non-markdown files. PRO (paid) feature "Smart Conflict" gives users one more option: merge small markdown files, or duplicate large markdown files or any-size non-markdown files.
See documents [here](./docs/pro/README.md) See documents [here](./docs/pro/README.md)
@ -171,20 +182,40 @@ See documents [here](./docs/pro/README.md)
- You can configure sync on save in settings. - You can configure sync on save in settings.
- In sync on save mode, if any error occurs, the plugin would **fail silently**. - In sync on save mode, if any error occurs, the plugin would **fail silently**.
## How To Deal With Hidden Files Or Folders ## Config Folder / Files and Bookmarks
By default, the plugin doesn't sync config folder / files of obsidian (normally `.obsidian` folder) because it's one of the hidden files.
However, in the latest version, you can enable syncing config folder in settings. Please be aware that it's an experimental feature. Notably some config files' modified times are changed everytime when Obsidian is opened, and this destroys the assumptions of the plugin, so some information may not be synced properly.
Moreover, the bookmarks of Obsidian are actually stored in `.obsidian/bookmarks.json` file. You can also set syncing this file (instead of the whole config folder) in settings. The plugin will keep the latest modified one across devices.
## Hidden Files Or Folders
**By default, all files or folder starting with `.` (dot) or `_` (underscore) are treated as hidden files, and would NOT be synced.** It's useful if you have some files just staying locally. But this strategy also means that themes / other plugins / settings of this plugin would neither be synced. **By default, all files or folder starting with `.` (dot) or `_` (underscore) are treated as hidden files, and would NOT be synced.** It's useful if you have some files just staying locally. But this strategy also means that themes / other plugins / settings of this plugin would neither be synced.
In the latest version, you can change the settings to allow syncing `_` files or folders, as well as `.obsidian` special config folder (but not any other `.` files or folders). In the latest version, you can change the settings to allow syncing `_` files or folders, as well as `.obsidian` special config folder as described above (but not any other `.` files or folders).
## PRO Features ## PRO (paid) Features
See [PRO](./docs/pro/README.md) for more details. See [PRO](./docs/pro/README.md) for more details.
## How To Debug ## How To Debug
See [here](./docs/how_to_debug/README.md) for more details. If you see any errors, please check the doc [here](./docs/how_to_debug/README.md) for more details.
Moreover, sometimes the program runs but slowly, you want to check the performance by [enabling the profiler](./docs/check_performance/README.md).
## Bonus: Import And Export Not-Oauth2 Plugin Settings By QR Code ## Bonus: Import And Export Not-Oauth2 Plugin Settings By QR Code
See [here](./docs/import_export_some_settings.md) for more details. See [here](./docs/import_export_some_settings.md) for more details.
## Download History
Download history can be viewed on the unofficial [Obsidian Stats](https://www.moritzjung.dev/obsidian-stats/plugins/remotely-save/#downloads) (NOT affiliated with official Obsidian and GitHub and Remotely Save).
## Star History
(NOT affiliated with official Obsidian and GitHub and Remotely Save.)
[![Star History Chart](https://api.star-history.com/svg?repos=remotely-save/remotely-save&type=Date)](https://star-history.com/#remotely-save/remotely-save&Date)

221
README.zh-cn.md Normal file
View File

@ -0,0 +1,221 @@
# Remotely Save
[English](./README.md) | 中文
这是Obsidian的一个非官方同步插件。如果你喜欢它或觉得它帮到了你请考虑在Github上给它一颗[星星 ![GitHub Repo stars](https://img.shields.io/github/stars/fyears/remotely-save?style=social)](https://github.com/fyears/remotely-save)。
[![BuildCI](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml/badge.svg)](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml)
[![最新版本的下载量](https://img.shields.io/github/downloads-pre/remotely-save/remotely-save/latest/main.js?sort=semver)](https://github.com/fyears/remotely-save/releases)
## 免责声明
- **这不是 Obsidian 提供的[官方同步服务](https://obsidian.md/sync)。**
## !!!警告!!!
**在使用此插件之前,一定,一定要记得备份你的 vault。**
## 功能
- 支持:
- Amazon S3 或兼容 S3 的服务Cloudflare R2 / BackBlaze B2 / MinIO / ...
- Dropbox
- 个人版本 OneDrive应用文件夹
- 个人版本 OneDrive根目录PRO 功能)
- WebdavNextCloud / InfiniCloud / Synology webdav 服务器 / ...
- Webdis
- Google DriveGDrivePRO 功能)
- BoxPRO 功能)
- pCloudPRO 功能)
- Yandex DiskPRO 功能)
- KoofrPRO 功能)
- Azure Blob StoragePRO 功能)
- [这里](./docs/services_connectable_or_not.md)详细展示了更多可连接(或不可连接)的服务。
- **支持 Obsidian 移动版。** vault 可以通过云服务作为“中介”在移动和桌面设备之间同步。
- **支持[端到端加密](./docs/encryption/README.md)。** 如果用户指定密码,文件在发送到云之前会使用 openssl / rclone crypt 格式加密。
- **支持计划自动同步。** 你也可以使用侧边栏按钮,或者或命令面板中的命令,来手动触发同步(又或者绑定热键组合然后触发)。
- **[最小侵入性](./docs/minimal_intrusive_design.md)。**
- 通过自定义正则表达式条件**跳过大文件和路径!**
- **[同步算法](./docs/sync_algorithm/v3/intro.md)文档公开。**
- 免费版本支持 **[基本冲突检测和处理](./docs/sync_algorithm/v3/intro.md)**。PRO 版本支持 **[高级智能冲突处理](./pro/README.md)**。
- 源代码可阅。详见[许可证](./LICENSE)。
## 限制
- **云服务会产生费用。** 始终记得注意成本和定价。具体来说,所有操作,包括但不限于下载、上传、列出所有文件、调用任何 api、存储大小可能会或可能不会产生费用。
- **来自浏览器环境的一些限制。** 更多技术细节在[文档](./docs/browser_env.md)中。
- **记得保护你的 `data.json` 文件。** 该文件包含敏感信息。
- 强烈建议**不要**与任何人共享你的 `data.json` 文件。
- 通常**不要**将此文件检入版本控制。默认情况下,插件会尝试在插件目录中创建一个 `.gitignore` 文件(如果不存在),以忽略 `git` 版本控制中的 `data.json`。如果你确切知道这意味着什么并想移除设置,请修改 `.gitignore` 文件或将其设置为空。
- **Obsidian 移动版 API 在同步大文件(>= 50 MB时存在性能问题。**
- 设置“跳过大文件”选项可以帮助解决同步大文件的问题。
## 问题、建议或错误
非常欢迎你提出问题、发布任何建议或报告任何错误该项目主要在GitHub上维护
- 问题:[GitHub 仓库讨论](https://github.com/remotely-save/remotely-save/discussions)
- 建议:也在[GitHub 仓库讨论](https://github.com/remotely-save/remotely-save/discussions)
- 错误:[GitHub 仓库 Issue](https://github.com/remotely-save/remotely-save/issues)(注意这里是 bug 反馈,不是讨论)
此外,插件作者可能会偶尔访问 Obsidian 官方论坛和官方 Discord 服务器,并关注与该插件相关的信息。
## 下载和安装
- 选项 #1:在官方“社区插件列表”中搜索,或访问此链接:[https://obsidian.md/plugins?id=remotely-save](https://obsidian.md/plugins?id=remotely-save)(应该会重定向到 Obsidian app然后安装插件。
- 选项 #2:你也可以使用 [Obsidian42 - BRAT](https://github.com/TfTHacker/obsidian42-brat) 来安装此插件。在 BRAT 的配置中输入 `remotely-save/remotely-save`
- 选项 #3[![GitHub release (latest by SemVer and asset including pre-releases)](https://img.shields.io/github/downloads-pre/fyears/remotely-save/latest/main.js?sort=semver)](https://github.com/fyears/remotely-save/releases) 从最新发布中手动下载文件(`main.js``manifest.json``styles.css`)。
- 选项 #4[![BuildCI](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml/badge.svg)](https://github.com/fyears/remotely-save/actions/workflows/auto-build.yml) 每个成功的构建的“摘要”下都有构建文件。它是由每个提交自动生成的,可能不会正常工作。
## 使用方法
### S3
- 教程/示例:
- [Cloudflare R2](./docs/remote_services/s3_cloudflare_r2/README.md)
- [BackBlaze B2](./docs/remote_services/s3_backblaze_b2/README.md)
- [Storj](./docs/remote_services/s3_storj_io/README.md)
- [腾讯云 COS](./docs/remote_services/s3_tencent_cloud_cos/README.zh-cn.md) | [Tencent Cloud COS](./docs/remote_services/s3_tencent_cloud_cos/README.md)
- [MinIO](./docs/remote_services/s3_minio/README.md)
- [又拍云](./docs/remote_services/s3_upyun/README.zh-cn.md)
- 准备你的 S3兼容服务信息[端点,区域](https://docs.aws.amazon.com/general/latest/gr/s3.html)[访问密钥 ID ,密钥](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-your-credentials.html),存储桶名称。
- 如果你使用 AWS S3还要创建[策略和用户](./docs/remote_services/s3_general/s3_user_policy.md)。
- 非常旧版本的 Obsidian 需要[配置 CORS](./docs/remote_services/s3_general/s3_cors_configure.md)。
- 下载并启用此插件。
- 在插件的设置中输入你的信息。
- 如果你没有在设置中设置前缀,存储桶应该是空的,并且仅用于同步一个 vault。你可以在设置中设置前缀以便同一个存储桶可以存储多个 vault。
- 如果你想启用端到端加密,也要在设置中设置一个密码。如果你没有指定密码,文件和文件夹将以明文、原始内容同步到云。
- **每次**你想在本地和远程之间同步你的 vault 的时候,点击侧边栏上的新“圆形箭头”图标。(或者,你可以在设置面板中配置自动同步(见下一章)。)在同步过程中,图标变成“两个半圆形箭头”。除了点击侧边栏上的图标,你还可以在命令面板中激活相应的命令。
- **同步时要有耐心。** 尤其是在第一次同步时。
- 如果你想在多个设备之间同步文件,**在使用默认设置时,你的 vault 名称应该相同**。
### Dropbox
- **此插件不是官方Dropbox产品。** 插件只是使用 Dropbox 的公共API。
- 授权后,插件可以读取你的姓名和电子邮件(在 Dropbox api 上无法取消选择),并读取和写入你的 Dropbox 的 `/Apps/remotely-save` 文件夹中的文件。
- 如果你决定授权此插件连接到 Dropbox请访问插件的设置页选择Dropbox 然后按照说明操作。[更多带截图的信息在这里](./docs/dropbox_review_material/README.md)。
- 基于密码的端到端加密也是可以的。但请注意,**vault 名称本身未加密**。
- 如果你想在多个设备之间同步文件,**在使用默认设置时,你的 vault 名称应该相同**。
### 个人 OneDrive应用文件夹
- **此插件不是官方 Microsoft / OneDrive 产品。** 插件只是使用 Microsoft 的 [OneDrive 公共 API](https://docs.microsoft.com/en-us/onedrive/developer/rest-api) 而已。
- 此插件仅适用于“个人 OneDrive”不适用于“OneDrive for Business。详见 [#11](https://github.com/fyears/remotely-save/issues/11)。
- 授权后插件可以读取你的姓名和电子邮件并读取和写入你的OneDrive的 `/Apps/remotely-save` 文件夹中的文件。**Remotely Save 的免费版本仅连接到应用文件夹,而 PRO 版本可以连接到 Onedrive 的根文件夹。见下面的 PRO 部分。**
- 如果你决定授权此插件连接到 OneDrive请访问插件的设置页选择OneDrive 然后按照说明操作。
- 基于密码的端到端加密也是可以的。但请注意,**vault 名称本身未加密**。
- 如果你想在多个设备之间同步文件,**在使用默认设置时,你的 vault 名称应该相同**。
- 你可能还想查看 [OneDrive 的常见问题](./docs/remote_services/onedrive/README.md)。
### webdav
- 教程/示例:
- [Nextcloud](./docs/remote_services/webdav_nextcloud/README.md)
- [The Good Cloud](./docs/remote_services/webdav_thegoodcloud/README.md)
- [ownCloud](./docs/remote_services/webdav_owncloud/README.md)
- [InfiniCloud](./docs/remote_services/webdav_infinicloud_teracloud/README.md)
- [Synology webdav 服务器](./docs/remote_services/webdav_synology_webdav_server/README.md) | [群晖 webdav 服务器](./docs/remote_services/webdav_synology_webdav_server/README.zh-cn.md)
- [dufs](./docs/remote_services/webdav_dufs/README.md)
- [AList中文](./docs/remote_services/webdav_alist/README.zh-cn.md) | [AList (English)](./docs/remote_services/webdav_alist/README.md)
- [坚果云](./docs/remote_services/webdav_jianguoyun/README.zh-cn.md) | [JianGuoYun/NutStore](./docs/remote_services/webdav_jianguoyun/README.md)
- [Open Media Vault](./docs/remote_services/webdav_openmediavault/README.md)
- [Nginx (`ngx_http_dav_module`, `nginx-dav-ext-module`, with Docker)](./docs/remote_services/webdav_nginx/README.md)
- [Apache (with Docker)](./docs/remote_services/webdav_apache/README.md)
- [Caddy with `http.handlers.webdav` module](./docs/remote_services/webdav_caddy/README.md)
- 非常旧版本的Obsidian需要[配置 CORS](./docs/remote_services/webdav_general/webav_cors.md)。
- 你的数据会同步到你的webdav服务器上的 `${vaultName}` 子文件夹。
- 基于密码的端到端加密也是可以的。但请注意,**vault 名称本身未加密**。
- 如果你想在多个设备之间同步文件,**在使用默认设置时,你的 vault 名称应该相同**。
### Webdis
- 教程:
- [Webdis](./docs/remote_services/webdis/README.md)
- 实验性质。
- 你必须自己设置和保护你的 web 服务器。
### Onedrive完整访问PRO 功能)
PRO付费功能“与 Onedrive完整同步”允许用户与 Onedrive 根文件夹进行同步。教程和限制在[这里](./docs/remote_services/onedrivefull/README.md)。
### Google DriveGDrivePRO 功能)
PRO付费功能“与 Google Drive 同步”允许用户与 Google Drive 进行同步。教程和限制在[这里](./docs/remote_services/googledrive/README.md)。
### BoxPRO 功能)
PRO付费功能“与 Box 同步”允许用户与 Box 同步。教程和限制在[这里](./docs/remote_services/box/README.md)。
### pCloudPRO 功能)
PRO付费功能“与 pCloud 同步”允许用户与 pCloud 同步(使用其原生 API 而不是 webdav。教程和限制在[这里](./docs/remote_services/pcloud/README.md)。
### Yandex DiskPRO 功能)
PRO付费功能“与 Yandex Disk 同步”允许用户与 Yandex Disk 同步(使用其原生 API 而不是 webdav。教程和限制在[这里](./docs/remote_services/yandexdisk/README.md)。
### KoofrPRO 功能)
PRO付费功能“与 Koofr 同步”允许用户与 Koofr 同步(使用其原生 API 而不是 webdav。教程和限制在[这里](./docs/remote_services/koofr/README.md)。
### Azure Blob StoragePRO 功能)
PRO付费功能“与 Azure Blob Storage 同步”允许用户与 Azure Blob Storage 同步。教程和限制在[这里](./docs/remote_services/azureblobstorage/README.md)。
## 智能冲突PRO功能
基本(免费)版本可以检测冲突,但用户必须选择保留较新版本或较大版本的文件两种选项之一。
PRO付费功能“智能冲突”为用户提供了另一个选项合并小的 markdown 文件,或复制大的 markdown 文件或任何大小的非 markdown 文件。
文档见[这里](./docs/pro/README.md)。
## 定时自动同步
- 你可以在设置中配置每 N 分钟自动同步。
- 在自动同步模式下,如果发生任何错误,插件会**静默失败**。
- 自动同步仅在 Obsidian 打开时有效。由于插件仅在 Obsidian 提供的浏览器环境中工作,因此**技术上不可能**在 Obsidian 后台自动同步。
## 保存时同步
- 你可以在设置中配置保存时同步。
- 在保存时同步模式下,如果发生任何错误,插件会**静默失败**。
## 配置文件夹/文件和书签
默认情况下,插件不同步 obsidian 的配置文件夹/文件(通常是 `.obsidian` 文件夹),因为它是隐藏文件之一。
然而,在最新版本中,你可以在设置中启用同步配置文件夹。请注意,这是一个实验性功能。特别是一些配置文件的修改时间每次 Obsidian 打开时都会改变,这破坏了插件的假设,因此某些信息可能无法正确同步。
此外Obsidian的书签实际上存储在 `.obsidian/bookmarks.json` 文件中的。你也可以在设置中设置同步这个文件(而不是整个配置文件夹)。插件将保持跨设备最新修改的文件。
## 隐藏文件或文件夹
**默认情况下,所有以 `.`(点)或 `_`(下划线)开头的文件或文件夹都被视为隐藏文件,不会被同步。** 如果你有一些文件只是本地保留,这很有用。但这种策略也意味着主题/其他插件/此插件的设置也不会被同步。
在最新版本中,你可以更改设置以允许同步 `_` 文件或文件夹,以及如上所述的 `.obsidian` 特殊配置文件夹(但不包括其他任何 `.` 文件或文件夹)。
## PRO付费功能
详见[PRO](./docs/pro/README.md)了解更多详情。
## 如何调试debug
如发生错误,查看[这里文档](./docs/how_to_debug/README.md)了解调试方式。
如果没有发生错误,但是运行起来很慢,你需要[开启“性能收集”](./docs/check_performance/README)来看看有没有哪一步特别慢。
## 额外功能:通过 QR 码导入和导出非 OAuth2 插件设置
详见[这里](./docs/import_export_some_settings.md)了解更多详情。
## 下载历史
下载历史可以从非官方的 [Obsidian Stats](https://www.moritzjung.dev/obsidian-stats/plugins/remotely-save/#downloads) 查阅。(和官方 ObsidianGitHubRemotely Save 均无利益关系。)
## 星星历史
(和官方 ObsidianGitHubRemotely Save 均无利益关系。)
[![星星历史 曲线图](https://api.star-history.com/svg?repos=remotely-save/remotely-save&type=Date)](https://star-history.com/#remotely-save/remotely-save&Date)

View File

@ -1,5 +1,5 @@
{ {
"$schema": "https://biomejs.dev/schemas/1.7.3/schema.json", "$schema": "https://biomejs.dev/schemas/1.8.3/schema.json",
"organizeImports": { "organizeImports": {
"enabled": true "enabled": true
}, },
@ -24,7 +24,7 @@
"jsxQuoteStyle": "double", "jsxQuoteStyle": "double",
"quoteProperties": "asNeeded", "quoteProperties": "asNeeded",
"semicolons": "always", "semicolons": "always",
"trailingComma": "es5" "trailingCommas": "es5"
} }
}, },
"linter": { "linter": {

View File

@ -0,0 +1,13 @@
# Check performance
1. Go to settings, scroll to the very end, and enable the "Enable Profiler" option.
2. Also enable "Enable Profiler Printing".
3. Check Console Output (directly or via `vConsole` plugin). More details are [here](../how_to_debug/README.md).
4. Sync!
5. You can also "Export Profiler Results" afterwards. A new file `_debug_remotely_save/profiler_results_exported_on_xxxx.md` will be generated.
In the console or exported files, you can see the time cost of each steps.
![profiler settings](./profiler_settings.png)
![profiler exported](./profiler_exported.png)

View File

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:5a71d0746a75c93aa4cb5be3f7964bfdf74722a10505f5a1965790738eaebdc4
size 265289

View File

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4ffd1557c2f714c56bfacd8166b85749d6bfa15c2f9c7363942b443d51288083
size 81259

View File

@ -42,5 +42,5 @@ filename_encoding = base64 # don't forget this!!!
You can use the `mount` command to view and see the files in file explorer! On Windows, the command should like this (the remote vault is mounted to drive `X:`): You can use the `mount` command to view and see the files in file explorer! On Windows, the command should like this (the remote vault is mounted to drive `X:`):
```bash ```bash
rclone mount webdav1crypt: X: --network-mode rclone mount webdav1crypt: X: --network-mode --vfs-cache-mode writes
``` ```

View File

@ -6,12 +6,18 @@ Ideally, users do not need to debug anything. But if something bad happened, we
See [here](./export_sync_plans.md). See [here](./export_sync_plans.md).
## Advanced: Check Console Output Directly ## Medium: Desktop: Check Console Output Directly
...of desktop and Android. ...of desktop and Android.
See [here](./check_console_output.md). See [here](./check_console_output.md).
## Medium: Mobile: Use `Obsidian vConsole` to Check Console Ouput Directly
...of mobile (iOS and Android).
See [here](./check_vconsole_output.md).
## Advanced: Use `Logstravaganza` to export logs ## Advanced: Use `Logstravaganza` to export logs
This method works for desktop and mobile devices (iOS, Android), especially useful for iOS. This method works for desktop and mobile devices (iOS, Android), especially useful for iOS.

View File

@ -18,6 +18,8 @@ Go to the plugin settings, scroll down to the section "Debug" -> "alter console
- If you are using Android - If you are using Android
You need to [enable USB debugging](https://developer.android.com/studio/debug/dev-options#enable) on your Android, then connect your Android to a computer using USB, then open the **desktop** Chrome browser and go to the special web page <chrome://inspect>. You shall be able to see the "inspect" link inside the special page, then click the link to open the console. After debugging, remember to turn off USB debugging. If you want to check the console **with the help of desktop Chrome**, you need to [enable USB debugging](https://developer.android.com/studio/debug/dev-options#enable) on your Android, then connect your Android to a computer using USB, then open the **desktop** Chrome browser and go to the special web page <chrome://inspect>. You shall be able to see the "inspect" link inside the special page, then click the link to open the console. After debugging, remember to turn off USB debugging.
If you want to check the console **directly on the mobile device**, check out [this doc](./check_vconsole_output.md).
Trigger the sync manually (by clicking the icon on the ribbon sidebar). Something (hopefully) helpful should show up in the console. You could understand what happened and what goes wrong more explictly by checking the output. Trigger the sync manually (by clicking the icon on the ribbon sidebar). Something (hopefully) helpful should show up in the console. You could understand what happened and what goes wrong more explictly by checking the output.

View File

@ -0,0 +1,21 @@
# Check "Obsidian vConsole" Output
It's quite hard to debug on mobile. But fortunately you can use another plugin to rescue!
This applies to both iOS (iPhone / iPad) and Android.
## Disable Auto Sync Firstly
You should disable auto sync to avoid any unexpected running.
## Set The Output Level To Debug
Go to the plugin settings, scroll down to the section "Debug" -> "alter console log level", and change it from "info" to "debug".
## Use "Obsidian vConsole"
1. Install the third-party plugin ["Obsidian vConsole"](https://github.com/zhouhua/obsidian-vconsole).
2. Enable "Obsidian vConsole". You shall see a green button in the right buttom corner of the interface of your mobile Obsidian. You can drag this green button to where you like.
3. Sync! And quickly click the vConsole green button, you will see the console logs in its panel! Moreover, you can check browser network and Storage (LocalStorage) in the panel!
4. You can copy (by clicking the small "disk" icon beside each line of the log) or take a screenshot of the logs, and report bugs in Remotely Save GitHub. You can click "Hide" in the panel to hide the panel.
5. If you don't need to debug any more, you can disable Obsidian vConsole plugin, then the green button should disappear.

View File

@ -1,7 +1,7 @@
# OneDrive # OneDrive (App Folder)
- **This plugin is NOT an official Microsoft / OneDrive product.** The plugin just uses Microsoft's [OneDrive's public API](https://docs.microsoft.com/en-us/onedrive/developer/rest-api). - **This plugin is NOT an official Microsoft / OneDrive product.** The plugin just uses Microsoft's [OneDrive's public API](https://docs.microsoft.com/en-us/onedrive/developer/rest-api).
- After the authorization, the plugin can read your name and email, and read and write files in your OneDrive's `/Apps/remotely-save` folder. - After the authorization, the plugin can read your name and email, and read and write files in your OneDrive's `/Apps/remotely-save` folder.**The free version of Remotely Save only connects to App Folder, while the PRO version can connect to the root folder in Onedrive.**
- If you decide to authorize this plugin to connect to OneDrive, please go to plugin's settings, and choose OneDrive then follow the instructions. - If you decide to authorize this plugin to connect to OneDrive, please go to plugin's settings, and choose OneDrive then follow the instructions.
- Password-based end-to-end encryption is also supported. But please be aware that **the vault name itself is not encrypted**. - Password-based end-to-end encryption is also supported. But please be aware that **the vault name itself is not encrypted**.
- If you want to sync the files across multiple devices, **your vault name should be the same** while using default settings. - If you want to sync the files across multiple devices, **your vault name should be the same** while using default settings.
@ -21,3 +21,11 @@ The solution is simple:
1. Backup your vault manually. 1. Backup your vault manually.
2. Go to onedrive website (<https://onedrive.live.com/>), and rename `/Application/Graph` to `/Application/remotely-save` (right click on the folder and you will see rename option) 2. Go to onedrive website (<https://onedrive.live.com/>), and rename `/Application/Graph` to `/Application/remotely-save` (right click on the folder and you will see rename option)
3. Come back to Obsidian and try to sync! 3. Come back to Obsidian and try to sync!
### Empty file is not uploaded
Onedrive's API does not allow uploading empty files. You can choose to skip them or raise errors in Remotely Save plugin's settings.
### How to connect to root folder rather than the App Folder?
As of June 2024, this is a new PRO feature. See the [doc](../onedrivefull/README.md).

View File

@ -0,0 +1,42 @@
# Onedrive (Full) (PRO)
# Intro
* It's a PRO feature of Remotely Save plugin.
* **This plugin is NOT an official Microsoft / Onedrive product, and just uses Onedrive's public api.**
* This still only applies to Onedrive for personal. The dev team doesn't have Onedrive for business account to develop and test on it.
# Steps
## Steps of Remotely Save subscription
1. Please sign up and sign in an online account, connect your plugin to your online account firstly. See [the PRO tutorial](../../pro/README.md) firstly.
2. Subscribe to "sync with Onedrive (Full)" feature online.
3. Go back to your Remotely Save plugin inside Obsidian, click "Check again" button in PRO settings. So that the plugin knows some features are enabled. In this case, sync with Onedrive (Full) should be detected.
## Steps of Connecting to your Onedrive
After you enabled the PRO feature in your Remotely Save plugin, you can connect to your Onedrive account now.
1. In Remotely Save settings, change your sync service to Onedrive (Full).
2. Click Auth, visit the link, go to Onedrive website to start.
3. Follow the instruction on Onedrive, and allow Remotely Save to connect.
4. You will be redirected back to Remotely Save plugin.
5. A notice will tell you that you've connected or not.
6. Sync! The plugin will create a vault folder **in the root** of your Onedrive and upload notes into that folder.
7. **Read the caveats below.**
# The caveats
* As of June 2024, this feature is in beta stage.
* **Back up your vault before using this feature.**
* **Back up everything in your Onedrive (besides the sync sub folder) before using this feature!**
* Onedrive's API does not allow uploading empty files. You can choose to skip them or raise errors in Remotely Save plugin's settings.
# What's the difference of Onedrive (App Folder) and Onedrive (Full)?
Due to history reasons, Remotely Save only supported uploading to App Folder back to year 2021. Because that greatly ensured the security and ensure not messing up with others files.
However, repeatedly some users want to sync to arbitrary root folder rather than `/Apps/remotely-save/` folder. Thus as of June 2024, the new PRO feature is finally developed.
As of June 2024, connecting to Onedrive (App Folder) is free, but connecting to Onedrive (Full) is a PRO feature.

View File

@ -0,0 +1,33 @@
# Caddy with `http.handlers.webdav` module
> modified from the instruction from @cyruz-git in https://github.com/remotely-save/remotely-save/issues/825
## Link
<https://caddyserver.com/download?package=github.com%2Fmholt%2Fcaddy-webdav>
## Steps
1. Download caddy with webdav module from <https://caddyserver.com/download?package=github.com%2Fmholt%2Fcaddy-webdav>. Or you can install Caddy then install the plugins.
2. Create a folder for storing webdav server files. Like `/usr/local/mywebdav`.
3. Create a `Caddyfile` (yeah the file name itself is `Caddyfile`.) like this:
```caddy
:8080 {
route /dav/* {
root /usr/local/mywebdav
basicauth {
# Username "Bob", password "hiccup"
Bob $2a$14$Zkx19XLiW6VYouLHR5NmfOFU0z2GTNmpkT/5qqR7hx4IjWJPDhjvG
}
uri strip_prefix /dav
webdav
}
}
```
The password hash is generated like [this](https://caddyserver.com/docs/caddyfile/directives/basic_auth).
4. In Remotely Save, setup:
* address `http://localhost:8080/dav/`
* username `Bob`
* password `hiccup`
* auth type: `basic`
5. Check the connection and sync!

View File

@ -0,0 +1,17 @@
# dufs webdav
## Link
<https://github.com/sigoden/dufs>
## Steps
1. Download the latest version: <https://github.com/sigoden/dufs/releases> and save it to a folder
2. Add the path environment variable.
3. Start the server in terminal, you can change the address (`127.0.0.1`) and username (`user1`) and password (`pass1`) accordingly:
```bash
dufs -A --enable-cors --bind 127.0.0.1 --port 8080 --auth user1:pass1@/:rw
```
4. In remotely-save setting page, select webdav type, then input the address/account/**webdav password**(not your account password).
5. In remotely-save setting page, click "Check Connectivity".
6. Sync!

View File

@ -1,7 +1,7 @@
{ {
"id": "remotely-save", "id": "remotely-save",
"name": "Remotely Save", "name": "Remotely Save",
"version": "0.5.10", "version": "0.5.25",
"minAppVersion": "0.13.21", "minAppVersion": "0.13.21",
"description": "Yet another unofficial plugin allowing users to synchronize notes between local device and the cloud service.", "description": "Yet another unofficial plugin allowing users to synchronize notes between local device and the cloud service.",
"author": "fyears", "author": "fyears",

View File

@ -1,7 +1,7 @@
{ {
"id": "remotely-save", "id": "remotely-save",
"name": "Remotely Save", "name": "Remotely Save",
"version": "0.5.10", "version": "0.5.25",
"minAppVersion": "0.13.21", "minAppVersion": "0.13.21",
"description": "Yet another unofficial plugin allowing users to synchronize notes between local device and the cloud service.", "description": "Yet another unofficial plugin allowing users to synchronize notes between local device and the cloud service.",
"author": "fyears", "author": "fyears",

View File

@ -1,15 +1,15 @@
{ {
"name": "remotely-save", "name": "remotely-save",
"version": "0.5.10", "version": "0.5.25",
"description": "This is yet another sync plugin for Obsidian app.", "description": "This is yet another sync plugin for Obsidian app.",
"scripts": { "scripts": {
"dev2": "node esbuild.config.mjs --watch", "dev2": "node esbuild.config.mjs --watch",
"build2": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "build2": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"build": "webpack --mode production", "build": "webpack --mode production",
"dev": "webpack --mode development --watch", "dev": "webpack --mode development --watch",
"format": "npx @biomejs/biome check --apply .", "format": "npx @biomejs/biome check --write .",
"clean": "npx rimraf main.js", "clean": "npx rimraf main.js",
"test": "cross-env TS_NODE_COMPILER_OPTIONS={\\\"module\\\":\\\"commonjs\\\"} mocha -r ts-node/register 'tests/**/*.ts' 'pro/tests/**/*.ts'" "test": "mocha --import=tsx 'tests/**/*.ts' 'pro/tests/**/*.ts'"
}, },
"browser": { "browser": {
"path": "path-browserify", "path": "path-browserify",
@ -25,55 +25,55 @@
"author": "", "author": "",
"license": "SEE LICENSE IN LICENSE", "license": "SEE LICENSE IN LICENSE",
"devDependencies": { "devDependencies": {
"@biomejs/biome": "1.7.3", "@biomejs/biome": "1.8.3",
"@microsoft/microsoft-graph-types": "^2.40.0", "@microsoft/microsoft-graph-types": "^2.40.0",
"@types/chai": "^4.3.14", "@types/chai": "^4.3.16",
"@types/chai-as-promised": "^7.1.8", "@types/chai-as-promised": "^7.1.8",
"@types/jsdom": "^21.1.6", "@types/jsdom": "^21.1.7",
"@types/lodash": "^4.17.0", "@types/lodash": "^4.17.7",
"@types/mime-types": "^2.1.4", "@types/mime-types": "^2.1.4",
"@types/mocha": "^10.0.6", "@types/mocha": "^10.0.7",
"@types/mustache": "^4.2.5", "@types/mustache": "^4.2.5",
"@types/node": "^20.12.7", "@types/node": "^20.14.12",
"@types/qrcode": "^1.5.5", "@types/qrcode": "^1.5.5",
"builtin-modules": "^3.3.0", "builtin-modules": "^4.0.0",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"esbuild": "^0.20.2", "esbuild": "^0.23.0",
"esbuild-plugin-inline-worker": "^0.1.1", "esbuild-plugin-inline-worker": "^0.1.1",
"jsdom": "^24.0.0", "jsdom": "^24.1.1",
"mocha": "^10.4.0", "mocha": "^10.7.0",
"npm-check-updates": "^16.14.20", "npm-check-updates": "^16.14.20",
"obsidian": "^1.5.7", "obsidian": "^1.5.7",
"openapi-typescript": "^7.0.0-rc.0", "openapi-typescript": "^7.1.0",
"ts-loader": "^9.5.1", "ts-loader": "^9.5.1",
"ts-node": "^10.9.2", "tslib": "^2.6.3",
"tslib": "^2.6.2", "tsx": "^4.16.2",
"typescript": "^5.4.5", "typescript": "^5.5.4",
"webdav-server": "^2.6.2", "webdav-server": "^2.6.2",
"webpack": "^5.91.0", "webpack": "^5.93.0",
"webpack-cli": "^5.1.4", "webpack-cli": "^5.1.4",
"worker-loader": "^3.0.8" "worker-loader": "^3.0.8"
}, },
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "^3.563.0", "@aws-sdk/client-s3": "^3.620.0",
"@aws-sdk/lib-storage": "^3.563.0", "@aws-sdk/lib-storage": "^3.620.0",
"@aws-sdk/signature-v4-crt": "^3.556.0", "@aws-sdk/signature-v4-crt": "^3.620.0",
"@aws-sdk/types": "^3.535.0", "@aws-sdk/types": "^3.609.0",
"@azure/msal-node": "^2.7.0", "@azure/msal-node": "^2.12.0",
"@azure/storage-blob": "^12.23.0", "@azure/storage-blob": "^12.24.0",
"@fyears/rclone-crypt": "^0.0.7", "@fyears/rclone-crypt": "^0.0.7",
"@fyears/tsqueue": "^1.0.1", "@fyears/tsqueue": "^1.0.1",
"@microsoft/microsoft-graph-client": "^3.0.7", "@microsoft/microsoft-graph-client": "^3.0.7",
"@sanity/diff-match-patch": "^3.1.1", "@sanity/diff-match-patch": "^3.1.1",
"@smithy/fetch-http-handler": "^2.5.0", "@smithy/fetch-http-handler": "^3.2.4",
"@smithy/protocol-http": "^3.3.0", "@smithy/protocol-http": "^4.1.0",
"@smithy/querystring-builder": "^2.2.0", "@smithy/querystring-builder": "^3.0.3",
"acorn": "^8.11.3", "acorn": "^8.12.1",
"aggregate-error": "^5.0.0", "aggregate-error": "^5.0.0",
"assert": "^2.1.0", "assert": "^2.1.0",
"aws-crt": "^1.21.2", "aws-crt": "^1.21.3",
"box-typescript-sdk-gen": "^1.0.0", "box-typescript-sdk-gen": "^1.3.0",
"buffer": "^6.0.3", "buffer": "^6.0.3",
"crypto-browserify": "^3.12.0", "crypto-browserify": "^3.12.0",
"dropbox": "^10.34.0", "dropbox": "^10.34.0",
@ -83,21 +83,21 @@
"localforage-getitems": "^1.4.2", "localforage-getitems": "^1.4.2",
"localforage-removeitems": "^1.4.0", "localforage-removeitems": "^1.4.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"lucide": "^0.376.1", "lucide": "^0.416.0",
"mime-types": "^2.1.35", "mime-types": "^2.1.35",
"mustache": "^4.2.0", "mustache": "^4.2.0",
"nanoid": "^5.0.7", "nanoid": "^5.0.7",
"node-diff3": "^3.1.2", "node-diff3": "^3.1.2",
"openapi-fetch": "^0.9.7", "openapi-fetch": "^0.10.2",
"p-queue": "^8.0.1", "p-queue": "^8.0.1",
"path-browserify": "^1.0.1", "path-browserify": "^1.0.1",
"pcloud-sdk-js": "^2.0.0", "pcloud-sdk-js": "^2.0.0",
"process": "^0.11.10", "process": "^0.11.10",
"qrcode": "^1.5.3", "qrcode": "^1.5.3",
"rfc4648": "^1.5.3", "rfc4648": "^1.5.3",
"rimraf": "^5.0.5", "rimraf": "^6.0.1",
"stream-browserify": "^3.0.0", "stream-browserify": "^3.0.0",
"url": "^0.11.3", "url": "^0.11.4",
"util": "^0.12.5", "util": "^0.12.5",
"webdav": "^5.6.0", "webdav": "^5.6.0",
"xregexp": "^5.1.1" "xregexp": "^5.1.1"

View File

@ -112,7 +112,9 @@ export const setConfigBySuccessfullAuthInplace = async (
saveUpdatedConfigFunc: () => Promise<any> | undefined saveUpdatedConfigFunc: () => Promise<any> | undefined
) => { ) => {
if (authRes.error !== undefined) { if (authRes.error !== undefined) {
throw Error(`you should not save the setting for ${authRes.error}`); throw Error(
`remotely save account auth failed, please auth again: ${authRes.error}`
);
} }
config.accessToken = authRes.access_token; config.accessToken = authRes.access_token;
@ -278,6 +280,11 @@ export const checkProRunnableAndFixInplace = async (
service: "googledrive", service: "googledrive",
name: "Google Drive", name: "Google Drive",
}, },
{
feature: "feature-onedrive_full",
service: "onedrivefull",
name: "Onedrive (Full)",
},
{ feature: "feature-box", service: "box", name: "Box" }, { feature: "feature-box", service: "box", name: "Box" },
{ feature: "feature-pcloud", service: "pcloud", name: "pCloud" }, { feature: "feature-pcloud", service: "pcloud", name: "pCloud" },
{ {

View File

@ -27,6 +27,7 @@ export const PRO_WEBSITE = global.DEFAULT_REMOTELYSAVE_WEBSITE;
export type PRO_FEATURE_TYPE = export type PRO_FEATURE_TYPE =
| "feature-smart_conflict" | "feature-smart_conflict"
| "feature-onedrive_full"
| "feature-google_drive" | "feature-google_drive"
| "feature-box" | "feature-box"
| "feature-pcloud" | "feature-pcloud"
@ -167,3 +168,24 @@ export interface AzureBlobStorageConfig {
partsConcurrency: number; partsConcurrency: number;
kind: "azureblobstorage"; kind: "azureblobstorage";
} }
///////////////////////////////////////////////////////////
// Onedrive (Full)
//////////////////////////////////////////////////////////
export const COMMAND_CALLBACK_ONEDRIVEFULL = "remotely-save-cb-onedrivefull";
export interface OnedriveFullConfig {
accessToken: string;
clientID: string;
authority: string;
refreshToken: string;
accessTokenExpiresInSeconds: number;
accessTokenExpiresAtTime: number;
deltaLink: string;
username: string;
credentialsShouldBeDeletedAtTime?: number;
remoteBaseDir?: string;
emptyFile: "skip" | "error";
kind: "onedrivefull";
}

34
pro/src/clearDupFiles.ts Normal file
View File

@ -0,0 +1,34 @@
import type { FakeFsLocal } from "../../src/fsLocal";
import { getFileRenameForDup } from "./conflictLogic";
export const getDupFiles = async (fsLocal: FakeFsLocal) => {
const allFilesAndFolders = await fsLocal.walk();
allFilesAndFolders.sort((a, b) => -(a.keyRaw.length - b.keyRaw.length)); // descending
const filenameSet: Set<string> = new Set();
const filesToBeRemoved: Set<string> = new Set();
for (const { keyRaw } of allFilesAndFolders) {
if (keyRaw.endsWith("/")) {
continue;
}
if (keyRaw.includes("dup")) {
filenameSet.add(keyRaw);
}
const dup = getFileRenameForDup(keyRaw);
if (filenameSet.has(dup)) {
filesToBeRemoved.add(dup);
}
}
return [...filesToBeRemoved];
};
export const clearDupFiles = async (
filesToBeRemoved: string[],
fsLocal: FakeFsLocal
) => {
await Promise.all(filesToBeRemoved.map(async (f) => await fsLocal.rm(f)));
};

View File

@ -20,14 +20,14 @@ import type { FakeFs } from "../../src/fsAll";
import { MERGABLE_SIZE } from "./baseTypesPro"; import { MERGABLE_SIZE } from "./baseTypesPro";
export function isMergable(a: Entity, b?: Entity) { export function isMergable(a: Entity, b?: Entity) {
if (b !== undefined && a.keyRaw !== b.keyRaw) { if (b !== undefined && a.key !== b.key) {
return false; return false;
} }
return ( return (
!a.keyRaw.endsWith("/") && !a.key!.endsWith("/") &&
a.sizeRaw <= MERGABLE_SIZE && a.sizeRaw <= MERGABLE_SIZE &&
(a.keyRaw.endsWith(".md") || a.keyRaw.endsWith(".markdown")) (a.key!.endsWith(".md") || a.key!.endsWith(".markdown"))
); );
} }
@ -38,9 +38,11 @@ export function isMergable(a: Entity, b?: Entity) {
* @param b * @param b
*/ */
function mergeDigInModified(a: string, o: string, b: string) { function mergeDigInModified(a: string, o: string, b: string) {
const { conflict, result } = mergeDigIn(a, o, b); const { conflict, result } = mergeDigIn(a, o, b, {
stringSeparator: /\n/,
});
for (let index = 0; index < result.length; ++index) { for (let index = 0; index < result.length; ++index) {
if (["<<<<<<<", "=======", ">>>>>>>"].contains(result[index])) { if (["<<<<<<<", "=======", ">>>>>>>"].includes(result[index])) {
result[index] = "`" + result[index] + "`"; result[index] = "`" + result[index] + "`";
} }
} }
@ -72,11 +74,26 @@ function getLCSText(a: string, b: string) {
* @param b * @param b
* @returns * @returns
*/ */
function twoWayMerge(a: string, b: string): string { export function twoWayMerge(a: string, b: string): string {
const aa = a.trim();
const bb = b.trim();
if (aa === "" && bb === "") {
return aa.length >= bb.length ? a : b;
}
if (bb === "") {
return a;
}
if (aa === "") {
return b;
}
// const c = getLCSText(a, b); // const c = getLCSText(a, b);
// const patches = makePatches(c, a); // const patches = makePatches(c, a);
// const [d] = applyPatches(patches, b); // const [d] = applyPatches(patches, b);
const c = getLCSText(a, b); const c = getLCSText(a, b); //.trim();
// console.debug(`(start) LCS Text:`);
// console.debug(c);
// console.debug(`(end) LCS Text.`);
const d = mergeDigInModified(a, c, b).result.join("\n"); const d = mergeDigInModified(a, c, b).result.join("\n");
return d; return d;
} }
@ -88,7 +105,7 @@ function twoWayMerge(a: string, b: string): string {
* @param orig * @param orig
* @returns * @returns
*/ */
function threeWayMerge(a: string, b: string, orig: string) { export function threeWayMerge(a: string, b: string, orig: string) {
return mergeDigInModified(a, orig, b).result.join("\n"); return mergeDigInModified(a, orig, b).result.join("\n");
} }
@ -150,7 +167,7 @@ export async function mergeFile(
key, key,
newArrayBuffer, newArrayBuffer,
rightEntity.mtimeCli ?? mtime, rightEntity.mtimeCli ?? mtime,
rightEntity.mtimeCli ?? mtime rightEntity.ctimeCli ?? rightEntity.mtimeCli ?? mtime
); );
return { return {
@ -159,7 +176,7 @@ export async function mergeFile(
}; };
} }
export function getFileRename(key: string) { export function getFileRenameForDup(key: string) {
if ( if (
key === "" || key === "" ||
key === "." || key === "." ||
@ -200,41 +217,108 @@ export function getFileRename(key: string) {
return res; return res;
} }
function arraysAreEqual(arr1: ArrayBuffer, arr2: ArrayBuffer) {
if (arr1.byteLength !== arr2.byteLength) {
return false;
}
const u1 = new Uint8Array(arr1);
const u2 = new Uint8Array(arr2);
for (let i = 0; i < u1.byteLength; ++i) {
if (u1[i] !== u2[i]) {
return false;
}
}
return true;
}
/**
* 1. download remote
* 2. compare
* 3. if the same, update local but not upload
* 4. if not the same, rename local and save remote
*/
async function tryDuplicateFileForSameSizes(
key: string,
key2: string,
fsLocal: FakeFs,
fsRemote: FakeFs,
uploadCallback: (entity: Entity | undefined) => Promise<any>,
downloadCallback: (entity: Entity | undefined) => Promise<any>
) {
console.debug(`tryDuplicateFileForSameSizes: ${key}`);
// 1. download
const remoteContent = await fsRemote.readFile(key);
// 2. compare
const localContent = await fsLocal.readFile(key);
const eq = arraysAreEqual(localContent, remoteContent);
if (eq) {
// 3. if the same, update local but not upload
// read meta of remote, as if we have downloaded the file
console.debug(`tryDuplicateFileForSameSizes: ${key} content equal`);
const entityRemote = await fsRemote.stat(key);
// write
const downloadResultEntity = await fsLocal.writeFile(
key,
remoteContent,
entityRemote.mtimeCli ?? Date.now(),
entityRemote.mtimeCli ?? Date.now()
);
await downloadCallback(downloadResultEntity);
// no uploadCallback here
} else {
// 4. if not the same, rename local and save remote
console.debug(`tryDuplicateFileForSameSizes: ${key} content not equal`);
await fsLocal.rename(key, key2);
const entityRemote = await fsRemote.stat(key);
const downloadResultEntity = await fsLocal.writeFile(
key,
remoteContent,
entityRemote.mtimeCli ?? Date.now(),
entityRemote.mtimeCli ?? Date.now()
);
await downloadCallback(downloadResultEntity);
const entityLocal = await fsLocal.stat(key2); // key2 here!
const uploadResultEntity = await fsRemote.writeFile(
key2, // key2 here!
localContent,
entityLocal.mtimeCli ?? Date.now(),
entityLocal.mtimeCli ?? Date.now()
);
await uploadCallback(uploadResultEntity);
}
}
/** /**
* local: x.md -> x.dup.md -> upload to remote * local: x.md -> x.dup.md -> upload to remote
* remote: x.md -> download to local -> using original name x.md * remote: x.md -> download to local -> using original name x.md
*/ */
export async function duplicateFile( async function tryDuplicateFileForDiffSizes(
key: string, key: string,
left: FakeFs, key2: string,
right: FakeFs, fsLocal: FakeFs,
uploadCallback: (entity: Entity) => Promise<any>, fsRemote: FakeFs,
downloadCallback: (entity: Entity) => Promise<any> uploadCallback: (entity: Entity | undefined) => Promise<any>,
downloadCallback: (entity: Entity | undefined) => Promise<any>
) { ) {
let key2 = getFileRename(key); console.debug(`tryDuplicateFileForDiffSizes: ${key}`);
let usable = false;
do { await fsLocal.rename(key, key2);
try {
const s = await left.stat(key2);
if (s === null || s === undefined) {
throw Error(`not exist $${key2}`);
}
console.debug(`key2=${key2} exists, cannot use for new file`);
key2 = getFileRename(key2);
console.debug(`key2=${key2} is prepared for next try`);
} catch (e) {
// not exists, exactly what we want
console.debug(`key2=${key2} doesn't exist, usable for new file`);
usable = true;
}
} while (!usable);
await left.rename(key, key2);
/** /**
* x.dup.md -> upload to remote * x.dup.md -> upload to remote
*/ */
async function f1() { async function f1() {
const k = await copyFile(key2, left, right); const k = await copyFile(key2, fsLocal, fsRemote);
await uploadCallback(k.entity); await uploadCallback(k.entity);
return k.entity; return k.entity;
} }
@ -243,7 +327,7 @@ export async function duplicateFile(
* x.md -> download to local * x.md -> download to local
*/ */
async function f2() { async function f2() {
const k = await copyFile(key, right, left); const k = await copyFile(key, fsRemote, fsLocal);
await downloadCallback(k.entity); await downloadCallback(k.entity);
return k.entity; return k.entity;
} }
@ -255,3 +339,56 @@ export async function duplicateFile(
download: resDownload, download: resDownload,
}; };
} }
export async function tryDuplicateFile(
key: string,
fsLocal: FakeFs,
fsRemote: FakeFs,
uploadCallback: (entity: Entity | undefined) => Promise<any>,
downloadCallback: (entity: Entity | undefined) => Promise<any>
) {
let key2 = getFileRenameForDup(key);
let usable = false;
do {
try {
const s = await fsLocal.stat(key2);
if (s === null || s === undefined) {
throw Error(`not exist $${key2}`);
}
console.debug(`key2=${key2} exists, cannot use for new file`);
key2 = getFileRenameForDup(key2);
console.debug(`key2=${key2} is prepared for next try`);
} catch (e) {
// not exists, exactly what we want
console.debug(`key2=${key2} doesn't exist, usable for new file`);
usable = true;
}
} while (!usable);
const localSize = await fsLocal.stat(key);
const remoteSize = await fsRemote.stat(key);
if (
localSize !== undefined &&
remoteSize !== undefined &&
localSize.sizeRaw === remoteSize.sizeRaw
) {
return await tryDuplicateFileForSameSizes(
key,
key2,
fsLocal,
fsRemote,
uploadCallback,
downloadCallback
);
} else {
return await tryDuplicateFileForDiffSizes(
key,
key2,
fsLocal,
fsRemote,
uploadCallback,
downloadCallback
);
}
}

View File

@ -320,12 +320,12 @@ export class FakeFsAzureBlobStorage extends FakeFs {
// if we can walk, we can connect // if we can walk, we can connect
try { try {
await this.walkPartial(); await this.walkPartial();
return true;
} catch (err) { } catch (err) {
console.debug(err); console.debug(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {

View File

@ -112,7 +112,7 @@ export const setConfigBySuccessfullAuthInplace = async (
) => { ) => {
if (authRes.access_token === undefined || authRes.access_token === "") { if (authRes.access_token === undefined || authRes.access_token === "") {
throw Error( throw Error(
`you should not save the setting for ${JSON.stringify(authRes)}` `remotely save account auth failed, please auth again: ${JSON.stringify(authRes)}`
); );
} }
@ -892,12 +892,12 @@ export class FakeFsBox extends FakeFs {
// if we can init, we can connect // if we can init, we can connect
try { try {
await this._init(); await this._init();
return true;
} catch (err) { } catch (err) {
console.debug(err); console.debug(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {
throw new Error("Method not implemented."); throw new Error("Method not implemented.");

View File

@ -728,12 +728,12 @@ export class FakeFsGoogleDrive extends FakeFs {
// if we can init, we can connect // if we can init, we can connect
try { try {
await this._init(); await this._init();
return true;
} catch (err) { } catch (err) {
console.debug(err); console.debug(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {

View File

@ -140,7 +140,7 @@ export const setConfigBySuccessfullAuthInplace = async (
) => { ) => {
if (authRes.access_token === undefined || authRes.access_token === "") { if (authRes.access_token === undefined || authRes.access_token === "") {
throw Error( throw Error(
`you should not save the setting for ${JSON.stringify(authRes)}` `remotely save account auth failed, please auth again: ${JSON.stringify(authRes)}`
); );
} }
@ -263,7 +263,7 @@ const getAuthMiddleware = (
saveUpdatedConfigFunc: any saveUpdatedConfigFunc: any
) => { ) => {
const authMiddleware: Middleware = { const authMiddleware: Middleware = {
async onRequest(req) { async onRequest({ request }) {
const getAccessToken = async () => { const getAccessToken = async () => {
if (koofrConfig.refreshToken === "") { if (koofrConfig.refreshToken === "") {
throw Error("The user has not manually auth yet."); throw Error("The user has not manually auth yet.");
@ -291,8 +291,8 @@ const getAuthMiddleware = (
}; };
const access = await getAccessToken(); const access = await getAccessToken();
req.headers.set("Authorization", `Bearer ${access}`); request.headers.set("Authorization", `Bearer ${access}`);
return req; return request;
}, },
}; };
return authMiddleware; return authMiddleware;
@ -555,12 +555,12 @@ export class FakeFsKoofr extends FakeFs {
// if we can init, we can connect // if we can init, we can connect
try { try {
await this._init(); await this._init();
return true;
} catch (err) { } catch (err) {
console.debug(err); console.debug(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {

964
pro/src/fsOnedriveFull.ts Normal file
View File

@ -0,0 +1,964 @@
import { CryptoProvider, PublicClientApplication } from "@azure/msal-node";
import type { AuthenticationProvider } from "@microsoft/microsoft-graph-client";
import type {
DriveItem,
FileSystemInfo,
UploadSession,
User,
} from "@microsoft/microsoft-graph-types";
import cloneDeep from "lodash/cloneDeep";
import { request, requestUrl } from "obsidian";
import {
DEFAULT_CONTENT_TYPE,
type Entity,
OAUTH2_FORCE_EXPIRE_MILLISECONDS,
ONEDRIVE_AUTHORITY,
ONEDRIVE_CLIENT_ID,
} from "../../src/baseTypes";
import { VALID_REQURL } from "../../src/baseTypesObs";
import { FakeFs } from "../../src/fsAll";
import { bufferToArrayBuffer } from "../../src/misc";
import {
COMMAND_CALLBACK_ONEDRIVEFULL,
type OnedriveFullConfig,
} from "./baseTypesPro";
const SCOPES = ["User.Read", "Files.ReadWrite", "offline_access"]; // not using Files.ReadWrite.All
const REDIRECT_URI = `obsidian://${COMMAND_CALLBACK_ONEDRIVEFULL}`; // diff from Onedrive (App Folder)
export const DEFAULT_ONEDRIVEFULL_CONFIG: OnedriveFullConfig = {
accessToken: "",
clientID: ONEDRIVE_CLIENT_ID ?? "",
authority: ONEDRIVE_AUTHORITY ?? "",
refreshToken: "",
accessTokenExpiresInSeconds: 0,
accessTokenExpiresAtTime: 0,
deltaLink: "",
username: "",
credentialsShouldBeDeletedAtTime: 0,
emptyFile: "skip",
kind: "onedrivefull",
};
////////////////////////////////////////////////////////////////////////////////
// Onedrive authorization using PKCE
////////////////////////////////////////////////////////////////////////////////
export async function getAuthUrlAndVerifier(
clientID: string,
authority: string
) {
const cryptoProvider = new CryptoProvider();
const { verifier, challenge } = await cryptoProvider.generatePkceCodes();
const pkceCodes = {
challengeMethod: "S256", // Use SHA256 Algorithm
verifier: verifier,
challenge: challenge,
};
const authCodeUrlParams = {
redirectUri: REDIRECT_URI,
scopes: SCOPES,
codeChallenge: pkceCodes.challenge, // PKCE Code Challenge
codeChallengeMethod: pkceCodes.challengeMethod, // PKCE Code Challenge Method
};
const pca = new PublicClientApplication({
auth: {
clientId: clientID,
authority: authority,
},
});
const authCodeUrl = await pca.getAuthCodeUrl(authCodeUrlParams);
return {
authUrl: authCodeUrl,
verifier: verifier,
};
}
/**
* Check doc from
* https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
* https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/graph-oauth?view=odsp-graph-online#code-flow
*/
export interface AccessCodeResponseSuccessfulType {
token_type: "Bearer" | "bearer";
expires_in: number;
ext_expires_in?: number;
scope: string;
access_token: string;
refresh_token?: string;
id_token?: string;
}
export interface AccessCodeResponseFailedType {
error: string;
error_description: string;
error_codes: number[];
timestamp: string;
trace_id: string;
correlation_id: string;
}
export const sendAuthReq = async (
clientID: string,
authority: string,
authCode: string,
verifier: string,
errorCallBack: any
) => {
// // original code snippets for references
// const authResponse = await pca.acquireTokenByCode({
// redirectUri: REDIRECT_URI,
// scopes: SCOPES,
// code: authCode,
// codeVerifier: verifier, // PKCE Code Verifier
// });
// console.info('authResponse')
// console.info(authResponse)
// return authResponse;
// Because of the CORS problem,
// we need to construct raw request using Obsidian request,
// instead of using msal
// https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
// https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/graph-oauth?view=odsp-graph-online#code-flow
try {
const rsp1 = await request({
url: `${authority}/oauth2/v2.0/token`,
method: "POST",
contentType: "application/x-www-form-urlencoded",
body: new URLSearchParams({
tenant: "consumers",
client_id: clientID,
scope: SCOPES.join(" "),
code: authCode,
redirect_uri: REDIRECT_URI,
grant_type: "authorization_code",
code_verifier: verifier,
}).toString(),
});
const rsp2 = JSON.parse(rsp1);
// console.info(rsp2);
if (rsp2.error !== undefined) {
return rsp2 as AccessCodeResponseFailedType;
} else {
return rsp2 as AccessCodeResponseSuccessfulType;
}
} catch (e) {
console.error(e);
await errorCallBack(e);
}
};
export const sendRefreshTokenReq = async (
clientID: string,
authority: string,
refreshToken: string
) => {
// also use Obsidian request to bypass CORS issue.
try {
const rsp1 = await request({
url: `${authority}/oauth2/v2.0/token`,
method: "POST",
contentType: "application/x-www-form-urlencoded",
body: new URLSearchParams({
tenant: "consumers",
client_id: clientID,
scope: SCOPES.join(" "),
refresh_token: refreshToken,
grant_type: "refresh_token",
}).toString(),
});
const rsp2 = JSON.parse(rsp1);
// console.info(rsp2);
if (rsp2.error !== undefined) {
return rsp2 as AccessCodeResponseFailedType;
} else {
return rsp2 as AccessCodeResponseSuccessfulType;
}
} catch (e) {
console.error(e);
throw e;
}
};
export const setConfigBySuccessfullAuthInplace = async (
config: OnedriveFullConfig,
authRes: AccessCodeResponseSuccessfulType,
saveUpdatedConfigFunc: () => Promise<any> | undefined
) => {
console.info("start updating local info of OneDrive token");
config.accessToken = authRes.access_token;
config.accessTokenExpiresAtTime =
Date.now() + authRes.expires_in - 5 * 60 * 1000;
config.accessTokenExpiresInSeconds = authRes.expires_in;
config.refreshToken = authRes.refresh_token!;
// manually set it expired after 80 days;
config.credentialsShouldBeDeletedAtTime =
Date.now() + OAUTH2_FORCE_EXPIRE_MILLISECONDS;
if (saveUpdatedConfigFunc !== undefined) {
await saveUpdatedConfigFunc();
}
console.info("finish updating local info of Onedrive token");
};
////////////////////////////////////////////////////////////////////////////////
// Other usual common methods
////////////////////////////////////////////////////////////////////////////////
/**
* This is different from Onedrive (App Folder)
*/
const getOnedrivePath = (fileOrFolderPath: string, remoteBaseDir: string) => {
// https://learn.microsoft.com/en-us/onedrive/developer/rest-api/concepts/addressing-driveitems?view=odsp-graph-online
const prefix = `/drive/root:/${remoteBaseDir}`;
let key = fileOrFolderPath;
if (fileOrFolderPath === "/" || fileOrFolderPath === "") {
// special
return prefix;
}
if (key.endsWith("/")) {
key = key.slice(0, key.length - 1);
}
if (key.startsWith("/")) {
console.warn(`why the path ${key} starts with '/'? but we just go on.`);
key = `${prefix}${key}`;
} else {
key = `${prefix}/${key}`;
}
return key;
};
const constructFromDriveItemToEntityError = (x: DriveItem) => {
const fullPathOriginal = `${x.parentReference?.path}/${x.name}`;
return `parentPath="${
x.parentReference?.path ?? "(no parentReference or path)"
}", selfName="${x.name}"`;
};
const fromDriveItemToEntity = (x: DriveItem, remoteBaseDir: string): Entity => {
let key = "";
// possible prefix:
// pure english: /drive/root:${remoteBaseDir}
const FIRST_COMMON_PREFIX_RAW = `/drive/root:/${remoteBaseDir}`;
const SECOND_COMMON_PREFIX_RAW = `/drive/root:/${encodeURIComponent(
remoteBaseDir
)}`;
if (
x.parentReference === undefined ||
x.parentReference === null ||
x.parentReference.path === undefined ||
x.parentReference.path === null
) {
throw Error("x.parentReference.path is undefinded or null");
}
const fullPathOriginal = `${x.parentReference?.path}/${x.name}`;
const matchFirstPrefixRes = fullPathOriginal.startsWith(
FIRST_COMMON_PREFIX_RAW
);
const matchSecondPrefixRes = fullPathOriginal.startsWith(
SECOND_COMMON_PREFIX_RAW
);
if (matchFirstPrefixRes) {
key = fullPathOriginal.substring(FIRST_COMMON_PREFIX_RAW.length + 1);
} else if (matchSecondPrefixRes) {
key = fullPathOriginal.substring(SECOND_COMMON_PREFIX_RAW.length + 1);
} else {
throw Error(
`we meet file/folder and do not know how to deal with it:\n${constructFromDriveItemToEntityError(
x
)}`
);
}
const isFolder = "folder" in x;
if (isFolder) {
key = `${key}/`;
}
const mtimeTry = x?.fileSystemInfo?.lastModifiedDateTime;
if (mtimeTry === undefined || mtimeTry === null) {
throw Error(`onedrive cannot parse mtime: ${JSON.stringify(x, null, 2)}`);
}
let ctimeTry = x?.fileSystemInfo?.createdDateTime;
if (ctimeTry === undefined || ctimeTry === null) {
// throw Error(`onedrive cannot parse ctime: ${JSON.stringify(x, null, 2)}`);
// it doesn't hurt, we just use mtimeTry to fullfill
ctimeTry = mtimeTry;
}
const mtimeSvr = Date.parse(mtimeTry);
const mtimeCli = Date.parse(mtimeTry);
const ctimeCli = Date.parse(ctimeTry);
return {
key: key,
keyRaw: key,
mtimeSvr: mtimeSvr,
mtimeCli: mtimeCli,
ctimeCli: ctimeCli,
size: isFolder ? 0 : x.size!,
sizeRaw: isFolder ? 0 : x.size!,
synthesizedFile: false,
// hash: ?? // TODO
};
};
////////////////////////////////////////////////////////////////////////////////
// The client.
////////////////////////////////////////////////////////////////////////////////
// to adapt to the required interface
class MyAuthProvider implements AuthenticationProvider {
onedriveFullConfig: OnedriveFullConfig;
saveUpdatedConfigFunc: () => Promise<any>;
constructor(
onedriveFullConfig: OnedriveFullConfig,
saveUpdatedConfigFunc: () => Promise<any>
) {
this.onedriveFullConfig = onedriveFullConfig;
this.saveUpdatedConfigFunc = saveUpdatedConfigFunc;
}
async getAccessToken() {
if (
this.onedriveFullConfig.accessToken === "" ||
this.onedriveFullConfig.refreshToken === ""
) {
throw Error("The user has not manually auth yet.");
}
const currentTs = Date.now();
if (this.onedriveFullConfig.accessTokenExpiresAtTime > currentTs) {
return this.onedriveFullConfig.accessToken;
} else {
// use refreshToken to refresh
const r = await sendRefreshTokenReq(
this.onedriveFullConfig.clientID,
this.onedriveFullConfig.authority,
this.onedriveFullConfig.refreshToken
);
if ((r as any).error !== undefined) {
const r2 = r as AccessCodeResponseFailedType;
throw Error(
`Error while refreshing accessToken: ${r2.error}, ${r2.error_codes}: ${r2.error_description}`
);
}
const r2 = r as AccessCodeResponseSuccessfulType;
this.onedriveFullConfig.accessToken = r2.access_token;
this.onedriveFullConfig.refreshToken = r2.refresh_token!;
this.onedriveFullConfig.accessTokenExpiresInSeconds = r2.expires_in;
this.onedriveFullConfig.accessTokenExpiresAtTime =
currentTs + r2.expires_in * 1000 - 60 * 2 * 1000;
await this.saveUpdatedConfigFunc();
console.info("Onedrive accessToken updated");
return this.onedriveFullConfig.accessToken;
}
}
}
/**
* to export the settings in qrcode,
* we want to "trim" or "shrink" the settings
* @param onedriveFullConfig
*/
export const getShrinkedSettings = (onedriveFullConfig: OnedriveFullConfig) => {
const config = cloneDeep(onedriveFullConfig);
config.accessToken = "x";
config.accessTokenExpiresInSeconds = 1;
config.accessTokenExpiresAtTime = 1;
return config;
};
export class FakeFsOnedriveFull extends FakeFs {
kind: "onedrivefull";
onedriveFullConfig: OnedriveFullConfig;
remoteBaseDir: string;
vaultFolderExists: boolean;
authGetter: MyAuthProvider;
saveUpdatedConfigFunc: () => Promise<any>;
foldersCreatedBefore: Set<string>;
constructor(
onedriveFullConfig: OnedriveFullConfig,
vaultName: string,
saveUpdatedConfigFunc: () => Promise<any>
) {
super();
this.kind = "onedrivefull";
this.onedriveFullConfig = onedriveFullConfig;
this.remoteBaseDir =
this.onedriveFullConfig.remoteBaseDir || vaultName || "";
this.vaultFolderExists = false;
this.saveUpdatedConfigFunc = saveUpdatedConfigFunc;
this.authGetter = new MyAuthProvider(
onedriveFullConfig,
saveUpdatedConfigFunc
);
this.foldersCreatedBefore = new Set();
}
async _init() {
// check token
if (
this.onedriveFullConfig.accessToken === "" ||
this.onedriveFullConfig.refreshToken === ""
) {
throw Error("The user has not manually auth yet.");
}
// check vault folder
// console.info(`checking remote has folder /${this.remoteBaseDir}`);
if (this.vaultFolderExists) {
// console.info(`already checked, /${this.remoteBaseDir} exist before`)
} else {
const k = await this._getJson("/drive/root/children");
// console.debug(k);
this.vaultFolderExists =
(k.value as DriveItem[]).filter((x) => x.name === this.remoteBaseDir)
.length > 0;
if (!this.vaultFolderExists) {
console.info(`remote does not have folder /${this.remoteBaseDir}`);
await this._postJson("/drive/root/children", {
name: `${this.remoteBaseDir}`,
folder: {},
"@microsoft.graph.conflictBehavior": "replace",
});
console.info(`remote folder /${this.remoteBaseDir} created`);
this.vaultFolderExists = true;
} else {
// console.info(`remote folder /${this.remoteBaseDir} exists`);
}
}
}
_buildUrl(pathFragOrig: string) {
const API_PREFIX = "https://graph.microsoft.com/v1.0";
let theUrl = "";
if (
pathFragOrig.startsWith("http://") ||
pathFragOrig.startsWith("https://")
) {
theUrl = pathFragOrig;
} else {
const pathFrag = encodeURI(pathFragOrig);
theUrl = `${API_PREFIX}${pathFrag}`;
}
// we want to support file name with hash #
// because every url we construct here do not contain the # symbol
// thus it should be safe to directly replace the character
theUrl = theUrl.replace(/#/g, "%23");
// console.debug(`building url: [${pathFragOrig}] => [${theUrl}]`)
return theUrl;
}
async _getJson(pathFragOrig: string) {
const theUrl = this._buildUrl(pathFragOrig);
console.debug(`getJson, theUrl=${theUrl}`);
return JSON.parse(
await request({
url: theUrl,
method: "GET",
contentType: "application/json",
headers: {
Authorization: `Bearer ${await this.authGetter.getAccessToken()}`,
"Cache-Control": "no-cache",
},
})
);
}
async _postJson(pathFragOrig: string, payload: any) {
const theUrl = this._buildUrl(pathFragOrig);
console.debug(`postJson, theUrl=${theUrl}`);
return JSON.parse(
await request({
url: theUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(payload),
headers: {
Authorization: `Bearer ${await this.authGetter.getAccessToken()}`,
},
})
);
}
async _patchJson(pathFragOrig: string, payload: any) {
const theUrl = this._buildUrl(pathFragOrig);
console.debug(`patchJson, theUrl=${theUrl}`);
return JSON.parse(
await request({
url: theUrl,
method: "PATCH",
contentType: "application/json",
body: JSON.stringify(payload),
headers: {
Authorization: `Bearer ${await this.authGetter.getAccessToken()}`,
},
})
);
}
async _deleteJson(pathFragOrig: string) {
const theUrl = this._buildUrl(pathFragOrig);
console.debug(`deleteJson, theUrl=${theUrl}`);
if (VALID_REQURL) {
await requestUrl({
url: theUrl,
method: "DELETE",
headers: {
Authorization: `Bearer ${await this.authGetter.getAccessToken()}`,
},
});
} else {
await fetch(theUrl, {
method: "DELETE",
headers: {
Authorization: `Bearer ${await this.authGetter.getAccessToken()}`,
},
});
}
}
async _putArrayBuffer(pathFragOrig: string, payload: ArrayBuffer) {
const theUrl = this._buildUrl(pathFragOrig);
console.debug(`putArrayBuffer, theUrl=${theUrl}`);
// TODO:
// 20220401: On Android, requestUrl has issue that text becomes base64.
// Use fetch everywhere instead!
// biome-ignore lint/correctness/noConstantCondition: hard code
if (false /*VALID_REQURL*/) {
const res = await requestUrl({
url: theUrl,
method: "PUT",
body: payload,
contentType: DEFAULT_CONTENT_TYPE,
headers: {
"Content-Type": DEFAULT_CONTENT_TYPE,
Authorization: `Bearer ${await this.authGetter.getAccessToken()}`,
},
});
return res.json as DriveItem | UploadSession;
} else {
const res = await fetch(theUrl, {
method: "PUT",
body: payload,
headers: {
"Content-Type": DEFAULT_CONTENT_TYPE,
Authorization: `Bearer ${await this.authGetter.getAccessToken()}`,
},
});
return (await res.json()) as DriveItem | UploadSession;
}
}
/**
* A specialized function to upload large files by parts
* @param pathFragOrig
* @param payload
* @param rangeMin
* @param rangeEnd the end, exclusive
* @param size
*/
async _putUint8ArrayByRange(
pathFragOrig: string,
payload: Uint8Array,
rangeStart: number,
rangeEnd: number,
size: number
) {
const theUrl = this._buildUrl(pathFragOrig);
console.debug(
`putUint8ArrayByRange, theUrl=${theUrl}, range=${rangeStart}-${
rangeEnd - 1
}, len=${rangeEnd - rangeStart}, size=${size}`
);
// NO AUTH HEADER here!
// TODO:
// 20220401: On Android, requestUrl has issue that text becomes base64.
// Use fetch everywhere instead!
// biome-ignore lint/correctness/noConstantCondition: hard code
if (false /*VALID_REQURL*/) {
const res = await requestUrl({
url: theUrl,
method: "PUT",
body: bufferToArrayBuffer(payload.subarray(rangeStart, rangeEnd)),
contentType: DEFAULT_CONTENT_TYPE,
headers: {
// no "Content-Length" allowed here
"Content-Range": `bytes ${rangeStart}-${rangeEnd - 1}/${size}`,
/* "Cache-Control": "no-cache", not allowed here!!! */
},
});
return res.json as DriveItem | UploadSession;
} else {
const res = await fetch(theUrl, {
method: "PUT",
body: payload.subarray(rangeStart, rangeEnd),
headers: {
"Content-Length": `${rangeEnd - rangeStart}`,
"Content-Range": `bytes ${rangeStart}-${rangeEnd - 1}/${size}`,
"Content-Type": DEFAULT_CONTENT_TYPE,
/* "Cache-Control": "no-cache", not allowed here!!! */
},
});
return (await res.json()) as DriveItem | UploadSession;
}
}
/**
* Use delta api to list all files and folders
* https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_delta?view=odsp-graph-online
*/
async walk(): Promise<Entity[]> {
await this._init();
const NEXT_LINK_KEY = "@odata.nextLink";
const DELTA_LINK_KEY = "@odata.deltaLink";
let res = await this._getJson(`/drive/root:/${this.remoteBaseDir}:/delta`);
const driveItems = res.value as DriveItem[];
// console.debug(driveItems);
while (NEXT_LINK_KEY in res) {
res = await this._getJson(res[NEXT_LINK_KEY]);
driveItems.push(...cloneDeep(res.value as DriveItem[]));
}
// lastly we should have delta link?
if (DELTA_LINK_KEY in res) {
this.onedriveFullConfig.deltaLink = res[DELTA_LINK_KEY];
await this.saveUpdatedConfigFunc();
}
// unify everything to Entity
const unifiedContents = driveItems
.map((x) => fromDriveItemToEntity(x, this.remoteBaseDir))
.filter((x) => x.key !== "/");
return unifiedContents;
}
async walkPartial(): Promise<Entity[]> {
await this._init();
const DELTA_LINK_KEY = "@odata.deltaLink";
const res = await this._getJson(
`/drive/root:/${this.remoteBaseDir}:/delta`
);
const driveItems = res.value as DriveItem[];
// console.debug(driveItems);
// lastly we should have delta link?
if (DELTA_LINK_KEY in res) {
this.onedriveFullConfig.deltaLink = res[DELTA_LINK_KEY];
await this.saveUpdatedConfigFunc();
}
// unify everything to Entity
const unifiedContents = driveItems
.map((x) => fromDriveItemToEntity(x, this.remoteBaseDir))
.filter((x) => x.key !== "/");
return unifiedContents;
}
async stat(key: string): Promise<Entity> {
await this._init();
return await this._statFromRoot(getOnedrivePath(key, this.remoteBaseDir));
}
async _statFromRoot(key: string): Promise<Entity> {
// console.info(`remotePath=${remotePath}`);
const rsp = await this._getJson(
`${key}?$select=cTag,eTag,fileSystemInfo,folder,file,name,parentReference,size`
);
// console.info(rsp);
const driveItem = rsp as DriveItem;
const res = fromDriveItemToEntity(driveItem, this.remoteBaseDir);
// console.info(res);
return res;
}
async mkdir(key: string, mtime?: number, ctime?: number): Promise<Entity> {
if (!key.endsWith("/")) {
throw Error(`you should not call mkdir on ${key}`);
}
await this._init();
const uploadFolder = getOnedrivePath(key, this.remoteBaseDir);
console.debug(`mkdir uploadFolder=${uploadFolder}`);
return await this._mkdirFromRoot(uploadFolder, mtime, ctime);
}
async _mkdirFromRoot(
key: string,
mtime?: number,
ctime?: number
): Promise<Entity> {
// console.debug(`foldersCreatedBefore=${Array.from(this.foldersCreatedBefore)}`);
if (this.foldersCreatedBefore.has(key)) {
// created, pass
// console.debug(`folder ${key} created.`)
} else {
// https://stackoverflow.com/questions/56479865/creating-nested-folders-in-one-go-onedrive-api
// use PATCH to create folder recursively!!!
const playload: any = {
folder: {},
"@microsoft.graph.conflictBehavior": "replace",
};
const fileSystemInfo: Record<string, string> = {};
if (mtime !== undefined && mtime !== 0) {
const mtimeStr = new Date(mtime).toISOString();
fileSystemInfo["lastModifiedDateTime"] = mtimeStr;
}
if (ctime !== undefined && ctime !== 0) {
const ctimeStr = new Date(ctime).toISOString();
fileSystemInfo["createdDateTime"] = ctimeStr;
}
if (Object.keys(fileSystemInfo).length > 0) {
playload["fileSystemInfo"] = fileSystemInfo;
}
await this._patchJson(key, playload);
}
const res = await this._statFromRoot(key);
return res;
}
async writeFile(
key: string,
content: ArrayBuffer,
mtime: number,
ctime: number
): Promise<Entity> {
if (key.endsWith("/")) {
throw Error(`you should not call writeFile on ${key}`);
}
await this._init();
const uploadFile = getOnedrivePath(key, this.remoteBaseDir);
console.debug(`uploadFile=${uploadFile}`);
return await this._writeFileFromRoot(
uploadFile,
content,
mtime,
ctime,
key,
this.onedriveFullConfig.emptyFile
);
}
async _writeFileFromRoot(
key: string,
content: ArrayBuffer,
mtime: number,
ctime: number,
origKey: string,
emptyFile: "skip" | "error"
): Promise<Entity> {
if (content.byteLength === 0) {
if (emptyFile === "error") {
throw Error(
`${origKey}: Empty file is not allowed in OneDrive, and please write something in it.`
);
} else {
return {
key: origKey,
keyRaw: origKey,
mtimeSvr: mtime,
mtimeCli: mtime,
ctimeCli: ctime,
size: 0,
sizeRaw: 0,
synthesizedFile: true,
// hash: ?? // TODO
};
}
}
const ctimeStr = new Date(ctime).toISOString();
const mtimeStr = new Date(mtime).toISOString();
// no need to create parent folders firstly, cool!
// hard code range size
const MIN_UNIT = 327680; // bytes in msft doc, about 0.32768 MB
const RANGE_SIZE = MIN_UNIT * 20; // about 6.5536 MB
const DIRECT_UPLOAD_MAX_SIZE = 1000 * 1000 * 4; // 4 Megabyte
if (content.byteLength < DIRECT_UPLOAD_MAX_SIZE) {
// directly using put!
await this._putArrayBuffer(
`${key}:/content?${new URLSearchParams({
"@microsoft.graph.conflictBehavior": "replace",
})}`,
content
);
if (mtime !== 0 && ctime !== 0) {
await this._patchJson(key, {
fileSystemInfo: {
lastModifiedDateTime: mtimeStr,
createdDateTime: ctimeStr,
} as FileSystemInfo,
});
}
} else {
// upload large files!
// ref: https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession?view=odsp-graph-online
// 1. create uploadSession
// uploadFile already starts with /drive/root:/${remoteBaseDir}
let playload: any = {
item: {
"@microsoft.graph.conflictBehavior": "replace",
},
};
if (mtime !== 0 && ctime !== 0) {
playload = {
item: {
"@microsoft.graph.conflictBehavior": "replace",
// this is only possible using uploadSession
fileSystemInfo: {
lastModifiedDateTime: mtimeStr,
createdDateTime: ctimeStr,
} as FileSystemInfo,
},
};
}
const s: UploadSession = await this._postJson(
`${key}:/createUploadSession`,
playload
);
const uploadUrl = s.uploadUrl!;
console.debug("uploadSession = ");
console.debug(s);
// 2. upload by ranges
// convert to uint8
const uint8 = new Uint8Array(content);
// upload the ranges one by one
let rangeStart = 0;
while (rangeStart < uint8.byteLength) {
await this._putUint8ArrayByRange(
uploadUrl,
uint8,
rangeStart,
Math.min(rangeStart + RANGE_SIZE, uint8.byteLength),
uint8.byteLength
);
rangeStart += RANGE_SIZE;
}
}
const res = await this._statFromRoot(key);
return res;
}
async readFile(key: string): Promise<ArrayBuffer> {
await this._init();
if (key.endsWith("/")) {
throw new Error(`you should not call readFile on folder ${key}`);
}
const downloadFile = getOnedrivePath(key, this.remoteBaseDir);
return await this._readFileFromRoot(downloadFile);
}
async _readFileFromRoot(key: string): Promise<ArrayBuffer> {
const rsp = await this._getJson(
`${key}?$select=@microsoft.graph.downloadUrl`
);
const downloadUrl: string = rsp["@microsoft.graph.downloadUrl"];
// biome-ignore lint/correctness/noConstantCondition: <explanation>
if (false /*VALID_REQURL*/) {
const content = (
await requestUrl({
url: downloadUrl,
headers: { "Cache-Control": "no-cache" },
})
).arrayBuffer;
return content;
} else {
// cannot set no-cache here, will have cors error
const content = await (
await fetch(downloadUrl, { cache: "no-store" })
).arrayBuffer();
return content;
}
}
async rename(key1: string, key2: string): Promise<void> {
if (key1 === "" || key1 === "/" || key2 === "" || key2 === "/") {
return;
}
const remoteFileName1 = getOnedrivePath(key1, this.remoteBaseDir);
const remoteFileName2 = getOnedrivePath(key2, this.remoteBaseDir);
await this._init();
await this._patchJson(remoteFileName1, {
name: remoteFileName2,
});
}
async rm(key: string): Promise<void> {
if (key === "" || key === "/") {
return;
}
const remoteFileName = getOnedrivePath(key, this.remoteBaseDir);
await this._init();
await this._deleteJson(remoteFileName);
}
async checkConnect(callbackFunc?: any): Promise<boolean> {
try {
const k = await this.getUserDisplayName();
if (k === "<unknown display name>") {
throw Error(`unknown display name!`);
}
} catch (err) {
console.debug(err);
callbackFunc?.(err);
return false;
}
return await this.checkConnectCommonOps(callbackFunc);
}
async getUserDisplayName() {
await this._init();
const res: User = await this._getJson("/me?$select=displayName");
return res.displayName || "<unknown display name>";
}
/**
*
* https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request
* https://docs.microsoft.com/en-us/graph/api/user-revokesigninsessions
* https://docs.microsoft.com/en-us/graph/api/user-invalidateallrefreshtokens
*/
async revokeAuth() {
// await this._init();
// await this._postJson("/me/revokeSignInSessions", {});
throw new Error("Method not implemented.");
}
async getRevokeAddr() {
return "https://account.live.com/consent/Manage";
}
allowEmptyFile(): boolean {
return false;
}
}

View File

@ -99,7 +99,9 @@ export const setConfigBySuccessfullAuthInplace = async (
saveUpdatedConfigFunc: () => Promise<any> | undefined saveUpdatedConfigFunc: () => Promise<any> | undefined
) => { ) => {
if (authRes === undefined) { if (authRes === undefined) {
throw Error(`you should not save the setting for undefined result`); throw Error(
`remotely save account auth failed, please auth again: undefined result`
);
} }
config.accessToken = authRes.access_token; config.accessToken = authRes.access_token;
@ -604,12 +606,12 @@ export class FakeFsPCloud extends FakeFs {
// if we can init, we can connect // if we can init, we can connect
try { try {
await this._init(); await this._init();
return true;
} catch (err) { } catch (err) {
console.debug(err); console.debug(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {

View File

@ -127,7 +127,7 @@ export const setConfigBySuccessfullAuthInplace = async (
) => { ) => {
if (authRes.access_token === undefined || authRes.access_token === "") { if (authRes.access_token === undefined || authRes.access_token === "") {
throw Error( throw Error(
`you should not save the setting for ${JSON.stringify(authRes)}` `remotely save account auth failed, please auth again: ${JSON.stringify(authRes)}`
); );
} }
@ -480,12 +480,12 @@ export class FakeFsYandexDisk extends FakeFs {
// if we can init, we can connect // if we can init, we can connect
try { try {
await this._init(); await this._init();
return true;
} catch (err) { } catch (err) {
console.debug(err); console.debug(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {

View File

@ -7,6 +7,11 @@
"protocol_pro_connect_fail": "Something went wrong from response from Remotely Save official website. Maybe the network connection is not good. Maybe you rejected the auth?", "protocol_pro_connect_fail": "Something went wrong from response from Remotely Save official website. Maybe the network connection is not good. Maybe you rejected the auth?",
"protocol_pro_connect_succ_revoke": "You've connected as user {{email}}. If you want to disconnect, click this button.", "protocol_pro_connect_succ_revoke": "You've connected as user {{email}}. If you want to disconnect, click this button.",
"protocol_onedrivefull_connecting": "Connecting to OneDrive...\nPlease DO NOT close this modal.",
"protocol_onedrivefull_connect_succ_revoke": "You've connected as user {{username}}. If you want to disconnect, click this button.",
"protocol_onedrivefull_connect_fail": "Something went wrong from response from OneDrive. Maybe you rejected the auth?",
"protocol_onedrivefull_connect_unknown": "Do not know how to deal with the callback: {{params}}",
"protocol_box_connecting": "Connectting", "protocol_box_connecting": "Connectting",
"protocol_box_connect_manualinput_succ": "You've connected", "protocol_box_connect_manualinput_succ": "You've connected",
"protocol_box_connect_fail": "Something went wrong from response from Box official website. Maybe the network connection is not good. Maybe you rejected the auth?", "protocol_box_connect_fail": "Something went wrong from response from Box official website. Maybe the network connection is not good. Maybe you rejected the auth?",
@ -27,6 +32,18 @@
"protocol_koofr_connect_fail": "Something went wrong from response from Koofr website. Maybe the network connection is not good. Maybe you rejected the auth?", "protocol_koofr_connect_fail": "Something went wrong from response from Koofr website. Maybe the network connection is not good. Maybe you rejected the auth?",
"protocol_koofr_connect_succ_revoke": "You've connected. If you want to disconnect, click this button.", "protocol_koofr_connect_succ_revoke": "You've connected. If you want to disconnect, click this button.",
"modal_onedrivefullauth_shortdesc": "Currently only OneDrive for personal is supported. OneDrive for Business is NOT supported (yet).\nVisit the address in a browser, and follow the steps.\nFinally you should be redirected to Obsidian.",
"modal_onedrivefullauth_shortdesc_linux": "It seems that you are using Obsidian on Linux, and you might not be able to jump back here properly. Please consider <a href=\"https://github.com/remotely-save/remotely-save/issues/415\">using</a> the flatpack version of Obsidian, or creating an <a href=\"https://github.com/remotely-save/remotely-save/blob/master/docs/linux.md\"><code>obsidian.desktop</code> file</a>.",
"modal_onedrivefullauth_copybutton": "Click to copy the auth url",
"modal_onedrivefullauth_copynotice": "The auth url is copied to the clipboard!",
"modal_onedrivefullrevokeauth_step1": "Step 1: Go to the following address, click the \"Edit\" button for the plugin, then click \"Remove these permissions\" button on the page.",
"modal_onedrivefullrevokeauth_step2": "Step 2: Click the button below, to clean the locally-saved login credentials.",
"modal_onedrivefullrevokeauth_clean": "Clean Locally-Saved Login Credentials",
"modal_onedrivefullrevokeauth_clean_desc": "You need to click the button.",
"modal_onedrivefullrevokeauth_clean_button": "Clean",
"modal_onedrivefullrevokeauth_clean_notice": "Cleaned!",
"modal_onedrivefullrevokeauth_clean_fail": "Something goes wrong while revoking.",
"modal_googledriveauth_tutorial": "<p>Please firstly go to the address, then go on the auth flow. In the end, you will see a code, please paste that code here and submit.</p>", "modal_googledriveauth_tutorial": "<p>Please firstly go to the address, then go on the auth flow. In the end, you will see a code, please paste that code here and submit.</p>",
"modal_googledriveauth_copybutton": "Click to copy the auth url", "modal_googledriveauth_copybutton": "Click to copy the auth url",
"modal_googledriveauth_copynotice": "The auth url is copied to the clipboard!", "modal_googledriveauth_copynotice": "The auth url is copied to the clipboard!",
@ -112,6 +129,33 @@
"modal_proauth_maualinput_notice": "Trying to connect, wait...", "modal_proauth_maualinput_notice": "Trying to connect, wait...",
"modal_proauth_maualinput_conn_fail": "Failed to connect", "modal_proauth_maualinput_conn_fail": "Failed to connect",
"modal_cleardupfiles_warning": "Warning: The plugin just stupidly finds all the file names that looks like duplicated files (.dup in file names). Also, this only deletes local files, so you need to trigger a sync to delete remote files.",
"modal_cleardupfiles_warning_confirm": "Confirm to delete",
"modal_cleardupfiles_warning_finished": "All the detected duplicated files are removed!",
"settings_onedrivefull": "Remote For Onedrive (for personal) (Full)",
"settings_chooseservice_onedrivefull": "OneDrive for personal (Full) (PRO)",
"settings_onedrivefull_disclaimer1": "Disclaimer: This app is NOT an official Microsoft / OneDrive product.",
"settings_onedrivefull_disclaimer2": "Disclaimer: The information is stored locally. Other malicious/harmful/faulty plugins could read the info. If you see any unintentional access to your Onedrive, please immediately disconnect this app on https://microsoft.com/consent .",
"settings_onedrivefull_folder": "We will create and sync inside the folder /{{remoteBaseDir}} on your OneDrive.",
"settings_onedrivefull_nobiz": "Currently only OneDrive for personal is supported. OneDrive for Business is NOT supported (yet).",
"settings_onedrivefull_pro_desc": "<p><strong>!!It's a PRO feature of Remotely Save! You need a Remotely Save online account for this feature!!</strong>(<a href=\"#settings-pro\">scroll down</a> for more info about PRO account.)</p>",
"settings_onedrivefull_notshowuphint": "OneDrive for personal (Full) Settings Not Available",
"settings_onedrivefull_notshowuphint_desc": "OneDrive for personal (Full) settings are not available, because you haven't subscribed to the PRO feature in your Remotely Save account.",
"settings_onedrivefull_notshowuphint_view_pro": "View PRO Settings",
"settings_onedrivefull_revoke": "Revoke Auth",
"settings_onedrivefull_revoke_desc": "You've connected as user {{username}}. If you want to disconnect, click this button.",
"settings_onedrivefull_revoke_button": "Revoke Auth",
"settings_onedrivefull_auth": "Auth",
"settings_onedrivefull_auth_desc": "Auth.",
"settings_onedrivefull_auth_button": "Auth",
"settings_onedrivefull_connect_succ": "Great! We can connect to OneDrive!",
"settings_onedrivefull_connect_fail": "We cannot connect to OneDrive.",
"settings_onedrivefull_emptyfile": "Empty File Handling",
"settings_onedrivefull_emptyfile_desc": "OneDrive doesn't allow uploading empty file (even in its official website). Do you want to show up errors or silently skip the empty files?",
"settings_onedrivefull_emptyfile_skip": "Skip",
"settings_onedrivefull_emptyfile_error": "Error and abort",
"settings_googledrive": "Google Drive (PRO) (beta)", "settings_googledrive": "Google Drive (PRO) (beta)",
"settings_chooseservice_googledrive": "Google Drive (PRO) (beta)", "settings_chooseservice_googledrive": "Google Drive (PRO) (beta)",
"settings_googledrive_disclaimer1": "Disclaimer: This app is NOT an official Google product. The app just uses Google Drive's public api.", "settings_googledrive_disclaimer1": "Disclaimer: This app is NOT an official Google product. The app just uses Google Drive's public api.",
@ -224,12 +268,13 @@
"settings_azureblobstorage_parts": "Parts Concurrency", "settings_azureblobstorage_parts": "Parts Concurrency",
"settings_azureblobstorage_parts_desc": "Large files are split into small parts to upload. How many parts do you want to upload in parallel at most?", "settings_azureblobstorage_parts_desc": "Large files are split into small parts to upload. How many parts do you want to upload in parallel at most?",
"settings_azureblobstorage_generatefolderobject": "Generate Folder Object Or Not", "settings_azureblobstorage_generatefolderobject": "Generate Folder Object Or Not",
"settings_azureblobstorage_generatefolderobject_desc": "Azure Blob Storage doesn't have \"real\" folder. If you set \"Generate\" here, the plugin will upload a zero-byte object endding with \"/\" to represent the folder. By default, the plugin skips generating folder object.", "settings_azureblobstorage_generatefolderobject_desc": "Azure Blob Storage doesn't have \"real\" folder. If you set \"Generate\" here, the plugin will upload a zero-byte object ending with \"/\" to represent the folder. By default, the plugin skips generating folder object.",
"settings_azureblobstorage_generatefolderobject_notgenerate": "Not generate (default)", "settings_azureblobstorage_generatefolderobject_notgenerate": "Not generate (default)",
"settings_azureblobstorage_generatefolderobject_generate": "Generate", "settings_azureblobstorage_generatefolderobject_generate": "Generate",
"settings_azureblobstorage_connect_succ": "Great! We can connect to Azure Blob Storage!", "settings_azureblobstorage_connect_succ": "Great! We can connect to Azure Blob Storage!",
"settings_azureblobstorage_connect_fail": "We cannot connect to Azure Blob Storage.", "settings_azureblobstorage_connect_fail": "We cannot connect to Azure Blob Storage.",
"settings_export_onedrivefull_button": "Export Onedrive (Full) Part",
"settings_export_googledrive_button": "Export Google Drive Part", "settings_export_googledrive_button": "Export Google Drive Part",
"settings_export_box_button": "Export Box Part", "settings_export_box_button": "Export Box Part",
"settings_export_pcloud_button": "Export pCloud Part", "settings_export_pcloud_button": "Export pCloud Part",
@ -237,6 +282,10 @@
"settings_export_koofr_button": "Export Koofr Part", "settings_export_koofr_button": "Export Koofr Part",
"settings_export_azureblobstorage_button": "Export Azure Blob Storage Part", "settings_export_azureblobstorage_button": "Export Azure Blob Storage Part",
"settings_cleardupfiles": "Clear Duplicated Files By Smart Conflict",
"settings_cleardupfiles_desc": "If you have ever used Smart Conflict (PRO) feature, the plugin may generate duplicated files. <strong>IF YOU ARE SURE THE DUPLICATED FILES ARE NO LONGER NEEDED</strong>, you can clear <strong>ALL</strong> of them locally here.",
"settings_cleardupfiles_button": "Start Scanning",
"settings_pro": "Account (for PRO features)", "settings_pro": "Account (for PRO features)",
"settings_pro_tutorial": "<p>Using <stong>basic</strong> features of Remotely Save is <strong>FREE</strong> and do <strong>NOT</strong> need an account.</p><p>However, you will <strong>need</strong> an online account and <strong>PAY</strong> for the <strong>PRO</strong> features such as smart conflict.</p><p>Firstly please click the button to sign up and sign in to the website: <a href=\"https://remotelysave.com\">https://remotelysave.com</a>. Notice: It's different from, and NOT affiliated with Obsidian account.</p><p>Secondly please \"connect\" your local device to your online account.", "settings_pro_tutorial": "<p>Using <stong>basic</strong> features of Remotely Save is <strong>FREE</strong> and do <strong>NOT</strong> need an account.</p><p>However, you will <strong>need</strong> an online account and <strong>PAY</strong> for the <strong>PRO</strong> features such as smart conflict.</p><p>Firstly please click the button to sign up and sign in to the website: <a href=\"https://remotelysave.com\">https://remotelysave.com</a>. Notice: It's different from, and NOT affiliated with Obsidian account.</p><p>Secondly please \"connect\" your local device to your online account.",
"settings_pro_features": "Features", "settings_pro_features": "Features",

View File

@ -7,6 +7,11 @@
"protocol_pro_connect_fail": "Remotely Save 官网返回错误。可能是网络连接不稳定。也可能是您拒绝了授权?", "protocol_pro_connect_fail": "Remotely Save 官网返回错误。可能是网络连接不稳定。也可能是您拒绝了授权?",
"protocol_pro_connect_succ_revoke": "您已连接上账号 {{email}}。如果要取消连接,请点击此按钮。", "protocol_pro_connect_succ_revoke": "您已连接上账号 {{email}}。如果要取消连接,请点击此按钮。",
"protocol_onedrivefull_connecting": "正在连接 OneDrive……\n请不要关闭此弹窗。",
"protocol_onedrivefull_connect_succ_revoke": "您已作为用户 {{username}} 连接上了。如果您想取消连接,请点击此按钮。",
"protocol_onedrivefull_connect_fail": "OneDrive 的回调请求有点异常。您是否拒绝了鉴权?",
"protocol_onedrivefull_connect_unknown": "不知道如何处理此 callback{{params}}",
"protocol_box_connecting": "正在连接", "protocol_box_connecting": "正在连接",
"protocol_box_connect_manualinput_succ": "连接成功", "protocol_box_connect_manualinput_succ": "连接成功",
"protocol_box_connect_fail": "Box 官网返回错误。可能是网络连接不稳定。也可能是您拒绝了授权?", "protocol_box_connect_fail": "Box 官网返回错误。可能是网络连接不稳定。也可能是您拒绝了授权?",
@ -27,6 +32,18 @@
"protocol_koofr_connect_fail": "Yandex Disk 官网返回错误。可能是网络连接不稳定。也可能是您拒绝了授权?", "protocol_koofr_connect_fail": "Yandex Disk 官网返回错误。可能是网络连接不稳定。也可能是您拒绝了授权?",
"protocol_koofr_connect_succ_revoke": "您已连接上账号。如果要取消连接,请点击此按钮。", "protocol_koofr_connect_succ_revoke": "您已连接上账号。如果要取消连接,请点击此按钮。",
"modal_onedrivefullauth_shortdesc": "现在只支持个人版 OneDrive不支持企业版。\n在浏览器中访问以下地址然后按照网页提示操作。\n到了最后您应该会被自动重定向回来 Obsidian。",
"modal_onedrivefullauth_shortdesc_linux": "您正在用 Linux有可能无法跳转回来。请考虑<a href=\"https://github.com/remotely-save/remotely-save/issues/415\">使用</a> flatpack 版本的 Obsidian或创建 <a href=\"https://github.com/remotely-save/remotely-save/blob/master/docs/linux.md\"><code>obsidian.desktop</code> 文件</a>。",
"modal_onedrivefullauth_copybutton": "点击此按钮从而复制鉴权 url",
"modal_onedrivefullauth_copynotice": "鉴权 url 已复制到剪贴板!",
"modal_onedrivefullrevokeauth_step1": "第 1 步用浏览器打开以下地址点击本插件对应的“Edit”按钮点击“Remove these permissions”按钮。",
"modal_onedrivefullrevokeauth_step2": "第 2 步:点击以下按钮,清理本地保存的登录信息。",
"modal_onedrivefullrevokeauth_clean": "清理本地保存的登录信息",
"modal_onedrivefullrevokeauth_clean_desc": "您需要点击“清理”按钮。",
"modal_onedrivefullrevokeauth_clean_button": "清理",
"modal_onedrivefullrevokeauth_clean_notice": "已清理!",
"modal_onedrivefullrevokeauth_clean_fail": "鉴权途中出错了。",
"modal_googledriveauth_tutorial": "<p>请访问此网址,然后会进入授权流程。最后,您会看到一个码,请复制粘贴到这里然后提交。</p>", "modal_googledriveauth_tutorial": "<p>请访问此网址,然后会进入授权流程。最后,您会看到一个码,请复制粘贴到这里然后提交。</p>",
"modal_googledriveauth_copybutton": "点击以复制网址", "modal_googledriveauth_copybutton": "点击以复制网址",
"modal_googledriveauth_copynotice": "网址已复制!", "modal_googledriveauth_copynotice": "网址已复制!",
@ -123,6 +140,29 @@
"modal_proauth_maualinput_notice": "正在连接,请稍候......", "modal_proauth_maualinput_notice": "正在连接,请稍候......",
"modal_proauth_maualinput_conn_fail": "连接失败", "modal_proauth_maualinput_conn_fail": "连接失败",
"modal_cleardupfiles_warning": "警告:插件只是简单地扫描所有文件名含有 .dup 的作为重复文件。另外,本操作只删除本地文件,因此您需要触发同步来删除远端文件。",
"modal_cleardupfiles_warning_confirm": "确认删除",
"modal_cleardupfiles_warning_finished": "所有检测到的重复文件已被删除!",
"settings_onedrivefull": "Onedrive个人版Full设置",
"settings_chooseservice_onedrivefull": "OneDrive个人版FullPRO",
"settings_onedrivefull_disclaimer1": "声明:此插件不是微软或 OneDrive 的官方产品。",
"settings_onedrivefull_disclaimer2": "声明:您所输入的信息存储于本地。其它有害的或者出错的插件,是有可能读取到这些信息的。如果您发现了 OneDrive 有不符合预期的访问,请立刻从 https://microsoft.com/consent 删除记录于此插件的连接鉴权。",
"settings_onedrivefull_folder": "我们会在您的 OneDrive 上创建此文件夹并在里面同步:/{{remoteBaseDir}}。",
"settings_onedrivefull_nobiz": "现在只支持个人版 OneDrive。暂时并不支持企业版 OneDrive。",
"settings_onedrivefull_revoke": "撤回鉴权",
"settings_onedrivefull_revoke_desc": "您现在使用了用户名 {{username}} 来连接。如果想取消连接,请点击此按钮。",
"settings_onedrivefull_revoke_button": "撤回鉴权",
"settings_onedrivefull_auth": "鉴权",
"settings_onedrivefull_auth_desc": "鉴权。",
"settings_onedrivefull_auth_button": "鉴权",
"settings_onedrivefull_connect_succ": "很好!我们可连接上 OneDrive",
"settings_onedrivefull_connect_fail": "我们未能连接上 OneDrive。",
"settings_onedrivefull_emptyfile": "空文件处理",
"settings_onedrivefull_emptyfile_desc": "OneDrive 不允许上传空文件(即使官网也是不允许的)。那么你想跳过空文件还是返回错误?",
"settings_onedrivefull_emptyfile_skip": "跳过",
"settings_onedrivefull_emptyfile_error": "返回错误和中断",
"settings_googledrive": "Google Drive (PRO) (beta)", "settings_googledrive": "Google Drive (PRO) (beta)",
"settings_chooseservice_googledrive": "Google Drive (PRO) (beta)", "settings_chooseservice_googledrive": "Google Drive (PRO) (beta)",
"settings_googledrive_disclaimer1": "声明:本插件不是 Google 的官方产品。只是用到了它的公开 API。", "settings_googledrive_disclaimer1": "声明:本插件不是 Google 的官方产品。只是用到了它的公开 API。",
@ -241,6 +281,7 @@
"settings_azureblobstorage_connect_succ": "很好!我们可连接上 Azure Blob Storage", "settings_azureblobstorage_connect_succ": "很好!我们可连接上 Azure Blob Storage",
"settings_azureblobstorage_connect_fail": "我们未能连接上 Azure Blob Storage。", "settings_azureblobstorage_connect_fail": "我们未能连接上 Azure Blob Storage。",
"settings_export_onedrivefull_button": "导出 OneDrive (Full) 部分",
"settings_export_googledrive_button": "导出 Google Drive 部分", "settings_export_googledrive_button": "导出 Google Drive 部分",
"settings_export_box_button": "导出 Box 部分", "settings_export_box_button": "导出 Box 部分",
"settings_export_pcloud_button": "导出 pCloud 部分", "settings_export_pcloud_button": "导出 pCloud 部分",
@ -248,6 +289,10 @@
"settings_export_koofr_button": "导出 Koofr 部分", "settings_export_koofr_button": "导出 Koofr 部分",
"settings_export_azureblobstorage_button": "导出 Azure Blob Storage 部分", "settings_export_azureblobstorage_button": "导出 Azure Blob Storage 部分",
"settings_cleardupfiles": "删除智能处理冲突生成的重复文件",
"settings_cleardupfiles_desc": "如果用过智能处理冲突 (PRO) 功能,插件可能会生成重复文件。<strong>如果您真的确认了所有重复文件都不需要了,</strong>那么可以删除本地的<strong>所有</strong>这些文件。",
"settings_cleardupfiles_button": "开始扫描",
"settings_pro": "账号PRO 付费功能)", "settings_pro": "账号PRO 付费功能)",
"settings_pro_tutorial": "<p>使用 Remotely Save 的<stong>基本</strong>功能是<strong>免费的</strong>,而且<strong>不</strong>需要注册对应账号。</p><p>但是,您<strong>需要</strong>注册账号和对<strong>PRO</strong>功能<strong>付费</strong>使用,如智能处理冲突功能。</p><p>第一步:点击按钮从而注册和登录网站:<a href=\"https://remotelysave.com\">https://remotelysave.com</a>。注意:这和 Obsidian 官方账号无关,是不同的账号。</p><p>第二部:点击“连接”按钮,从而连接本设备和在线账号。", "settings_pro_tutorial": "<p>使用 Remotely Save 的<stong>基本</strong>功能是<strong>免费的</strong>,而且<strong>不</strong>需要注册对应账号。</p><p>但是,您<strong>需要</strong>注册账号和对<strong>PRO</strong>功能<strong>付费</strong>使用,如智能处理冲突功能。</p><p>第一步:点击按钮从而注册和登录网站:<a href=\"https://remotelysave.com\">https://remotelysave.com</a>。注意:这和 Obsidian 官方账号无关,是不同的账号。</p><p>第二部:点击“连接”按钮,从而连接本设备和在线账号。",
"settings_pro_features": "功能", "settings_pro_features": "功能",

View File

@ -7,6 +7,11 @@
"protocol_pro_connect_fail": "Remotely Save 官網返回錯誤。可能是網路連線不穩定。也可能是您拒絕了授權?", "protocol_pro_connect_fail": "Remotely Save 官網返回錯誤。可能是網路連線不穩定。也可能是您拒絕了授權?",
"protocol_pro_connect_succ_revoke": "您已連線上賬號 {{email}}。如果要取消連線,請點選此按鈕。", "protocol_pro_connect_succ_revoke": "您已連線上賬號 {{email}}。如果要取消連線,請點選此按鈕。",
"protocol_onedrivefull_connecting": "正在連線 OneDrive……\n請不要關閉此彈窗。",
"protocol_onedrivefull_connect_succ_revoke": "您已作為使用者 {{username}} 連線上了。如果您想取消連線,請點選此按鈕。",
"protocol_onedrivefull_connect_fail": "OneDrive 的回撥請求有點異常。您是否拒絕了鑑權?",
"protocol_onedrivefull_connect_unknown": "不知道如何處理此 callback{{params}}",
"protocol_box_connecting": "正在連線", "protocol_box_connecting": "正在連線",
"protocol_box_connect_manualinput_succ": "連線成功", "protocol_box_connect_manualinput_succ": "連線成功",
"protocol_box_connect_fail": "Box 官網返回錯誤。可能是網路連線不穩定。也可能是您拒絕了授權?", "protocol_box_connect_fail": "Box 官網返回錯誤。可能是網路連線不穩定。也可能是您拒絕了授權?",
@ -27,6 +32,18 @@
"protocol_koofr_connect_fail": "Yandex Disk 官網返回錯誤。可能是網路連線不穩定。也可能是您拒絕了授權?", "protocol_koofr_connect_fail": "Yandex Disk 官網返回錯誤。可能是網路連線不穩定。也可能是您拒絕了授權?",
"protocol_koofr_connect_succ_revoke": "您已連線上賬號。如果要取消連線,請點選此按鈕。", "protocol_koofr_connect_succ_revoke": "您已連線上賬號。如果要取消連線,請點選此按鈕。",
"modal_onedrivefullauth_shortdesc": "現在只支援個人版 OneDrive不支援企業版。\n在瀏覽器中訪問以下地址然後按照網頁提示操作。\n到了最後您應該會被自動重定向回來 Obsidian。",
"modal_onedrivefullauth_shortdesc_linux": "您正在用 Linux有可能無法跳轉回來。請考慮<a href=\"https://github.com/remotely-save/remotely-save/issues/415\">使用</a> flatpack 版本的 Obsidian或建立 <a href=\"https://github.com/remotely-save/remotely-save/blob/master/docs/linux.md\"><code>obsidian.desktop</code> 檔案</a>。",
"modal_onedrivefullauth_copybutton": "點選此按鈕從而複製鑑權 url",
"modal_onedrivefullauth_copynotice": "鑑權 url 已複製到剪貼簿!",
"modal_onedrivefullrevokeauth_step1": "第 1 步用瀏覽器開啟以下地址點選本外掛對應的“Edit”按鈕點選“Remove these permissions”按鈕。",
"modal_onedrivefullrevokeauth_step2": "第 2 步:點選以下按鈕,清理本地儲存的登入資訊。",
"modal_onedrivefullrevokeauth_clean": "清理本地儲存的登入資訊",
"modal_onedrivefullrevokeauth_clean_desc": "您需要點選“清理”按鈕。",
"modal_onedrivefullrevokeauth_clean_button": "清理",
"modal_onedrivefullrevokeauth_clean_notice": "已清理!",
"modal_onedrivefullrevokeauth_clean_fail": "鑑權途中出錯了。",
"modal_googledriveauth_tutorial": "<p>請訪問此網址,然後會進入授權流程。最後,您會看到一個碼,請複製貼上到這裡然後提交。</p>", "modal_googledriveauth_tutorial": "<p>請訪問此網址,然後會進入授權流程。最後,您會看到一個碼,請複製貼上到這裡然後提交。</p>",
"modal_googledriveauth_copybutton": "點選以複製網址", "modal_googledriveauth_copybutton": "點選以複製網址",
"modal_googledriveauth_copynotice": "網址已複製!", "modal_googledriveauth_copynotice": "網址已複製!",
@ -123,6 +140,29 @@
"modal_proauth_maualinput_notice": "正在連線,請稍候......", "modal_proauth_maualinput_notice": "正在連線,請稍候......",
"modal_proauth_maualinput_conn_fail": "連線失敗", "modal_proauth_maualinput_conn_fail": "連線失敗",
"modal_cleardupfiles_warning": "警告:外掛只是簡單地掃描所有檔名含有 .dup 的作為重複檔案。另外,本操作只刪除本地檔案,因此您需要觸發同步來刪除遠端檔案。",
"modal_cleardupfiles_warning_confirm": "確認刪除",
"modal_cleardupfiles_warning_finished": "所有檢測到的重複檔案已被刪除!",
"settings_onedrivefull": "Onedrive個人版Full設定",
"settings_chooseservice_onedrivefull": "OneDrive個人版FullPRO",
"settings_onedrivefull_disclaimer1": "宣告:此外掛不是微軟或 OneDrive 的官方產品。",
"settings_onedrivefull_disclaimer2": "宣告:您所輸入的資訊儲存於本地。其它有害的或者出錯的外掛,是有可能讀取到這些資訊的。如果您發現了 OneDrive 有不符合預期的訪問,請立刻從 https://microsoft.com/consent 刪除記錄於此外掛的連線鑑權。",
"settings_onedrivefull_folder": "我們會在您的 OneDrive 上建立此資料夾並在裡面同步:/{{remoteBaseDir}}。",
"settings_onedrivefull_nobiz": "現在只支援個人版 OneDrive。暫時並不支援企業版 OneDrive。",
"settings_onedrivefull_revoke": "撤回鑑權",
"settings_onedrivefull_revoke_desc": "您現在使用了使用者名稱 {{username}} 來連線。如果想取消連線,請點選此按鈕。",
"settings_onedrivefull_revoke_button": "撤回鑑權",
"settings_onedrivefull_auth": "鑑權",
"settings_onedrivefull_auth_desc": "鑑權。",
"settings_onedrivefull_auth_button": "鑑權",
"settings_onedrivefull_connect_succ": "很好!我們可連線上 OneDrive",
"settings_onedrivefull_connect_fail": "我們未能連線上 OneDrive。",
"settings_onedrivefull_emptyfile": "空檔案處理",
"settings_onedrivefull_emptyfile_desc": "OneDrive 不允許上傳空檔案(即使官網也是不允許的)。那麼你想跳過空檔案還是返回錯誤?",
"settings_onedrivefull_emptyfile_skip": "跳過",
"settings_onedrivefull_emptyfile_error": "返回錯誤和中斷",
"settings_googledrive": "Google Drive (PRO) (beta)", "settings_googledrive": "Google Drive (PRO) (beta)",
"settings_chooseservice_googledrive": "Google Drive (PRO) (beta)", "settings_chooseservice_googledrive": "Google Drive (PRO) (beta)",
"settings_googledrive_disclaimer1": "宣告:本外掛不是 Google 的官方產品。只是用到了它的公開 API。", "settings_googledrive_disclaimer1": "宣告:本外掛不是 Google 的官方產品。只是用到了它的公開 API。",
@ -241,6 +281,7 @@
"settings_azureblobstorage_connect_succ": "很好!我們可連線上 Azure Blob Storage", "settings_azureblobstorage_connect_succ": "很好!我們可連線上 Azure Blob Storage",
"settings_azureblobstorage_connect_fail": "我們未能連線上 Azure Blob Storage。", "settings_azureblobstorage_connect_fail": "我們未能連線上 Azure Blob Storage。",
"settings_export_onedrivefull_button": "匯出 OneDrive (Full) 部分",
"settings_export_googledrive_button": "匯出 Google Drive 部分", "settings_export_googledrive_button": "匯出 Google Drive 部分",
"settings_export_box_button": "匯出 Box 部分", "settings_export_box_button": "匯出 Box 部分",
"settings_export_pcloud_button": "匯出 pCloud 部分", "settings_export_pcloud_button": "匯出 pCloud 部分",
@ -248,6 +289,10 @@
"settings_export_koofr_button": "匯出 Koofr 部分", "settings_export_koofr_button": "匯出 Koofr 部分",
"settings_export_azureblobstorage_button": "匯出 Azure Blob Storage 部分", "settings_export_azureblobstorage_button": "匯出 Azure Blob Storage 部分",
"settings_cleardupfiles": "刪除智慧處理衝突生成的重複檔案",
"settings_cleardupfiles_desc": "如果用過智慧處理衝突 (PRO) 功能,外掛可能會生成重複檔案。<strong>如果您真的確認了所有重複檔案都不需要了,</strong>那麼可以刪除本地的<strong>所有</strong>這些檔案。",
"settings_cleardupfiles_button": "開始掃描",
"settings_pro": "賬號PRO 付費功能)", "settings_pro": "賬號PRO 付費功能)",
"settings_pro_tutorial": "<p>使用 Remotely Save 的<stong>基本</strong>功能是<strong>免費的</strong>,而且<strong>不</strong>需要註冊對應賬號。</p><p>但是,您<strong>需要</strong>註冊賬號和對<strong>PRO</strong>功能<strong>付費</strong>使用,如智慧處理衝突功能。</p><p>第一步:點選按鈕從而註冊和登入網站:<a href=\"https://remotelysave.com\">https://remotelysave.com</a>。注意:這和 Obsidian 官方賬號無關,是不同的賬號。</p><p>第二部:點選“連線”按鈕,從而連線本裝置和線上賬號。", "settings_pro_tutorial": "<p>使用 Remotely Save 的<stong>基本</strong>功能是<strong>免費的</strong>,而且<strong>不</strong>需要註冊對應賬號。</p><p>但是,您<strong>需要</strong>註冊賬號和對<strong>PRO</strong>功能<strong>付費</strong>使用,如智慧處理衝突功能。</p><p>第一步:點選按鈕從而註冊和登入網站:<a href=\"https://remotelysave.com\">https://remotelysave.com</a>。注意:這和 Obsidian 官方賬號無關,是不同的賬號。</p><p>第二部:點選“連線”按鈕,從而連線本裝置和線上賬號。",
"settings_pro_features": "功能", "settings_pro_features": "功能",

View File

@ -0,0 +1,90 @@
import { type App, Modal, Notice, Setting } from "obsidian";
import { FakeFsLocal } from "../../src/fsLocal";
import type { TransItemType } from "../../src/i18n";
import type RemotelySavePlugin from "../../src/main";
import { stringToFragment } from "../../src/misc";
import { clearDupFiles, getDupFiles } from "./clearDupFiles";
class ClearDupFilesModal extends Modal {
readonly plugin: RemotelySavePlugin;
readonly t: (x: TransItemType, vars?: any) => string;
readonly files: string[];
readonly fsLocal: FakeFsLocal;
constructor(
app: App,
plugin: RemotelySavePlugin,
t: (x: TransItemType, vars?: any) => string,
files: string[],
fsLocal: FakeFsLocal
) {
super(app);
this.plugin = plugin;
this.t = t;
this.files = files;
this.fsLocal = fsLocal;
}
async onOpen() {
const t = this.t;
const { contentEl } = this;
contentEl.createEl("p", {
text: t("modal_cleardupfiles_warning"),
});
contentEl.createEl("pre").createEl("code", {
text: this.files.join("\n"),
});
new Setting(contentEl)
.addButton((button) => {
button.setButtonText(t("modal_cleardupfiles_warning_confirm"));
button.onClick(async () => {
await clearDupFiles(this.files, this.fsLocal);
new Notice(t("modal_cleardupfiles_warning_finished"));
this.close();
});
})
.addButton((button) => {
button.setButtonText(t("goback"));
button.onClick(() => {
this.close();
});
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
export const generateClearDupFilesSettingsPart = (
containerEl: HTMLElement,
t: (x: TransItemType, vars?: any) => string,
app: App,
plugin: RemotelySavePlugin
) => {
new Setting(containerEl)
.setName(t("settings_cleardupfiles"))
.setDesc(stringToFragment(t("settings_cleardupfiles_desc")))
.addButton(async (button) => {
button.setButtonText(t("settings_cleardupfiles_button"));
button.onClick(async () => {
const fsLocal = new FakeFsLocal(
app.vault,
plugin.settings.syncConfigDir ?? false,
plugin.settings.syncBookmarks ?? false,
app.vault.configDir,
plugin.manifest.id,
undefined,
plugin.settings.deleteToWhere ?? "system"
);
const files = await getDupFiles(fsLocal);
const modal = new ClearDupFilesModal(app, plugin, t, files, fsLocal);
modal.open();
});
});
};

View File

@ -95,6 +95,10 @@ class GoogleDriveAuthModal extends Modal {
k.expires_in * 1000; k.expires_in * 1000;
this.plugin.settings.googledrive.accessTokenExpiresAtTimeMs = this.plugin.settings.googledrive.accessTokenExpiresAtTimeMs =
ts + k.expires_in * 1000 - 60 * 2 * 1000; ts + k.expires_in * 1000 - 60 * 2 * 1000;
// manually set it expired after 60 days;
this.plugin.settings.googledrive.credentialsShouldBeDeletedAtTimeMs =
Date.now() + 1000 * 60 * 60 * 24 * 59;
await this.plugin.saveSettings(); await this.plugin.saveSettings();
// try to remove data in clipboard // try to remove data in clipboard

View File

@ -0,0 +1,337 @@
import cloneDeep from "lodash/cloneDeep";
import { type App, Modal, Notice, Platform, Setting } from "obsidian";
import { getClient } from "../../src/fsGetter";
import type { TransItemType } from "../../src/i18n";
import type RemotelySavePlugin from "../../src/main";
import { stringToFragment } from "../../src/misc";
import { ChangeRemoteBaseDirModal } from "../../src/settings";
import {
DEFAULT_ONEDRIVEFULL_CONFIG,
getAuthUrlAndVerifier as getAuthUrlAndVerifierOnedriveFull,
sendRefreshTokenReq as sendRefreshTokenReqOnedriveFull,
} from "./fsOnedriveFull";
export class OnedriveFullAuthModal extends Modal {
readonly plugin: RemotelySavePlugin;
readonly authDiv: HTMLDivElement;
readonly revokeAuthDiv: HTMLDivElement;
readonly revokeAuthSetting: Setting;
constructor(
app: App,
plugin: RemotelySavePlugin,
authDiv: HTMLDivElement,
revokeAuthDiv: HTMLDivElement,
revokeAuthSetting: Setting
) {
super(app);
this.plugin = plugin;
this.authDiv = authDiv;
this.revokeAuthDiv = revokeAuthDiv;
this.revokeAuthSetting = revokeAuthSetting;
}
async onOpen() {
const { contentEl } = this;
const { authUrl, verifier } = await getAuthUrlAndVerifierOnedriveFull(
this.plugin.settings.onedrivefull.clientID,
this.plugin.settings.onedrivefull.authority
);
this.plugin.oauth2Info.verifier = verifier;
const t = (x: TransItemType, vars?: any) => {
return this.plugin.i18n.t(x, vars);
};
t("modal_onedrivefullauth_shortdesc")
.split("\n")
.forEach((val) => {
contentEl.createEl("p", {
text: val,
});
});
if (Platform.isLinux) {
t("modal_onedrivefullauth_shortdesc_linux")
.split("\n")
.forEach((val) => {
contentEl.createEl("p", {
text: stringToFragment(val),
});
});
}
const div2 = contentEl.createDiv();
div2.createEl(
"button",
{
text: t("modal_onedrivefullauth_copybutton"),
},
(el) => {
el.onclick = async () => {
await navigator.clipboard.writeText(authUrl);
new Notice(t("modal_onedrivefullauth_copynotice"));
};
}
);
contentEl.createEl("p").createEl("a", {
href: authUrl,
text: authUrl,
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
export class OnedriveFullRevokeAuthModal extends Modal {
readonly plugin: RemotelySavePlugin;
readonly authDiv: HTMLDivElement;
readonly revokeAuthDiv: HTMLDivElement;
constructor(
app: App,
plugin: RemotelySavePlugin,
authDiv: HTMLDivElement,
revokeAuthDiv: HTMLDivElement
) {
super(app);
this.plugin = plugin;
this.authDiv = authDiv;
this.revokeAuthDiv = revokeAuthDiv;
}
async onOpen() {
const { contentEl } = this;
const t = (x: TransItemType, vars?: any) => {
return this.plugin.i18n.t(x, vars);
};
contentEl.createEl("p", {
text: t("modal_onedrivefullrevokeauth_step1"),
});
const consentUrl = "https://microsoft.com/consent";
contentEl.createEl("p").createEl("a", {
href: consentUrl,
text: consentUrl,
});
contentEl.createEl("p", {
text: t("modal_onedrivefullrevokeauth_step2"),
});
new Setting(contentEl)
.setName(t("modal_onedrivefullrevokeauth_clean"))
.setDesc(t("modal_onedrivefullrevokeauth_clean_desc"))
.addButton(async (button) => {
button.setButtonText(t("modal_onedrivefullrevokeauth_clean_button"));
button.onClick(async () => {
try {
this.plugin.settings.onedrivefull = JSON.parse(
JSON.stringify(DEFAULT_ONEDRIVEFULL_CONFIG)
);
await this.plugin.saveSettings();
this.authDiv.toggleClass(
"onedrivefull-auth-button-hide",
this.plugin.settings.onedrivefull.username !== ""
);
this.revokeAuthDiv.toggleClass(
"onedrivefull-revoke-auth-button-hide",
this.plugin.settings.onedrivefull.username === ""
);
new Notice(t("modal_onedrivefullrevokeauth_clean_notice"));
this.close();
} catch (err) {
console.error(err);
new Notice(t("modal_onedrivefullrevokeauth_clean_fail"));
}
});
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
export const generateOnedriveFullSettingsPart = (
containerEl: HTMLElement,
t: (x: TransItemType, vars?: any) => string,
app: App,
plugin: RemotelySavePlugin,
saveUpdatedConfigFunc: () => Promise<any> | undefined
) => {
const onedriveFullDiv = containerEl.createEl("div", {
cls: "onedrivefull-hide",
});
onedriveFullDiv.toggleClass(
"onedrivefull-hide",
plugin.settings.serviceType !== "onedrivefull"
);
onedriveFullDiv.createEl("h2", { text: t("settings_onedrivefull") });
const onedriveFullLongDescDiv = onedriveFullDiv.createEl("div", {
cls: "settings-long-desc",
});
for (const c of [
t("settings_onedrivefull_disclaimer1"),
t("settings_onedrivefull_disclaimer2"),
]) {
onedriveFullLongDescDiv.createEl("p", {
text: c,
cls: "onedrivefull-disclaimer",
});
}
onedriveFullLongDescDiv.createEl("p", {
text: t("settings_onedrivefull_folder", {
remoteBaseDir:
plugin.settings.onedrivefull.remoteBaseDir || app.vault.getName(),
}),
});
onedriveFullLongDescDiv.createEl("p", {
text: t("settings_onedrivefull_nobiz"),
});
onedriveFullLongDescDiv.createDiv({
text: stringToFragment(t("settings_onedrivefull_pro_desc")),
cls: "onedrivefull-disclaimer",
});
const onedriveFullNotShowUpHintSetting = new Setting(onedriveFullDiv)
.setName(t("settings_onedrivefull_notshowuphint"))
.setDesc(t("settings_onedrivefull_notshowuphint_desc"))
.addButton(async (button) => {
button.setButtonText(t("settings_onedrivefull_notshowuphint_view_pro"));
button.onClick(async () => {
window.location.href = "#settings-pro";
});
});
const onedriveFullAllowedToUsedDiv = onedriveFullDiv.createDiv();
// if pro enabled, show up; otherwise hide.
const allowOnedriveFull =
plugin.settings.pro?.enabledProFeatures.filter(
(x) => x.featureName === "feature-onedrive_full"
).length === 1;
console.debug(`allow to show up onedriveFull settings? ${allowOnedriveFull}`);
if (allowOnedriveFull) {
onedriveFullAllowedToUsedDiv.removeClass("onedrivefull-allow-to-use-hide");
onedriveFullNotShowUpHintSetting.settingEl.addClass(
"onedrivefull-allow-to-use-hide"
);
} else {
onedriveFullAllowedToUsedDiv.addClass("onedrivefull-allow-to-use-hide");
onedriveFullNotShowUpHintSetting.settingEl.removeClass(
"onedrivefull-allow-to-use-hide"
);
}
const onedriveFullSelectAuthDiv = onedriveFullAllowedToUsedDiv.createDiv();
const onedriveFullAuthDiv = onedriveFullSelectAuthDiv.createDiv({
cls: "onedrivefull-auth-button-hide settings-auth-related",
});
const onedriveFullRevokeAuthDiv = onedriveFullSelectAuthDiv.createDiv({
cls: "onedrivefull-revoke-auth-button-hide settings-auth-related",
});
const onedriveFullRevokeAuthSetting = new Setting(onedriveFullRevokeAuthDiv)
.setName(t("settings_onedrivefull_revoke"))
.setDesc(t("settings_onedrivefull_revoke_desc"))
.addButton(async (button) => {
button.setButtonText(t("settings_onedrivefull_revoke_button"));
button.onClick(async () => {
new OnedriveFullRevokeAuthModal(
app,
plugin,
onedriveFullAuthDiv,
onedriveFullRevokeAuthDiv
).open();
});
});
new Setting(onedriveFullAuthDiv)
.setName(t("settings_onedrivefull_auth"))
.setDesc(t("settings_onedrivefull_auth_desc"))
.addButton(async (button) => {
button.setButtonText(t("settings_onedrivefull_auth_button"));
button.onClick(async () => {
const modal = new OnedriveFullAuthModal(
app,
plugin,
onedriveFullAuthDiv,
onedriveFullRevokeAuthDiv,
onedriveFullRevokeAuthSetting
);
plugin.oauth2Info.helperModal = modal;
plugin.oauth2Info.authDiv = onedriveFullAuthDiv;
plugin.oauth2Info.revokeDiv = onedriveFullRevokeAuthDiv;
plugin.oauth2Info.revokeAuthSetting = onedriveFullRevokeAuthSetting;
modal.open();
});
});
onedriveFullAuthDiv.toggleClass(
"onedrivefull-auth-button-hide",
plugin.settings.onedrivefull.refreshToken !== ""
);
onedriveFullRevokeAuthDiv.toggleClass(
"onedrivefull-revoke-auth-button-hide",
plugin.settings.onedrivefull.refreshToken === ""
);
let newonedriveFullRemoteBaseDir =
plugin.settings.onedrivefull.remoteBaseDir || "";
new Setting(onedriveFullAllowedToUsedDiv)
.setName(t("settings_remotebasedir"))
.setDesc(t("settings_remotebasedir_desc"))
.addText((text) =>
text
.setPlaceholder(app.vault.getName())
.setValue(newonedriveFullRemoteBaseDir)
.onChange((value) => {
newonedriveFullRemoteBaseDir = value.trim();
})
)
.addButton((button) => {
button.setButtonText(t("confirm"));
button.onClick(() => {
new ChangeRemoteBaseDirModal(
app,
plugin,
newonedriveFullRemoteBaseDir,
"onedrivefull"
).open();
});
});
new Setting(onedriveFullAllowedToUsedDiv)
.setName(t("settings_checkonnectivity"))
.setDesc(t("settings_checkonnectivity_desc"))
.addButton(async (button) => {
button.setButtonText(t("settings_checkonnectivity_button"));
button.onClick(async () => {
new Notice(t("settings_checkonnectivity_checking"));
const client = getClient(plugin.settings, app.vault.getName(), () =>
plugin.saveSettings()
);
const errors = { msg: "" };
const res = await client.checkConnect((err: any) => {
errors.msg = `${err}`;
});
if (res) {
new Notice(t("settings_onedrivefull_connect_succ"));
} else {
new Notice(t("settings_onedrivefull_connect_fail"));
new Notice(errors.msg);
}
});
});
return {
onedriveFullDiv: onedriveFullDiv,
onedriveFullAllowedToUsedDiv: onedriveFullAllowedToUsedDiv,
onedriveFullNotShowUpHintSetting: onedriveFullNotShowUpHintSetting,
};
};

View File

@ -248,6 +248,8 @@ export const generateProSettingsPart = (
app: App, app: App,
plugin: RemotelySavePlugin, plugin: RemotelySavePlugin,
saveUpdatedConfigFunc: () => Promise<any> | undefined, saveUpdatedConfigFunc: () => Promise<any> | undefined,
onedriveFullAllowedToUsedDiv: HTMLDivElement,
onedriveFullNotShowUpHintSetting: Setting,
googleDriveAllowedToUsedDiv: HTMLDivElement, googleDriveAllowedToUsedDiv: HTMLDivElement,
googleDriveNotShowUpHintSetting: Setting, googleDriveNotShowUpHintSetting: Setting,
boxAllowedToUsedDiv: HTMLDivElement, boxAllowedToUsedDiv: HTMLDivElement,
@ -306,6 +308,27 @@ export const generateProSettingsPart = (
) )
); );
const allowOnedriveFull =
plugin.settings.pro?.enabledProFeatures.filter(
(x) => x.featureName === "feature-onedrive_full"
).length === 1;
console.debug(
`allow to show up OnedriveFull settings? ${allowOnedriveFull}`
);
if (allowOnedriveFull) {
onedriveFullAllowedToUsedDiv.removeClass(
"onedrivefull-allow-to-use-hide"
);
onedriveFullNotShowUpHintSetting.settingEl.addClass(
"onedrivefull-allow-to-use-hide"
);
} else {
onedriveFullAllowedToUsedDiv.addClass("onedrivefull-allow-to-use-hide");
onedriveFullNotShowUpHintSetting.settingEl.removeClass(
"onedrivefull-allow-to-use-hide"
);
}
const allowGoogleDrive = const allowGoogleDrive =
plugin.settings.pro?.enabledProFeatures.filter( plugin.settings.pro?.enabledProFeatures.filter(
(x) => x.featureName === "feature-google_drive" (x) => x.featureName === "feature-google_drive"

View File

@ -28,6 +28,8 @@ import {
} from "../../src/metadataOnRemote"; } from "../../src/metadataOnRemote";
import { import {
atWhichLevel, atWhichLevel,
checkValidName,
getFolderLevels,
getParentFolder, getParentFolder,
isHiddenPath, isHiddenPath,
isSpecialFolderNameToSkip, isSpecialFolderNameToSkip,
@ -36,7 +38,7 @@ import {
} from "../../src/misc"; } from "../../src/misc";
import type { Profiler } from "../../src/profiler"; import type { Profiler } from "../../src/profiler";
import { checkProRunnableAndFixInplace } from "./account"; import { checkProRunnableAndFixInplace } from "./account";
import { duplicateFile, isMergable, mergeFile } from "./conflictLogic"; import { isMergable, mergeFile, tryDuplicateFile } from "./conflictLogic";
import { import {
clearFileContentHistoryByVaultAndProfile, clearFileContentHistoryByVaultAndProfile,
getFileContentHistoryByVaultAndProfile, getFileContentHistoryByVaultAndProfile,
@ -59,6 +61,17 @@ const copyEntityAndFixTimeFormat = (
result.mtimeCliFmt = unixTimeToStr(result.mtimeCli); result.mtimeCliFmt = unixTimeToStr(result.mtimeCli);
} }
} }
if (result.ctimeCli !== undefined) {
if (result.ctimeCli === 0) {
result.ctimeCli = undefined;
} else {
if (serviceType === "s3" || serviceType === "dropbox") {
// round to second instead of millisecond
result.ctimeCli = Math.floor(result.ctimeCli / 1000.0) * 1000;
}
result.ctimeCliFmt = unixTimeToStr(result.ctimeCli);
}
}
if (result.mtimeSvr !== undefined) { if (result.mtimeSvr !== undefined) {
if (result.mtimeSvr === 0) { if (result.mtimeSvr === 0) {
result.mtimeSvr = undefined; result.mtimeSvr = undefined;
@ -116,37 +129,229 @@ const isInsideObsFolder = (x: string, configDir: string) => {
return x === configDir || x.startsWith(`${configDir}/`); return x === configDir || x.startsWith(`${configDir}/`);
}; };
const isSkipItemByName = ( const isBookmarksFile = (x: string, configDir: string) => {
if (!configDir.startsWith(".")) {
throw Error(`configDir should starts with . but we get ${configDir}`);
}
return (
x === configDir ||
x === `${configDir}/` ||
x === `${configDir}/bookmarks.json`
);
};
interface IsSkipResult {
enableAllowMode: boolean;
isExplictlyAllowed: boolean;
isExplictlyIgnored: boolean;
finalIsIgnored: boolean;
}
export const checkIsSkipItemOrNotByName = (
key: string, key: string,
syncConfigDir: boolean, syncConfigDir: boolean,
syncBookmarks: boolean,
syncUnderscoreItems: boolean, syncUnderscoreItems: boolean,
configDir: string, configDir: string,
ignorePaths: string[] ignorePaths: string[],
) => { onlyAllowPaths: string[]
): IsSkipResult => {
if (key === undefined) { if (key === undefined) {
throw Error(`isSkipItemByName meets undefinded key!`); throw Error(`checkIsSkipItemOrNotByName meets undefinded key!`);
} }
if (ignorePaths !== undefined && ignorePaths.length > 0) {
for (const r of ignorePaths) { let finalIsIgnored: boolean | undefined = undefined;
let enableAllowMode = false;
let isExplictlyAllowed = false;
if (onlyAllowPaths !== undefined && onlyAllowPaths.length > 0) {
for (const r of onlyAllowPaths) {
if (r.trim() === "") {
// ignore empty lines
continue;
}
enableAllowMode = true; // we really want to check the allow list
if (XRegExp(r, "A").test(key)) { if (XRegExp(r, "A").test(key)) {
return true; isExplictlyAllowed = true;
} }
} }
} }
if (syncConfigDir && isInsideObsFolder(key, configDir)) { // we want to determine "is skippable or not".
return false; // if the key meets the allow list,
// it may or may not be skippable,
// and is deferred to next checking steps
// if the key doesn't meet the allow list,
// it must be skippable.
if (enableAllowMode && !isExplictlyAllowed) {
finalIsIgnored = true; // must be skippable
} }
let isExplictlyIgnored = false;
if (ignorePaths !== undefined && ignorePaths.length > 0) {
for (const r of ignorePaths) {
if (r.trim() === "") {
// ignore empty lines
continue;
}
if (XRegExp(r, "A").test(key)) {
if (finalIsIgnored === undefined) {
isExplictlyIgnored = true;
finalIsIgnored = true;
}
}
}
}
// sync config, not sync bookmarks: sync config and **force syncing bookmarks as well**
// not sync config, sync bookmarks: sync bookmars, not other config
// not sync config, not sync bookmarks: not sync config
if (finalIsIgnored === undefined) {
if (syncConfigDir) {
if (isInsideObsFolder(key, configDir)) {
// force sync everything
finalIsIgnored = false;
} else {
// not config files, do not judge now, do nothing
}
} else if (syncBookmarks) {
// not sync config, sync bookmarks
if (isBookmarksFile(key, configDir)) {
// sync everything of bookmarks
finalIsIgnored = false;
} else if (isInsideObsFolder(key, configDir)) {
// not sync any other thing in config
finalIsIgnored = true;
} else {
// not config files, do not judge now, do nothing
}
} else {
// not sync config, and not sync bookmarks
if (isInsideObsFolder(key, configDir)) {
// not sync any thing in config
finalIsIgnored = true;
} else {
// not config files, do not judge now, do nothing
}
}
}
if (isSpecialFolderNameToSkip(key, [])) { if (isSpecialFolderNameToSkip(key, [])) {
// some special dirs and files are always skipped // some special dirs and files are always skipped
return true; if (finalIsIgnored === undefined) {
isExplictlyIgnored = true;
finalIsIgnored = true;
}
} }
return (
const checkIsHidden =
isHiddenPath(key, true, false) || isHiddenPath(key, true, false) ||
(!syncUnderscoreItems && isHiddenPath(key, false, true)) || (!syncUnderscoreItems && isHiddenPath(key, false, true)) ||
key === "/" || key === "/" ||
key === DEFAULT_FILE_NAME_FOR_METADATAONREMOTE || key === DEFAULT_FILE_NAME_FOR_METADATAONREMOTE ||
key === DEFAULT_FILE_NAME_FOR_METADATAONREMOTE2 key === DEFAULT_FILE_NAME_FOR_METADATAONREMOTE2;
); if (finalIsIgnored === undefined) {
isExplictlyIgnored = checkIsHidden;
finalIsIgnored = checkIsHidden;
}
if (finalIsIgnored === undefined) {
throw Error(`no finalIsIgnored in checkIsSkipItemOrNotByName for ${key}`);
}
return {
enableAllowMode: enableAllowMode,
isExplictlyAllowed: isExplictlyAllowed,
isExplictlyIgnored: isExplictlyIgnored,
finalIsIgnored: finalIsIgnored,
};
};
/**
* | finalIgnored | reason | explictlyIgnored | allowMode | explictlyAllowed |
* | ------------------------------- | -------------------------------------------- | ---------------- | --------- | ---------------- |
* | no | nothing blocking | no | no | no |
* | yes, MAY be changed by children | allow mode not allowed, inexplicitly ignored | no | yes | no |
* | no, MAY apply to parents | allow mode allowed | no | yes | yes |
* | yes, also apply to children | explictly ignored | yes | no | no |
* | yes, also apply to children | explictly ignored | yes | yes | no |
* | yes, also apply to children | explictly ignored | yes | yes | yes |
*/
export const getSkipItemsByList = (
skipOrNotResults: Record<string, IsSkipResult>
): string[] => {
const allPotentialKeys = Object.keys(skipOrNotResults);
// from short(shadow) to long(deep) , ascending
const sortedKeys = allPotentialKeys.sort((k1, k2) => k1.length - k2.length);
// we deal with explicty ignored list firstly, apply them to children
const explictlyIgnoredSet = new Set<string>();
for (const key of sortedKeys) {
if (skipOrNotResults[key].isExplictlyIgnored) {
skipOrNotResults[key].finalIsIgnored = true;
explictlyIgnoredSet.add(key);
} else {
const parents = getFolderLevels(key, true).reverse();
for (const key2 of parents) {
if (explictlyIgnoredSet.has(key2)) {
skipOrNotResults[key].isExplictlyIgnored = true;
skipOrNotResults[key].finalIsIgnored = true;
explictlyIgnoredSet.add(key);
break;
}
}
}
}
// we deal with explictly allow list secondly, apply them to PARENTS if possible
let enableAllowMode = false;
if (
allPotentialKeys.length > 0 &&
allPotentialKeys[0] !== undefined &&
skipOrNotResults[allPotentialKeys[0]] !== undefined
) {
enableAllowMode = skipOrNotResults[allPotentialKeys[0]].enableAllowMode;
}
if (enableAllowMode) {
for (let index = 0; index < sortedKeys.length; index++) {
// reverse order, long(deep) to short(shadow), ascending
const key = sortedKeys[sortedKeys.length - index - 1];
if (
!skipOrNotResults[key].isExplictlyIgnored &&
skipOrNotResults[key].isExplictlyAllowed
) {
// the file is explictly allowed, and not explictly ignored by anywhere
// we allow all its parents!
const parents = getFolderLevels(key, true).reverse();
for (const key2 of parents) {
if (
key2 in skipOrNotResults &&
!skipOrNotResults[key2].isExplictlyIgnored &&
!explictlyIgnoredSet.has(key2)
) {
skipOrNotResults[key2].isExplictlyAllowed = true;
skipOrNotResults[key2].finalIsIgnored = false; // from ignored to allowed
} else {
throw Error(
`${key}'s parent ${key2} in abnormal state: ${JSON.stringify(skipOrNotResults[key2])}`
);
}
}
}
}
}
// get all finalIsIgnored
const result: string[] = [];
for (const key of sortedKeys) {
if (skipOrNotResults[key].finalIsIgnored) {
result.push(key);
}
}
console.debug(`finalIsIgnored list= ${JSON.stringify(result)}`);
return result;
}; };
export type SyncPlanType = Record<string, MixedEntity>; export type SyncPlanType = Record<string, MixedEntity>;
@ -157,9 +362,11 @@ const ensembleMixedEnties = async (
remoteEntityList: Entity[], remoteEntityList: Entity[],
syncConfigDir: boolean, syncConfigDir: boolean,
syncBookmarks: boolean,
configDir: string, configDir: string,
syncUnderscoreItems: boolean, syncUnderscoreItems: boolean,
ignorePaths: string[], ignorePaths: string[],
onlyAllowPaths: string[],
fsEncrypt: FakeFsEncrypt, fsEncrypt: FakeFsEncrypt,
serviceType: SUPPORTED_SERVICES_TYPE, serviceType: SUPPORTED_SERVICES_TYPE,
@ -173,25 +380,40 @@ const ensembleMixedEnties = async (
const finalMappings: SyncPlanType = {}; const finalMappings: SyncPlanType = {};
const skipOrNotResults: Record<string, IsSkipResult> = {};
// remote has to be first // remote has to be first
let remoteMaySkipCountAndNotConfig = 0;
for (const remote of remoteEntityList) { for (const remote of remoteEntityList) {
const remoteCopied = ensureMTimeOfRemoteEntityValid( const remoteCopied = ensureMTimeOfRemoteEntityValid(
copyEntityAndFixTimeFormat(remote, serviceType) copyEntityAndFixTimeFormat(remote, serviceType)
); );
const key = remoteCopied.key!; const key = remoteCopied.key!;
if (
isSkipItemByName( const skipOrNot = checkIsSkipItemOrNotByName(
key, key,
syncConfigDir, syncConfigDir,
syncUnderscoreItems, syncBookmarks,
configDir, syncUnderscoreItems,
ignorePaths configDir,
) ignorePaths,
) { onlyAllowPaths
continue; );
skipOrNotResults[key] = skipOrNot;
if (skipOrNot.finalIsIgnored && !key.startsWith(configDir)) {
remoteMaySkipCountAndNotConfig += 1;
} }
// 20240907: users (not on windows) doesn't like it. revert back now.
// TODO: platform specific but not introducing obsidian dependency into sync.ts
// const checkValidNameResult = checkValidName(key);
// if (!checkValidNameResult.result) {
// throw Error(
// `your remote folder/file name is invalid: ${checkValidNameResult.reason}`
// );
// }
finalMappings[key] = { finalMappings[key] = {
key: key, key: key,
remote: remoteCopied, remote: remoteCopied,
@ -201,27 +423,34 @@ const ensembleMixedEnties = async (
profiler?.insert("ensembleMixedEnties: finish remote"); profiler?.insert("ensembleMixedEnties: finish remote");
profiler?.insertSize("sizeof finalMappings", finalMappings); profiler?.insertSize("sizeof finalMappings", finalMappings);
if (Object.keys(finalMappings).length === 0 || localEntityList.length === 0) { if (
Object.keys(finalMappings).filter((k) => !k.startsWith(configDir)).length -
remoteMaySkipCountAndNotConfig ===
0 ||
localEntityList.filter((e) => !e.key?.startsWith(configDir)).length === 0
) {
// Special checking: // Special checking:
// if one side is totally empty, // if one side is totally empty,
// usually that's a hard rest. // usually that's a hard rest.
// So we need to ignore everything of prevSyncEntityList to avoid deletions! // So we need to ignore everything of prevSyncEntityList to avoid deletions!
// TODO: acutally erase everything of prevSyncEntityList? // TODO: acutally erase everything of prevSyncEntityList?
// TODO: local should also go through a isSkipItemByName checking beforehand // TODO: local should also go through a checkIsSkipItemOrNotByName checking beforehand
} else { } else {
// normally go through the prevSyncEntityList // normally go through the prevSyncEntityList
for (const prevSync of prevSyncEntityList) { for (const prevSync of prevSyncEntityList) {
const key = prevSync.key!; const key = prevSync.key!;
if (
isSkipItemByName( if (!(key in skipOrNotResults)) {
const skipOrNot = checkIsSkipItemOrNotByName(
key, key,
syncConfigDir, syncConfigDir,
syncBookmarks,
syncUnderscoreItems, syncUnderscoreItems,
configDir, configDir,
ignorePaths ignorePaths,
) onlyAllowPaths
) { );
continue; skipOrNotResults[key] = skipOrNot;
} }
// TODO: abstraction leaking? // TODO: abstraction leaking?
@ -247,18 +476,29 @@ const ensembleMixedEnties = async (
// (we don't consume prevSync here because it gains no benefit) // (we don't consume prevSync here because it gains no benefit)
for (const local of localEntityList) { for (const local of localEntityList) {
const key = local.key!; const key = local.key!;
if (
isSkipItemByName( if (!(key in skipOrNotResults)) {
const skipOrNot = checkIsSkipItemOrNotByName(
key, key,
syncConfigDir, syncConfigDir,
syncBookmarks,
syncUnderscoreItems, syncUnderscoreItems,
configDir, configDir,
ignorePaths ignorePaths,
) onlyAllowPaths
) { );
continue; skipOrNotResults[key] = skipOrNot;
} }
// 20240907: users (not on windows) doesn't like it. revert back now.
// TODO: platform specific but not introducing obsidian dependency into sync.ts
// const checkValidNameResult = checkValidName(key);
// if (!checkValidNameResult.result) {
// throw Error(
// `your local folder/file name is invalid: ${checkValidNameResult.reason}`
// );
// }
// TODO: abstraction leaking? // TODO: abstraction leaking?
const localCopied = await fsEncrypt.encryptEntity( const localCopied = await fsEncrypt.encryptEntity(
copyEntityAndFixTimeFormat(local, serviceType) copyEntityAndFixTimeFormat(local, serviceType)
@ -276,6 +516,15 @@ const ensembleMixedEnties = async (
profiler?.insert("ensembleMixedEnties: finish local"); profiler?.insert("ensembleMixedEnties: finish local");
profiler?.insertSize("sizeof finalMappings", finalMappings); profiler?.insertSize("sizeof finalMappings", finalMappings);
// we check the skipOrNotResults again! in case we adjust some paths!
const allReallySkipKeys = getSkipItemsByList(skipOrNotResults);
for (const key of allReallySkipKeys) {
delete finalMappings[key];
}
profiler?.insert("ensembleMixedEnties: finish parsing all skip items");
profiler?.insertSize("sizeof finalMappings", finalMappings);
// console.debug("in the end of ensembleMixedEnties, finalMappings is:"); // console.debug("in the end of ensembleMixedEnties, finalMappings is:");
// console.debug(finalMappings); // console.debug(finalMappings);
@ -296,11 +545,12 @@ const getSyncPlanInplace = async (
syncDirection: SyncDirectionType, syncDirection: SyncDirectionType,
profiler: Profiler | undefined, profiler: Profiler | undefined,
settings: RemotelySavePluginSettings, settings: RemotelySavePluginSettings,
triggerSource: SyncTriggerSourceType triggerSource: SyncTriggerSourceType,
configDir: string
) => { ) => {
profiler?.addIndent(); profiler?.addIndent();
profiler?.insert("getSyncPlanInplace: enter"); profiler?.insert("getSyncPlanInplace: enter");
// from long(deep) to short(shadow) // from long(deep) to short(shadow), descending
const sortedKeys = Object.keys(mixedEntityMappings).sort( const sortedKeys = Object.keys(mixedEntityMappings).sort(
(k1, k2) => k2.length - k1.length (k1, k2) => k2.length - k1.length
); );
@ -393,14 +643,36 @@ const getSyncPlanInplace = async (
mixedEntry.change = false; mixedEntry.change = false;
keptFolder.add(getParentFolder(key)); keptFolder.add(getParentFolder(key));
} else if (syncDirection === "incremental_pull_and_delete_only") { } else if (syncDirection === "incremental_pull_and_delete_only") {
mixedEntry.decisionBranch = 135; if (
mixedEntry.decision = "folder_to_be_deleted_on_local"; key === `${configDir}/` ||
mixedEntry.change = true; key === `${configDir}/bookmarks.json`
) {
// special: never delete .obsidian folder!
mixedEntry.decisionBranch = 137;
mixedEntry.decision = "folder_existed_both_then_do_nothing";
mixedEntry.change = false;
keptFolder.add(getParentFolder(key));
} else {
mixedEntry.decisionBranch = 135;
mixedEntry.decision = "folder_to_be_deleted_on_local";
mixedEntry.change = true;
}
} else { } else {
// bidirectional // bidirectional
mixedEntry.decisionBranch = 124; if (
mixedEntry.decision = "folder_to_be_deleted_on_local"; key === `${configDir}/` ||
mixedEntry.change = true; key === `${configDir}/bookmarks.json`
) {
// special: never delete .obsidian folder!
mixedEntry.decisionBranch = 138;
mixedEntry.decision = "folder_existed_both_then_do_nothing";
mixedEntry.change = false;
keptFolder.add(getParentFolder(key));
} else {
mixedEntry.decisionBranch = 124;
mixedEntry.decision = "folder_to_be_deleted_on_local";
mixedEntry.change = true;
}
} }
} else { } else {
// then the folder is created on local // then the folder is created on local
@ -582,7 +854,11 @@ const getSyncPlanInplace = async (
if (prevSync === undefined) { if (prevSync === undefined) {
// Didn't exist means both are new // Didn't exist means both are new
if (syncDirection === "bidirectional") { if (syncDirection === "bidirectional") {
if (conflictAction === "keep_newer") { if (
conflictAction === "keep_newer" ||
(conflictAction === "smart_conflict" &&
key.startsWith(`${configDir}/`))
) {
if ( if (
(local.mtimeCli ?? local.mtimeSvr ?? 0) >= (local.mtimeCli ?? local.mtimeSvr ?? 0) >=
(remote.mtimeCli ?? remote.mtimeSvr ?? 0) (remote.mtimeCli ?? remote.mtimeSvr ?? 0)
@ -640,7 +916,11 @@ const getSyncPlanInplace = async (
} else { } else {
// Both exist but don't compare means both are modified // Both exist but don't compare means both are modified
if (syncDirection === "bidirectional") { if (syncDirection === "bidirectional") {
if (conflictAction === "keep_newer") { if (
conflictAction === "keep_newer" ||
(conflictAction === "smart_conflict" &&
key.startsWith(`${configDir}/`))
) {
if ( if (
(local.mtimeCli ?? local.mtimeSvr ?? 0) >= (local.mtimeCli ?? local.mtimeSvr ?? 0) >=
(remote.mtimeCli ?? remote.mtimeSvr ?? 0) (remote.mtimeCli ?? remote.mtimeSvr ?? 0)
@ -834,13 +1114,35 @@ const getSyncPlanInplace = async (
mixedEntry.decision = "conflict_created_then_do_nothing"; mixedEntry.decision = "conflict_created_then_do_nothing";
mixedEntry.change = false; mixedEntry.change = false;
} else if (syncDirection === "incremental_pull_and_delete_only") { } else if (syncDirection === "incremental_pull_and_delete_only") {
mixedEntry.decisionBranch = 39; if (
mixedEntry.decision = "remote_is_deleted_thus_also_delete_local"; key === `${configDir}/` ||
mixedEntry.change = true; key === `${configDir}/bookmarks.json`
) {
// special: never delete .obsidian/bookmarks.json file!
mixedEntry.decisionBranch = 139;
mixedEntry.decision = "conflict_created_then_keep_local";
mixedEntry.change = true;
keptFolder.add(getParentFolder(key));
} else {
mixedEntry.decisionBranch = 39;
mixedEntry.decision = "remote_is_deleted_thus_also_delete_local";
mixedEntry.change = true;
}
} else { } else {
mixedEntry.decisionBranch = 7; if (
mixedEntry.decision = "remote_is_deleted_thus_also_delete_local"; key === `${configDir}/` ||
mixedEntry.change = true; key === `${configDir}/bookmarks.json`
) {
// special: never delete .obsidian/bookmarks.json file!
mixedEntry.decisionBranch = 140;
mixedEntry.decision = "conflict_created_then_keep_local";
mixedEntry.change = true;
keptFolder.add(getParentFolder(key));
} else {
mixedEntry.decisionBranch = 7;
mixedEntry.decision = "remote_is_deleted_thus_also_delete_local";
mixedEntry.change = true;
}
} }
} else { } else {
// if A is in the previous list and MODIFIED, A has been deleted by B but modified by A // if A is in the previous list and MODIFIED, A has been deleted by B but modified by A
@ -890,6 +1192,8 @@ const getSyncPlanInplace = async (
keptFolder.delete("/"); keptFolder.delete("/");
keptFolder.delete(""); keptFolder.delete("");
if (keptFolder.size > 0) { if (keptFolder.size > 0) {
console.error(sortedKeys);
console.error(mixedEntityMappings);
throw Error(`unexpectedly keptFolder no decisions: ${[...keptFolder]}`); throw Error(`unexpectedly keptFolder no decisions: ${[...keptFolder]}`);
} }
@ -902,13 +1206,14 @@ const getSyncPlanInplace = async (
mixedEntityMappings["/$@meta"] = { mixedEntityMappings["/$@meta"] = {
key: "/$@meta", // don't mess up with the types key: "/$@meta", // don't mess up with the types
sideNotes: { sideNotes: {
version: "20240616 fs version", version: "20240714 fs version",
generateTime: currTime, generateTime: currTime,
generateTimeFmt: currTimeFmt, generateTimeFmt: currTimeFmt,
service: settings.serviceType, service: settings.serviceType,
concurrency: settings.concurrency, concurrency: settings.concurrency,
hasPassword: settings.password !== "", hasPassword: settings.password !== "",
syncConfigDir: settings.syncConfigDir, syncConfigDir: settings.syncConfigDir,
syncBookmarks: settings.syncBookmarks,
syncUnderscoreItems: settings.syncUnderscoreItems, syncUnderscoreItems: settings.syncUnderscoreItems,
skipSizeLargerThan: settings.skipSizeLargerThan, skipSizeLargerThan: settings.skipSizeLargerThan,
protectModifyPercentage: settings.protectModifyPercentage, protectModifyPercentage: settings.protectModifyPercentage,
@ -1342,27 +1647,31 @@ const dispatchOperationToActualV3 = async (
r.key r.key
); );
const mtimeCli = (await fsLocal.stat(r.key)).mtimeCli!; const mtimeCli = (await fsLocal.stat(r.key)).mtimeCli!;
const { upload, download } = await duplicateFile( await tryDuplicateFile(
r.key, r.key,
fsLocal, fsLocal,
fsEncrypt, fsEncrypt,
async (upload) => { async (upload) => {
// TODO: abstract away the dirty hack if (upload !== undefined) {
fullfillMTimeOfRemoteEntityInplace(upload, mtimeCli); // TODO: abstract away the dirty hack
await upsertPrevSyncRecordByVaultAndProfile( fullfillMTimeOfRemoteEntityInplace(upload, mtimeCli);
db, await upsertPrevSyncRecordByVaultAndProfile(
vaultRandomID, db,
profileID, vaultRandomID,
upload profileID,
); upload
);
}
}, },
async (download) => { async (download) => {
await upsertPrevSyncRecordByVaultAndProfile( if (download !== undefined) {
db, await upsertPrevSyncRecordByVaultAndProfile(
vaultRandomID, db,
profileID, vaultRandomID,
download profileID,
); download
);
}
} }
); );
} }
@ -1621,7 +1930,7 @@ export async function syncer(
) => any, ) => any,
callbackSyncProcess?: any callbackSyncProcess?: any
) { ) {
console.info(`startting sync.`); console.info(`starting sync.`);
markIsSyncingFunc(true); markIsSyncingFunc(true);
let everythingOk = true; let everythingOk = true;
@ -1696,9 +2005,11 @@ export async function syncer(
prevSyncEntityList, prevSyncEntityList,
remoteEntityList, remoteEntityList,
settings.syncConfigDir ?? false, settings.syncConfigDir ?? false,
settings.syncBookmarks ?? false,
configDir, configDir,
settings.syncUnderscoreItems ?? false, settings.syncUnderscoreItems ?? false,
settings.ignorePaths ?? [], settings.ignorePaths ?? [],
settings.onlyAllowPaths ?? [],
fsEncrypt, fsEncrypt,
settings.serviceType, settings.serviceType,
profiler profiler
@ -1712,7 +2023,8 @@ export async function syncer(
settings.syncDirection ?? "bidirectional", settings.syncDirection ?? "bidirectional",
profiler, profiler,
settings, settings,
triggerSource triggerSource,
configDir
); );
console.debug(`mixedEntityMappings:`); console.debug(`mixedEntityMappings:`);
console.debug(mixedEntityMappings); // for debugging console.debug(mixedEntityMappings); // for debugging
@ -1777,6 +2089,6 @@ export async function syncer(
await ribboonFunc?.(triggerSource, step); await ribboonFunc?.(triggerSource, step);
await statusBarFunc?.(triggerSource, step, everythingOk); await statusBarFunc?.(triggerSource, step, everythingOk);
console.info(`endding sync.`); console.info(`ending sync.`);
markIsSyncingFunc(false); markIsSyncingFunc(false);
} }

View File

@ -1,68 +1,296 @@
import { deepStrictEqual, rejects, throws } from "assert"; import { deepStrictEqual, rejects, throws } from "assert";
import { getFileRename } from "../src/conflictLogic"; import {
getFileRenameForDup,
threeWayMerge,
twoWayMerge,
} from "../src/conflictLogic";
describe("New name is generated", () => { describe("New name is generated", () => {
it("should throw for empty file", async () => { it("should throw for empty file", async () => {
for (const key of ["", "/", ".", ".."]) { for (const key of ["", "/", ".", ".."]) {
throws(() => getFileRename(key)); throws(() => getFileRenameForDup(key));
} }
}); });
it("should throw for folder", async () => { it("should throw for folder", async () => {
for (const key of ["sss/", "ssss/yyy/"]) { for (const key of ["sss/", "ssss/yyy/"]) {
throws(() => getFileRename(key)); throws(() => getFileRenameForDup(key));
} }
}); });
it("should correctly get no ext files renamed", async () => { it("should correctly get no ext files renamed", async () => {
deepStrictEqual(getFileRename("abc"), "abc.dup"); deepStrictEqual(getFileRenameForDup("abc"), "abc.dup");
deepStrictEqual(getFileRename("xxxx/yyyy/abc"), "xxxx/yyyy/abc.dup"); deepStrictEqual(getFileRenameForDup("xxxx/yyyy/abc"), "xxxx/yyyy/abc.dup");
}); });
it("should correctly get dot files renamed", async () => { it("should correctly get dot files renamed", async () => {
deepStrictEqual(getFileRename(".abc"), ".abc.dup"); deepStrictEqual(getFileRenameForDup(".abc"), ".abc.dup");
deepStrictEqual(getFileRename("xxxx/yyyy/.efg"), "xxxx/yyyy/.efg.dup"); deepStrictEqual(
getFileRenameForDup("xxxx/yyyy/.efg"),
"xxxx/yyyy/.efg.dup"
);
deepStrictEqual(getFileRename("xxxx/yyyy/hij."), "xxxx/yyyy/hij.dup"); deepStrictEqual(getFileRenameForDup("xxxx/yyyy/hij."), "xxxx/yyyy/hij.dup");
}); });
it("should correctly get normal files renamed", async () => { it("should correctly get normal files renamed", async () => {
deepStrictEqual(getFileRename("abc.efg"), "abc.dup.efg"); deepStrictEqual(getFileRenameForDup("abc.efg"), "abc.dup.efg");
deepStrictEqual( deepStrictEqual(
getFileRename("xxxx/yyyy/abc.efg"), getFileRenameForDup("xxxx/yyyy/abc.efg"),
"xxxx/yyyy/abc.dup.efg" "xxxx/yyyy/abc.dup.efg"
); );
deepStrictEqual( deepStrictEqual(
getFileRename("xxxx/yyyy/abc.tar.gz"), getFileRenameForDup("xxxx/yyyy/abc.tar.gz"),
"xxxx/yyyy/abc.tar.dup.gz" "xxxx/yyyy/abc.tar.dup.gz"
); );
deepStrictEqual( deepStrictEqual(
getFileRename("xxxx/yyyy/.abc.efg"), getFileRenameForDup("xxxx/yyyy/.abc.efg"),
"xxxx/yyyy/.abc.dup.efg" "xxxx/yyyy/.abc.dup.efg"
); );
}); });
it("should correctly get duplicated files renamed again", async () => { it("should correctly get duplicated files renamed again", async () => {
deepStrictEqual(getFileRename("abc.dup"), "abc.dup.dup"); deepStrictEqual(getFileRenameForDup("abc.dup"), "abc.dup.dup");
deepStrictEqual( deepStrictEqual(
getFileRename("xxxx/yyyy/.abc.dup"), getFileRenameForDup("xxxx/yyyy/.abc.dup"),
"xxxx/yyyy/.abc.dup.dup" "xxxx/yyyy/.abc.dup.dup"
); );
deepStrictEqual( deepStrictEqual(
getFileRename("xxxx/yyyy/abc.dup.md"), getFileRenameForDup("xxxx/yyyy/abc.dup.md"),
"xxxx/yyyy/abc.dup.dup.md" "xxxx/yyyy/abc.dup.dup.md"
); );
deepStrictEqual( deepStrictEqual(
getFileRename("xxxx/yyyy/.abc.dup.md"), getFileRenameForDup("xxxx/yyyy/.abc.dup.md"),
"xxxx/yyyy/.abc.dup.dup.md" "xxxx/yyyy/.abc.dup.dup.md"
); );
}); });
}); });
describe("Two way merge", () => {
it("should correctly merge from zero files", async () => {
const a = "aaa";
const b = "bbb";
const res = twoWayMerge(a, b);
const expected = `\`<<<<<<<\`
aaa
\`=======\`
bbb
\`>>>>>>>\``;
deepStrictEqual(expected, res);
});
it("should correctly merge from common lines", async () => {
const a = `
Something is cool. 1
Other thing is cooler.
`;
const b = `
Anything is cool. 2
Other thing is cooler.
`;
const res = twoWayMerge(a, b);
// console.log(res);
const expected = `
\`<<<<<<<\`
Something is cool. 1
\`=======\`
Anything is cool. 2
\`>>>>>>>\`
Other thing is cooler.
`;
deepStrictEqual(expected, res);
});
it("should merge by lines", async () => {
const a = `
Something is cool. 1
`;
const b = `
Something is cooler. 2
`;
const res = twoWayMerge(a, b);
// console.log(res);
const expected = `
\`<<<<<<<\`
Something is cool. 1
\`=======\`
Something is cooler. 2
\`>>>>>>>\`
`;
deepStrictEqual(expected, res);
});
});
describe("Three way merge", () => {
it("should correctly merge from zero files", async () => {
const orig = "";
const a = "aaa";
const b = "bbb";
const res = threeWayMerge(a, b, orig);
const expected = `\`<<<<<<<\`
aaa
\`=======\`
bbb
\`>>>>>>>\``;
deepStrictEqual(expected, res);
});
it("should correctly merge after adding lines on both sides", async () => {
const orig = `
* [ ] A1
* [ ] A2
* [ ] A3
`;
const a = `
* [ ] A1
* [ ] new line after A1
* [ ] A2
* [ ] A3
`;
const b = `
* [ ] A1
* [ ] A2
* [ ] New line after A2
* [ ] A3
`;
const res = threeWayMerge(a, b, orig);
// console.log(res);
const expected = `
* [ ] A1
* [ ] new line after A1
* [ ] A2
* [ ] New line after A2
* [ ] A3
`;
deepStrictEqual(expected, res);
});
it("should correctly merge after adding lines on both sides (again)", async () => {
const orig = `
* [ ]
* [ ]
* [ ] A3
`;
const a = `
* [ ]
* [ ] new line after
* [ ]
* [ ] A3
`;
const b = `
* [ ]
* [ ]
* [ ] New line after
* [ ] A3
`;
const res = threeWayMerge(a, b, orig);
// console.log(res);
const expected = `
* [ ]
* [ ] new line after
* [ ]
* [ ] New line after
* [ ] A3
`;
deepStrictEqual(expected, res);
});
it("should correctly merge after deleting lines on both sides", async () => {
const orig = `
* [ ]
* [ ]
* [ ] A3
* [ ] A4
`;
const a = `
* [ ]
* [ ] A3
* [ ] A4
`;
const b = `
* [ ]
* [ ] A3
* [ ] A4
`;
const res = threeWayMerge(a, b, orig);
// console.log(res);
const expected = `
\`<<<<<<<\`
* [ ]
\`=======\`
* [ ]
\`>>>>>>>\`
* [ ] A3
* [ ] A4
`;
deepStrictEqual(expected, res);
});
it("should correctly merge after adding on one side and deleting on other side", async () => {
const orig = `
* [ ]
* [ ] A3
* [ ] A4
`;
const a = `
* [ ]
* [ ]
* [ ] A3
* [ ] A4
`;
const b = `
* [ ] A3
* [ ] A4
`;
const res = threeWayMerge(a, b, orig);
// console.log(res);
const expected = `
\`<<<<<<<\`
* [ ]
* [ ]
\`=======\`
\`>>>>>>>\`
* [ ] A3
* [ ] A4
`;
deepStrictEqual(expected, res);
});
it("should correctly merge after adding on one side and deleting on other side (again)", async () => {
const orig = `
* [ ]
* [ ] A3
* [ ] A4
`;
const a = `
* [ ] A3
* [ ] A4
`;
const b = `
* [ ]
* [ ]
* [ ] A3
* [ ] A4
`;
const res = threeWayMerge(a, b, orig);
// console.log(res);
const expected = `
\`<<<<<<<\`
\`=======\`
* [ ]
* [ ]
\`>>>>>>>\`
* [ ] A3
* [ ] A4
`;
deepStrictEqual(expected, res);
});
});

154
pro/tests/sync.test.ts Normal file
View File

@ -0,0 +1,154 @@
import { strict as assert } from "assert";
import { checkIsSkipItemOrNotByName } from "../src/sync";
describe("Sync: checkIsSkipItemOrNotByName", () => {
it("should be ok everywhere for empty config", async () => {
let isSkip = checkIsSkipItemOrNotByName(
"xxx.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ [],
/* onlyAllowPaths */ []
).finalIsIgnored;
assert.ok(!isSkip);
isSkip = checkIsSkipItemOrNotByName(
"xxx.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ [""],
/* onlyAllowPaths */ ["", "\n"]
).finalIsIgnored;
assert.ok(!isSkip);
});
it("should be ok for deny list", async () => {
let isSkip = checkIsSkipItemOrNotByName(
"xxx.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ ["xxx"],
/* onlyAllowPaths */ []
).finalIsIgnored;
assert.ok(isSkip);
isSkip = checkIsSkipItemOrNotByName(
"yyy.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ ["xxx"],
/* onlyAllowPaths */ []
).finalIsIgnored;
assert.ok(!isSkip);
isSkip = checkIsSkipItemOrNotByName(
"xxx.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ ["xxx$"],
/* onlyAllowPaths */ []
).finalIsIgnored;
assert.ok(!isSkip);
// if we deny a folder, we have to deny all the sub files
// TODO: it's soooo hard to do the path resolution in this func with regex,
// so we defer the detection to later steps now.
// the test here doesn't work.
// isSkip = checkIsSkipItemOrNotByName(
// 'xxx/yyy.md',
// false,
// false,
// false,
// '.obsidian',
// /* ignorePaths */ ['xxx/$'],
// /* onlyAllowPaths */ []
// ).finalIsIgnored;
// assert.ok(isSkip);
});
it("should be ok for allow list", async () => {
let isSkip = checkIsSkipItemOrNotByName(
"xxx.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ [],
/* onlyAllowPaths */ ["xxx"]
).finalIsIgnored;
assert.ok(!isSkip);
isSkip = checkIsSkipItemOrNotByName(
"yyy.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ [""],
/* onlyAllowPaths */ ["xxx"]
).finalIsIgnored;
assert.ok(isSkip);
isSkip = checkIsSkipItemOrNotByName(
"xxx.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ [],
/* onlyAllowPaths */ ["xxx$"]
).finalIsIgnored;
assert.ok(isSkip);
// should NOT skip because we allow the sub file AND not deny the folder
// TODO: it's soooo hard to do the path resolution in this func with regex,
// so we defer the detection to later steps now.
// the test here doesn't work.
// isSkip = checkIsSkipItemOrNotByName(
// 'xxx/',
// false,
// false,
// false,
// '.obsidian',
// /* ignorePaths */ [],
// /* onlyAllowPaths */ ['xxx/yyy.md']
// ).finalIsIgnored;
// assert.ok(!isSkip);
});
it("should detect the name by two lists together", async () => {
// should skip because we ignore the path
let isSkip = checkIsSkipItemOrNotByName(
"xxx.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ ["xxx"],
/* onlyAllowPaths */ ["yyy"]
).finalIsIgnored;
assert.ok(isSkip);
// should skip because we disallow the whole folder
isSkip = checkIsSkipItemOrNotByName(
"xxx/yyy.md",
false,
false,
false,
".obsidian",
/* ignorePaths */ ["xxx"],
/* onlyAllowPaths */ ["xxx/yyy.md"]
).finalIsIgnored;
assert.ok(isSkip);
});
});

View File

@ -8,6 +8,7 @@ import type {
BoxConfig, BoxConfig,
GoogleDriveConfig, GoogleDriveConfig,
KoofrConfig, KoofrConfig,
OnedriveFullConfig,
PCloudConfig, PCloudConfig,
ProConfig, ProConfig,
YandexDiskConfig, YandexDiskConfig,
@ -31,6 +32,7 @@ export type SUPPORTED_SERVICES_TYPE =
| "webdav" | "webdav"
| "dropbox" | "dropbox"
| "onedrive" | "onedrive"
| "onedrivefull"
| "webdis" | "webdis"
| "googledrive" | "googledrive"
| "box" | "box"
@ -96,6 +98,8 @@ export interface WebdavConfig {
depth?: WebdavDepthType; depth?: WebdavDepthType;
remoteBaseDir?: string; remoteBaseDir?: string;
customHeaders?: string;
/** /**
* @deprecated * @deprecated
*/ */
@ -114,6 +118,7 @@ export interface OnedriveConfig {
credentialsShouldBeDeletedAtTime?: number; credentialsShouldBeDeletedAtTime?: number;
remoteBaseDir?: string; remoteBaseDir?: string;
emptyFile: "skip" | "error"; emptyFile: "skip" | "error";
kind: "onedrive";
} }
export interface WebdisConfig { export interface WebdisConfig {
@ -135,6 +140,7 @@ export type CipherMethodType = "rclone-base64" | "openssl-base64" | "unknown";
export type QRExportType = "basic_and_advanced" | SUPPORTED_SERVICES_TYPE; export type QRExportType = "basic_and_advanced" | SUPPORTED_SERVICES_TYPE;
export interface ProfilerConfig { export interface ProfilerConfig {
enable?: boolean;
enablePrinting?: boolean; enablePrinting?: boolean;
recordSize?: boolean; recordSize?: boolean;
} }
@ -144,6 +150,7 @@ export interface RemotelySavePluginSettings {
webdav: WebdavConfig; webdav: WebdavConfig;
dropbox: DropboxConfig; dropbox: DropboxConfig;
onedrive: OnedriveConfig; onedrive: OnedriveConfig;
onedrivefull: OnedriveFullConfig;
webdis: WebdisConfig; webdis: WebdisConfig;
googledrive: GoogleDriveConfig; googledrive: GoogleDriveConfig;
box: BoxConfig; box: BoxConfig;
@ -161,11 +168,13 @@ export interface RemotelySavePluginSettings {
concurrency?: number; concurrency?: number;
syncConfigDir?: boolean; syncConfigDir?: boolean;
syncBookmarks?: boolean;
syncUnderscoreItems?: boolean; syncUnderscoreItems?: boolean;
lang?: LangTypeAndAuto; lang?: LangTypeAndAuto;
agreeToUseSyncV3?: boolean; agreeToUseSyncV3?: boolean;
skipSizeLargerThan?: number; skipSizeLargerThan?: number;
ignorePaths?: string[]; ignorePaths?: string[];
onlyAllowPaths?: string[];
enableStatusBarInfo?: boolean; enableStatusBarInfo?: boolean;
deleteToWhere?: "system" | "obsidian"; deleteToWhere?: "system" | "obsidian";
conflictAction?: ConflictActionType; conflictAction?: ConflictActionType;
@ -263,6 +272,8 @@ export interface Entity {
keyRaw: string; keyRaw: string;
mtimeCli?: number; mtimeCli?: number;
mtimeCliFmt?: string; mtimeCliFmt?: string;
ctimeCli?: number;
ctimeCliFmt?: string;
mtimeSvr?: number; mtimeSvr?: number;
mtimeSvrFmt?: string; mtimeSvrFmt?: string;
prevSyncTime?: number; prevSyncTime?: number;

View File

@ -41,7 +41,7 @@ export async function copyFile(key: string, left: FakeFs, right: FakeFs) {
key, key,
content, content,
statsLeft.mtimeCli, statsLeft.mtimeCli,
statsLeft.mtimeCli /* TODO */ statsLeft.ctimeCli ?? statsLeft.mtimeCli
), ),
content: content, content: content,
}; };

View File

@ -200,7 +200,10 @@ export class CipherRclone {
action: "encryptContent", action: "encryptContent",
inputContent: input, inputContent: input,
}, },
[channel.port1, input] [
channel.port1,
// input // the array buffer might be re-used later, so we CANNOT transfer here
]
); );
}); });
} }
@ -244,7 +247,10 @@ export class CipherRclone {
action: "decryptContent", action: "decryptContent",
inputContent: input, inputContent: input,
}, },
[channel.port1, input] [
channel.port1,
input, // not transfer for safety
]
); );
}); });
} }

View File

@ -141,7 +141,7 @@ ctx.addEventListener("message", async (event: any) => {
status: "ok", status: "ok",
outputContent: outputContent, outputContent: outputContent,
}, },
[outputContent] [outputContent] // on worker side, we don't reuse anything so it's safe to transfer
); );
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@ -166,7 +166,7 @@ ctx.addEventListener("message", async (event: any) => {
status: "ok", status: "ok",
outputContent: outputContent, outputContent: outputContent,
}, },
[outputContent] [outputContent] // on worker side, we don't reuse anything so it's safe to transfer
); );
} catch (error) { } catch (error) {
console.error(error); console.error(error);

View File

@ -1,3 +1,5 @@
import isEqual from "lodash/isEqual";
import { nanoid } from "nanoid";
import type { Entity } from "./baseTypes"; import type { Entity } from "./baseTypes";
export abstract class FakeFs { export abstract class FakeFs {
@ -16,6 +18,49 @@ export abstract class FakeFs {
abstract rename(key1: string, key2: string): Promise<void>; abstract rename(key1: string, key2: string): Promise<void>;
abstract rm(key: string): Promise<void>; abstract rm(key: string): Promise<void>;
abstract checkConnect(callbackFunc?: any): Promise<boolean>; abstract checkConnect(callbackFunc?: any): Promise<boolean>;
async checkConnectCommonOps(callbackFunc?: any) {
try {
console.info(`check connect: create folder`);
const folderName = `rs-test-folder-${nanoid()}/`;
await this.mkdir(folderName);
// await delay(3000);
console.info(`check connect: upload file`);
const filename = `${folderName}rs-test-file-${nanoid()}`;
const ctime = Date.now();
const mtime1 = Date.now();
const content1 = new ArrayBuffer(100);
await this.writeFile(filename, content1, mtime1, ctime);
// await delay(3000);
console.info(`check connect: overwrite file`);
const mtime2 = Date.now();
const content2 = new ArrayBuffer(200);
await this.writeFile(filename, content2, mtime2, ctime);
// await delay(3000);
console.info(`check connect: download file`);
const content3 = await this.readFile(filename);
if (!isEqual(content2, content3)) {
throw Error(`downloaded file is not equal with uploaded file!`);
}
// await delay(3000);
console.info(`check connect: delete file`);
await this.rm(filename);
// await delay(3000);
console.info(`check connect: delete folder`);
await this.rm(folderName);
// await delay(3000);
return true;
} catch (err) {
console.error(err);
callbackFunc?.(err);
return false;
}
}
abstract getUserDisplayName(): Promise<string>; abstract getUserDisplayName(): Promise<string>;
abstract revokeAuth(): Promise<any>; abstract revokeAuth(): Promise<any>;
abstract allowEmptyFile(): boolean; abstract allowEmptyFile(): boolean;

View File

@ -741,14 +741,15 @@ export class FakeFsDropbox extends FakeFs {
await this._init(); await this._init();
const results = await this._statFromRoot(`/${this.remoteBaseDir}`); const results = await this._statFromRoot(`/${this.remoteBaseDir}`);
if (results === undefined) { if (results === undefined) {
return false; throw Error(`cannot check root vault folder!`);
} }
return true;
} catch (err) { } catch (err) {
console.debug(err); console.debug(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName() { async getUserDisplayName() {

View File

@ -91,7 +91,8 @@ export class FakeFsEncrypt extends FakeFs {
this.password !== "" ? method : "no password" this.password !== "" ? method : "no password"
})`; })`;
if (method === "rclone-base64") { if (this.password !== "" && method === "rclone-base64") {
// no need to init if no password or not rclone
this.cipherRClone = new rclone.CipherRclone(password, 5); this.cipherRClone = new rclone.CipherRclone(password, 5);
} }
} }
@ -137,6 +138,8 @@ export class FakeFsEncrypt extends FakeFs {
}; };
} }
} else { } else {
// the config has a password
if (this.method === "unknown") { if (this.method === "unknown") {
return { return {
ok: false, ok: false,

View File

@ -2,6 +2,7 @@ import { FakeFsAzureBlobStorage } from "../pro/src/fsAzureBlobStorage";
import { FakeFsBox } from "../pro/src/fsBox"; import { FakeFsBox } from "../pro/src/fsBox";
import { FakeFsGoogleDrive } from "../pro/src/fsGoogleDrive"; import { FakeFsGoogleDrive } from "../pro/src/fsGoogleDrive";
import { FakeFsKoofr } from "../pro/src/fsKoofr"; import { FakeFsKoofr } from "../pro/src/fsKoofr";
import { FakeFsOnedriveFull } from "../pro/src/fsOnedriveFull";
import { FakeFsPCloud } from "../pro/src/fsPCloud"; import { FakeFsPCloud } from "../pro/src/fsPCloud";
import { FakeFsYandexDisk } from "../pro/src/fsYandexDisk"; import { FakeFsYandexDisk } from "../pro/src/fsYandexDisk";
import type { RemotelySavePluginSettings } from "./baseTypes"; import type { RemotelySavePluginSettings } from "./baseTypes";
@ -41,6 +42,12 @@ export function getClient(
vaultName, vaultName,
saveUpdatedConfigFunc saveUpdatedConfigFunc
); );
case "onedrivefull":
return new FakeFsOnedriveFull(
settings.onedrivefull,
vaultName,
saveUpdatedConfigFunc
);
case "webdis": case "webdis":
return new FakeFsWebdis( return new FakeFsWebdis(
settings.webdis, settings.webdis,

View File

@ -9,6 +9,7 @@ import type { Profiler } from "./profiler";
export class FakeFsLocal extends FakeFs { export class FakeFsLocal extends FakeFs {
vault: Vault; vault: Vault;
syncConfigDir: boolean; syncConfigDir: boolean;
syncBookmarks: boolean;
configDir: string; configDir: string;
pluginID: string; pluginID: string;
profiler: Profiler | undefined; profiler: Profiler | undefined;
@ -17,6 +18,7 @@ export class FakeFsLocal extends FakeFs {
constructor( constructor(
vault: Vault, vault: Vault,
syncConfigDir: boolean, syncConfigDir: boolean,
syncBookmarks: boolean,
configDir: string, configDir: string,
pluginID: string, pluginID: string,
profiler: Profiler | undefined, profiler: Profiler | undefined,
@ -26,6 +28,7 @@ export class FakeFsLocal extends FakeFs {
this.vault = vault; this.vault = vault;
this.syncConfigDir = syncConfigDir; this.syncConfigDir = syncConfigDir;
this.syncBookmarks = syncBookmarks;
this.configDir = configDir; this.configDir = configDir;
this.pluginID = pluginID; this.pluginID = pluginID;
this.profiler = profiler; this.profiler = profiler;
@ -96,13 +99,16 @@ export class FakeFsLocal extends FakeFs {
this.profiler?.insert("finish transforming walk for local"); this.profiler?.insert("finish transforming walk for local");
if (this.syncConfigDir) { if (this.syncConfigDir || this.syncBookmarks) {
this.profiler?.insert("into syncConfigDir"); this.profiler?.insert("into syncConfigDir or syncBookmarks");
const bookmarksOnly = !this.syncConfigDir;
const syncFiles = await listFilesInObsFolder( const syncFiles = await listFilesInObsFolder(
this.configDir, this.configDir,
this.vault, this.vault,
this.pluginID this.pluginID,
bookmarksOnly
); );
// console.debug(`syncFiles in obs: ${JSON.stringify(syncFiles, null, 2)}`);
for (const f of syncFiles) { for (const f of syncFiles) {
local.push(f); local.push(f);
} }
@ -127,8 +133,10 @@ export class FakeFsLocal extends FakeFs {
return { return {
key: isFolder ? `${key}/` : key, // local always unencrypted key: isFolder ? `${key}/` : key, // local always unencrypted
keyRaw: isFolder ? `${key}/` : key, keyRaw: isFolder ? `${key}/` : key,
ctimeCli: statRes.ctime,
mtimeCli: statRes.mtime, mtimeCli: statRes.mtime,
mtimeSvr: statRes.mtime, mtimeSvr: statRes.mtime,
ctimeCliFmt: unixTimeToStr(statRes.ctime),
mtimeCliFmt: unixTimeToStr(statRes.mtime), mtimeCliFmt: unixTimeToStr(statRes.mtime),
mtimeSvrFmt: unixTimeToStr(statRes.mtime), mtimeSvrFmt: unixTimeToStr(statRes.mtime),
size: statRes.size, // local always unencrypted size: statRes.size, // local always unencrypted

View File

@ -47,7 +47,7 @@ export class FakeFsMock extends FakeFs {
} }
async checkConnect(callbackFunc?: any): Promise<boolean> { async checkConnect(callbackFunc?: any): Promise<boolean> {
return true; return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {

View File

@ -35,6 +35,7 @@ export const DEFAULT_ONEDRIVE_CONFIG: OnedriveConfig = {
username: "", username: "",
credentialsShouldBeDeletedAtTime: 0, credentialsShouldBeDeletedAtTime: 0,
emptyFile: "skip", emptyFile: "skip",
kind: "onedrive",
}; };
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
@ -251,6 +252,10 @@ const fromDriveItemToEntity = (x: DriveItem, remoteBaseDir: string): Entity => {
// why?? /drive/root:/Apps/Graph // why?? /drive/root:/Apps/Graph
const FIFTH_COMMON_PREFIX_REGEX = /^\/drive\/root:\/[^\/]+\/Graph\//g; const FIFTH_COMMON_PREFIX_REGEX = /^\/drive\/root:\/[^\/]+\/Graph\//g;
// why again?? /drive/root:/Apps/Graph 1
const SIXTH_COMMON_PREFIX_REGEX = /^\/drive\/root:\/[^\/]+\/Graph 1\//g;
const SIXTH_COMMON_PREFIX_REGEX_V2 = /^\/drive\/root:\/[^\/]+\/Graph%201\//g;
// or the root is absolute path /Livefolders, // or the root is absolute path /Livefolders,
// e.g.: /Livefolders/应用/remotely-save/${remoteBaseDir} // e.g.: /Livefolders/应用/remotely-save/${remoteBaseDir}
const SECOND_COMMON_PREFIX_REGEX = /^\/Livefolders\/[^\/]+\/remotely-save\//g; const SECOND_COMMON_PREFIX_REGEX = /^\/Livefolders\/[^\/]+\/remotely-save\//g;
@ -263,6 +268,9 @@ const fromDriveItemToEntity = (x: DriveItem, remoteBaseDir: string): Entity => {
// another possibile prefix // another possibile prefix
const FOURTH_COMMON_PREFIX_RAW = `/drive/items/`; const FOURTH_COMMON_PREFIX_RAW = `/drive/items/`;
// when to use decode?
const remoteBaseDirEncoded = encodeURIComponent(remoteBaseDir);
if ( if (
x.parentReference === undefined || x.parentReference === undefined ||
x.parentReference === null || x.parentReference === null ||
@ -274,10 +282,17 @@ const fromDriveItemToEntity = (x: DriveItem, remoteBaseDir: string): Entity => {
const fullPathOriginal = `${x.parentReference.path}/${x.name}`; const fullPathOriginal = `${x.parentReference.path}/${x.name}`;
const matchFirstPrefixRes = fullPathOriginal.match(FIRST_COMMON_PREFIX_REGEX); const matchFirstPrefixRes = fullPathOriginal.match(FIRST_COMMON_PREFIX_REGEX);
const matchFifthPrefixRes = fullPathOriginal.match(FIFTH_COMMON_PREFIX_REGEX); const matchFifthPrefixRes = fullPathOriginal.match(FIFTH_COMMON_PREFIX_REGEX);
const matchSixthPrefixRes = fullPathOriginal.match(SIXTH_COMMON_PREFIX_REGEX);
const matchSixthV2PrefixRes = fullPathOriginal.match(
SIXTH_COMMON_PREFIX_REGEX_V2
);
const matchSecondPrefixRes = fullPathOriginal.match( const matchSecondPrefixRes = fullPathOriginal.match(
SECOND_COMMON_PREFIX_REGEX SECOND_COMMON_PREFIX_REGEX
); );
const matchThirdPrefixRes = fullPathOriginal.match(THIRD_COMMON_PREFIX_REGEX); const matchThirdPrefixRes = fullPathOriginal.match(THIRD_COMMON_PREFIX_REGEX);
// first
if ( if (
matchFirstPrefixRes !== null && matchFirstPrefixRes !== null &&
fullPathOriginal.startsWith(`${matchFirstPrefixRes[0]}${remoteBaseDir}`) fullPathOriginal.startsWith(`${matchFirstPrefixRes[0]}${remoteBaseDir}`)
@ -285,24 +300,102 @@ const fromDriveItemToEntity = (x: DriveItem, remoteBaseDir: string): Entity => {
const foundPrefix = `${matchFirstPrefixRes[0]}${remoteBaseDir}`; const foundPrefix = `${matchFirstPrefixRes[0]}${remoteBaseDir}`;
key = fullPathOriginal.substring(foundPrefix.length + 1); key = fullPathOriginal.substring(foundPrefix.length + 1);
} else if ( } else if (
matchFirstPrefixRes !== null &&
fullPathOriginal.startsWith(
`${matchFirstPrefixRes[0]}${remoteBaseDirEncoded}`
)
) {
const foundPrefix = `${matchFirstPrefixRes[0]}${remoteBaseDirEncoded}`;
key = fullPathOriginal.substring(foundPrefix.length + 1);
}
// fifth
else if (
matchFifthPrefixRes !== null && matchFifthPrefixRes !== null &&
fullPathOriginal.startsWith(`${matchFifthPrefixRes[0]}${remoteBaseDir}`) fullPathOriginal.startsWith(`${matchFifthPrefixRes[0]}${remoteBaseDir}`)
) { ) {
const foundPrefix = `${matchFifthPrefixRes[0]}${remoteBaseDir}`; const foundPrefix = `${matchFifthPrefixRes[0]}${remoteBaseDir}`;
key = fullPathOriginal.substring(foundPrefix.length + 1); key = fullPathOriginal.substring(foundPrefix.length + 1);
} else if ( } else if (
matchFifthPrefixRes !== null &&
fullPathOriginal.startsWith(
`${matchFifthPrefixRes[0]}${remoteBaseDirEncoded}`
)
) {
const foundPrefix = `${matchFifthPrefixRes[0]}${remoteBaseDirEncoded}`;
key = fullPathOriginal.substring(foundPrefix.length + 1);
}
// sixth
else if (
matchSixthPrefixRes !== null &&
fullPathOriginal.startsWith(`${matchSixthPrefixRes[0]}${remoteBaseDir}`)
) {
const foundPrefix = `${matchSixthPrefixRes[0]}${remoteBaseDir}`;
key = fullPathOriginal.substring(foundPrefix.length + 1);
} else if (
matchSixthPrefixRes !== null &&
fullPathOriginal.startsWith(
`${matchSixthPrefixRes[0]}${remoteBaseDirEncoded}`
)
) {
const foundPrefix = `${matchSixthPrefixRes[0]}${remoteBaseDirEncoded}`;
key = fullPathOriginal.substring(foundPrefix.length + 1);
}
// sixth v2
else if (
matchSixthV2PrefixRes !== null &&
fullPathOriginal.startsWith(`${matchSixthV2PrefixRes[0]}${remoteBaseDir}`)
) {
const foundPrefix = `${matchSixthV2PrefixRes[0]}${remoteBaseDir}`;
key = fullPathOriginal.substring(foundPrefix.length + 1);
} else if (
matchSixthV2PrefixRes !== null &&
fullPathOriginal.startsWith(
`${matchSixthV2PrefixRes[0]}${remoteBaseDirEncoded}`
)
) {
const foundPrefix = `${matchSixthV2PrefixRes[0]}${remoteBaseDirEncoded}`;
key = fullPathOriginal.substring(foundPrefix.length + 1);
}
// second
else if (
matchSecondPrefixRes !== null && matchSecondPrefixRes !== null &&
fullPathOriginal.startsWith(`${matchSecondPrefixRes[0]}${remoteBaseDir}`) fullPathOriginal.startsWith(`${matchSecondPrefixRes[0]}${remoteBaseDir}`)
) { ) {
const foundPrefix = `${matchSecondPrefixRes[0]}${remoteBaseDir}`; const foundPrefix = `${matchSecondPrefixRes[0]}${remoteBaseDir}`;
key = fullPathOriginal.substring(foundPrefix.length + 1); key = fullPathOriginal.substring(foundPrefix.length + 1);
} else if ( } else if (
matchSecondPrefixRes !== null &&
fullPathOriginal.startsWith(
`${matchSecondPrefixRes[0]}${remoteBaseDirEncoded}`
)
) {
const foundPrefix = `${matchSecondPrefixRes[0]}${remoteBaseDirEncoded}`;
key = fullPathOriginal.substring(foundPrefix.length + 1);
}
// third
else if (
matchThirdPrefixRes !== null && matchThirdPrefixRes !== null &&
fullPathOriginal.startsWith(`${matchThirdPrefixRes[0]}${remoteBaseDir}`) fullPathOriginal.startsWith(`${matchThirdPrefixRes[0]}${remoteBaseDir}`)
) { ) {
const foundPrefix = `${matchThirdPrefixRes[0]}${remoteBaseDir}`; const foundPrefix = `${matchThirdPrefixRes[0]}${remoteBaseDir}`;
key = fullPathOriginal.substring(foundPrefix.length + 1); key = fullPathOriginal.substring(foundPrefix.length + 1);
} else if (x.parentReference.path.startsWith(FOURTH_COMMON_PREFIX_RAW)) { } else if (
matchThirdPrefixRes !== null &&
fullPathOriginal.startsWith(
`${matchThirdPrefixRes[0]}${remoteBaseDirEncoded}`
)
) {
const foundPrefix = `${matchThirdPrefixRes[0]}${remoteBaseDirEncoded}`;
key = fullPathOriginal.substring(foundPrefix.length + 1);
}
// fourth
else if (x.parentReference.path.startsWith(FOURTH_COMMON_PREFIX_RAW)) {
// it's something like // it's something like
// /drive/items/<some_id>!<another_id>:/${remoteBaseDir}/<subfolder> // /drive/items/<some_id>!<another_id>:/${remoteBaseDir}/<subfolder>
// with uri encoded! // with uri encoded!
@ -320,16 +413,31 @@ const fromDriveItemToEntity = (x: DriveItem, remoteBaseDir: string): Entity => {
key = x.name; key = x.name;
} else { } else {
throw Error( throw Error(
`we meet file/folder and do not know how to deal with it:\n${constructFromDriveItemToEntityError( `file/folder with /drive/items/, no idea how to deal with it:
x fullPathOriginal=${fullPathOriginal}
)}` matchFirstPrefixRes=${matchFirstPrefixRes}
matchFifthPrefixRes=${matchFifthPrefixRes}
matchSixthPrefixRes=${matchSixthPrefixRes}
matchSixthV2PrefixRes=${matchSixthV2PrefixRes}
matchSecondPrefixRes=${matchSecondPrefixRes}
matchThirdPrefixRes=${matchThirdPrefixRes}
${constructFromDriveItemToEntityError(x)}`
); );
} }
} else { }
// others
else {
throw Error( throw Error(
`we meet file/folder and do not know how to deal with it:\n${constructFromDriveItemToEntityError( `file/folder, no idea how to deal with it without known prefix:
x fullPathOriginal=${fullPathOriginal}
)}` matchFirstPrefixRes=${matchFirstPrefixRes}
matchFifthPrefixRes=${matchFifthPrefixRes}
matchSixthPrefixRes=${matchSixthPrefixRes}
matchSixthV2PrefixRes=${matchSixthV2PrefixRes}
matchSecondPrefixRes=${matchSecondPrefixRes}
matchThirdPrefixRes=${matchThirdPrefixRes}
${constructFromDriveItemToEntityError(x)}`
); );
} }
@ -338,13 +446,27 @@ const fromDriveItemToEntity = (x: DriveItem, remoteBaseDir: string): Entity => {
key = `${key}/`; key = `${key}/`;
} }
const mtimeSvr = Date.parse(x?.fileSystemInfo!.lastModifiedDateTime!); const mtimeTry = x?.fileSystemInfo?.lastModifiedDateTime;
const mtimeCli = Date.parse(x?.fileSystemInfo!.lastModifiedDateTime!); if (mtimeTry === undefined || mtimeTry === null) {
throw Error(`onedrive cannot parse mtime: ${JSON.stringify(x, null, 2)}`);
}
let ctimeTry = x?.fileSystemInfo?.createdDateTime;
if (ctimeTry === undefined || ctimeTry === null) {
// throw Error(`onedrive cannot parse ctime: ${JSON.stringify(x, null, 2)}`);
// it doesn't hurt, we just use mtimeTry to fullfill
ctimeTry = mtimeTry;
}
const mtimeSvr = Date.parse(mtimeTry);
const mtimeCli = Date.parse(mtimeTry);
const ctimeCli = Date.parse(ctimeTry);
return { return {
key: key, key: key,
keyRaw: key, keyRaw: key,
mtimeSvr: mtimeSvr, mtimeSvr: mtimeSvr,
mtimeCli: mtimeCli, mtimeCli: mtimeCli,
ctimeCli: ctimeCli,
size: isFolder ? 0 : x.size!, size: isFolder ? 0 : x.size!,
sizeRaw: isFolder ? 0 : x.size!, sizeRaw: isFolder ? 0 : x.size!,
synthesizedFile: false, synthesizedFile: false,
@ -813,6 +935,7 @@ export class FakeFsOnedrive extends FakeFs {
keyRaw: origKey, keyRaw: origKey,
mtimeSvr: mtime, mtimeSvr: mtime,
mtimeCli: mtime, mtimeCli: mtime,
ctimeCli: ctime,
size: 0, size: 0,
sizeRaw: 0, sizeRaw: 0,
synthesizedFile: true, synthesizedFile: true,
@ -925,11 +1048,24 @@ export class FakeFsOnedrive extends FakeFs {
).arrayBuffer; ).arrayBuffer;
return content; return content;
} else { } else {
// cannot set no-cache here, will have cors error // so strange, sometimes (!!!)
const content = await ( // we cannot download the file because of CORS
await fetch(downloadUrl, { cache: "no-store" }) try {
).arrayBuffer(); // cannot set no-cache here, will have cors error
return content; const content = await (
await fetch(downloadUrl, { cache: "no-store" })
).arrayBuffer();
return content;
} catch (e) {
// let's try again to bypass the CORS
const content = (
await requestUrl({
url: downloadUrl,
headers: { "Cache-Control": "no-cache" },
})
).arrayBuffer;
return content;
}
} }
} }
@ -958,12 +1094,16 @@ export class FakeFsOnedrive extends FakeFs {
async checkConnect(callbackFunc?: any): Promise<boolean> { async checkConnect(callbackFunc?: any): Promise<boolean> {
try { try {
const k = await this.getUserDisplayName(); const k = await this.getUserDisplayName();
return k !== "<unknown display name>"; if (k === "<unknown display name>") {
throw Error(`unknown display name!`);
}
} catch (err) { } catch (err) {
console.debug(err); console.debug(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName() { async getUserDisplayName() {

View File

@ -831,14 +831,11 @@ export class FakeFsS3 extends FakeFs {
results.$metadata === undefined || results.$metadata === undefined ||
results.$metadata.httpStatusCode === undefined results.$metadata.httpStatusCode === undefined
) { ) {
const err = "results or $metadata or httStatusCode is undefined"; throw Error("results or $metadata or httStatusCode is undefined");
console.debug(err); }
if (callbackFunc !== undefined) { if (results.$metadata.httpStatusCode !== 200) {
callbackFunc(err); throw Error(`not 200 httpStatusCode`);
}
return false;
} }
return results.$metadata.httpStatusCode === 200;
} catch (err: any) { } catch (err: any) {
console.debug(err); console.debug(err);
if (callbackFunc !== undefined) { if (callbackFunc !== undefined) {
@ -854,9 +851,10 @@ export class FakeFsS3 extends FakeFs {
callbackFunc(err); callbackFunc(err);
} }
} }
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {

View File

@ -4,8 +4,6 @@ import { getReasonPhrase } from "http-status-codes/build/cjs/utils-functions";
import chunk from "lodash/chunk"; import chunk from "lodash/chunk";
import cloneDeep from "lodash/cloneDeep"; import cloneDeep from "lodash/cloneDeep";
import flatten from "lodash/flatten"; import flatten from "lodash/flatten";
import isString from "lodash/isString";
import { nanoid } from "nanoid";
import { Platform, type RequestUrlParam, requestUrl } from "obsidian"; import { Platform, type RequestUrlParam, requestUrl } from "obsidian";
import type { import type {
FileStat, FileStat,
@ -170,23 +168,37 @@ const getWebdavPath = (fileOrFolderPath: string, remoteBaseDir: string) => {
return key; return key;
}; };
/**
* sometimes the path startswith /../../......
* we want to make sure the path is compatible
*/
const stripLeadingPath = (x: string) => {
let y = x;
while (y.startsWith("/..")) {
y = y.slice("/..".length);
}
return y;
};
const getNormPath = (fileOrFolderPath: string, remoteBaseDir: string) => { const getNormPath = (fileOrFolderPath: string, remoteBaseDir: string) => {
const strippedFileOrFolderPath = stripLeadingPath(fileOrFolderPath);
if ( if (
!( !(
fileOrFolderPath === `/${remoteBaseDir}` || strippedFileOrFolderPath === `/${remoteBaseDir}` ||
fileOrFolderPath.startsWith(`/${remoteBaseDir}/`) strippedFileOrFolderPath.startsWith(`/${remoteBaseDir}/`)
) )
) { ) {
throw Error( throw Error(
`"${fileOrFolderPath}" doesn't starts with "/${remoteBaseDir}/"` `"${fileOrFolderPath}" after stripping doesn't starts with "/${remoteBaseDir}/"`
); );
} }
const result = strippedFileOrFolderPath.slice(`/${remoteBaseDir}/`.length);
return fileOrFolderPath.slice(`/${remoteBaseDir}/`.length); return result;
}; };
const fromWebdavItemToEntity = (x: FileStat, remoteBaseDir: string): Entity => { const fromWebdavItemToEntity = (x: FileStat, remoteBaseDir: string): Entity => {
let key = getNormPath(x.filename, remoteBaseDir); let key = getNormPath(x.filename, remoteBaseDir);
if (x.type === "directory" && !key.endsWith("/")) { if (x.type === "directory" && !key.endsWith("/")) {
key = `${key}/`; key = `${key}/`;
} }
@ -209,6 +221,36 @@ const tryEncodeURI = (x: string) => {
return encodeURI(x); return encodeURI(x);
}; };
const tryEncodeUsernamePassword = (x: string) => {
if (onlyAscii(x)) {
return x;
}
return unescape(encodeURIComponent(x));
};
const parseCustomHeaders = (x: string): Record<string, string> => {
const y = x.trim();
if (y === "") {
return {};
}
const z = y.split("\n");
const res: Record<string, string> = {};
for (const kv of z) {
if (!kv.includes(":")) {
continue;
}
const [keyRaw, ...valueArr] = kv.split(":");
const key = keyRaw.trim();
const value = valueArr.join(":").trim();
res[key] = value;
}
return res;
};
export class FakeFsWebdav extends FakeFs { export class FakeFsWebdav extends FakeFs {
kind: "webdav"; kind: "webdav";
@ -218,7 +260,8 @@ export class FakeFsWebdav extends FakeFs {
vaultFolderExists: boolean; vaultFolderExists: boolean;
saveUpdatedConfigFunc: () => Promise<any>; saveUpdatedConfigFunc: () => Promise<any>;
supportNativePartial: boolean; supportApachePartial: boolean;
supportSabrePartial: boolean;
isNextcloud: boolean; isNextcloud: boolean;
nextcloudUploadServerAddress: string; nextcloudUploadServerAddress: string;
@ -235,7 +278,8 @@ export class FakeFsWebdav extends FakeFs {
this.vaultFolderExists = false; this.vaultFolderExists = false;
this.saveUpdatedConfigFunc = saveUpdatedConfigFunc; this.saveUpdatedConfigFunc = saveUpdatedConfigFunc;
this.supportNativePartial = false; this.supportApachePartial = false;
this.supportSabrePartial = false;
this.isNextcloud = false; this.isNextcloud = false;
this.nextcloudUploadServerAddress = ""; this.nextcloudUploadServerAddress = "";
} }
@ -246,16 +290,21 @@ export class FakeFsWebdav extends FakeFs {
return; return;
} }
const headers = { const cacheHeader = {
"Cache-Control": "no-cache", "Cache-Control": "no-cache",
}; };
const customHeaders = parseCustomHeaders(
this.webdavConfig.customHeaders ?? ""
);
const headers = { ...cacheHeader, ...customHeaders };
if ( if (
this.webdavConfig.username !== "" && this.webdavConfig.username !== "" &&
this.webdavConfig.password !== "" this.webdavConfig.password !== ""
) { ) {
this.client = createClient(this.webdavConfig.address, { this.client = createClient(this.webdavConfig.address, {
username: this.webdavConfig.username, username: tryEncodeUsernamePassword(this.webdavConfig.username),
password: this.webdavConfig.password, password: tryEncodeUsernamePassword(this.webdavConfig.password),
headers: headers, headers: headers,
authType: authType:
this.webdavConfig.authType === "digest" this.webdavConfig.authType === "digest"
@ -364,14 +413,21 @@ export class FakeFsWebdav extends FakeFs {
// taken from https://github.com/perry-mitchell/webdav-client/blob/master/source/operations/partialUpdateFileContents.ts // taken from https://github.com/perry-mitchell/webdav-client/blob/master/source/operations/partialUpdateFileContents.ts
// which is under MIT license // which is under MIT license
if ( if (
(compliance.server.includes("Apache") && compliance.server.includes("Apache") &&
compliance.compliance.includes( compliance.compliance.includes("<http://apache.org/dav/propset/fs/1>")
"<http://apache.org/dav/propset/fs/1>"
)) ||
compliance.compliance.includes("sabredav-partialupdate")
) { ) {
this.supportNativePartial = true; this.supportApachePartial = true;
console.debug(`supportNativePartial=true`); console.debug(
`supportApachePartial=true, compliance=${JSON.stringify(compliance)}`
);
return true;
}
if (compliance.compliance.includes("sabredav-partialupdate")) {
this.supportSabrePartial = true;
console.debug(
`supportSabrePartial=true, compliance=${JSON.stringify(compliance)}`
);
return true; return true;
} }
@ -387,7 +443,9 @@ export class FakeFsWebdav extends FakeFs {
this.webdavConfig.depth === "auto_unknown" || this.webdavConfig.depth === "auto_unknown" ||
this.webdavConfig.depth === "auto_1" || this.webdavConfig.depth === "auto_1" ||
this.webdavConfig.depth === "auto_infinity" /* don't trust auto now */ || this.webdavConfig.depth === "auto_infinity" /* don't trust auto now */ ||
this.webdavConfig.depth === "manual_1" this.webdavConfig.depth === "manual_1" ||
this.webdavConfig.address.includes("jianguoyun.com") ||
this.webdavConfig.address.includes("teracloud.jp")
) { ) {
// the remote doesn't support infinity propfind, // the remote doesn't support infinity propfind,
// we need to do a bfs here // we need to do a bfs here
@ -402,15 +460,17 @@ export class FakeFsWebdav extends FakeFs {
// console.debug(itemsToFetchChunks); // console.debug(itemsToFetchChunks);
const subContents = [] as FileStat[]; const subContents = [] as FileStat[];
for (const singleChunk of itemsToFetchChunks) { for (const singleChunk of itemsToFetchChunks) {
const r = singleChunk.map((x) => { const r = singleChunk.map(async (x) => {
return this.client.getDirectoryContents(x, { let k = (await this.client.getDirectoryContents(x, {
deep: false, deep: false,
details: false /* no need for verbose details here */, details: false /* no need for verbose details here */,
// TODO: to support .obsidian, // TODO: to support .obsidian,
// we need to load all files including dot, // we need to load all files including dot,
// anyway to reduce the resources? // anyway to reduce the resources?
// glob: "/**" /* avoid dot files by using glob */, // glob: "/**" /* avoid dot files by using glob */,
}) as Promise<FileStat[]>; })) as FileStat[];
k = k.filter((sub) => stripLeadingPath(sub.filename) !== x);
return k;
}); });
const r3 = await Promise.all(r); const r3 = await Promise.all(r);
for (const r4 of r3) { for (const r4 of r3) {
@ -432,7 +492,7 @@ export class FakeFsWebdav extends FakeFs {
const f = subContents[i]; const f = subContents[i];
contents.push(f); contents.push(f);
if (f.type === "directory") { if (f.type === "directory") {
q.push(f.filename); q.push(stripLeadingPath(f.filename));
} }
} }
} }
@ -450,7 +510,11 @@ export class FakeFsWebdav extends FakeFs {
} }
)) as FileStat[]; )) as FileStat[];
} }
return contents.map((x) => fromWebdavItemToEntity(x, this.remoteBaseDir));
const result = contents
.map((x) => fromWebdavItemToEntity(x, this.remoteBaseDir))
.filter((x) => x.keyRaw !== "/");
return result;
} }
async walkPartial(): Promise<Entity[]> { async walkPartial(): Promise<Entity[]> {
@ -463,7 +527,9 @@ export class FakeFsWebdav extends FakeFs {
details: false /* no need for verbose details here */, details: false /* no need for verbose details here */,
} }
)) as FileStat[]; )) as FileStat[];
return contents.map((x) => fromWebdavItemToEntity(x, this.remoteBaseDir)); return contents
.map((x) => fromWebdavItemToEntity(x, this.remoteBaseDir))
.filter((x) => x.keyRaw !== "/");
} }
async stat(key: string): Promise<Entity> { async stat(key: string): Promise<Entity> {
@ -540,7 +606,11 @@ export class FakeFsWebdav extends FakeFs {
} }
// larger than 10 MB // larger than 10 MB
if (!this.isNextcloud && !this.supportNativePartial) { if (
!this.isNextcloud &&
!this.supportApachePartial &&
!this.supportSabrePartial
) {
// give up and upload by whole, and directly return // give up and upload by whole, and directly return
return await this._writeFileFromRootFull( return await this._writeFileFromRootFull(
key, key,
@ -561,8 +631,16 @@ export class FakeFsWebdav extends FakeFs {
ctime, ctime,
origKey origKey
); );
} else if (this.supportNativePartial) { } else if (this.supportApachePartial) {
return await this._writeFileFromRootNativePartial( return await this._writeFileFromRootApachePartial(
key,
content,
mtime,
ctime,
origKey
);
} else if (this.supportSabrePartial) {
return await this._writeFileFromRootSabrePartial(
key, key,
content, content,
mtime, mtime,
@ -578,7 +656,7 @@ export class FakeFsWebdav extends FakeFs {
console.error(e); console.error(e);
throw e; throw e;
// this.isNextcloud = false; // this.isNextcloud = false;
// this.supportNativePartial = false; // this.supportApachePartial = false;
// return await this._writeFileFromRootFull( // return await this._writeFileFromRootFull(
// key, // key,
// content, // content,
@ -646,8 +724,8 @@ export class FakeFsWebdav extends FakeFs {
console.debug(`tmpFolderName=${tmpFolderName}`); console.debug(`tmpFolderName=${tmpFolderName}`);
const clientForUpload = createClient(uploadServerAddress, { const clientForUpload = createClient(uploadServerAddress, {
username: this.webdavConfig.username, username: tryEncodeUsernamePassword(this.webdavConfig.username),
password: this.webdavConfig.password, password: tryEncodeUsernamePassword(this.webdavConfig.password),
headers: { headers: {
"Cache-Control": "no-cache", "Cache-Control": "no-cache",
}, },
@ -723,7 +801,7 @@ export class FakeFsWebdav extends FakeFs {
return k; return k;
} }
async _writeFileFromRootNativePartial( async _writeFileFromRootApachePartial(
key: string, key: string,
content: ArrayBuffer, content: ArrayBuffer,
mtime: number, mtime: number,
@ -745,6 +823,8 @@ export class FakeFsWebdav extends FakeFs {
content.byteLength, content.byteLength,
sizePerChunk sizePerChunk
); );
// TODO: parallel
for (let i = 0; i < chunkRanges.length; ++i) { for (let i = 0; i < chunkRanges.length; ++i) {
const { start, end } = chunkRanges[i]; const { start, end } = chunkRanges[i];
await this.client.partialUpdateFileContents( await this.client.partialUpdateFileContents(
@ -759,6 +839,47 @@ export class FakeFsWebdav extends FakeFs {
return await this.stat(origKey); return await this.stat(origKey);
} }
async _writeFileFromRootSabrePartial(
key: string,
content: ArrayBuffer,
mtime: number,
ctime: number,
origKey: string
): Promise<Entity> {
// firstly upload a 0-byte data
await this._writeFileFromRootFull(
key,
new ArrayBuffer(0),
mtime,
ctime,
origKey
);
// then "update" by chunks
const sizePerChunk = 5 * 1024 * 1024; // 5 mb
const chunkRanges = splitFileSizeToChunkRanges(
content.byteLength,
sizePerChunk
);
// diff from apachePartial: we use "append" header here for dufs...
// we cannot parallel here
for (let i = 0; i < chunkRanges.length; ++i) {
const { start, end } = chunkRanges[i];
await this.client.customRequest(key, {
method: "PATCH",
headers: {
"X-Update-Range": "append",
"Content-Type": "application/x-sabredav-partialupdate",
},
data: content.slice(start, end + 1),
});
}
// lastly return
return await this.stat(origKey);
}
async readFile(key: string): Promise<ArrayBuffer> { async readFile(key: string): Promise<ArrayBuffer> {
if (key.endsWith("/")) { if (key.endsWith("/")) {
throw Error(`you should not call readFile on ${key}`); throw Error(`you should not call readFile on ${key}`);
@ -823,17 +944,15 @@ export class FakeFsWebdav extends FakeFs {
await this._init(); await this._init();
const results = await this._statFromRoot(`/${this.remoteBaseDir}/`); const results = await this._statFromRoot(`/${this.remoteBaseDir}/`);
if (results === undefined) { if (results === undefined) {
const err = "results is undefined"; throw Error("cannot stat root vault folder!");
console.error(err);
callbackFunc?.(err);
return false;
} }
return true;
} catch (err) { } catch (err) {
console.error(err); console.error(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {

View File

@ -117,7 +117,7 @@ export class FakeFsWebdis extends FakeFs {
let cursor = "0"; let cursor = "0";
const res: Entity[] = []; const res: Entity[] = [];
do { do {
const command = `SCAN/${cursor}/MATCH/rs:fs:v1:*:meta/COUNT/1000`; const command = `SCAN/${cursor}/MATCH/rs:fs:v1:${encodeURIComponent(this.remoteBaseDir + "/")}*:meta/COUNT/1000`;
const rsp = (await (await this._fetchCommand("GET", command)).json())[ const rsp = (await (await this._fetchCommand("GET", command)).json())[
"SCAN" "SCAN"
]; ];
@ -136,7 +136,7 @@ export class FakeFsWebdis extends FakeFs {
async walkPartial(): Promise<Entity[]> { async walkPartial(): Promise<Entity[]> {
let cursor = "0"; let cursor = "0";
const res: Entity[] = []; const res: Entity[] = [];
const command = `SCAN/${cursor}/MATCH/rs:fs:v1:*:meta/COUNT/10`; // fewer keys const command = `SCAN/${cursor}/MATCH/rs:fs:v1:${encodeURIComponent(this.remoteBaseDir + "/")}*:meta/COUNT/10`; // fewer keys
const rsp = (await (await this._fetchCommand("GET", command)).json())[ const rsp = (await (await this._fetchCommand("GET", command)).json())[
"SCAN" "SCAN"
]; ];
@ -252,12 +252,16 @@ export class FakeFsWebdis extends FakeFs {
const k = await ( const k = await (
await this._fetchCommand("GET", "PING/helloworld") await this._fetchCommand("GET", "PING/helloworld")
).json(); ).json();
return isEqual(k, { PING: "helloworld" }); if (!isEqual(k, { PING: "helloworld" })) {
throw Error(`no correct ping response`);
}
} catch (err: any) { } catch (err: any) {
console.error(err); console.error(err);
callbackFunc?.(err); callbackFunc?.(err);
return false; return false;
} }
return await this.checkConnectCommonOps(callbackFunc);
// return true;
} }
async getUserDisplayName(): Promise<string> { async getUserDisplayName(): Promise<string> {

View File

@ -1,13 +1,14 @@
import cloneDeep from "lodash/cloneDeep"; import cloneDeep from "lodash/cloneDeep";
import QRCode from "qrcode"; import QRCode from "qrcode";
import { getShrinkedSettings as getShrinkedSettingsOnedriveFull } from "../pro/src/fsOnedriveFull";
import { import {
COMMAND_URI, COMMAND_URI,
type QRExportType, type QRExportType,
type RemotelySavePluginSettings, type RemotelySavePluginSettings,
type UriParams, type UriParams,
} from "./baseTypes"; } from "./baseTypes";
import { getShrinkedSettings } from "./fsOnedrive"; import { getShrinkedSettings as getShrinkedSettingsOnedrive } from "./fsOnedrive";
export const exportQrCodeUri = async ( export const exportQrCodeUri = async (
settings: RemotelySavePluginSettings, settings: RemotelySavePluginSettings,
@ -22,6 +23,7 @@ export const exportQrCodeUri = async (
delete settings2.s3; delete settings2.s3;
delete settings2.dropbox; delete settings2.dropbox;
delete settings2.onedrive; delete settings2.onedrive;
delete settings2.onedrivefull;
delete settings2.webdav; delete settings2.webdav;
delete settings2.webdis; delete settings2.webdis;
delete settings2.googledrive; delete settings2.googledrive;
@ -36,7 +38,11 @@ export const exportQrCodeUri = async (
} else if (exportFields === "dropbox") { } else if (exportFields === "dropbox") {
settings2 = { dropbox: cloneDeep(settings.dropbox) }; settings2 = { dropbox: cloneDeep(settings.dropbox) };
} else if (exportFields === "onedrive") { } else if (exportFields === "onedrive") {
settings2 = { onedrive: getShrinkedSettings(settings.onedrive) }; settings2 = { onedrive: getShrinkedSettingsOnedrive(settings.onedrive) };
} else if (exportFields === "onedrivefull") {
settings2 = {
onedrivefull: getShrinkedSettingsOnedriveFull(settings.onedrivefull),
};
} else if (exportFields === "webdav") { } else if (exportFields === "webdav") {
settings2 = { webdav: cloneDeep(settings.webdav) }; settings2 = { webdav: cloneDeep(settings.webdav) };
} else if (exportFields === "webdis") { } else if (exportFields === "webdis") {

View File

@ -31,7 +31,7 @@
"protocol_dropbox_connect_succ_revoke": "You've connected as user {{username}}. If you want to disconnect, click this button.", "protocol_dropbox_connect_succ_revoke": "You've connected as user {{username}}. If you want to disconnect, click this button.",
"protocol_dropbox_connect_fail": "Something went wrong from response from Dropbox. Maybe the network connection is not good. Maybe you rejected the auth?", "protocol_dropbox_connect_fail": "Something went wrong from response from Dropbox. Maybe the network connection is not good. Maybe you rejected the auth?",
"protocol_dropbox_connect_unknown": "Do not know how to deal with the callback: {{params}}", "protocol_dropbox_connect_unknown": "Do not know how to deal with the callback: {{params}}",
"protocol_dropbox_no_modal": "You are not startting Dropbox connection from the settings page. Abort.", "protocol_dropbox_no_modal": "You are not starting Dropbox connection from the settings page. Abort.",
"protocol_onedrive_connecting": "Connecting to OneDrive...\nPlease DO NOT close this modal.", "protocol_onedrive_connecting": "Connecting to OneDrive...\nPlease DO NOT close this modal.",
"protocol_onedrive_connect_succ_revoke": "You've connected as user {{username}}. If you want to disconnect, click this button.", "protocol_onedrive_connect_succ_revoke": "You've connected as user {{username}}. If you want to disconnect, click this button.",
"protocol_onedrive_connect_fail": "Something went wrong from response from OneDrive. Maybe you rejected the auth?", "protocol_onedrive_connect_fail": "Something went wrong from response from OneDrive. Maybe you rejected the auth?",
@ -110,7 +110,7 @@
"modal_onedriverevokeauth_clean_button": "Clean", "modal_onedriverevokeauth_clean_button": "Clean",
"modal_onedriverevokeauth_clean_notice": "Cleaned!", "modal_onedriverevokeauth_clean_notice": "Cleaned!",
"modal_onedriverevokeauth_clean_fail": "Something goes wrong while revoking.", "modal_onedriverevokeauth_clean_fail": "Something goes wrong while revoking.",
"modal_syncconfig_attn": "Attention 1/2: This only syncs (copies) the whole Obsidian config dir, not other startting-with-dot folders or files. Except for ignoring folders .git and node_modules, it also doesn't understand the meaning of sub-files and sub-folders inside the config dir.\nAttention 2/2: After the config dir is synced, plugins settings might be corrupted, and Obsidian might need to be restarted to load the new settings.\nIf you are agreed to take your own risk, please click the following second confirm button.", "modal_syncconfig_attn": "Attention 1/2: This only syncs (copies) the whole Obsidian config dir, not other starting-with-dot folders or files. Except for ignoring folders .git and node_modules, it also doesn't understand the meaning of sub-files and sub-folders inside the config dir.\nAttention 2/2: After the config dir is synced, plugins settings might be corrupted, and Obsidian might need to be restarted to load the new settings.\nIf you are agreed to take your own risk, please click the following second confirm button.",
"modal_syncconfig_secondconfirm": "The Second Confirm To Enable.", "modal_syncconfig_secondconfirm": "The Second Confirm To Enable.",
"modal_syncconfig_notice": "You've enabled syncing config folder!", "modal_syncconfig_notice": "You've enabled syncing config folder!",
"modal_qr_shortdesc": "This exports (partial) settings.\nYou can use another device to scan this qrcode.\nOr, you can click the button to copy the special uri and paste it into another device's web browser or Remotely Save Import Setting.", "modal_qr_shortdesc": "This exports (partial) settings.\nYou can use another device to scan this qrcode.\nOr, you can click the button to copy the special uri and paste it into another device's web browser or Remotely Save Import Setting.",
@ -149,7 +149,9 @@
"settings_skiplargefiles_desc": "Skip files with sizes larger than the threshold. Here 1 MB = 10^6 bytes.", "settings_skiplargefiles_desc": "Skip files with sizes larger than the threshold. Here 1 MB = 10^6 bytes.",
"settings_skiplargefiles_notset": "(not set)", "settings_skiplargefiles_notset": "(not set)",
"settings_ignorepaths": "Regex Of Paths To Ignore", "settings_ignorepaths": "Regex Of Paths To Ignore",
"settings_ignorepaths_desc": "Regex of paths of folders or files to ignore. One regex per line. The path is relative to the vault root without leading slash.", "settings_ignorepaths_desc": "Regex of paths of folders or files to ignore. One regex per line. The path is relative to the vault root without leading slash. Non-empty allow paths and non-empty ignore paths are effective together.",
"settings_onlyallowpaths": "Regex Of Paths To Allow",
"settings_onlyallowpaths_desc": "Regex of paths of folders or files to allow to sync. One regex per line. The path is relative to the vault root without leading slash. If this setting is not empty, all paths you want to sync including config dirs must be explicitly set here. Non-empty allow paths and non-empty ignore paths are effective together.",
"settings_enablestatusbar_info": "Show Last Successful Sync In Status Bar", "settings_enablestatusbar_info": "Show Last Successful Sync In Status Bar",
"settings_enablestatusbar_info_desc": "Show the time of the last successful sync in the status bar.", "settings_enablestatusbar_info_desc": "Show the time of the last successful sync in the status bar.",
"settings_enablestatusbar_reloadrequired_notice": "Reload the plugin for the changes to take effect.", "settings_enablestatusbar_reloadrequired_notice": "Reload the plugin for the changes to take effect.",
@ -192,7 +194,7 @@
"settings_s3_reverse_proxy_no_sign_url": "S3 Reverse Proxy (No Sign) Url (experimental)", "settings_s3_reverse_proxy_no_sign_url": "S3 Reverse Proxy (No Sign) Url (experimental)",
"settings_s3_reverse_proxy_no_sign_url_desc": "S3 reverse proxy url without signature. This is useful if you use a revers proxy but do not change the original credential signature. No http(s):// prefix. Leave it blank if you don't know what it is.", "settings_s3_reverse_proxy_no_sign_url_desc": "S3 reverse proxy url without signature. This is useful if you use a revers proxy but do not change the original credential signature. No http(s):// prefix. Leave it blank if you don't know what it is.",
"settings_s3_generatefolderobject": "Generate Folder Object Or Not", "settings_s3_generatefolderobject": "Generate Folder Object Or Not",
"settings_s3_generatefolderobject_desc": "S3 doesn't have \"real\" folder. If you set \"Generate\" here (or use old version), the plugin will upload a zero-byte object endding with \"/\" to represent the folder. In the new version, the plugin skips generating folder object by default.", "settings_s3_generatefolderobject_desc": "S3 doesn't have \"real\" folder. If you set \"Generate\" here (or use old version), the plugin will upload a zero-byte object ending with \"/\" to represent the folder. In the new version, the plugin skips generating folder object by default.",
"settings_s3_generatefolderobject_notgenerate": "Not generate (default)", "settings_s3_generatefolderobject_notgenerate": "Not generate (default)",
"settings_s3_generatefolderobject_generate": "Generate", "settings_s3_generatefolderobject_generate": "Generate",
"settings_s3_connect_succ": "Great! The bucket can be accessed.", "settings_s3_connect_succ": "Great! The bucket can be accessed.",
@ -215,7 +217,7 @@
"settings_dropbox_auth_button": "Auth", "settings_dropbox_auth_button": "Auth",
"settings_dropbox_connect_succ": "Great! We can connect to Dropbox!", "settings_dropbox_connect_succ": "Great! We can connect to Dropbox!",
"settings_dropbox_connect_fail": "We cannot connect to Dropbox.", "settings_dropbox_connect_fail": "We cannot connect to Dropbox.",
"settings_onedrive": "Remote For Onedrive (for personal)", "settings_onedrive": "Remote For Onedrive (for personal) (App Folder)",
"settings_onedrive_disclaimer1": "Disclaimer: This app is NOT an official Microsoft / OneDrive product.", "settings_onedrive_disclaimer1": "Disclaimer: This app is NOT an official Microsoft / OneDrive product.",
"settings_onedrive_disclaimer2": "Disclaimer: The information is stored locally. Other malicious/harmful/faulty plugins could read the info. If you see any unintentional access to your Onedrive, please immediately disconnect this app on https://microsoft.com/consent .", "settings_onedrive_disclaimer2": "Disclaimer: The information is stored locally. Other malicious/harmful/faulty plugins could read the info. If you see any unintentional access to your Onedrive, please immediately disconnect this app on https://microsoft.com/consent .",
"settings_onedrive_folder": "We will create and sync inside the folder /Apps/{{pluginID}}/{{remoteBaseDir}} on your OneDrive.", "settings_onedrive_folder": "We will create and sync inside the folder /Apps/{{pluginID}}/{{remoteBaseDir}} on your OneDrive.",
@ -232,6 +234,7 @@
"settings_onedrive_emptyfile_desc": "OneDrive doesn't allow uploading empty file (even in its official website). Do you want to show up errors or silently skip the empty files?", "settings_onedrive_emptyfile_desc": "OneDrive doesn't allow uploading empty file (even in its official website). Do you want to show up errors or silently skip the empty files?",
"settings_onedrive_emptyfile_skip": "Skip", "settings_onedrive_emptyfile_skip": "Skip",
"settings_onedrive_emptyfile_error": "Error and abort", "settings_onedrive_emptyfile_error": "Error and abort",
"settings_webdav": "Remote For Webdav", "settings_webdav": "Remote For Webdav",
"settings_webdav_disclaimer1": "Disclaimer: The information is stored locally. Other malicious/harmful/faulty plugins may read the info. If you see any unintentional access to your webdav server, please immediately change the username and password.", "settings_webdav_disclaimer1": "Disclaimer: The information is stored locally. Other malicious/harmful/faulty plugins may read the info. If you see any unintentional access to your webdav server, please immediately change the username and password.",
"settings_webdav_cors_os": "Obsidian desktop>=0.13.25 or iOS>=1.1.1 or Android>=1.2.1 supports bypassing CORS locally. But you are using an old version, and you're suggested to upgrade Obsidian.", "settings_webdav_cors_os": "Obsidian desktop>=0.13.25 or iOS>=1.1.1 or Android>=1.2.1 supports bypassing CORS locally. But you are using an old version, and you're suggested to upgrade Obsidian.",
@ -249,9 +252,12 @@
"settings_webdav_depth_desc": "Webdav servers should be configured to allow requests with header Depth being '1' or 'Infinity'. If you are not sure what's this, choose \"depth='1'\". If you are sure your server supports depth='infinity', please choose that to get way better performance.", "settings_webdav_depth_desc": "Webdav servers should be configured to allow requests with header Depth being '1' or 'Infinity'. If you are not sure what's this, choose \"depth='1'\". If you are sure your server supports depth='infinity', please choose that to get way better performance.",
"settings_webdav_depth_1": "only supports depth='1'", "settings_webdav_depth_1": "only supports depth='1'",
"settings_webdav_depth_inf": "supports depth='infinity'", "settings_webdav_depth_inf": "supports depth='infinity'",
"settings_webdav_customheaders": "Custom Headers Sent To Servers",
"settings_webdav_customheaders_desc": "Some users may want to set custom headers. If you don't know what it is, just leave it empty. Input them like: <code>X-Header1:value1</code> in each line. All spaces around header keys and values will be removed.",
"settings_webdav_connect_succ": "Great! The webdav server can be accessed.", "settings_webdav_connect_succ": "Great! The webdav server can be accessed.",
"settings_webdav_connect_fail": "The webdav server cannot be reached (possible to be any of address/username/password/authtype errors).", "settings_webdav_connect_fail": "The webdav server cannot be reached (possible to be any of address/username/password/authtype errors).",
"settings_webdav_connect_fail_withcors": "The webdav server cannot be reached (possible to be any of address/username/password/authtype/CORS errors).", "settings_webdav_connect_fail_withcors": "The webdav server cannot be reached (possible to be any of address/username/password/authtype/CORS errors).",
"settings_webdis": "Remote For Webdis", "settings_webdis": "Remote For Webdis",
"settings_webdis_disclaimer1": "Disclaimer: This app is NOT an official Redis® Ltd / Redis® OSS / Webdis product. Redis is a registered trademark of Redis Ltd.", "settings_webdis_disclaimer1": "Disclaimer: This app is NOT an official Redis® Ltd / Redis® OSS / Webdis product. Redis is a registered trademark of Redis Ltd.",
"settings_webdis_disclaimer2": "Disclaimer: The information is stored locally. Other malicious/harmful/faulty plugins may read the info. If you see any unintentional access to your Webdis server, please immediately change the username and password.", "settings_webdis_disclaimer2": "Disclaimer: The information is stored locally. Other malicious/harmful/faulty plugins may read the info. If you see any unintentional access to your Webdis server, please immediately change the username and password.",
@ -278,6 +284,8 @@
"settings_syncunderscore_desc": "Sync files or folders starting with _ (\"underscore\") or not", "settings_syncunderscore_desc": "Sync files or folders starting with _ (\"underscore\") or not",
"settings_configdir": "Sync Config Dir (experimental)", "settings_configdir": "Sync Config Dir (experimental)",
"settings_configdir_desc": "Sync config dir {{configDir}} or not (inner folder .git and node_modules would be ignored). Please be aware that this may impact all your plugins' or Obsidian's settings, and may require you restart Obsidian after sync. Enable this at your own risk.", "settings_configdir_desc": "Sync config dir {{configDir}} or not (inner folder .git and node_modules would be ignored). Please be aware that this may impact all your plugins' or Obsidian's settings, and may require you restart Obsidian after sync. Enable this at your own risk.",
"settings_bookmarks": "Sync Bookmarks (experimental)",
"settings_bookmarks_desc": "Sync {{configDir}}/bookmarks.json or not. If you sync config dir, this option will be ignore and treated as \"enabled\".",
"settings_deletetowhere": "Deletion Destination", "settings_deletetowhere": "Deletion Destination",
"settings_deletetowhere_desc": "Which trash should the plugin put the files into while deleting?", "settings_deletetowhere_desc": "Which trash should the plugin put the files into while deleting?",
"settings_deletetowhere_system_trash": "system trash (default)", "settings_deletetowhere_system_trash": "system trash (default)",
@ -315,7 +323,7 @@
"settings_export_basic_and_advanced_button": "Export Basic And Advanced Part", "settings_export_basic_and_advanced_button": "Export Basic And Advanced Part",
"settings_export_s3_button": "Export S3 Part", "settings_export_s3_button": "Export S3 Part",
"settings_export_dropbox_button": "Export Dropbox Part", "settings_export_dropbox_button": "Export Dropbox Part",
"settings_export_onedrive_button": "Export OneDrive Part", "settings_export_onedrive_button": "Export OneDrive (App Folder) Part",
"settings_export_webdav_button": "Export Webdav Part", "settings_export_webdav_button": "Export Webdav Part",
"settings_export_webdis_button": "Export Webdis Part", "settings_export_webdis_button": "Export Webdis Part",
"settings_import": "Import", "settings_import": "Import",
@ -332,10 +340,11 @@
"settings_obfuscatesettingfile": "Obfuscate The Setting File Or Not", "settings_obfuscatesettingfile": "Obfuscate The Setting File Or Not",
"settings_obfuscatesettingfile_desc": "The setting file (data.json) has some sensitive information. It's strongly recommended to obfuscate it to avoid unexpected read and modification. If you are sure to view and edit it manually, you can disable the obfuscation.", "settings_obfuscatesettingfile_desc": "The setting file (data.json) has some sensitive information. It's strongly recommended to obfuscate it to avoid unexpected read and modification. If you are sure to view and edit it manually, you can disable the obfuscation.",
"settings_viewconsolelog": "View Console Log", "settings_viewconsolelog": "View Console Log",
"settings_viewconsolelog_desc": "On desktop, please press \"ctrl+shift+i\" or \"cmd+shift+i\" to view the log. On mobile, please install the third-party plugin <a href='https://obsidian.md/plugins?search=Logstravaganza'>Logstravaganza</a> to export the console log to a note.", "settings_viewconsolelog_desc": "On desktop, please press \"ctrl+shift+i\" or \"cmd+option+i\" to view the log. On mobile, please install the third-party plugin <a href='https://obsidian.md/plugins?search=Logstravaganza'>Logstravaganza</a> to export the console log to a note.",
"settings_syncplans": "Export Sync Plans", "settings_syncplans": "Export Sync Plans",
"settings_syncplans_desc": "Sync plans are created every time after you trigger sync and before the actual sync. Useful to know what would actually happen in those sync. Click the button to export sync plans.", "settings_syncplans_desc": "Sync plans are created every time after you trigger sync and before the actual sync. Useful to know what would actually happen in those sync. Click the button to export sync plans.",
"settings_syncplans_button_1_only_change": "Export latest 1 (change part)", "settings_syncplans_button_1_only_change": "Export latest 1 (change part)",
"settings_syncplans_button_5_only_change": "Export latest 5 (change part)",
"settings_syncplans_button_1": "Export latest 1", "settings_syncplans_button_1": "Export latest 1",
"settings_syncplans_button_5": "Export latest 5", "settings_syncplans_button_5": "Export latest 5",
"settings_syncplans_button_all": "Export All", "settings_syncplans_button_all": "Export All",
@ -352,6 +361,8 @@
"settings_profiler_results_desc": "The plugin records the time cost of each steps. Here you can export them to know which step is slow.", "settings_profiler_results_desc": "The plugin records the time cost of each steps. Here you can export them to know which step is slow.",
"settings_profiler_results_notice": "Profiler results exported.", "settings_profiler_results_notice": "Profiler results exported.",
"settings_profiler_results_button_all": "Export All", "settings_profiler_results_button_all": "Export All",
"settings_profiler_enableprofiler": "Enable Profiler",
"settings_profiler_enableprofiler_desc": "Collect performance data or not?",
"settings_profiler_enabledebugprint": "Enable Profiler Printing", "settings_profiler_enabledebugprint": "Enable Profiler Printing",
"settings_profiler_enabledebugprint_desc": "Print profiler result in each insertion to console or not?", "settings_profiler_enabledebugprint_desc": "Print profiler result in each insertion to console or not?",
"settings_profiler_recordsize": "Enable Profiler Recording Size", "settings_profiler_recordsize": "Enable Profiler Recording Size",

View File

@ -58,7 +58,7 @@
"statusbar_time_days": "{{time}} 天前", "statusbar_time_days": "{{time}} 天前",
"statusbar_time_hours": "{{time}} 小时前", "statusbar_time_hours": "{{time}} 小时前",
"statusbar_time_minutes": "{{time}} 分钟前", "statusbar_time_minutes": "{{time}} 分钟前",
"statusbar_time_lessminute": "1 分钟内", "statusbar_time_lessminute": "1 分钟内",
"statusbar_time_now": "刚刚", "statusbar_time_now": "刚刚",
"statusbar_syncing": "正在同步", "statusbar_syncing": "正在同步",
"statusbar_lastsync_label": "日期:{{date}}", "statusbar_lastsync_label": "日期:{{date}}",
@ -148,7 +148,9 @@
"settings_skiplargefiles_desc": "跳过大于某一个阈值的文件。这里 1 MB = 10^6 bytes。", "settings_skiplargefiles_desc": "跳过大于某一个阈值的文件。这里 1 MB = 10^6 bytes。",
"settings_skiplargefiles_notset": "(不设置)", "settings_skiplargefiles_notset": "(不设置)",
"settings_ignorepaths": "忽略的文件或文件夹的正则表达式", "settings_ignorepaths": "忽略的文件或文件夹的正则表达式",
"settings_ignorepaths_desc": "忽略的文件或文件夹的正则表达式。每行一条。路径是相对于库Vault根目录的没有前置 / 符号。", "settings_ignorepaths_desc": "忽略的文件或文件夹的正则表达式。每行一条。路径是相对于库Vault根目录的没有前置 / 符号。非空的忽略列表和非空的允许列表会一起生效。",
"settings_onlyallowpaths": "允许同步的文件或文件夹的正则表达式",
"settings_onlyallowpaths_desc": "允许同步的文件或文件夹的正则表达式。每行一条。路径是相对于库Vault根目录的没有前置 / 符号。如果这个设置非空,那么所有您想同步的路径(包括隐藏的设置文件夹)都要明确地列出到这里。非空的忽略列表和非空的允许列表会一起生效。",
"settings_enablestatusbar_info": "在状态栏显示上一次成功的同步", "settings_enablestatusbar_info": "在状态栏显示上一次成功的同步",
"settings_enablestatusbar_info_desc": "在状态栏显示上一次成功的同步的时间。", "settings_enablestatusbar_info_desc": "在状态栏显示上一次成功的同步的时间。",
"settings_enablestatusbar_reloadrequired_notice": "需要重新载入此插件才生效。", "settings_enablestatusbar_reloadrequired_notice": "需要重新载入此插件才生效。",
@ -214,7 +216,7 @@
"settings_dropbox_auth_button": "鉴权", "settings_dropbox_auth_button": "鉴权",
"settings_dropbox_connect_succ": "很好!我们可连接上 Dropbox", "settings_dropbox_connect_succ": "很好!我们可连接上 Dropbox",
"settings_dropbox_connect_fail": "我们未能连接上 Dropbox。", "settings_dropbox_connect_fail": "我们未能连接上 Dropbox。",
"settings_onedrive": "Onedrive个人版设置", "settings_onedrive": "Onedrive个人版App Folder设置",
"settings_onedrive_disclaimer1": "声明:此插件不是微软或 OneDrive 的官方产品。", "settings_onedrive_disclaimer1": "声明:此插件不是微软或 OneDrive 的官方产品。",
"settings_onedrive_disclaimer2": "声明:您所输入的信息存储于本地。其它有害的或者出错的插件,是有可能读取到这些信息的。如果您发现了 OneDrive 有不符合预期的访问,请立刻从 https://microsoft.com/consent 删除记录于此插件的连接鉴权。", "settings_onedrive_disclaimer2": "声明:您所输入的信息存储于本地。其它有害的或者出错的插件,是有可能读取到这些信息的。如果您发现了 OneDrive 有不符合预期的访问,请立刻从 https://microsoft.com/consent 删除记录于此插件的连接鉴权。",
"settings_onedrive_folder": "我们会在您的 OneDrive 上创建此文件夹并在里面同步:/Apps/{{pluginID}}/{{remoteBaseDir}}。", "settings_onedrive_folder": "我们会在您的 OneDrive 上创建此文件夹并在里面同步:/Apps/{{pluginID}}/{{remoteBaseDir}}。",
@ -231,6 +233,7 @@
"settings_onedrive_emptyfile_desc": "OneDrive 不允许上传空文件(即使官网也是不允许的)。那么你想跳过空文件还是返回错误?", "settings_onedrive_emptyfile_desc": "OneDrive 不允许上传空文件(即使官网也是不允许的)。那么你想跳过空文件还是返回错误?",
"settings_onedrive_emptyfile_skip": "跳过", "settings_onedrive_emptyfile_skip": "跳过",
"settings_onedrive_emptyfile_error": "返回错误和中断", "settings_onedrive_emptyfile_error": "返回错误和中断",
"settings_webdav": "Webdav 设置", "settings_webdav": "Webdav 设置",
"settings_webdav_disclaimer1": "声明:您所输入的信息存储于本地。其它有害的或者出错的插件,是有可能读取到这些信息的。如果您发现了 Webdav 服务器有不符合预期的访问,请立刻修改用户名和密码。", "settings_webdav_disclaimer1": "声明:您所输入的信息存储于本地。其它有害的或者出错的插件,是有可能读取到这些信息的。如果您发现了 Webdav 服务器有不符合预期的访问,请立刻修改用户名和密码。",
"settings_webdav_cors_os": "Obsidian 桌面版>=0.13.25 或 iOS>=1.1.1 或 Android>=1.2.1 支持跳过 CORS 设置。但您正在使用旧版,建议升级。", "settings_webdav_cors_os": "Obsidian 桌面版>=0.13.25 或 iOS>=1.1.1 或 Android>=1.2.1 支持跳过 CORS 设置。但您正在使用旧版,建议升级。",
@ -248,9 +251,12 @@
"settings_webdav_depth_desc": "Webdav 服务器会被设为接收 Depth header 为“1”或“Infinity”请求。如果您不清楚如何设置可以选择 depth='1'。如果那你确认服务器支持 depth='infinity',请选择它,会获得更加好的性能。", "settings_webdav_depth_desc": "Webdav 服务器会被设为接收 Depth header 为“1”或“Infinity”请求。如果您不清楚如何设置可以选择 depth='1'。如果那你确认服务器支持 depth='infinity',请选择它,会获得更加好的性能。",
"settings_webdav_depth_1": "只支持 depth='1'", "settings_webdav_depth_1": "只支持 depth='1'",
"settings_webdav_depth_inf": "支持 depth='infinity'", "settings_webdav_depth_inf": "支持 depth='infinity'",
"settings_webdav_customheaders": "发送到服务器的自定义 Header",
"settings_webdav_customheaders_desc": "有些用户需要设置自定义 header。如果您不知道是什么可以直接留空不填。输入格式每行形如 <code>X-Header1:value1</code>。header 的 key 和 value 之间的空格会被删除。",
"settings_webdav_connect_succ": "很好!可以连接上 Webdav 服务器。", "settings_webdav_connect_succ": "很好!可以连接上 Webdav 服务器。",
"settings_webdav_connect_fail": "无法连接上 Webdav 服务器。(可能是地址/账号/密码/鉴权类型等错误。)", "settings_webdav_connect_fail": "无法连接上 Webdav 服务器。(可能是地址/账号/密码/鉴权类型等错误。)",
"settings_webdav_connect_fail_withcors": "无法连接上 Webdav 服务器。(可能是地址/账号/密码/鉴权类型/CORS 等错误。)", "settings_webdav_connect_fail_withcors": "无法连接上 Webdav 服务器。(可能是地址/账号/密码/鉴权类型/CORS 等错误。)",
"settings_webdis": "Webdis 设置", "settings_webdis": "Webdis 设置",
"settings_webdis_disclaimer1": "声明:此插件不是 Redis® Ltd 或 Redis® 软件或 Wedis 的官方产品。Redis 是 Redis Ltd 的注册商标。", "settings_webdis_disclaimer1": "声明:此插件不是 Redis® Ltd 或 Redis® 软件或 Wedis 的官方产品。Redis 是 Redis Ltd 的注册商标。",
"settings_webdis_disclaimer2": "声明:您所输入的信息存储于本地。其它有害的或者出错的插件,是有可能读取到这些信息的。如果您发现了 Webdis 服务器有不符合预期的访问,请立刻修改用户名和密码。", "settings_webdis_disclaimer2": "声明:您所输入的信息存储于本地。其它有害的或者出错的插件,是有可能读取到这些信息的。如果您发现了 Webdis 服务器有不符合预期的访问,请立刻修改用户名和密码。",
@ -277,6 +283,8 @@
"settings_syncunderscore_desc": "是否同步“_”下划线开始的文件或文件夹。", "settings_syncunderscore_desc": "是否同步“_”下划线开始的文件或文件夹。",
"settings_configdir": "同步配置文件夹(实验性质)", "settings_configdir": "同步配置文件夹(实验性质)",
"settings_configdir_desc": "是否同步 Obsidian 的配置文件夹 {{configDir}}(其中的 .git 和 node_modules 依然会被忽略)。请注意,此设置可能会影响到您 Obsidian 或者所有的插件设置,也可能需要您同步完毕后重启 Obsidian。如果您同意自行承受其风险则可以开启本设置。", "settings_configdir_desc": "是否同步 Obsidian 的配置文件夹 {{configDir}}(其中的 .git 和 node_modules 依然会被忽略)。请注意,此设置可能会影响到您 Obsidian 或者所有的插件设置,也可能需要您同步完毕后重启 Obsidian。如果您同意自行承受其风险则可以开启本设置。",
"settings_bookmarks": "同步书签(实验性质)",
"settings_bookmarks_desc": "是否同步书签 {{configDir}}/bookmarks.json 。如果您设置了同步配置文件夹,此选项会被忽略并设为“开启”。",
"settings_deletetowhere": "删除文件到哪里", "settings_deletetowhere": "删除文件到哪里",
"settings_deletetowhere_desc": "插件触发删除操作时候,删除到哪里?", "settings_deletetowhere_desc": "插件触发删除操作时候,删除到哪里?",
"settings_deletetowhere_system_trash": "系统回收站(默认)", "settings_deletetowhere_system_trash": "系统回收站(默认)",
@ -314,7 +322,7 @@
"settings_export_basic_and_advanced_button": "导出基本或进阶设置", "settings_export_basic_and_advanced_button": "导出基本或进阶设置",
"settings_export_s3_button": "导出 S3 部分", "settings_export_s3_button": "导出 S3 部分",
"settings_export_dropbox_button": "导出 Dropbox 部分", "settings_export_dropbox_button": "导出 Dropbox 部分",
"settings_export_onedrive_button": "导出 OneDrive 部分", "settings_export_onedrive_button": "导出 OneDrive (App Folder) 部分",
"settings_export_webdav_button": "导出 Webdav 部分", "settings_export_webdav_button": "导出 Webdav 部分",
"settings_export_webdis_button": "导出 Webdis 部分", "settings_export_webdis_button": "导出 Webdis 部分",
"settings_import": "导入", "settings_import": "导入",
@ -335,6 +343,7 @@
"settings_syncplans": "导出同步计划", "settings_syncplans": "导出同步计划",
"settings_syncplans_desc": "每次您启动同步,并在实际上传下载前,插件会生成同步计划。它可以使您知道每次同步发生了什么。点击按钮可以导出同步计划。", "settings_syncplans_desc": "每次您启动同步,并在实际上传下载前,插件会生成同步计划。它可以使您知道每次同步发生了什么。点击按钮可以导出同步计划。",
"settings_syncplans_button_1_only_change": "导出最近 1 次(仅修改部分)", "settings_syncplans_button_1_only_change": "导出最近 1 次(仅修改部分)",
"settings_syncplans_button_5_only_change": "导出最近 5 次(仅修改部分)",
"settings_syncplans_button_1": "导出最近 1 次", "settings_syncplans_button_1": "导出最近 1 次",
"settings_syncplans_button_5": "导出最近 5 次", "settings_syncplans_button_5": "导出最近 5 次",
"settings_syncplans_button_all": "导出所有", "settings_syncplans_button_all": "导出所有",
@ -351,6 +360,12 @@
"settings_profiler_results_desc": "插件记录了每次同步每一步的耗时。这里可以导出记录得知哪一步最慢。", "settings_profiler_results_desc": "插件记录了每次同步每一步的耗时。这里可以导出记录得知哪一步最慢。",
"settings_profiler_results_notice": "性能数据已导出", "settings_profiler_results_notice": "性能数据已导出",
"settings_profiler_results_button_all": "导出所有", "settings_profiler_results_button_all": "导出所有",
"settings_profiler_enableprofiler": "性能收集",
"settings_profiler_enableprofiler_desc": "是否开启性能收集功能?",
"settings_profiler_enabledebugprint": "性能收集输出",
"settings_profiler_enabledebugprint_desc": "是否直接输出性能收集结果到终端里?",
"settings_profiler_recordsize": "性能收集统计对象大小",
"settings_profiler_recordsize_desc": "是否收集对象的大小?",
"settings_outputbasepathvaultid": "输出资料库对应的位置和随机分配的 ID", "settings_outputbasepathvaultid": "输出资料库对应的位置和随机分配的 ID",
"settings_outputbasepathvaultid_desc": "用于调试。", "settings_outputbasepathvaultid_desc": "用于调试。",
"settings_outputbasepathvaultid_button": "输出", "settings_outputbasepathvaultid_button": "输出",

View File

@ -57,7 +57,7 @@
"statusbar_time_days": "{{time}} 天前", "statusbar_time_days": "{{time}} 天前",
"statusbar_time_hours": "{{time}} 小時前", "statusbar_time_hours": "{{time}} 小時前",
"statusbar_time_minutes": "{{time}} 分鐘前", "statusbar_time_minutes": "{{time}} 分鐘前",
"statusbar_time_lessminute": "1 分鐘內", "statusbar_time_lessminute": "1 分鐘內",
"statusbar_time_now": "剛剛", "statusbar_time_now": "剛剛",
"statusbar_syncing": "正在同步", "statusbar_syncing": "正在同步",
"statusbar_lastsync_label": "日期:{{date}}", "statusbar_lastsync_label": "日期:{{date}}",
@ -147,7 +147,9 @@
"settings_skiplargefiles_desc": "跳過大於某一個閾值的檔案。這裡 1 MB = 10^6 bytes。", "settings_skiplargefiles_desc": "跳過大於某一個閾值的檔案。這裡 1 MB = 10^6 bytes。",
"settings_skiplargefiles_notset": "(不設定)", "settings_skiplargefiles_notset": "(不設定)",
"settings_ignorepaths": "忽略的檔案或資料夾的正則表示式", "settings_ignorepaths": "忽略的檔案或資料夾的正則表示式",
"settings_ignorepaths_desc": "忽略的檔案或資料夾的正則表示式。每行一條。路徑是相對於庫Vault根目錄的沒有前置 / 符號。", "settings_ignorepaths_desc": "忽略的檔案或資料夾的正則表示式。每行一條。路徑是相對於庫Vault根目錄的沒有前置 / 符號。非空的忽略列表和非空的允許列表會一起生效。",
"settings_onlyallowpaths": "允許同步的檔案或資料夾的正則表示式",
"settings_onlyallowpaths_desc": "允許同步的檔案或資料夾的正則表示式。每行一條。路徑是相對於庫Vault根目錄的沒有前置 / 符號。如果這個設定非空,那麼所有您想同步的路徑(包括隱藏的設定資料夾)都要明確地列出到這裡。非空的忽略列表和非空的允許列表會一起生效。",
"settings_enablestatusbar_info": "在狀態列顯示上一次成功的同步", "settings_enablestatusbar_info": "在狀態列顯示上一次成功的同步",
"settings_enablestatusbar_info_desc": "在狀態列顯示上一次成功的同步的時間。", "settings_enablestatusbar_info_desc": "在狀態列顯示上一次成功的同步的時間。",
"settings_enablestatusbar_reloadrequired_notice": "需要重新載入此外掛才生效。", "settings_enablestatusbar_reloadrequired_notice": "需要重新載入此外掛才生效。",
@ -213,7 +215,7 @@
"settings_dropbox_auth_button": "鑑權", "settings_dropbox_auth_button": "鑑權",
"settings_dropbox_connect_succ": "很好!我們可連線上 Dropbox", "settings_dropbox_connect_succ": "很好!我們可連線上 Dropbox",
"settings_dropbox_connect_fail": "我們未能連線上 Dropbox。", "settings_dropbox_connect_fail": "我們未能連線上 Dropbox。",
"settings_onedrive": "Onedrive個人版設定", "settings_onedrive": "Onedrive個人版App Folder設定",
"settings_onedrive_disclaimer1": "宣告:此外掛不是微軟或 OneDrive 的官方產品。", "settings_onedrive_disclaimer1": "宣告:此外掛不是微軟或 OneDrive 的官方產品。",
"settings_onedrive_disclaimer2": "宣告:您所輸入的資訊儲存於本地。其它有害的或者出錯的外掛,是有可能讀取到這些資訊的。如果您發現了 OneDrive 有不符合預期的訪問,請立刻從 https://microsoft.com/consent 刪除記錄於此外掛的連線鑑權。", "settings_onedrive_disclaimer2": "宣告:您所輸入的資訊儲存於本地。其它有害的或者出錯的外掛,是有可能讀取到這些資訊的。如果您發現了 OneDrive 有不符合預期的訪問,請立刻從 https://microsoft.com/consent 刪除記錄於此外掛的連線鑑權。",
"settings_onedrive_folder": "我們會在您的 OneDrive 上建立此資料夾並在裡面同步:/Apps/{{pluginID}}/{{remoteBaseDir}}。", "settings_onedrive_folder": "我們會在您的 OneDrive 上建立此資料夾並在裡面同步:/Apps/{{pluginID}}/{{remoteBaseDir}}。",
@ -230,6 +232,7 @@
"settings_onedrive_emptyfile_desc": "OneDrive 不允許上傳空檔案(即使官網也是不允許的)。那麼你想跳過空檔案還是返回錯誤?", "settings_onedrive_emptyfile_desc": "OneDrive 不允許上傳空檔案(即使官網也是不允許的)。那麼你想跳過空檔案還是返回錯誤?",
"settings_onedrive_emptyfile_skip": "跳過", "settings_onedrive_emptyfile_skip": "跳過",
"settings_onedrive_emptyfile_error": "返回錯誤和中斷", "settings_onedrive_emptyfile_error": "返回錯誤和中斷",
"settings_webdav": "Webdav 設定", "settings_webdav": "Webdav 設定",
"settings_webdav_disclaimer1": "宣告:您所輸入的資訊儲存於本地。其它有害的或者出錯的外掛,是有可能讀取到這些資訊的。如果您發現了 Webdav 伺服器有不符合預期的訪問,請立刻修改使用者名稱和密碼。", "settings_webdav_disclaimer1": "宣告:您所輸入的資訊儲存於本地。其它有害的或者出錯的外掛,是有可能讀取到這些資訊的。如果您發現了 Webdav 伺服器有不符合預期的訪問,請立刻修改使用者名稱和密碼。",
"settings_webdav_cors_os": "Obsidian 桌面版>=0.13.25 或 iOS>=1.1.1 或 Android>=1.1.1 支援跳過 CORS 設定。但您正在使用舊版,建議升級。", "settings_webdav_cors_os": "Obsidian 桌面版>=0.13.25 或 iOS>=1.1.1 或 Android>=1.1.1 支援跳過 CORS 設定。但您正在使用舊版,建議升級。",
@ -247,9 +250,12 @@
"settings_webdav_depth_desc": "Webdav 伺服器會被設為接收 Depth header 為“1”或“Infinity”請求。如果您不清楚如何設定可以選擇 depth='1'。如果那你確認伺服器支援 depth='infinity',請選擇它,會獲得更加好的效能。", "settings_webdav_depth_desc": "Webdav 伺服器會被設為接收 Depth header 為“1”或“Infinity”請求。如果您不清楚如何設定可以選擇 depth='1'。如果那你確認伺服器支援 depth='infinity',請選擇它,會獲得更加好的效能。",
"settings_webdav_depth_1": "只支援 depth='1'", "settings_webdav_depth_1": "只支援 depth='1'",
"settings_webdav_depth_inf": "支援 depth='infinity'", "settings_webdav_depth_inf": "支援 depth='infinity'",
"settings_webdav_customheaders": "傳送到伺服器的自定義 Header",
"settings_webdav_customheaders_desc": "有些使用者需要設定自定義 header。如果您不知道是什麼可以直接留空不填。輸入格式每行形如 <code>X-Header1:value1</code>。header 的 key 和 value 之間的空格會被刪除。",
"settings_webdav_connect_succ": "很好!可以連線上 Webdav 伺服器。", "settings_webdav_connect_succ": "很好!可以連線上 Webdav 伺服器。",
"settings_webdav_connect_fail": "無法連線上 Webdav 伺服器。(可能是地址/賬號/密碼/鑑權型別等錯誤。)", "settings_webdav_connect_fail": "無法連線上 Webdav 伺服器。(可能是地址/賬號/密碼/鑑權型別等錯誤。)",
"settings_webdav_connect_fail_withcors": "無法連線上 Webdav 伺服器。(可能是地址/賬號/密碼/鑑權型別/CORS 等錯誤。)", "settings_webdav_connect_fail_withcors": "無法連線上 Webdav 伺服器。(可能是地址/賬號/密碼/鑑權型別/CORS 等錯誤。)",
"settings_webdis": "Webdis 設置", "settings_webdis": "Webdis 設置",
"settings_webdis_disclaimer1": "聲明:此插件不是 Redis® Ltd 或 Redis® 軟件或 Wedis 的官方產品。Redis 是 Redis Ltd 的註冊商標。", "settings_webdis_disclaimer1": "聲明:此插件不是 Redis® Ltd 或 Redis® 軟件或 Wedis 的官方產品。Redis 是 Redis Ltd 的註冊商標。",
"settings_webdis_disclaimer2": "聲明:您所輸入的信息存儲於本地。其它有害的或者出錯的插件,是有可能讀取到這些信息的。如果您發現了 Webdis 服務器有不符合預期的訪問,請立刻修改用戶名和密碼。", "settings_webdis_disclaimer2": "聲明:您所輸入的信息存儲於本地。其它有害的或者出錯的插件,是有可能讀取到這些信息的。如果您發現了 Webdis 服務器有不符合預期的訪問,請立刻修改用戶名和密碼。",
@ -276,6 +282,8 @@
"settings_syncunderscore_desc": "是否同步“_”下劃線開始的檔案或資料夾。", "settings_syncunderscore_desc": "是否同步“_”下劃線開始的檔案或資料夾。",
"settings_configdir": "同步配置資料夾(實驗性質)", "settings_configdir": "同步配置資料夾(實驗性質)",
"settings_configdir_desc": "是否同步 Obsidian 的配置資料夾 {{configDir}}(其中的 .git 和 node_modules 依然會被忽略)。請注意,此設定可能會影響到您 Obsidian 或者所有的外掛設定,也可能需要您同步完畢後重啟 Obsidian。如果您同意自行承受其風險則可以開啟本設定。", "settings_configdir_desc": "是否同步 Obsidian 的配置資料夾 {{configDir}}(其中的 .git 和 node_modules 依然會被忽略)。請注意,此設定可能會影響到您 Obsidian 或者所有的外掛設定,也可能需要您同步完畢後重啟 Obsidian。如果您同意自行承受其風險則可以開啟本設定。",
"settings_bookmarks": "同步書籤(實驗性質)",
"settings_bookmarks_desc": "是否同步書籤 {{configDir}}/bookmarks.json 。如果您設定了同步配置資料夾,此選項會被忽略並設為“開啟”。",
"settings_deletetowhere": "刪除檔案到哪裡", "settings_deletetowhere": "刪除檔案到哪裡",
"settings_deletetowhere_desc": "外掛觸發刪除操作時候,刪除到哪裡?", "settings_deletetowhere_desc": "外掛觸發刪除操作時候,刪除到哪裡?",
"settings_deletetowhere_system_trash": "系統回收站(預設)", "settings_deletetowhere_system_trash": "系統回收站(預設)",
@ -313,7 +321,7 @@
"settings_export_basic_and_advanced_button": "匯出基本或進階設定", "settings_export_basic_and_advanced_button": "匯出基本或進階設定",
"settings_export_s3_button": "匯出 S3 部分", "settings_export_s3_button": "匯出 S3 部分",
"settings_export_dropbox_button": "匯出 Dropbox 部分", "settings_export_dropbox_button": "匯出 Dropbox 部分",
"settings_export_onedrive_button": "匯出 OneDrive 部分", "settings_export_onedrive_button": "匯出 OneDrive (App Folder) 部分",
"settings_export_webdav_button": "匯出 Webdav 部分", "settings_export_webdav_button": "匯出 Webdav 部分",
"settings_export_webdis_button": "匯出 Webdis 部分", "settings_export_webdis_button": "匯出 Webdis 部分",
"settings_import": "匯入", "settings_import": "匯入",
@ -334,6 +342,7 @@
"settings_syncplans": "匯出同步計劃", "settings_syncplans": "匯出同步計劃",
"settings_syncplans_desc": "每次您啟動同步,並在實際上傳下載前,外掛會生成同步計劃。它可以使您知道每次同步發生了什麼。點選按鈕可以匯出同步計劃。", "settings_syncplans_desc": "每次您啟動同步,並在實際上傳下載前,外掛會生成同步計劃。它可以使您知道每次同步發生了什麼。點選按鈕可以匯出同步計劃。",
"settings_syncplans_button_1_only_change": "匯出最近 1 次(僅修改部分)", "settings_syncplans_button_1_only_change": "匯出最近 1 次(僅修改部分)",
"settings_syncplans_button_5_only_change": "匯出最近 5 次(僅修改部分)",
"settings_syncplans_button_1": "匯出最近 1 次", "settings_syncplans_button_1": "匯出最近 1 次",
"settings_syncplans_button_5": "匯出最近 5 次", "settings_syncplans_button_5": "匯出最近 5 次",
"settings_syncplans_button_all": "匯出所有", "settings_syncplans_button_all": "匯出所有",
@ -350,6 +359,12 @@
"settings_profiler_results_desc": "外掛記錄了每次同步每一步的耗時。這裡可以匯出記錄得知哪一步最慢。", "settings_profiler_results_desc": "外掛記錄了每次同步每一步的耗時。這裡可以匯出記錄得知哪一步最慢。",
"settings_profiler_results_notice": "效能資料已匯出", "settings_profiler_results_notice": "效能資料已匯出",
"settings_profiler_results_button_all": "匯出所有", "settings_profiler_results_button_all": "匯出所有",
"settings_profiler_enableprofiler": "效能收集",
"settings_profiler_enableprofiler_desc": "是否開啟效能收集功能?",
"settings_profiler_enabledebugprint": "效能收集輸出",
"settings_profiler_enabledebugprint_desc": "是否直接輸出效能收集結果到終端裡?",
"settings_profiler_recordsize": "效能收集統計物件大小",
"settings_profiler_recordsize_desc": "是否收集物件的大小?",
"settings_outputbasepathvaultid": "輸出資料庫對應的位置和隨機分配的 ID", "settings_outputbasepathvaultid": "輸出資料庫對應的位置和隨機分配的 ID",
"settings_outputbasepathvaultid_desc": "用於除錯。", "settings_outputbasepathvaultid_desc": "用於除錯。",
"settings_outputbasepathvaultid_button": "輸出", "settings_outputbasepathvaultid_button": "輸出",

View File

@ -26,6 +26,7 @@ import {
import { import {
COMMAND_CALLBACK_BOX, COMMAND_CALLBACK_BOX,
COMMAND_CALLBACK_KOOFR, COMMAND_CALLBACK_KOOFR,
COMMAND_CALLBACK_ONEDRIVEFULL,
COMMAND_CALLBACK_PCLOUD, COMMAND_CALLBACK_PCLOUD,
COMMAND_CALLBACK_PRO, COMMAND_CALLBACK_PRO,
COMMAND_CALLBACK_YANDEXDISK, COMMAND_CALLBACK_YANDEXDISK,
@ -43,6 +44,12 @@ import {
sendAuthReq as sendAuthReqKoofr, sendAuthReq as sendAuthReqKoofr,
setConfigBySuccessfullAuthInplace as setConfigBySuccessfullAuthInplaceKoofr, setConfigBySuccessfullAuthInplace as setConfigBySuccessfullAuthInplaceKoofr,
} from "../pro/src/fsKoofr"; } from "../pro/src/fsKoofr";
import {
type AccessCodeResponseSuccessfulType as AccessCodeResponseSuccessfulTypeOnedriveFull,
DEFAULT_ONEDRIVEFULL_CONFIG,
sendAuthReq as sendAuthReqOnedriveFull,
setConfigBySuccessfullAuthInplace as setConfigBySuccessfullAuthInplaceOnedriveFull,
} from "../pro/src/fsOnedriveFull";
import { import {
type AuthAllowFirstRes as AuthAllowFirstResPCloud, type AuthAllowFirstRes as AuthAllowFirstResPCloud,
DEFAULT_PCLOUD_CONFIG, DEFAULT_PCLOUD_CONFIG,
@ -78,7 +85,7 @@ import { FakeFsEncrypt } from "./fsEncrypt";
import { getClient } from "./fsGetter"; import { getClient } from "./fsGetter";
import { FakeFsLocal } from "./fsLocal"; import { FakeFsLocal } from "./fsLocal";
import { import {
type AccessCodeResponseSuccessfulType, type AccessCodeResponseSuccessfulType as AccessCodeResponseSuccessfulTypeOnedrive,
DEFAULT_ONEDRIVE_CONFIG, DEFAULT_ONEDRIVE_CONFIG,
sendAuthReq as sendAuthReqOnedrive, sendAuthReq as sendAuthReqOnedrive,
setConfigBySuccessfullAuthInplace as setConfigBySuccessfullAuthInplaceOnedrive, setConfigBySuccessfullAuthInplace as setConfigBySuccessfullAuthInplaceOnedrive,
@ -101,7 +108,7 @@ import {
upsertPluginVersionByVault, upsertPluginVersionByVault,
} from "./localdb"; } from "./localdb";
import { changeMobileStatusBar } from "./misc"; import { changeMobileStatusBar } from "./misc";
import { DEFAULT_PROFILER_CONFIG, type Profiler } from "./profiler"; import { DEFAULT_PROFILER_CONFIG, Profiler } from "./profiler";
import { RemotelySaveSettingTab } from "./settings"; import { RemotelySaveSettingTab } from "./settings";
import { SyncAlgoV3Modal } from "./syncAlgoV3Notice"; import { SyncAlgoV3Modal } from "./syncAlgoV3Notice";
@ -110,6 +117,7 @@ const DEFAULT_SETTINGS: RemotelySavePluginSettings = {
webdav: DEFAULT_WEBDAV_CONFIG, webdav: DEFAULT_WEBDAV_CONFIG,
dropbox: DEFAULT_DROPBOX_CONFIG, dropbox: DEFAULT_DROPBOX_CONFIG,
onedrive: DEFAULT_ONEDRIVE_CONFIG, onedrive: DEFAULT_ONEDRIVE_CONFIG,
onedrivefull: DEFAULT_ONEDRIVEFULL_CONFIG,
webdis: DEFAULT_WEBDIS_CONFIG, webdis: DEFAULT_WEBDIS_CONFIG,
googledrive: DEFAULT_GOOGLEDRIVE_CONFIG, googledrive: DEFAULT_GOOGLEDRIVE_CONFIG,
box: DEFAULT_BOX_CONFIG, box: DEFAULT_BOX_CONFIG,
@ -127,11 +135,13 @@ const DEFAULT_SETTINGS: RemotelySavePluginSettings = {
agreeToUploadExtraMetadata: true, // as of 20240106, it's safe to assume every new user agrees with this agreeToUploadExtraMetadata: true, // as of 20240106, it's safe to assume every new user agrees with this
concurrency: 5, concurrency: 5,
syncConfigDir: false, syncConfigDir: false,
syncBookmarks: false,
syncUnderscoreItems: false, syncUnderscoreItems: false,
lang: "auto", lang: "auto",
logToDB: false, logToDB: false,
skipSizeLargerThan: -1, skipSizeLargerThan: -1,
ignorePaths: [], ignorePaths: [],
onlyAllowPaths: [],
enableStatusBarInfo: true, enableStatusBarInfo: true,
deleteToWhere: "system", deleteToWhere: "system",
agreeToUseSyncV3: false, agreeToUseSyncV3: false,
@ -222,15 +232,18 @@ export default class RemotelySavePlugin extends Plugin {
appContainerObserver?: MutationObserver; appContainerObserver?: MutationObserver;
async syncRun(triggerSource: SyncTriggerSourceType = "manual") { async syncRun(triggerSource: SyncTriggerSourceType = "manual") {
// const profiler = new Profiler( let profiler: Profiler | undefined = undefined;
// undefined, if (this.settings.profiler?.enable ?? false) {
// this.settings.profiler?.enablePrinting ?? false, profiler = new Profiler(
// this.settings.profiler?.recordSize ?? false undefined,
// ); this.settings.profiler?.enablePrinting ?? false,
const profiler: Profiler | undefined = undefined; this.settings.profiler?.recordSize ?? false
);
}
const fsLocal = new FakeFsLocal( const fsLocal = new FakeFsLocal(
this.app.vault, this.app.vault,
this.settings.syncConfigDir ?? false, this.settings.syncConfigDir ?? false,
this.settings.syncBookmarks ?? false,
this.app.vault.configDir, this.app.vault.configDir,
this.manifest.id, this.manifest.id,
profiler, profiler,
@ -727,7 +740,7 @@ export default class RemotelySavePlugin extends Plugin {
const self = this; const self = this;
setConfigBySuccessfullAuthInplaceOnedrive( setConfigBySuccessfullAuthInplaceOnedrive(
this.settings.onedrive, this.settings.onedrive,
rsp as AccessCodeResponseSuccessfulType, rsp as AccessCodeResponseSuccessfulTypeOnedrive,
() => self.saveSettings() () => self.saveSettings()
); );
@ -771,6 +784,91 @@ export default class RemotelySavePlugin extends Plugin {
} }
); );
this.registerObsidianProtocolHandler(
COMMAND_CALLBACK_ONEDRIVEFULL,
async (inputParams) => {
if (
inputParams.code !== undefined &&
this.oauth2Info?.verifier !== undefined
) {
if (this.oauth2Info.helperModal !== undefined) {
const k = this.oauth2Info.helperModal.contentEl;
k.empty();
t("protocol_onedrivefull_connecting")
.split("\n")
.forEach((val) => {
k.createEl("p", {
text: val,
});
});
}
const rsp = await sendAuthReqOnedriveFull(
this.settings.onedrivefull.clientID,
this.settings.onedrivefull.authority,
inputParams.code,
this.oauth2Info.verifier,
async (e: any) => {
new Notice(t("protocol_onedrivefull_connect_fail"));
new Notice(`${e}`);
return; // throw?
}
);
if ((rsp as any).error !== undefined) {
new Notice(`${JSON.stringify(rsp)}`);
throw Error(`${JSON.stringify(rsp)}`);
}
const self = this;
setConfigBySuccessfullAuthInplaceOnedriveFull(
this.settings.onedrivefull,
rsp as AccessCodeResponseSuccessfulTypeOnedriveFull,
() => self.saveSettings()
);
const client = getClient(
this.settings,
this.app.vault.getName(),
() => self.saveSettings()
);
this.settings.onedrivefull.username =
await client.getUserDisplayName();
await this.saveSettings();
this.oauth2Info.verifier = ""; // reset it
this.oauth2Info.helperModal?.close(); // close it
this.oauth2Info.helperModal = undefined;
this.oauth2Info.authDiv?.toggleClass(
"onedrivefull-auth-button-hide",
this.settings.onedrivefull.username !== ""
);
this.oauth2Info.authDiv = undefined;
this.oauth2Info.revokeAuthSetting?.setDesc(
t("protocol_onedrivefull_connect_succ_revoke", {
username: this.settings.onedrivefull.username,
})
);
this.oauth2Info.revokeAuthSetting = undefined;
this.oauth2Info.revokeDiv?.toggleClass(
"onedrivefull-revoke-auth-button-hide",
this.settings.onedrivefull.username === ""
);
this.oauth2Info.revokeDiv = undefined;
} else {
new Notice(t("protocol_onedrivefull_connect_fail"));
throw Error(
t("protocol_onedrivefull_connect_unknown", {
params: JSON.stringify(inputParams),
})
);
}
}
);
this.registerObsidianProtocolHandler( this.registerObsidianProtocolHandler(
COMMAND_CALLBACK_PRO, COMMAND_CALLBACK_PRO,
async (inputParams) => { async (inputParams) => {
@ -1243,12 +1341,18 @@ export default class RemotelySavePlugin extends Plugin {
cloneDeep(DEFAULT_SETTINGS), cloneDeep(DEFAULT_SETTINGS),
messyConfigToNormal(await this.loadData()) messyConfigToNormal(await this.loadData())
); );
if (this.settings.syncBookmarks === undefined) {
this.settings.syncBookmarks = false;
}
if (this.settings.dropbox.clientID === "") { if (this.settings.dropbox.clientID === "") {
this.settings.dropbox.clientID = DEFAULT_SETTINGS.dropbox.clientID; this.settings.dropbox.clientID = DEFAULT_SETTINGS.dropbox.clientID;
} }
if (this.settings.dropbox.remoteBaseDir === undefined) { if (this.settings.dropbox.remoteBaseDir === undefined) {
this.settings.dropbox.remoteBaseDir = ""; this.settings.dropbox.remoteBaseDir = "";
} }
if (this.settings.onedrive.clientID === "") { if (this.settings.onedrive.clientID === "") {
this.settings.onedrive.clientID = DEFAULT_SETTINGS.onedrive.clientID; this.settings.onedrive.clientID = DEFAULT_SETTINGS.onedrive.clientID;
} }
@ -1261,6 +1365,14 @@ export default class RemotelySavePlugin extends Plugin {
if (this.settings.onedrive.emptyFile === undefined) { if (this.settings.onedrive.emptyFile === undefined) {
this.settings.onedrive.emptyFile = "skip"; this.settings.onedrive.emptyFile = "skip";
} }
if (this.settings.onedrive.kind === undefined) {
this.settings.onedrive.kind = "onedrive";
}
if (this.settings.onedrivefull === undefined) {
this.settings.onedrivefull = DEFAULT_ONEDRIVEFULL_CONFIG;
}
if (this.settings.webdav.manualRecursive === undefined) { if (this.settings.webdav.manualRecursive === undefined) {
this.settings.webdav.manualRecursive = true; this.settings.webdav.manualRecursive = true;
} }
@ -1278,6 +1390,9 @@ export default class RemotelySavePlugin extends Plugin {
if (this.settings.webdav.remoteBaseDir === undefined) { if (this.settings.webdav.remoteBaseDir === undefined) {
this.settings.webdav.remoteBaseDir = ""; this.settings.webdav.remoteBaseDir = "";
} }
if (this.settings.webdav.customHeaders === undefined) {
this.settings.webdav.customHeaders = "";
}
if (this.settings.s3.partsConcurrency === undefined) { if (this.settings.s3.partsConcurrency === undefined) {
this.settings.s3.partsConcurrency = 20; this.settings.s3.partsConcurrency = 20;
} }
@ -1297,6 +1412,9 @@ export default class RemotelySavePlugin extends Plugin {
if (this.settings.ignorePaths === undefined) { if (this.settings.ignorePaths === undefined) {
this.settings.ignorePaths = []; this.settings.ignorePaths = [];
} }
if (this.settings.onlyAllowPaths === undefined) {
this.settings.onlyAllowPaths = [];
}
if (this.settings.enableStatusBarInfo === undefined) { if (this.settings.enableStatusBarInfo === undefined) {
this.settings.enableStatusBarInfo = true; this.settings.enableStatusBarInfo = true;
} }
@ -1355,6 +1473,9 @@ export default class RemotelySavePlugin extends Plugin {
if (this.settings.profiler === undefined) { if (this.settings.profiler === undefined) {
this.settings.profiler = DEFAULT_PROFILER_CONFIG; this.settings.profiler = DEFAULT_PROFILER_CONFIG;
} }
if (this.settings.profiler.enable === undefined) {
this.settings.profiler.enable = false;
}
if (this.settings.profiler.enablePrinting === undefined) { if (this.settings.profiler.enablePrinting === undefined) {
this.settings.profiler.enablePrinting = false; this.settings.profiler.enablePrinting = false;
} }
@ -1439,6 +1560,7 @@ export default class RemotelySavePlugin extends Plugin {
this.settings.dropbox.refreshToken !== "" && this.settings.dropbox.refreshToken !== "" &&
current >= this.settings!.dropbox!.credentialsShouldBeDeletedAtTime! current >= this.settings!.dropbox!.credentialsShouldBeDeletedAtTime!
) { ) {
console.warn(`dropbox expired`);
dropboxExpired = true; dropboxExpired = true;
this.settings.dropbox = cloneDeep(DEFAULT_DROPBOX_CONFIG); this.settings.dropbox = cloneDeep(DEFAULT_DROPBOX_CONFIG);
needSave = true; needSave = true;
@ -1449,16 +1571,29 @@ export default class RemotelySavePlugin extends Plugin {
this.settings.onedrive.refreshToken !== "" && this.settings.onedrive.refreshToken !== "" &&
current >= this.settings!.onedrive!.credentialsShouldBeDeletedAtTime! current >= this.settings!.onedrive!.credentialsShouldBeDeletedAtTime!
) { ) {
console.warn(`onedrive expired`);
onedriveExpired = true; onedriveExpired = true;
this.settings.onedrive = cloneDeep(DEFAULT_ONEDRIVE_CONFIG); this.settings.onedrive = cloneDeep(DEFAULT_ONEDRIVE_CONFIG);
needSave = true; needSave = true;
} }
let onedriveFullExpired = false;
if (
this.settings.onedrivefull.refreshToken !== "" &&
current >= this.settings!.onedrivefull!.credentialsShouldBeDeletedAtTime!
) {
console.warn(`onedrive full expired`);
onedriveFullExpired = true;
this.settings.onedrivefull = cloneDeep(DEFAULT_ONEDRIVEFULL_CONFIG);
needSave = true;
}
let googleDriveExpired = false; let googleDriveExpired = false;
if ( if (
this.settings.googledrive.refreshToken !== "" && this.settings.googledrive.refreshToken !== "" &&
current >= this.settings!.googledrive!.credentialsShouldBeDeletedAtTimeMs! current >= this.settings!.googledrive!.credentialsShouldBeDeletedAtTimeMs!
) { ) {
console.warn(`google drive expired`);
googleDriveExpired = true; googleDriveExpired = true;
this.settings.googledrive = cloneDeep(DEFAULT_GOOGLEDRIVE_CONFIG); this.settings.googledrive = cloneDeep(DEFAULT_GOOGLEDRIVE_CONFIG);
needSave = true; needSave = true;
@ -1469,6 +1604,7 @@ export default class RemotelySavePlugin extends Plugin {
this.settings.box.refreshToken !== "" && this.settings.box.refreshToken !== "" &&
current >= this.settings!.box!.credentialsShouldBeDeletedAtTimeMs! current >= this.settings!.box!.credentialsShouldBeDeletedAtTimeMs!
) { ) {
console.warn(`box expired`);
boxExpired = true; boxExpired = true;
this.settings.box = cloneDeep(DEFAULT_BOX_CONFIG); this.settings.box = cloneDeep(DEFAULT_BOX_CONFIG);
needSave = true; needSave = true;
@ -1479,6 +1615,7 @@ export default class RemotelySavePlugin extends Plugin {
this.settings.pcloud.accessToken !== "" && this.settings.pcloud.accessToken !== "" &&
current >= this.settings!.pcloud!.credentialsShouldBeDeletedAtTimeMs! current >= this.settings!.pcloud!.credentialsShouldBeDeletedAtTimeMs!
) { ) {
console.warn(`pcloud expired`);
pCloudExpired = true; pCloudExpired = true;
this.settings.pcloud = cloneDeep(DEFAULT_PCLOUD_CONFIG); this.settings.pcloud = cloneDeep(DEFAULT_PCLOUD_CONFIG);
needSave = true; needSave = true;
@ -1489,6 +1626,7 @@ export default class RemotelySavePlugin extends Plugin {
this.settings.yandexdisk.refreshToken !== "" && this.settings.yandexdisk.refreshToken !== "" &&
current >= this.settings!.yandexdisk!.credentialsShouldBeDeletedAtTimeMs! current >= this.settings!.yandexdisk!.credentialsShouldBeDeletedAtTimeMs!
) { ) {
console.warn(`yandex disk expired`);
yandexDiskExpired = true; yandexDiskExpired = true;
this.settings.yandexdisk = cloneDeep(DEFAULT_YANDEXDISK_CONFIG); this.settings.yandexdisk = cloneDeep(DEFAULT_YANDEXDISK_CONFIG);
needSave = true; needSave = true;
@ -1499,6 +1637,7 @@ export default class RemotelySavePlugin extends Plugin {
this.settings.koofr.refreshToken !== "" && this.settings.koofr.refreshToken !== "" &&
current >= this.settings!.koofr!.credentialsShouldBeDeletedAtTimeMs! current >= this.settings!.koofr!.credentialsShouldBeDeletedAtTimeMs!
) { ) {
console.warn(`koofr expired`);
koofrExpired = true; koofrExpired = true;
this.settings.koofr = cloneDeep(DEFAULT_KOOFR_CONFIG); this.settings.koofr = cloneDeep(DEFAULT_KOOFR_CONFIG);
needSave = true; needSave = true;
@ -1522,7 +1661,13 @@ export default class RemotelySavePlugin extends Plugin {
} }
if (onedriveExpired) { if (onedriveExpired) {
new Notice( new Notice(
`${this.manifest.name}: You haven't manually auth OneDrive for many days, you need to re-auth it again.`, `${this.manifest.name}: You haven't manually auth OneDrive (App Folder) for many days, you need to re-auth it again.`,
6000
);
}
if (onedriveFullExpired) {
new Notice(
`${this.manifest.name}: You haven't manually auth OneDrive (Full) for many days, you need to re-auth it again.`,
6000 6000
); );
} }
@ -1757,6 +1902,7 @@ export default class RemotelySavePlugin extends Plugin {
const fsLocal = new FakeFsLocal( const fsLocal = new FakeFsLocal(
this.app.vault, this.app.vault,
this.settings.syncConfigDir ?? false, this.settings.syncConfigDir ?? false,
this.settings.syncBookmarks ?? false,
this.app.vault.configDir, this.app.vault.configDir,
this.manifest.id, this.manifest.id,
undefined, undefined,

View File

@ -279,7 +279,7 @@ export const reverseString = (x: string) => {
}; };
export interface SplitRange { export interface SplitRange {
partNum: number; // startting from 1 partNum: number; // starting from 1
start: number; start: number;
end: number; // exclusive end: number; // exclusive
} }
@ -316,7 +316,7 @@ export const getTypeName = (obj: any) => {
}; };
/** /**
* Startting from 1 * starting from 1
* @param x * @param x
* @returns * @returns
*/ */
@ -467,6 +467,21 @@ export const isSpecialFolderNameToSkip = (
return true; return true;
} }
} }
// microsoft tmp files...
const p = x.split("/");
if (p.length > 0) {
const f = p[p.length - 1]; // file name
if (f.startsWith("~$")) {
const suffixList = ["doc", "docx", "ppt", "pptx", "xls", "xlsx"];
for (const suffix of suffixList) {
if (f.endsWith(`.${suffix}`)) {
return true;
}
}
}
}
return false; return false;
}; };
@ -727,3 +742,110 @@ export const getSha1 = async (x: ArrayBuffer, stringify: "base64" | "hex") => {
} }
throw Error(`not supported stringify option = ${stringify}`); throw Error(`not supported stringify option = ${stringify}`);
}; };
/**
* https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
* https://support.microsoft.com/en-us/office/restrictions-and-limitations-in-onedrive-and-sharepoint-64883a5d-228e-48f5-b3d2-eb39e07630fa#invalidcharacters
*/
export const checkValidName = (x: string) => {
if (x === undefined || x === "") {
// what??
return {
reason: "empty",
result: false,
};
}
// The following reserved characters:
const invalidChars = '*"<>:|?'.split("");
for (const c of invalidChars) {
if (x.includes(c)) {
return {
reason: `reserved character: ${c}`,
result: false,
};
}
}
// directory component
for (const c of [".", ".."]) {
if (
x === c ||
x.endsWith(`/${c}`) ||
x.startsWith(`${c}/`) ||
x.includes(`/${c}/`)
) {
return {
reason: `directory being ${c}`,
result: false,
};
}
}
// reserved file names
const reservedNames = [
"CON",
"PRN",
"AUX",
"NUL",
"COM0",
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6",
"COM7",
"COM8",
"COM9",
"COM¹",
"COM²",
"COM³",
"LPT0",
"LPT1",
"LPT2",
"LPT3",
"LPT4",
"LPT5",
"LPT6",
"LPT7",
"LPT8",
"LPT9",
"LPT¹",
"LPT²",
"LPT³",
];
for (const f of reservedNames) {
if (
x === f ||
x.startsWith(`${f}.`) ||
x.startsWith(`${f}/`) ||
x.includes(`/${f}/`) ||
x.endsWith(`/${f}`) ||
x.includes(`/${f}.`)
) {
return {
reason: `reserved folder/file name: ${f}`,
result: false,
};
}
}
// Do not end a file or directory name with a space or a period.
if (
x.endsWith(" ") ||
x.endsWith(".") ||
x.includes(" /") ||
x.includes("./")
) {
return {
reason: `folder/file name ending with a space or a period`,
result: false,
};
}
return {
reason: "ok",
result: true,
};
};

View File

@ -34,11 +34,15 @@ const isLikelyPluginSubFiles = (x: string) => {
export const listFilesInObsFolder = async ( export const listFilesInObsFolder = async (
configDir: string, configDir: string,
vault: Vault, vault: Vault,
pluginId: string pluginId: string,
bookmarksOnly: boolean
): Promise<Entity[]> => { ): Promise<Entity[]> => {
const q = new Queue([configDir]); const q = new Queue([configDir]);
const CHUNK_SIZE = 10; const CHUNK_SIZE = 10;
const contents: Entity[] = []; let contents: Entity[] = [];
let iterRound = 0;
while (q.length > 0) { while (q.length > 0) {
const itemsToFetch: string[] = []; const itemsToFetch: string[] = [];
while (q.length > 0) { while (q.length > 0) {
@ -115,6 +119,23 @@ export const listFilesInObsFolder = async (
} }
} }
} }
if (bookmarksOnly && iterRound > 1) {
// list until bookmarks.json is found or next level is arrived.
break;
}
iterRound += 1;
} }
// console.debug(`contents in obs config: ${JSON.stringify(contents)}`);
if (bookmarksOnly) {
contents = contents.filter(
(e) =>
e.key === `${configDir}/` || e.key === `${configDir}/bookmarks.json`
);
}
return contents; return contents;
}; };

View File

@ -10,6 +10,7 @@ interface BreakPoint {
} }
export const DEFAULT_PROFILER_CONFIG: ProfilerConfig = { export const DEFAULT_PROFILER_CONFIG: ProfilerConfig = {
enable: false,
enablePrinting: false, enablePrinting: false,
recordSize: false, recordSize: false,
}; };

View File

@ -23,8 +23,10 @@ import type {
import cloneDeep from "lodash/cloneDeep"; import cloneDeep from "lodash/cloneDeep";
import { generateAzureBlobStorageSettingsPart } from "../pro/src/settingsAzureBlobStorage"; import { generateAzureBlobStorageSettingsPart } from "../pro/src/settingsAzureBlobStorage";
import { generateBoxSettingsPart } from "../pro/src/settingsBox"; import { generateBoxSettingsPart } from "../pro/src/settingsBox";
import { generateClearDupFilesSettingsPart } from "../pro/src/settingsClearDupFiles";
import { generateGoogleDriveSettingsPart } from "../pro/src/settingsGoogleDrive"; import { generateGoogleDriveSettingsPart } from "../pro/src/settingsGoogleDrive";
import { generateKoofrSettingsPart } from "../pro/src/settingsKoofr"; import { generateKoofrSettingsPart } from "../pro/src/settingsKoofr";
import { generateOnedriveFullSettingsPart } from "../pro/src/settingsOnedriveFull";
import { generatePCloudSettingsPart } from "../pro/src/settingsPCloud"; import { generatePCloudSettingsPart } from "../pro/src/settingsPCloud";
import { generateProSettingsPart } from "../pro/src/settingsPro"; import { generateProSettingsPart } from "../pro/src/settingsPro";
import { generateYandexDiskSettingsPart } from "../pro/src/settingsYandexDisk"; import { generateYandexDiskSettingsPart } from "../pro/src/settingsYandexDisk";
@ -1636,6 +1638,27 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
}); });
}); });
new Setting(webdavDiv)
.setName(t("settings_webdav_customheaders"))
.setDesc(stringToFragment(t("settings_webdav_customheaders_desc")))
.addTextArea((textArea) => {
textArea
.setPlaceholder(`X-Header1: Value1\nX-Header2: Value2`)
.setValue(`${this.plugin.settings.webdav.customHeaders ?? ""}`)
.onChange(async (value) => {
this.plugin.settings.webdav.customHeaders = value
.trim()
.split("\n")
.filter((x) => x.trim() !== "")
.join("\n");
await this.plugin.saveSettings();
});
textArea.inputEl.rows = 10;
textArea.inputEl.cols = 30;
textArea.inputEl.addClass("webdav-customheaders-textarea");
});
let newWebdavRemoteBaseDir = let newWebdavRemoteBaseDir =
this.plugin.settings.webdav.remoteBaseDir || ""; this.plugin.settings.webdav.remoteBaseDir || "";
new Setting(webdavDiv) new Setting(webdavDiv)
@ -1815,6 +1838,22 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
}); });
}); });
//////////////////////////////////////////////////
// below for Onedrive (Full)
//////////////////////////////////////////////////
const {
onedriveFullDiv,
onedriveFullAllowedToUsedDiv,
onedriveFullNotShowUpHintSetting,
} = generateOnedriveFullSettingsPart(
containerEl,
t,
this.app,
this.plugin,
() => this.plugin.saveSettings()
);
////////////////////////////////////////////////// //////////////////////////////////////////////////
// below for googledrive // below for googledrive
////////////////////////////////////////////////// //////////////////////////////////////////////////
@ -1905,10 +1944,21 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
dropdown.addOption("webdav", t("settings_chooseservice_webdav")); dropdown.addOption("webdav", t("settings_chooseservice_webdav"));
dropdown.addOption("onedrive", t("settings_chooseservice_onedrive")); dropdown.addOption("onedrive", t("settings_chooseservice_onedrive"));
dropdown.addOption("webdis", t("settings_chooseservice_webdis")); dropdown.addOption("webdis", t("settings_chooseservice_webdis"));
dropdown.addOption("separator line", "-----");
(dropdown.selectEl.lastChild as HTMLElement).setAttribute(
"disabled",
"disabled"
);
dropdown.addOption( dropdown.addOption(
"googledrive", "googledrive",
t("settings_chooseservice_googledrive") t("settings_chooseservice_googledrive")
); );
dropdown.addOption(
"onedrivefull",
t("settings_chooseservice_onedrivefull")
);
dropdown.addOption("box", t("settings_chooseservice_box")); dropdown.addOption("box", t("settings_chooseservice_box"));
dropdown.addOption("pcloud", t("settings_chooseservice_pcloud")); dropdown.addOption("pcloud", t("settings_chooseservice_pcloud"));
dropdown.addOption( dropdown.addOption(
@ -1937,6 +1987,10 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
"onedrive-hide", "onedrive-hide",
this.plugin.settings.serviceType !== "onedrive" this.plugin.settings.serviceType !== "onedrive"
); );
onedriveFullDiv.toggleClass(
"onedrivefull-hide",
this.plugin.settings.serviceType !== "onedrivefull"
);
webdavDiv.toggleClass( webdavDiv.toggleClass(
"webdav-hide", "webdav-hide",
this.plugin.settings.serviceType !== "webdav" this.plugin.settings.serviceType !== "webdav"
@ -2193,6 +2247,27 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
textArea.inputEl.addClass("ignorepaths-textarea"); textArea.inputEl.addClass("ignorepaths-textarea");
}); });
new Setting(basicDiv)
.setName(t("settings_onlyallowpaths"))
.setDesc(t("settings_onlyallowpaths_desc"))
.setClass("onlyallowpaths-settings")
.addTextArea((textArea) => {
textArea
.setValue(`${(this.plugin.settings.onlyAllowPaths ?? []).join("\n")}`)
.onChange(async (value) => {
this.plugin.settings.onlyAllowPaths = value
.trim()
.split("\n")
.filter((x) => x.trim() !== "");
await this.plugin.saveSettings();
});
textArea.inputEl.rows = 10;
textArea.inputEl.cols = 30;
textArea.inputEl.addClass("onlyallowpaths-textarea");
});
////////////////////////////////////////////////// //////////////////////////////////////////////////
// below for advanced settings // below for advanced settings
////////////////////////////////////////////////// //////////////////////////////////////////////////
@ -2271,6 +2346,27 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
}); });
}); });
new Setting(advDiv)
.setName(t("settings_bookmarks"))
.setDesc(
t("settings_bookmarks_desc", {
configDir: this.app.vault.configDir,
})
)
.addDropdown((dropdown) => {
dropdown.addOption("disable", t("disable"));
dropdown.addOption("enable", t("enable"));
dropdown
.setValue(
`${this.plugin.settings.syncBookmarks ? "enable" : "disable"}`
)
.onChange(async (val) => {
this.plugin.settings.syncBookmarks = val === "enable";
await this.plugin.saveSettings();
});
});
new Setting(advDiv) new Setting(advDiv)
.setName(t("settings_deletetowhere")) .setName(t("settings_deletetowhere"))
.setDesc(t("settings_deletetowhere_desc")) .setDesc(t("settings_deletetowhere_desc"))
@ -2327,6 +2423,8 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
}); });
}); });
generateClearDupFilesSettingsPart(advDiv, t, this.app, this.plugin);
const percentage1 = new Setting(advDiv) const percentage1 = new Setting(advDiv)
.setName(t("settings_protectmodifypercentage")) .setName(t("settings_protectmodifypercentage"))
.setDesc(t("settings_protectmodifypercentage_desc")); .setDesc(t("settings_protectmodifypercentage_desc"));
@ -2519,6 +2617,16 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
).open(); ).open();
}); });
}) })
.addButton(async (button) => {
button.setButtonText(t("settings_export_onedrivefull_button"));
button.onClick(async () => {
new ExportSettingsQrCodeModal(
this.app,
this.plugin,
"onedrivefull"
).open();
});
})
.addButton(async (button) => { .addButton(async (button) => {
button.setButtonText(t("settings_export_webdav_button")); button.setButtonText(t("settings_export_webdav_button"));
button.onClick(async () => { button.onClick(async () => {
@ -2643,6 +2751,8 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
this.app, this.app,
this.plugin, this.plugin,
() => this.plugin.saveSettings(), () => this.plugin.saveSettings(),
onedriveFullAllowedToUsedDiv,
onedriveFullNotShowUpHintSetting,
googleDriveAllowedToUsedDiv, googleDriveAllowedToUsedDiv,
googleDriveNotShowUpHintSetting, googleDriveNotShowUpHintSetting,
boxAllowedToUsedDiv, boxAllowedToUsedDiv,
@ -2737,6 +2847,19 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
new Notice(t("settings_syncplans_notice")); new Notice(t("settings_syncplans_notice"));
}); });
}) })
.addButton(async (button) => {
button.setButtonText(t("settings_syncplans_button_5_only_change"));
button.onClick(async () => {
await exportVaultSyncPlansToFiles(
this.plugin.db,
this.app.vault,
this.plugin.vaultRandomID,
5,
true
);
new Notice(t("settings_syncplans_notice"));
});
})
.addButton(async (button) => { .addButton(async (button) => {
button.setButtonText(t("settings_syncplans_button_1")); button.setButtonText(t("settings_syncplans_button_1"));
button.onClick(async () => { button.onClick(async () => {
@ -2817,6 +2940,25 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
}); });
}); });
new Setting(debugDiv)
.setName(t("settings_profiler_enableprofiler"))
.setDesc(t("settings_profiler_enableprofiler_desc"))
.addDropdown((dropdown) => {
dropdown.addOption("enable", t("enable"));
dropdown.addOption("disable", t("disable"));
dropdown
.setValue(
this.plugin.settings.profiler?.enable ? "enable" : "disable"
)
.onChange(async (val: string) => {
if (this.plugin.settings.profiler === undefined) {
this.plugin.settings.profiler = DEFAULT_PROFILER_CONFIG;
}
this.plugin.settings.profiler.enable = val === "enable";
await this.plugin.saveSettings();
});
});
new Setting(debugDiv) new Setting(debugDiv)
.setName(t("settings_profiler_enabledebugprint")) .setName(t("settings_profiler_enabledebugprint"))
.setDesc(t("settings_profiler_enabledebugprint_desc")) .setDesc(t("settings_profiler_enabledebugprint_desc"))

View File

@ -62,6 +62,25 @@
display: none; display: none;
} }
.onedrivefull-allow-to-use-hide {
display: none;
}
.onedrivefull-disclaimer {
font-weight: bold;
}
.onedrivefull-hide {
display: none;
}
.onedrivefull-auth-button-hide {
display: none;
}
.onedrivefull-revoke-auth-button-hide {
display: none;
}
.webdav-disclaimer { .webdav-disclaimer {
font-weight: bold; font-weight: bold;
} }
@ -69,6 +88,10 @@
display: none; display: none;
} }
.webdav-customheaders-textarea {
font-family: monospace;
}
.webdis-disclaimer { .webdis-disclaimer {
font-weight: bold; font-weight: bold;
} }
@ -191,6 +214,10 @@
font-family: monospace; font-family: monospace;
} }
.onlyallowpaths-textarea {
font-family: monospace;
}
.logtohttpserver-warning { .logtohttpserver-warning {
color: red; color: red;
font-weight: bolder; font-weight: bolder;

View File

@ -16,6 +16,9 @@ const DEFAULT_SETTINGS: RemotelySavePluginSettings = {
onedrive: { onedrive: {
username: "test 🍎 emoji", username: "test 🍎 emoji",
} as any, } as any,
onedrivefull: {
username: "test 🍎 emoji",
} as any,
webdis: { webdis: {
address: "addr", address: "addr",
} as any, } as any,

View File

@ -363,6 +363,82 @@ describe("Misc: split chunk ranges", () => {
}); });
}); });
describe("Misc: check valid file names", () => {
it("should be ok for normal file nmes", () => {
let item = "what/.hidden/what/what/what";
assert.ok(misc.checkValidName(item).result);
item = "ssss/%%%^^^$xxxx.md";
assert.ok(misc.checkValidName(item).result);
});
it("should be not ok for reserved characters", () => {
let item = "a**";
assert.ok(!misc.checkValidName(item).result);
item = "a?*";
assert.ok(!misc.checkValidName(item).result);
item = "<>:";
assert.ok(!misc.checkValidName(item).result);
item = "<>:/ssss";
assert.ok(!misc.checkValidName(item).result);
});
it("should be not ok for reserved names", () => {
let item = "CON";
assert.ok(!misc.checkValidName(item).result);
item = "CON.txt";
assert.ok(!misc.checkValidName(item).result);
item = "CON.md";
assert.ok(!misc.checkValidName(item).result);
item = "con"; // lower case is ok
assert.ok(misc.checkValidName(item).result);
item = "CON/";
assert.ok(!misc.checkValidName(item).result);
item = "CON.dir/";
assert.ok(!misc.checkValidName(item).result);
item = "CON.dir.folder/";
assert.ok(!misc.checkValidName(item).result);
item = "xxx/CON";
assert.ok(!misc.checkValidName(item).result);
item = "xxx/CON.txt";
assert.ok(!misc.checkValidName(item).result);
item = "xxx/CON.txt.md";
assert.ok(!misc.checkValidName(item).result);
});
it("should be not ok for invalid endings", () => {
let item = "xxx ";
assert.ok(!misc.checkValidName(item).result);
item = "/xxx ";
assert.ok(!misc.checkValidName(item).result);
item = "xxx.yyy.";
assert.ok(!misc.checkValidName(item).result);
item = "xxx.yyy.";
assert.ok(!misc.checkValidName(item).result);
item = "xxx /";
assert.ok(!misc.checkValidName(item).result);
item = "xxx.yyy./";
assert.ok(!misc.checkValidName(item).result);
});
});
describe("Misc: Dropbox: should fix the folder name cases", () => { describe("Misc: Dropbox: should fix the folder name cases", () => {
it("should do nothing on empty folders", () => { it("should do nothing on empty folders", () => {
const input: any[] = []; const input: any[] = [];